mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-24 00:35:31 +00:00
Merge reviewed PR #3221: experimental native Antigravity plugin and hooks
This commit is contained in:
36 files changed
+2549
-54
No files matched your search
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Antigravity Lifecycle Hook Bridge
|
||||
*
|
||||
* Bridges Google Antigravity's protojson hook contract (stdin/stdout JSON with
|
||||
* camelCase keys and { decision, reason } responses) to ECC's internal hook
|
||||
* runtime (exit-code/stderr based).
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
const { runPreBash } = require('./bash-hook-dispatcher');
|
||||
const { run: runGateGuard } = require('./gateguard-fact-force');
|
||||
const { run: runDocFileWarning } = require('./doc-file-warning');
|
||||
const { run: runPostEditAccumulator } = require('./post-edit-accumulator');
|
||||
const { readStdinRaw, resolveMaxStdin } = require('./hook-input');
|
||||
const { isHookEnabled, isDryRun } = require('../lib/hook-flags');
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
mode: 'pre-tool-use',
|
||||
hook: null,
|
||||
};
|
||||
|
||||
for (let i = 2; i < argv.length; i += 1) {
|
||||
if (argv[i] === '--mode') {
|
||||
options.mode = argv[i + 1] || options.mode;
|
||||
i += 1;
|
||||
} else if (argv[i] === '--hook') {
|
||||
options.hook = argv[i + 1] || options.hook;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function adaptAntigravityInputToEcc(antigravityData) {
|
||||
if (!antigravityData || typeof antigravityData !== 'object') {
|
||||
return { tool_name: '', tool_input: {} };
|
||||
}
|
||||
|
||||
const toolCall = antigravityData.toolCall || {};
|
||||
const toolName = toolCall.name || antigravityData.tool_name || '';
|
||||
const args = toolCall.args || antigravityData.tool_input || {};
|
||||
|
||||
// Normalize Antigravity tools to ECC tool conventions
|
||||
const toolInput = {
|
||||
...args,
|
||||
command: args.CommandLine || args.command || '',
|
||||
file_path: args.TargetFile || args.file_path || args.path || '',
|
||||
};
|
||||
|
||||
return {
|
||||
tool_name: ({ run_command: 'Bash', write_to_file: 'Write', replace_file_content: 'Edit', multi_replace_file_content: 'Edit' })[toolName] || toolName,
|
||||
tool_input: toolInput,
|
||||
session_id: antigravityData.conversationId || antigravityData.session_id || '',
|
||||
cwd: args.Cwd || antigravityData.cwd || antigravityData.workspacePaths?.[0] || '',
|
||||
conversation_id: antigravityData.conversationId || '',
|
||||
workspace_paths: antigravityData.workspacePaths || [],
|
||||
};
|
||||
}
|
||||
|
||||
function writeFailure(mode, reason) {
|
||||
process.stdout.write(JSON.stringify({
|
||||
decision: mode === 'pre-tool-use' ? 'deny' : 'allow',
|
||||
...(mode === 'pre-tool-use' ? { reason } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv);
|
||||
process.env.ECC_HOOK_CONFIG ||= path.resolve(__dirname, '../../ecc/setup.json');
|
||||
const profiles = options.hook === 'pre:bash:dispatcher' ? 'minimal,standard,strict' : undefined;
|
||||
if (!isHookEnabled(options.hook, { profiles }) || isDryRun()) {
|
||||
process.stdout.write(JSON.stringify(options.mode === 'post-tool-use' ? {} : { decision: 'allow' }));
|
||||
return;
|
||||
}
|
||||
const maxStdin = resolveMaxStdin(process.env.ECC_HOOK_INPUT_MAX_BYTES);
|
||||
|
||||
let raw = '';
|
||||
try {
|
||||
const inputResult = await readStdinRaw(process.stdin, { maxStdin });
|
||||
if (inputResult.truncated) throw new Error('Incomplete hook input');
|
||||
raw = inputResult.raw;
|
||||
} catch (_err) {
|
||||
writeFailure(options.mode, 'ECC hook input could not be read completely');
|
||||
return;
|
||||
}
|
||||
|
||||
let antigravityPayload = {};
|
||||
try {
|
||||
antigravityPayload = JSON.parse(raw);
|
||||
if (!antigravityPayload || typeof antigravityPayload !== 'object' || Array.isArray(antigravityPayload)) {
|
||||
throw new Error('Invalid hook input');
|
||||
}
|
||||
} catch (_parseErr) {
|
||||
writeFailure(options.mode, 'ECC hook input must be a valid JSON object');
|
||||
return;
|
||||
}
|
||||
|
||||
const eccPayload = adaptAntigravityInputToEcc(antigravityPayload);
|
||||
const eccJsonString = JSON.stringify(eccPayload);
|
||||
|
||||
if (options.mode === 'pre-tool-use') {
|
||||
let result = { exitCode: 0, stderr: '' };
|
||||
|
||||
if (options.hook === 'pre:bash:dispatcher') {
|
||||
result = runPreBash(eccJsonString);
|
||||
} else if (options.hook === 'pre:edit-write:gateguard-fact-force') {
|
||||
result = runGateGuard(eccJsonString);
|
||||
} else if (options.hook === 'pre:config-protection') {
|
||||
const child = spawnSync(process.execPath, [path.join(__dirname, 'config-protection.js')], {
|
||||
input: eccJsonString,
|
||||
encoding: 'utf8',
|
||||
timeout: 4000,
|
||||
});
|
||||
result = {
|
||||
exitCode: child.error || child.status === null ? 2 : child.status,
|
||||
stderr: child.stderr || '',
|
||||
stdout: typeof child.stdout === 'string' ? child.stdout : '',
|
||||
};
|
||||
} else if (options.hook === 'pre:write:doc-file-warning') {
|
||||
result = runDocFileWarning(eccJsonString);
|
||||
}
|
||||
|
||||
const output = typeof result?.stdout === 'string'
|
||||
? result.stdout
|
||||
: (typeof result?.output === 'string' ? result.output : null);
|
||||
let hookOutput = null;
|
||||
if (output) {
|
||||
try {
|
||||
const parsed = JSON.parse(output);
|
||||
hookOutput = parsed && typeof parsed === 'object' ? parsed.hookSpecificOutput : null;
|
||||
} catch {
|
||||
hookOutput = null;
|
||||
}
|
||||
}
|
||||
const denied = Boolean(
|
||||
(result && ((result.exitCode !== undefined && result.exitCode !== 0) || result.denied || result.blocked))
|
||||
|| hookOutput?.permissionDecision === 'deny'
|
||||
);
|
||||
const context = result?.additionalContext || hookOutput?.additionalContext;
|
||||
const reason = denied
|
||||
? hookOutput?.permissionDecisionReason || result?.stderr || result?.reason || 'Blocked by ECC safety hook'
|
||||
: (Array.isArray(context) ? context.join(' ') : context);
|
||||
process.stdout.write(JSON.stringify({
|
||||
decision: denied ? 'deny' : 'allow',
|
||||
...(reason ? { reason: String(reason).replace(/\r?\n/g, ' ').trim() } : {}),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Both accumulator and batch formatter use the same session-scoped temp file.
|
||||
if (eccPayload.session_id) process.env.CLAUDE_SESSION_ID = String(eccPayload.session_id);
|
||||
|
||||
if (options.mode === 'post-tool-use') {
|
||||
if (options.hook === 'post:edit:accumulator' && !antigravityPayload.error) {
|
||||
runPostEditAccumulator(eccJsonString);
|
||||
}
|
||||
process.stdout.write(JSON.stringify({}));
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.mode === 'stop') {
|
||||
if (antigravityPayload.fullyIdle === false) {
|
||||
process.stdout.write(JSON.stringify({ decision: 'allow' }));
|
||||
return;
|
||||
}
|
||||
let stopResult = { exitCode: 0, stderr: '' };
|
||||
|
||||
const stopScript = {
|
||||
'stop:format-typecheck': 'stop-format-typecheck.js',
|
||||
'stop:check-console-log': 'check-console-log.js',
|
||||
}[options.hook];
|
||||
if (stopScript) {
|
||||
const child = spawnSync(process.execPath, [path.join(__dirname, stopScript)], {
|
||||
input: eccJsonString,
|
||||
cwd: eccPayload.cwd || undefined,
|
||||
encoding: 'utf8',
|
||||
timeout: options.hook === 'stop:format-typecheck' ? 280000 : 25000,
|
||||
});
|
||||
stopResult = {
|
||||
stderr: child.stderr || (child.error ? 'ECC stop hook failed: ' + child.error.message : ''),
|
||||
};
|
||||
}
|
||||
|
||||
if (stopResult && stopResult.stderr) {
|
||||
process.stdout.write(JSON.stringify({
|
||||
decision: 'continue',
|
||||
reason: stopResult.stderr.replace(/\r?\n/g, ' ').trim(),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
process.stdout.write(JSON.stringify({ decision: 'allow' }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Default passthrough
|
||||
process.stdout.write(JSON.stringify({ decision: 'allow' }));
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch(() => {
|
||||
writeFailure(parseArgs(process.argv).mode, 'ECC safety hook failed unexpectedly');
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
adaptAntigravityInputToEcc,
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const { shellQuote } = require('./control-pane/actions');
|
||||
|
||||
/**
|
||||
* Antigravity Hooks Generator
|
||||
*
|
||||
* Generates valid Antigravity hooks.json configuration matching Antigravity's
|
||||
* lifecycle schema (PreToolUse, PostToolUse, Stop) and pointing to the ECC
|
||||
* hook bridge.
|
||||
*/
|
||||
|
||||
function buildAntigravityHooksConfig(options = {}) {
|
||||
const { bridgeScript } = options;
|
||||
if (typeof bridgeScript !== 'string' || !path.isAbsolute(bridgeScript) || bridgeScript.includes('\0')) {
|
||||
throw new Error('bridgeScript must be an absolute path');
|
||||
}
|
||||
let quotedBridgeScript;
|
||||
if (process.platform === 'win32') {
|
||||
if (/[%"!$`\r\n]/.test(bridgeScript)) {
|
||||
throw new Error('bridgeScript contains unsafe shell expansion characters');
|
||||
}
|
||||
quotedBridgeScript = `"${bridgeScript}"`;
|
||||
} else {
|
||||
quotedBridgeScript = shellQuote(bridgeScript);
|
||||
}
|
||||
|
||||
const preToolUseHandlers = [
|
||||
{
|
||||
matcher: 'run_command',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:bash:dispatcher`,
|
||||
timeout: 15,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
matcher: 'write_to_file|replace_file_content|multi_replace_file_content',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:edit-write:gateguard-fact-force`,
|
||||
timeout: 10,
|
||||
},
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:config-protection`,
|
||||
timeout: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// Runtime hook flags select the profile, including explicit environment overrides.
|
||||
preToolUseHandlers.push({
|
||||
matcher: 'write_to_file',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:write:doc-file-warning`,
|
||||
timeout: 5,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const stopHandlers = [
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode stop --hook stop:format-typecheck`,
|
||||
timeout: 300,
|
||||
},
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode stop --hook stop:check-console-log`,
|
||||
timeout: 30,
|
||||
},
|
||||
];
|
||||
|
||||
return {
|
||||
'ecc-guard': {
|
||||
PreToolUse: preToolUseHandlers,
|
||||
PostToolUse: [{
|
||||
matcher: 'write_to_file|replace_file_content|multi_replace_file_content',
|
||||
hooks: [{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode post-tool-use --hook post:edit:accumulator`,
|
||||
timeout: 10,
|
||||
}],
|
||||
}],
|
||||
Stop: stopHandlers,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildAntigravityHooksConfig,
|
||||
};
|
||||
@@ -0,0 +1,72 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { createManagedScaffoldOperation } = require('./install-targets/helpers');
|
||||
const { formatPackageSourcePath } = require('./install/package-source');
|
||||
|
||||
/**
|
||||
* Antigravity MCP Configuration Generator
|
||||
*
|
||||
* Generates valid Antigravity mcp_config.json containing the ECC Memory Vault
|
||||
* stdio server so that Antigravity agents have native access to .ecc/memory/.
|
||||
*/
|
||||
|
||||
function buildAntigravityMcpConfig(options = {}) {
|
||||
const { memoryScript } = options;
|
||||
if (typeof memoryScript !== 'string' || !path.isAbsolute(memoryScript) || memoryScript.includes('\0')) {
|
||||
throw new Error('memoryScript must be an absolute path');
|
||||
}
|
||||
|
||||
return {
|
||||
mcpServers: {
|
||||
'ecc-memory': {
|
||||
command: 'node',
|
||||
args: [memoryScript],
|
||||
env: {
|
||||
ECC_MEMORY_HARNESS: 'antigravity',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function planAntigravityMemoryRuntime(moduleId, repoRoot, targetRoot) {
|
||||
const sourcePaths = [
|
||||
'package.json',
|
||||
'scripts/memory-mcp.mjs',
|
||||
'scripts/lib/missing-dependency.js',
|
||||
'scripts/lib/memory-vault.js',
|
||||
'scripts/lib/memory-vault-format.js',
|
||||
'scripts/lib/path-safety.js',
|
||||
];
|
||||
const operations = sourcePaths.map(sourcePath => createManagedScaffoldOperation(
|
||||
moduleId, sourcePath, path.join(targetRoot, sourcePath), 'preserve-relative-path'
|
||||
));
|
||||
function addDependency(name, fromRoot, destinationRoot, ancestors = [], packageChain = []) {
|
||||
let manifestPath;
|
||||
try {
|
||||
manifestPath = require.resolve(`${name}/package.json`, { paths: [fromRoot] });
|
||||
} catch (error) {
|
||||
throw new Error(`Cannot install Antigravity memory dependency ${name}. Run npm install in ${repoRoot}: ${error.message}`);
|
||||
}
|
||||
if (ancestors.includes(manifestPath)) return;
|
||||
const packageRoot = path.dirname(manifestPath);
|
||||
const destinationPath = path.join(destinationRoot, 'node_modules', name);
|
||||
const sourceChain = [...packageChain, name];
|
||||
operations.push(createManagedScaffoldOperation(
|
||||
moduleId, formatPackageSourcePath(sourceChain), destinationPath, 'preserve-relative-path'
|
||||
));
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
||||
for (const dependency of Object.keys(manifest.dependencies || {})) {
|
||||
addDependency(dependency, packageRoot, destinationPath, [...ancestors, manifestPath], sourceChain);
|
||||
}
|
||||
}
|
||||
addDependency('ajv', repoRoot, targetRoot);
|
||||
return operations;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildAntigravityMcpConfig,
|
||||
planAntigravityMemoryRuntime,
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Antigravity Plugin Manifest Generator
|
||||
*
|
||||
* Generates valid Antigravity plugin.json declaring the ECC plugin.
|
||||
*/
|
||||
|
||||
function buildAntigravityPluginManifest(options = {}) {
|
||||
const version = options.version || require('../../package.json').version;
|
||||
return {
|
||||
name: 'ecc',
|
||||
description: 'ECC - The Agent Harness Operating System for Antigravity',
|
||||
version,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildAntigravityPluginManifest,
|
||||
};
|
||||
@@ -103,16 +103,23 @@ const HARNESS_CAPABILITIES = deepFreeze([
|
||||
},
|
||||
{
|
||||
id: 'antigravity',
|
||||
label: 'Antigravity',
|
||||
targetIds: ['antigravity'],
|
||||
channel: 'managed-project',
|
||||
installMode: 'managed-project',
|
||||
label: 'Google Antigravity',
|
||||
targetIds: ['antigravity-home', 'antigravity'],
|
||||
channel: 'native-plugin',
|
||||
installMode: 'native-plugin',
|
||||
guidedReady: false,
|
||||
availability: 'advanced',
|
||||
destination: './.agents',
|
||||
scopes: [scope('project', 'antigravity', './.agents')],
|
||||
hooks: hooks('not-configured', false, 'ECC hooks are not configured by this adapter.'),
|
||||
aliases: ['google-antigravity'],
|
||||
destination: 'Selected Antigravity scope: ~/.gemini/config/plugins/ecc or ./.agents',
|
||||
scopes: [
|
||||
scope('user', 'antigravity-home', '~/.gemini/config/plugins/ecc'),
|
||||
scope('project', 'antigravity', './.agents'),
|
||||
],
|
||||
hooks: hooks(
|
||||
'profile-selection',
|
||||
true,
|
||||
'ECC hooks are configured through Antigravity PreToolUse and Stop lifecycle hooks.'
|
||||
),
|
||||
aliases: ['google-antigravity', 'gemini-antigravity', 'agy'],
|
||||
},
|
||||
{
|
||||
id: 'copilot',
|
||||
|
||||
@@ -7,7 +7,8 @@ const { isDeepStrictEqual } = require('util');
|
||||
|
||||
const { loadInstallManifests } = require('./install-manifests');
|
||||
const { readInstallState, validateInstallState } = require('./install-state');
|
||||
const { assertWithinTrustedRoot } = require('./path-safety');
|
||||
const { assertWithinTrustedRoot, isWithinRoot } = require('./path-safety');
|
||||
const { isPackageSourcePath, resolvePackageSourcePath } = require('./install/package-source');
|
||||
const { createInstallPlanFromRequest } = require('./install/runtime');
|
||||
const { assertNoNewUserOwnedFile, prepareUserOwnedFileGuard } = require('./install/ownership-guard');
|
||||
const { withOpenCodeInstallLocks } = require('./install/opencode-install-lock');
|
||||
@@ -198,6 +199,17 @@ function resolveOperationSourcePath(repoRoot, operation) {
|
||||
throw createUnsafeRepairSourceError();
|
||||
}
|
||||
|
||||
if (isPackageSourcePath(sourceRelativePath)) {
|
||||
let packageSourcePath;
|
||||
try {
|
||||
packageSourcePath = resolvePackageSourcePath(repoRoot, sourceRelativePath);
|
||||
} catch {
|
||||
throw createUnsafeRepairSourceError();
|
||||
}
|
||||
// An unresolvable package reports as a missing source, not an unsafe one.
|
||||
return packageSourcePath || path.resolve(repoRoot, sourceRelativePath);
|
||||
}
|
||||
|
||||
return assertSafeRepairSourcePath(
|
||||
path.resolve(repoRoot, sourceRelativePath),
|
||||
repoRoot
|
||||
@@ -788,13 +800,18 @@ function inspectManagedOperation(repoRoot, trustedRoot, operation, linkIndex = n
|
||||
}
|
||||
}
|
||||
|
||||
function summarizeManagedOperationHealth(repoRoot, trustedRoot, operations, target = null) {
|
||||
function trustedRootForDestination(destinationPath, targetRoot, trustedRoots = [targetRoot]) {
|
||||
const parent = typeof destinationPath === 'string' ? path.dirname(destinationPath) : destinationPath;
|
||||
return trustedRoots.find(root => isWithinRoot(parent, root)) || targetRoot;
|
||||
}
|
||||
|
||||
function summarizeManagedOperationHealth(repoRoot, trustedRoot, operations, target = null, trustedRoots = [trustedRoot]) {
|
||||
const linkIndex = buildLinkIndexForOperations(operations, trustedRoot);
|
||||
return operations.reduce(
|
||||
(summary, operation) => {
|
||||
const inspection = inspectManagedOperation(
|
||||
repoRoot,
|
||||
trustedRoot,
|
||||
trustedRootForDestination(operation.destinationPath, trustedRoot, trustedRoots),
|
||||
operation,
|
||||
linkIndex,
|
||||
target
|
||||
@@ -1110,11 +1127,21 @@ function collectTargetPathIssues(record, state, issues) {
|
||||
}
|
||||
|
||||
function collectOperationHealthIssues(record, context, state, issues) {
|
||||
let trustedRoots;
|
||||
try {
|
||||
trustedRoots = getInstallTargetAdapter(record.adapter.id || record.adapter.target)
|
||||
.resolveTrustedRoots(context);
|
||||
} catch (error) {
|
||||
// Report an unsafe root for this target without aborting the other targets.
|
||||
issues.push(buildIssue('error', 'unsafe-trusted-root', error.message));
|
||||
return;
|
||||
}
|
||||
const operationHealth = summarizeManagedOperationHealth(
|
||||
context.repoRoot,
|
||||
record.targetRoot,
|
||||
getManagedOperations(state),
|
||||
record.adapter.target
|
||||
record.adapter.target,
|
||||
trustedRoots
|
||||
);
|
||||
const destinationPaths = entries => entries.map(entry => entry.destinationPath);
|
||||
|
||||
@@ -1594,7 +1621,8 @@ function planOpencodeBuildRepair(repair, build) {
|
||||
desiredPlan.sourceRoot || context.repoRoot,
|
||||
record.targetRoot,
|
||||
desiredPlan.operations,
|
||||
record.adapter.target
|
||||
record.adapter.target,
|
||||
repair.trustedRoots
|
||||
);
|
||||
const unsafeOperationResult = getUnsafeOperationResult(record, operationHealth);
|
||||
if (unsafeOperationResult) return unsafeOperationResult;
|
||||
@@ -1657,12 +1685,12 @@ function executeGuardedRepairOperation(repair, plan, operation, repairedPaths) {
|
||||
const repairedPath = executeRepairOperation(
|
||||
desiredPlan.sourceRoot || context.repoRoot,
|
||||
operation,
|
||||
record.targetRoot,
|
||||
trustedRootForDestination(operation.destinationPath, record.targetRoot, repair.trustedRoots),
|
||||
{
|
||||
linkIndex: repairLinkIndex,
|
||||
target: record.adapter.target,
|
||||
settingsLockHeld,
|
||||
writeOptions: apply.getOpenCodeActivationWriteOptions(operation, activationSnapshot),
|
||||
linkIndex: repairLinkIndex,
|
||||
target: record.adapter.target,
|
||||
settingsLockHeld,
|
||||
writeOptions: apply.getOpenCodeActivationWriteOptions(operation, activationSnapshot),
|
||||
}
|
||||
);
|
||||
if (repairedPath) {
|
||||
@@ -1749,7 +1777,8 @@ function repairManagedRecord(repair, build) {
|
||||
repairSourceRoot,
|
||||
record.targetRoot,
|
||||
desiredPlan.operations,
|
||||
record.adapter.target
|
||||
record.adapter.target,
|
||||
repair.trustedRoots
|
||||
);
|
||||
|
||||
const unsafeOperationResult = getUnsafeOperationResult(record, operationHealth);
|
||||
@@ -1802,7 +1831,8 @@ function repairManagedRecord(repair, build) {
|
||||
|
||||
// Repair one discovered record. `repair` carries the record, lifecycle
|
||||
// context, caller options, the OpenCode build runner, an optional OpenCode
|
||||
// lease, and whether the Claude settings lock is already held.
|
||||
// lease, whether the Claude settings lock is already held, and the adapter's
|
||||
// trusted roots for destinations outside the target root.
|
||||
function runRecordRepair(repair) {
|
||||
const { record, context, options } = repair;
|
||||
const needsOpencodeBuild = record.adapter.target === 'opencode'
|
||||
@@ -1852,6 +1882,8 @@ function repairInstalledStates(options = {}) {
|
||||
|
||||
let releaseSettingsLock = null;
|
||||
try {
|
||||
const trustedRoots = getInstallTargetAdapter(record.adapter.id || record.adapter.target)
|
||||
.resolveTrustedRoots(context);
|
||||
preflightOpenCodeHookDeactivation(record, context);
|
||||
releaseSettingsLock = acquireRepairSettingsLock(record, options);
|
||||
return runRecordRepair({
|
||||
@@ -1861,6 +1893,7 @@ function repairInstalledStates(options = {}) {
|
||||
buildOpencodeRunner,
|
||||
opencodeLease,
|
||||
settingsLockHeld: Boolean(releaseSettingsLock),
|
||||
trustedRoots,
|
||||
});
|
||||
} catch (error) {
|
||||
return repairErrorResult(record, error.message);
|
||||
@@ -1922,12 +1955,22 @@ function repairInstalledStates(options = {}) {
|
||||
}
|
||||
|
||||
|
||||
function resolveRecordTrustedRoots(record, context) {
|
||||
const adapter = record.adapter && getInstallTargetAdapter(record.adapter.id || record.adapter.target);
|
||||
return adapter && typeof adapter.resolveTrustedRoots === 'function'
|
||||
? adapter.resolveTrustedRoots(context)
|
||||
: [record.targetRoot];
|
||||
}
|
||||
|
||||
function uninstallInstalledStates(options = {}) {
|
||||
const records = discoverInstalledStates({
|
||||
homeDir: options.homeDir,
|
||||
projectRoot: options.projectRoot,
|
||||
targets: options.targets,
|
||||
const context = {
|
||||
homeDir: options.homeDir || process.env.HOME || os.homedir(),
|
||||
projectRoot: options.projectRoot || process.cwd(),
|
||||
env: resolveInvocationEnvironment(options),
|
||||
};
|
||||
const records = discoverInstalledStates({
|
||||
...context,
|
||||
targets: options.targets,
|
||||
}).filter(record => record.exists);
|
||||
|
||||
const results = records.map(record => {
|
||||
@@ -1984,6 +2027,8 @@ function uninstallInstalledStates(options = {}) {
|
||||
);
|
||||
}
|
||||
|
||||
const trustedRoots = resolveRecordTrustedRoots(record, context);
|
||||
|
||||
const { isScriptBoundary, retainScriptBoundary } = require('./install/opencode-script-boundary');
|
||||
// Remove owned script bodies first. Keep their CommonJS scope while any
|
||||
// retained or user-created JavaScript still relies on that boundary.
|
||||
@@ -1996,7 +2041,7 @@ function uninstallInstalledStates(options = {}) {
|
||||
retainedPaths.push(operation.destinationPath);
|
||||
continue;
|
||||
}
|
||||
const outcome = executeUninstallOperation(operation, record.targetRoot, {
|
||||
const outcome = executeUninstallOperation(operation, trustedRootForDestination(operation.destinationPath, record.targetRoot, trustedRoots), {
|
||||
preserveDriftedCopies: true,
|
||||
target: record.adapter.target,
|
||||
settingsLockHeld: Boolean(releaseSettingsLock),
|
||||
@@ -2020,7 +2065,8 @@ function uninstallInstalledStates(options = {}) {
|
||||
}
|
||||
|
||||
for (const cleanupTarget of cleanupTargets) {
|
||||
cleanupEmptyParentDirs(cleanupTarget, record.targetRoot);
|
||||
const matchingRoot = trustedRootForDestination(cleanupTarget, record.targetRoot, trustedRoots);
|
||||
cleanupEmptyParentDirs(cleanupTarget, matchingRoot);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -5,7 +5,7 @@ const { getInstallTargetAdapter, planInstallTargetScaffold } = require('./instal
|
||||
const { resolveInvocationEnvironment } = require('./invocation-environment');
|
||||
|
||||
const DEFAULT_REPO_ROOT = path.join(__dirname, '../..');
|
||||
const SUPPORTED_INSTALL_TARGETS = ['claude', 'claude-project', 'cursor', 'antigravity', 'codex', 'copilot', 'gemini', 'opencode', 'codebuddy', 'joycode', 'qwen', 'zed', 'hermes', 'openclaw', 'kimi', 'adal', 'grok'];
|
||||
const SUPPORTED_INSTALL_TARGETS = ['claude', 'claude-project', 'cursor', 'antigravity', 'antigravity-home', 'codex', 'copilot', 'gemini', 'opencode', 'codebuddy', 'joycode', 'qwen', 'zed', 'hermes', 'openclaw', 'kimi', 'adal', 'grok'];
|
||||
const COMPONENT_FAMILY_PREFIXES = {
|
||||
baseline: 'baseline:',
|
||||
language: 'lang:',
|
||||
@@ -77,6 +77,14 @@ const LEGACY_COMPAT_BASE_MODULE_IDS_BY_TARGET = Object.freeze({
|
||||
'skill-unified-memory',
|
||||
'workflow-quality',
|
||||
],
|
||||
'antigravity-home': [
|
||||
'rules-core',
|
||||
'agents-core',
|
||||
'commands-core',
|
||||
'hooks-runtime',
|
||||
'platform-configs',
|
||||
'workflow-quality',
|
||||
],
|
||||
zed: [
|
||||
'rules-core',
|
||||
'agents-core',
|
||||
@@ -765,6 +773,7 @@ function resolveInstallPlan(options = {}) {
|
||||
targetAdapterId: scaffoldPlan ? scaffoldPlan.adapter.id : null,
|
||||
homeDir: targetPlanningInput ? targetPlanningInput.homeDir : null,
|
||||
targetRoot: scaffoldPlan ? scaffoldPlan.targetRoot : null,
|
||||
trustedRoots: scaffoldPlan ? scaffoldPlan.trustedRoots : (scaffoldPlan?.targetRoot ? [scaffoldPlan.targetRoot] : []),
|
||||
installStatePath: scaffoldPlan ? scaffoldPlan.installStatePath : null,
|
||||
operations: scaffoldPlan ? scaffoldPlan.operations : [],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const {
|
||||
HOME_INSTALL_EXCLUDED_SOURCE_PATHS,
|
||||
createFlatRuleOperations,
|
||||
createInstallTargetAdapter,
|
||||
createManagedOperation,
|
||||
createManagedScaffoldOperation,
|
||||
isForeignPlatformPath,
|
||||
normalizeRelativePath,
|
||||
} = require('./helpers');
|
||||
const { buildAntigravityHooksConfig } = require('../antigravity-hooks');
|
||||
const { buildAntigravityMcpConfig, planAntigravityMemoryRuntime } = require('../antigravity-mcp');
|
||||
const { buildAntigravityPluginManifest } = require('../antigravity-plugin');
|
||||
const { getHookProfile } = require('../hook-flags');
|
||||
const { isWithinRoot } = require('../path-safety');
|
||||
|
||||
module.exports = createInstallTargetAdapter({
|
||||
id: 'antigravity-home',
|
||||
target: 'antigravity-home',
|
||||
kind: 'home',
|
||||
rootSegments: ['.gemini', 'config', 'plugins', 'ecc'],
|
||||
installStatePathSegments: ['ecc-install-state.json'],
|
||||
nativeRootRelativePath: '.gemini',
|
||||
excludedSourcePaths: HOME_INSTALL_EXCLUDED_SOURCE_PATHS,
|
||||
resolveTrustedRoots(input, targetRoot) {
|
||||
const configRoot = path.dirname(path.dirname(targetRoot));
|
||||
const workflowsRoot = path.join(configRoot, 'workflows');
|
||||
if (!isWithinRoot(workflowsRoot, configRoot)) {
|
||||
throw new Error('Refusing Antigravity workflows outside the trusted config root.');
|
||||
}
|
||||
return [targetRoot, workflowsRoot];
|
||||
},
|
||||
planOperations(input, adapter) {
|
||||
const modules = Array.isArray(input.modules)
|
||||
? input.modules
|
||||
: (input.module ? [input.module] : []);
|
||||
const {
|
||||
repoRoot,
|
||||
projectRoot,
|
||||
homeDir,
|
||||
} = input;
|
||||
const planningInput = {
|
||||
repoRoot,
|
||||
projectRoot,
|
||||
homeDir,
|
||||
};
|
||||
const targetRoot = adapter.resolveRoot(planningInput);
|
||||
|
||||
return modules.flatMap(module => {
|
||||
const paths = Array.isArray(module.paths) ? module.paths : [];
|
||||
return paths
|
||||
.filter(p => !isForeignPlatformPath(p, 'antigravity') && !adapter.excludesSourcePath(p))
|
||||
.flatMap(sourceRelativePath => {
|
||||
const normalizedSourcePath = normalizeRelativePath(sourceRelativePath);
|
||||
|
||||
if (
|
||||
normalizedSourcePath === 'rules'
|
||||
|| normalizedSourcePath.startsWith('rules/')
|
||||
) {
|
||||
return createFlatRuleOperations({
|
||||
moduleId: module.id,
|
||||
repoRoot,
|
||||
sourceRelativePath: normalizedSourcePath,
|
||||
destinationDir: path.join(targetRoot, 'rules'),
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedSourcePath === 'commands'
|
||||
|| normalizedSourcePath.startsWith('commands/')
|
||||
) {
|
||||
const commandRelativePath = normalizedSourcePath === 'commands'
|
||||
? ''
|
||||
: normalizedSourcePath.slice('commands/'.length);
|
||||
const workflowsRoot = path.join(
|
||||
path.dirname(path.dirname(targetRoot)),
|
||||
'workflows'
|
||||
);
|
||||
return [
|
||||
createManagedScaffoldOperation(
|
||||
module.id,
|
||||
normalizedSourcePath,
|
||||
path.join(workflowsRoot, commandRelativePath),
|
||||
'preserve-relative-path'
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedSourcePath === 'agents'
|
||||
|| normalizedSourcePath.startsWith('agents/')
|
||||
) {
|
||||
const agentRelativePath = normalizedSourcePath === 'agents'
|
||||
? ''
|
||||
: normalizedSourcePath.slice('agents/'.length);
|
||||
return [
|
||||
createManagedOperation({
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: normalizedSourcePath,
|
||||
destinationPath: path.join(targetRoot, 'agents', agentRelativePath),
|
||||
strategy: 'preserve-relative-path',
|
||||
contentTransform: 'antigravity-agent-frontmatter',
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedSourcePath === 'skills'
|
||||
|| normalizedSourcePath.startsWith('skills/')
|
||||
) {
|
||||
const skillRelativePath = normalizedSourcePath === 'skills'
|
||||
? ''
|
||||
: normalizedSourcePath.slice('skills/'.length);
|
||||
return [
|
||||
createManagedScaffoldOperation(
|
||||
module.id,
|
||||
normalizedSourcePath,
|
||||
path.join(targetRoot, 'skills', skillRelativePath),
|
||||
'preserve-relative-path'
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
if (
|
||||
module.id === 'hooks-runtime'
|
||||
&& normalizedSourcePath === 'hooks'
|
||||
) {
|
||||
const profile = getHookProfile(input.env);
|
||||
return [
|
||||
createManagedScaffoldOperation(module.id, 'package.json', path.join(targetRoot, 'package.json'), 'preserve-relative-path'),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: 'hooks/hooks.json',
|
||||
destinationPath: path.join(targetRoot, 'hooks.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: buildAntigravityHooksConfig({
|
||||
profile,
|
||||
bridgeScript: path.join(targetRoot, 'scripts', 'hooks', 'antigravity-hook-bridge.js'),
|
||||
}),
|
||||
}),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: 'hooks/hooks.json',
|
||||
destinationPath: path.join(targetRoot, 'ecc', 'setup.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: { hooks: { enabled: true, profile } },
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
if (
|
||||
module.id === 'platform-configs'
|
||||
&& (normalizedSourcePath === 'mcp-configs' || normalizedSourcePath === '.mcp.json')
|
||||
) {
|
||||
const antigravityMcp = buildAntigravityMcpConfig({
|
||||
memoryScript: path.join(targetRoot, 'scripts', 'memory-mcp.mjs'),
|
||||
});
|
||||
|
||||
const operations = [
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: '.mcp.json',
|
||||
destinationPath: path.join(targetRoot, 'mcp_config.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: antigravityMcp,
|
||||
}),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: 'plugin.json',
|
||||
destinationPath: path.join(targetRoot, 'plugin.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: buildAntigravityPluginManifest(),
|
||||
}),
|
||||
];
|
||||
|
||||
if (repoRoot && fs.existsSync(path.join(repoRoot, 'scripts', 'memory-mcp.mjs'))) {
|
||||
operations.push(...planAntigravityMemoryRuntime(module.id, repoRoot, targetRoot));
|
||||
}
|
||||
|
||||
return operations;
|
||||
}
|
||||
|
||||
if (normalizedSourcePath === 'scripts/hooks' || normalizedSourcePath === 'scripts/lib') {
|
||||
return [adapter.createScaffoldOperation(module.id, normalizedSourcePath, planningInput)];
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const {
|
||||
@@ -7,8 +8,22 @@ const {
|
||||
createManagedScaffoldOperation,
|
||||
normalizeRelativePath,
|
||||
} = require('./helpers');
|
||||
const { buildAntigravityHooksConfig } = require('../antigravity-hooks');
|
||||
const { buildAntigravityMcpConfig, planAntigravityMemoryRuntime } = require('../antigravity-mcp');
|
||||
const { buildAntigravityPluginManifest } = require('../antigravity-plugin');
|
||||
const { getHookProfile } = require('../hook-flags');
|
||||
|
||||
const SUPPORTED_SOURCE_PREFIXES = ['rules', 'commands', 'agents', 'skills'];
|
||||
const SUPPORTED_SOURCE_PREFIXES = [
|
||||
'rules',
|
||||
'commands',
|
||||
'agents',
|
||||
'skills',
|
||||
'hooks',
|
||||
'scripts/hooks',
|
||||
'scripts/lib',
|
||||
'mcp-configs',
|
||||
'.mcp.json',
|
||||
];
|
||||
|
||||
function supportsAntigravitySourcePath(sourceRelativePath) {
|
||||
const normalizedPath = normalizeRelativePath(sourceRelativePath);
|
||||
@@ -39,6 +54,7 @@ module.exports = createInstallTargetAdapter({
|
||||
kind: 'project',
|
||||
rootSegments: ['.agents'],
|
||||
installStatePathSegments: ['ecc-install-state.json'],
|
||||
nativeRootRelativePath: '.agents',
|
||||
supportsModule(module) {
|
||||
const paths = Array.isArray(module && module.paths) ? module.paths : [];
|
||||
return paths.length > 0;
|
||||
@@ -130,6 +146,81 @@ module.exports = createInstallTargetAdapter({
|
||||
];
|
||||
}
|
||||
|
||||
if (
|
||||
module.id === 'hooks-runtime'
|
||||
&& normalizedSourcePath === 'hooks'
|
||||
) {
|
||||
const profile = getHookProfile(input.env);
|
||||
return [
|
||||
createManagedScaffoldOperation(module.id, 'package.json', path.join(targetRoot, 'package.json'), 'preserve-relative-path'),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: 'hooks/hooks.json',
|
||||
destinationPath: path.join(targetRoot, 'hooks.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: buildAntigravityHooksConfig({
|
||||
profile,
|
||||
bridgeScript: path.join(targetRoot, 'scripts', 'hooks', 'antigravity-hook-bridge.js'),
|
||||
}),
|
||||
}),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: 'hooks/hooks.json',
|
||||
destinationPath: path.join(targetRoot, 'ecc', 'setup.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: { hooks: { enabled: true, profile } },
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
if (
|
||||
module.id === 'platform-configs'
|
||||
&& (normalizedSourcePath === 'mcp-configs' || normalizedSourcePath === '.mcp.json')
|
||||
) {
|
||||
const antigravityMcp = buildAntigravityMcpConfig({
|
||||
memoryScript: path.join(targetRoot, 'scripts', 'memory-mcp.mjs'),
|
||||
});
|
||||
|
||||
const operations = [
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: '.mcp.json',
|
||||
destinationPath: path.join(targetRoot, 'mcp_config.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: antigravityMcp,
|
||||
}),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
sourceRelativePath: 'plugin.json',
|
||||
destinationPath: path.join(targetRoot, 'plugins', 'ecc', 'plugin.json'),
|
||||
strategy: 'merge-json',
|
||||
ownership: 'managed',
|
||||
scaffoldOnly: false,
|
||||
mergePayload: buildAntigravityPluginManifest(),
|
||||
}),
|
||||
];
|
||||
|
||||
if (repoRoot && fs.existsSync(path.join(repoRoot, 'scripts', 'memory-mcp.mjs'))) {
|
||||
operations.push(...planAntigravityMemoryRuntime(module.id, repoRoot, targetRoot));
|
||||
}
|
||||
|
||||
return operations;
|
||||
}
|
||||
|
||||
if (normalizedSourcePath === 'scripts/hooks' || normalizedSourcePath === 'scripts/lib') {
|
||||
return [adapter.createScaffoldOperation(module.id, normalizedSourcePath, planningInput)];
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
});
|
||||
|
||||
@@ -386,6 +386,13 @@ function createInstallTargetAdapter(config) {
|
||||
}
|
||||
return path.join(baseRoot, ...adapter.rootSegments);
|
||||
},
|
||||
resolveTrustedRoots(input = {}) {
|
||||
const root = adapter.resolveRoot(input);
|
||||
if (typeof config.resolveTrustedRoots === 'function') {
|
||||
return config.resolveTrustedRoots(input, root);
|
||||
}
|
||||
return [root];
|
||||
},
|
||||
getInstallStatePath(input = {}) {
|
||||
const root = adapter.resolveRoot(input);
|
||||
return path.join(root, ...adapter.installStatePathSegments);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const adalProject = require('./adal-project');
|
||||
const antigravityHome = require('./antigravity-home');
|
||||
const antigravityProject = require('./antigravity-project');
|
||||
const claudeHome = require('./claude-home');
|
||||
const claudeProject = require('./claude-project');
|
||||
@@ -21,6 +22,7 @@ const ADAPTERS = Object.freeze([
|
||||
claudeHome,
|
||||
claudeProject,
|
||||
cursorProject,
|
||||
antigravityHome,
|
||||
antigravityProject,
|
||||
codexHome,
|
||||
copilotProject,
|
||||
@@ -73,6 +75,9 @@ function planInstallTargetScaffold(options = {}) {
|
||||
}
|
||||
const targetRoot = adapter.resolveRoot(planningInput);
|
||||
const installStatePath = adapter.getInstallStatePath(planningInput);
|
||||
const trustedRoots = typeof adapter.resolveTrustedRoots === 'function'
|
||||
? adapter.resolveTrustedRoots(planningInput)
|
||||
: [targetRoot];
|
||||
const operations = adapter.planOperations({
|
||||
...planningInput,
|
||||
modules,
|
||||
@@ -85,6 +90,7 @@ function planInstallTargetScaffold(options = {}) {
|
||||
kind: adapter.kind,
|
||||
},
|
||||
targetRoot,
|
||||
trustedRoots,
|
||||
installStatePath,
|
||||
validationIssues,
|
||||
operations,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { isDeepStrictEqual } = require('util');
|
||||
|
||||
const {
|
||||
hasExplicitCommitAttributionPreference,
|
||||
@@ -21,6 +22,7 @@ const {
|
||||
getOpenCodeSourceActivationKind,
|
||||
planMaterializesHookRuntime,
|
||||
shouldDisableOpenCodeHooks,
|
||||
shouldDisableAntigravityHooks,
|
||||
} = require('./hook-consent');
|
||||
const {
|
||||
getClaudeSettingsPath,
|
||||
@@ -33,7 +35,7 @@ const {
|
||||
validateRecordedManagedHooks,
|
||||
} = require('./claude-settings');
|
||||
const { filterMcpConfig, parseDisabledMcpServers } = require('../mcp-config');
|
||||
const { assertWithinTrustedRoot } = require('../path-safety');
|
||||
const { assertWithinTrustedRoot, isWithinRoot } = require('../path-safety');
|
||||
const {
|
||||
assertSafeClaudeSkillOperation,
|
||||
prepareClaudeSkillMigration,
|
||||
@@ -86,10 +88,10 @@ function buildLinkIndexForPlan(plan) {
|
||||
return buildInstallIndex(mappings);
|
||||
}
|
||||
|
||||
function readJsonObject(filePath, label) {
|
||||
function readJsonObject(filePath, label, readContent = () => fs.readFileSync(filePath, 'utf8')) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
||||
parsed = JSON.parse(readContent());
|
||||
} catch (error) {
|
||||
const wrappedError = new Error(`Failed to parse ${label} at ${filePath}: ${error.message}`);
|
||||
wrappedError.code = error.code;
|
||||
@@ -257,7 +259,15 @@ function writeClaudeCommitAttributionPreference(settingsPath, options = {}) {
|
||||
|
||||
function isMcpConfigPath(filePath) {
|
||||
const basename = path.basename(String(filePath || ''));
|
||||
return basename === '.mcp.json' || basename === 'mcp.json';
|
||||
return basename === '.mcp.json' || basename === 'mcp.json' || basename === 'mcp_config.json';
|
||||
}
|
||||
|
||||
function getTrustedRootsForPlan(plan) {
|
||||
if (!plan) return [];
|
||||
if (Array.isArray(plan.trustedRoots) && plan.trustedRoots.length > 0) {
|
||||
return plan.trustedRoots;
|
||||
}
|
||||
return plan.targetRoot ? [plan.targetRoot] : [];
|
||||
}
|
||||
|
||||
function withMcpMergeExclusions(plan, disabledServers) {
|
||||
@@ -291,7 +301,9 @@ function assertSafeInstallOperation(plan, operation) {
|
||||
throw new Error('Refusing to apply install operation: missing destination path.');
|
||||
}
|
||||
|
||||
const targetRoot = plan && plan.targetRoot;
|
||||
const trustedRoots = getTrustedRootsForPlan(plan);
|
||||
const matchingRoot = trustedRoots.find(root => isWithinRoot(operation.destinationPath, root));
|
||||
const targetRoot = matchingRoot || (plan && plan.targetRoot);
|
||||
assertWithinTrustedRoot(operation.destinationPath, targetRoot, 'install ECC file');
|
||||
|
||||
const resolvedRoot = path.resolve(targetRoot);
|
||||
@@ -703,6 +715,68 @@ function preflightClaudeSettingsOperations(plan) {
|
||||
}));
|
||||
}
|
||||
|
||||
function withoutManagedAntigravityHooks(plan, operation) {
|
||||
const content = readInstalledFileNoFollow(plan, operation);
|
||||
const config = content === null ? {} : JSON.parse(content.toString('utf8'));
|
||||
if (!config || typeof config !== 'object' || Array.isArray(config)) {
|
||||
throw new Error(`Invalid Antigravity hooks config: ${operation.destinationPath}`);
|
||||
}
|
||||
if (Object.hasOwn(config, 'ecc-guard')
|
||||
&& !isDeepStrictEqual(config['ecc-guard'], operation.mergePayload?.['ecc-guard'])) {
|
||||
throw new Error(`Refusing to disable modified Antigravity hooks in ${operation.destinationPath}.`);
|
||||
}
|
||||
const userHooks = Object.fromEntries(Object.entries(config).filter(([name]) => name !== 'ecc-guard'));
|
||||
return {
|
||||
content: formatJson(userHooks),
|
||||
expectedContent: content === null ? { kind: 'absent' } : {
|
||||
kind: 'sha256', digest: crypto.createHash('sha256').update(content).digest('hex'),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function prepareAntigravityHookDeactivation(plan, migration, previousState) {
|
||||
if (!shouldDisableAntigravityHooks(plan)) return migration;
|
||||
const hooksPath = path.join(plan.targetRoot, 'hooks.json');
|
||||
const previousHooks = previousState.operations.find(operation => (
|
||||
operation.ownership === 'managed' && operation.kind === 'merge-json'
|
||||
&& operation.moduleId === 'hooks-runtime'
|
||||
&& comparablePath(operation.destinationPath) === comparablePath(hooksPath)
|
||||
));
|
||||
if (!previousHooks) return migration;
|
||||
const removal = { ...previousHooks, kind: 'remove-antigravity-hooks' };
|
||||
// Check before ordinary writes, then re-read at the guarded write boundary.
|
||||
withoutManagedAntigravityHooks(plan, removal);
|
||||
const disabledSetup = {
|
||||
...previousHooks,
|
||||
kind: 'merge-json',
|
||||
destinationPath: path.join(plan.targetRoot, 'ecc', 'setup.json'),
|
||||
mergePayload: { hooks: { enabled: false } },
|
||||
};
|
||||
assertSafeInstallOperation(plan, disabledSetup);
|
||||
readOptionalJsonObject(disabledSetup.destinationPath, 'managed hook setup');
|
||||
const changed = new Set([hooksPath, disabledSetup.destinationPath].map(comparablePath));
|
||||
return {
|
||||
...migration,
|
||||
appliedOperations: [
|
||||
...migration.appliedOperations, removal,
|
||||
{ ...disabledSetup, kind: 'disable-antigravity-hook-setup' },
|
||||
],
|
||||
warnings: [...migration.warnings, 'Disabling previously installed Antigravity hooks; preserving user hook namespaces.'],
|
||||
finalState: {
|
||||
...migration.finalState,
|
||||
operations: [
|
||||
...migration.finalState.operations.filter(operation => !changed.has(comparablePath(operation.destinationPath))),
|
||||
{ ...previousHooks, mergePayload: {} }, disabledSetup,
|
||||
],
|
||||
},
|
||||
bridgeState: {
|
||||
...migration.bridgeState,
|
||||
request: { ...migration.bridgeState.request, hookConsent: getRecordedHookConsent(previousState) },
|
||||
},
|
||||
requiresBridgeState: true,
|
||||
};
|
||||
}
|
||||
|
||||
function prepareHookConsentMigration(plan, migration) {
|
||||
if (shouldDisableOpenCodeHooks(plan) && migration.requiresBridgeState) {
|
||||
const previousState = readPreviousInstallState(plan);
|
||||
@@ -732,6 +806,9 @@ function prepareHookConsentMigration(plan, migration) {
|
||||
if (!previousState) {
|
||||
return migration;
|
||||
}
|
||||
if (shouldDisableAntigravityHooks(plan)) {
|
||||
return prepareAntigravityHookDeactivation(plan, migration, previousState);
|
||||
}
|
||||
|
||||
const removals = (previousState.operations || [])
|
||||
.filter(operation => operation.kind === 'update-claude-settings')
|
||||
@@ -926,6 +1003,32 @@ function applyInstallPlanLocked(rawPlan, dependencies = {}, settingsLockHeld = f
|
||||
}
|
||||
assertOpenCodeActivationUnchanged(appliedPlan, operation, activationSnapshot);
|
||||
|
||||
if (['remove-antigravity-hooks', 'disable-antigravity-hook-setup'].includes(operation.kind)) {
|
||||
const current = operation.kind === 'disable-antigravity-hook-setup'
|
||||
? readInstalledFileNoFollow(appliedPlan, operation) : null;
|
||||
const disabled = operation.kind === 'remove-antigravity-hooks'
|
||||
? withoutManagedAntigravityHooks(appliedPlan, operation)
|
||||
: {
|
||||
content: formatJson(deepMergeJson(
|
||||
readJsonObject(operation.destinationPath, 'managed hook setup', () => current || '{}'),
|
||||
operation.mergePayload
|
||||
)),
|
||||
expectedContent: current === null ? { kind: 'absent' } : {
|
||||
kind: 'sha256', digest: crypto.createHash('sha256').update(current).digest('hex'),
|
||||
},
|
||||
};
|
||||
writeFileNoFollow(operation.destinationPath, disabled.content, {
|
||||
action: 'disable Antigravity hooks',
|
||||
expectedContent: disabled.expectedContent,
|
||||
validateDestination(destinationPath) {
|
||||
assertSafeInstallOperation(appliedPlan, { destinationPath });
|
||||
return destinationPath;
|
||||
},
|
||||
});
|
||||
writtenDestinations.add(operation.destinationPath);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
operation.kind === 'update-claude-settings'
|
||||
|| operation.kind === 'remove-claude-settings-hooks'
|
||||
|
||||
@@ -7,7 +7,7 @@ const { assertWithinTrustedRoot } = require('../path-safety');
|
||||
const { sameFileIdentity } = require('./claude-settings-lock');
|
||||
|
||||
function isCodexUserConfig(plan, operation) {
|
||||
if (!plan.adapter || plan.adapter.id !== 'codex-home' || operation.kind !== 'copy-file') {
|
||||
if (plan?.adapter?.id !== 'codex-home' || operation?.kind !== 'copy-file') {
|
||||
return false;
|
||||
}
|
||||
const relativePath = path.relative(plan.targetRoot, operation.destinationPath);
|
||||
|
||||
@@ -274,6 +274,7 @@ function isHookRuntimeOperation(operation = {}) {
|
||||
|| source.startsWith('.cursor/hooks/')
|
||||
|| source === '.cursor/hooks.json'
|
||||
|| destination.endsWith('/hooks/hooks.json')
|
||||
|| destination.endsWith('/hooks.json')
|
||||
|| destination.endsWith('/.cursor/hooks.json')
|
||||
|| destination.includes('/.cursor/hooks/')
|
||||
);
|
||||
@@ -366,6 +367,11 @@ function shouldDisableOpenCodeHooks(plan = {}) {
|
||||
&& (plan.hookConsent === 'declined' || !planSelectsHookRuntime(plan));
|
||||
}
|
||||
|
||||
function shouldDisableAntigravityHooks(plan = {}) {
|
||||
return ['antigravity', 'antigravity-home'].includes(plan.target)
|
||||
&& plan.hookConsent === 'declined';
|
||||
}
|
||||
|
||||
function setStatePreviewHookConsent(statePreview, hookConsent) {
|
||||
if (!statePreview || !statePreview.request) {
|
||||
return statePreview;
|
||||
@@ -500,5 +506,6 @@ module.exports = {
|
||||
planMaterializesHookRuntime,
|
||||
resolveHookConsentFlags,
|
||||
shouldDisableOpenCodeHooks,
|
||||
shouldDisableAntigravityHooks,
|
||||
withHookConsent,
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const { assertWithinTrustedRoot } = require('../path-safety');
|
||||
|
||||
// npm may hoist a dependency beside the ECC package instead of nesting it, so
|
||||
// a path relative to the repository would need `..`. Dependency sources are
|
||||
// recorded as `node_modules/<name>[/node_modules/<name>...]/<file>` instead,
|
||||
// mirroring the installed layout, and Node resolves each package from the
|
||||
// repository when the source is read.
|
||||
const PACKAGE_DIR = 'node_modules';
|
||||
const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
|
||||
|
||||
function isPackageSourcePath(sourceRelativePath) {
|
||||
return typeof sourceRelativePath === 'string'
|
||||
&& sourceRelativePath.split(/[/\\]+/)[0] === PACKAGE_DIR;
|
||||
}
|
||||
|
||||
function formatPackageSourcePath(packageChain, relativeFile = '') {
|
||||
const segments = packageChain.flatMap(name => [PACKAGE_DIR, ...name.split('/')]);
|
||||
return path.posix.join(...segments, ...relativeFile.split(/[/\\]+/).filter(Boolean));
|
||||
}
|
||||
|
||||
function parsePackageSourcePath(sourceRelativePath) {
|
||||
const parts = String(sourceRelativePath).split(/[/\\]+/);
|
||||
const packageChain = [];
|
||||
let index = 0;
|
||||
while (parts[index] === PACKAGE_DIR) {
|
||||
const scoped = String(parts[index + 1] || '').startsWith('@');
|
||||
const name = scoped ? `${parts[index + 1]}/${parts[index + 2] || ''}` : parts[index + 1];
|
||||
if (!PACKAGE_NAME.test(String(name || ''))) {
|
||||
throw new Error(`Invalid package source path: ${sourceRelativePath}`);
|
||||
}
|
||||
packageChain.push(name);
|
||||
index += scoped ? 3 : 2;
|
||||
}
|
||||
const relativeFile = parts.slice(index);
|
||||
if (packageChain.length === 0 || relativeFile.some(part => part === '' || part === '.' || part === '..')) {
|
||||
throw new Error(`Invalid package source path: ${sourceRelativePath}`);
|
||||
}
|
||||
return { packageChain, relativeFile };
|
||||
}
|
||||
|
||||
// Returns null when a package in the chain cannot be resolved. Throws when the
|
||||
// path itself is malformed.
|
||||
function resolvePackageSourcePath(repoRoot, sourceRelativePath) {
|
||||
const { packageChain, relativeFile } = parsePackageSourcePath(sourceRelativePath);
|
||||
let packageRoot = repoRoot;
|
||||
for (const name of packageChain) {
|
||||
try {
|
||||
packageRoot = path.dirname(require.resolve(`${name}/package.json`, { paths: [packageRoot] }));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return assertWithinTrustedRoot(path.join(packageRoot, ...relativeFile), packageRoot, 'read package source');
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
formatPackageSourcePath,
|
||||
isPackageSourcePath,
|
||||
parsePackageSourcePath,
|
||||
resolvePackageSourcePath,
|
||||
};
|
||||
@@ -9,6 +9,7 @@ const { getInstallTargetAdapter } = require('../install-targets/registry');
|
||||
const { resolveInvocationEnvironment } = require('../invocation-environment');
|
||||
const { disableUnselectedOpenCodeHooks } = require('./hook-consent');
|
||||
const { readHooksConfig } = require('../hooks-config');
|
||||
const { isPackageSourcePath, resolvePackageSourcePath } = require('./package-source');
|
||||
const {
|
||||
materializeManagedHooks,
|
||||
} = require('./claude-settings');
|
||||
@@ -176,14 +177,18 @@ function materializeScaffoldOperation(sourceRoot, operation) {
|
||||
destinationPath: operation.destinationPath,
|
||||
strategy: operation.strategy || 'merge-json',
|
||||
ownership: operation.ownership || 'managed',
|
||||
scaffoldOnly: Object.hasOwn(operation, 'scaffoldOnly') ? operation.scaffoldOnly : false,
|
||||
mergePayload: readJsonObject(path.join(sourceRoot, operation.sourceRelativePath), operation.sourceRelativePath)
|
||||
scaffoldOnly: typeof operation.scaffoldOnly === 'boolean' ? operation.scaffoldOnly : false,
|
||||
mergePayload: operation.mergePayload !== undefined
|
||||
? JSON.parse(JSON.stringify(operation.mergePayload))
|
||||
: readJsonObject(path.join(sourceRoot, operation.sourceRelativePath), operation.sourceRelativePath)
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
const sourcePath = path.join(sourceRoot, operation.sourceRelativePath);
|
||||
if (!fs.existsSync(sourcePath)) {
|
||||
const sourcePath = isPackageSourcePath(operation.sourceRelativePath)
|
||||
? resolvePackageSourcePath(sourceRoot, operation.sourceRelativePath)
|
||||
: path.join(sourceRoot, operation.sourceRelativePath);
|
||||
if (!sourcePath || !fs.existsSync(sourcePath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -363,6 +368,7 @@ function createManifestInstallPlan(options = {}) {
|
||||
},
|
||||
homeDir: plan.homeDir,
|
||||
targetRoot: plan.targetRoot,
|
||||
trustedRoots: plan.trustedRoots || (plan.targetRoot ? [plan.targetRoot] : []),
|
||||
installRoot: plan.targetRoot,
|
||||
installStatePath: plan.installStatePath,
|
||||
warnings: Array.isArray(options.warnings) ? [...options.warnings] : [],
|
||||
|
||||
@@ -6,7 +6,7 @@ const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const { assertSafeInstallOperation } = require('./install/apply');
|
||||
const { assertWithinTrustedRoot, realpathNearestExisting } = require('./path-safety');
|
||||
const { assertWithinTrustedRoot, isWithinRoot, realpathNearestExisting } = require('./path-safety');
|
||||
|
||||
const VALID_CLAUDE_SCOPES = new Set(['user', 'project', 'local']);
|
||||
const VALID_CLAUDE_HOOKS = new Set(['off', 'minimal', 'standard', 'strict']);
|
||||
@@ -208,7 +208,11 @@ function readOwnedDestinations(plan, dependencies) {
|
||||
);
|
||||
}
|
||||
const destinationPath = operation.destinationPath;
|
||||
assertWithinTrustedRoot(destinationPath, plan.targetRoot, 'trust install-state ownership');
|
||||
const trustedRoots = Array.isArray(plan.trustedRoots) && plan.trustedRoots.length > 0
|
||||
? plan.trustedRoots
|
||||
: [plan.targetRoot];
|
||||
const matchingRoot = trustedRoots.find(root => isWithinRoot(destinationPath, root)) || plan.targetRoot;
|
||||
assertWithinTrustedRoot(destinationPath, matchingRoot, 'trust install-state ownership');
|
||||
const canonicalDestination = canonicalPath(destinationPath);
|
||||
const plannedOperation = plannedByDestination.get(canonicalDestination);
|
||||
if (!plannedOperation) continue;
|
||||
|
||||
@@ -73,7 +73,7 @@ const DEFAULT_SKILL_PROBE = path.join('skills', 'continuous-learning-v2');
|
||||
function resolveEccRoot(options = {}) {
|
||||
const envRoot = options.envRoot !== undefined
|
||||
? options.envRoot
|
||||
: (process.env.CLAUDE_PLUGIN_ROOT || '');
|
||||
: (process.env.CLAUDE_PLUGIN_ROOT || process.env.ANTIGRAVITY_PLUGIN_ROOT || process.env.GEMINI_PLUGIN_ROOT || '');
|
||||
|
||||
if (envRoot && envRoot.trim()) {
|
||||
return envRoot.trim();
|
||||
@@ -110,6 +110,12 @@ function resolveEccRoot(options = {}) {
|
||||
return claudeDir;
|
||||
}
|
||||
|
||||
// Antigravity global plugin install — ~/.gemini/config/plugins/ecc
|
||||
const antigravityPluginDir = path.join(homeDir, '.gemini', 'config', 'plugins', 'ecc');
|
||||
if (isRoot(antigravityPluginDir)) {
|
||||
return antigravityPluginDir;
|
||||
}
|
||||
|
||||
// Exact legacy plugin install locations. These preserve backwards
|
||||
// compatibility without scanning arbitrary plugin trees.
|
||||
const legacyPluginRoots = PLUGIN_ROOT_SEGMENTS.map((segments) =>
|
||||
|
||||
Reference in new issue
Block a user