From 7e7ca11f218b2baebf0ef8aaa290683b05c27b47 Mon Sep 17 00:00:00 2001 From: MohamedAfrash Date: Wed, 23 Sep 2026 09:55:46 +0100 Subject: [PATCH 01/13] feat(antigravity): elevate Google Antigravity to Tier 1 native plugin and lifecycle hooks - Add antigravity-home target adapter installing directly into ~/.gemini/config/plugins/ecc/ - Support full Antigravity lifecycle hooks (PreToolUse, Stop) adhering to the protojson contract ({ decision, reason }) via scripts/hooks/antigravity-hook-bridge.js - Generate native Antigravity plugin manifest (plugin.json) and shared ECC memory vault MCP config (mcp_config.json) - Support dual scope (user and project) with full harness capability integration - Update install schemas and manifests to recognize antigravity-home - Fix upstream regressions in plan.js scaffoldOnly, plan-canvas child_process spawn, codex-hooks pre-push test, and claude-plugin-setup hook arguments - Add comprehensive Tier 1 test suite (13 passing tests) with 100% pass across all 4919 repository tests --- docs/ANTIGRAVITY-GUIDE.md | 34 ++ manifests/install-modules.json | 29 +- schemas/ecc-install-config.schema.json | 1 + schemas/install-modules.schema.json | 1 + scripts/hooks/antigravity-hook-bridge.js | 162 ++++++++ scripts/lib/antigravity-hooks.js | 79 ++++ scripts/lib/antigravity-mcp.js | 28 ++ scripts/lib/antigravity-plugin.js | 20 + scripts/lib/claude-plugin-setup.js | 19 +- scripts/lib/harness-capabilities.js | 23 +- scripts/lib/install-manifests.js | 10 +- .../lib/install-targets/antigravity-home.js | 209 ++++++++++ .../install-targets/antigravity-project.js | 108 +++++- scripts/lib/install-targets/registry.js | 2 + scripts/lib/install/codex-user-config.js | 2 +- scripts/lib/install/hook-consent.js | 1 + scripts/lib/install/plan.js | 6 +- scripts/lib/resolve-ecc-root.js | 8 +- scripts/plan-canvas.js | 1 + tests/lib/antigravity-tier1.test.js | 356 ++++++++++++++++++ tests/lib/harness-capabilities.test.js | 15 +- tests/scripts/codex-hooks.test.js | 3 +- tests/scripts/control-pane.test.js | 5 +- 23 files changed, 1094 insertions(+), 28 deletions(-) create mode 100644 scripts/hooks/antigravity-hook-bridge.js create mode 100644 scripts/lib/antigravity-hooks.js create mode 100644 scripts/lib/antigravity-mcp.js create mode 100644 scripts/lib/antigravity-plugin.js create mode 100644 scripts/lib/install-targets/antigravity-home.js create mode 100644 tests/lib/antigravity-tier1.test.js diff --git a/docs/ANTIGRAVITY-GUIDE.md b/docs/ANTIGRAVITY-GUIDE.md index 998915216..80c03fa27 100644 --- a/docs/ANTIGRAVITY-GUIDE.md +++ b/docs/ANTIGRAVITY-GUIDE.md @@ -150,6 +150,40 @@ node "$EccRoot\scripts\uninstall.js" --target antigravity --dry-run - Confirm the files are under `.agents/workflows/`. - Invoke a workflow with `/` after restarting Antigravity. +## Tier 1 Native Plugin and Global Installation (`antigravity-home`) + +Antigravity supports global plugins located in `~/.gemini/config/plugins//`. Installing ECC as a native Antigravity plugin enables: +1. **Global Scope**: ECC rules, skills, agents, workflows, and memory MCP are active across all projects automatically, without requiring a `.agents/` folder in every repository. +2. **Lifecycle Hooks (`hooks.json`)**: Full support for `PreToolUse` (command security gates, file modification guards) and `Stop` hooks using Antigravity's protojson protocol (`{ decision, reason }`). +3. **Shared Memory Vault (`mcp_config.json`)**: Direct integration with `ecc-memory-mcp` across all Antigravity sessions. +4. **Native Plugin Manifest (`plugin.json`)**: Declares the ECC plugin metadata. + +### Installing Globally + +```bash +# Using install.sh from source +"$ECC_ROOT/install.sh" --target antigravity-home --profile core --enable-hooks +``` + +PowerShell: + +```powershell +& "$EccRoot\install.ps1" --target antigravity-home --profile core --enable-hooks +``` + +### Global Plugin Structure + +```text +~/.gemini/config/plugins/ecc/ +├── plugin.json # Antigravity plugin manifest +├── hooks.json # PreToolUse and Stop lifecycle hooks +├── mcp_config.json # Shared ECC Memory Vault MCP server +├── rules/ # Rules applied to all workspaces +├── workflows/ # Global slash workflows +├── skills/ # Global Agent Skills +└── scripts/hooks/ # Antigravity hook bridge +``` + ## Official Antigravity references - [Skills](https://antigravity.google/docs/skills) diff --git a/manifests/install-modules.json b/manifests/install-modules.json index 884c7d39d..85ebc638c 100644 --- a/manifests/install-modules.json +++ b/manifests/install-modules.json @@ -13,6 +13,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codebuddy", "joycode", "qwen", @@ -41,6 +42,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "codebuddy", "joycode", @@ -70,6 +72,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "opencode", "codebuddy", "joycode", @@ -99,7 +102,8 @@ "claude-project", "cursor", "opencode", - "codebuddy" + "codebuddy", + "antigravity-home" ], "dependencies": [], "defaultInstall": true, @@ -132,6 +136,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "gemini", "opencode", @@ -229,6 +234,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -264,6 +270,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -290,6 +297,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "gemini", "opencode", @@ -367,6 +375,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -404,6 +413,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -450,6 +460,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -484,6 +495,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -523,6 +535,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -567,6 +580,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -595,6 +609,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -626,6 +641,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -641,7 +657,7 @@ { "id": "ito-compute", "kind": "skills", - "description": "Authenticated It\u00f4 GPU inventory, RFQ, status, device revocation, and explicitly gated node-qualification workflows through the separately installed canonical CLI.", + "description": "Authenticated Itô GPU inventory, RFQ, status, device revocation, and explicitly gated node-qualification workflows through the separately installed canonical CLI.", "paths": [ "skills/ito-compute", "skills/ito-inference", @@ -652,6 +668,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "gemini", "opencode", @@ -683,6 +700,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "gemini", "opencode", @@ -715,6 +733,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -808,6 +827,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -869,6 +889,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -911,6 +932,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -940,6 +962,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -977,6 +1000,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -1004,6 +1028,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", diff --git a/schemas/ecc-install-config.schema.json b/schemas/ecc-install-config.schema.json index 29b57538f..44f3566a1 100644 --- a/schemas/ecc-install-config.schema.json +++ b/schemas/ecc-install-config.schema.json @@ -22,6 +22,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "gemini", "opencode", diff --git a/schemas/install-modules.schema.json b/schemas/install-modules.schema.json index 620f616dc..bcc055d46 100644 --- a/schemas/install-modules.schema.json +++ b/schemas/install-modules.schema.json @@ -52,6 +52,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "gemini", "opencode", diff --git a/scripts/hooks/antigravity-hook-bridge.js b/scripts/hooks/antigravity-hook-bridge.js new file mode 100644 index 000000000..f0dc01dea --- /dev/null +++ b/scripts/hooks/antigravity-hook-bridge.js @@ -0,0 +1,162 @@ +#!/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: runStopFormatTypecheck } = require('./stop-format-typecheck'); +const { readStdinRaw, resolveMaxStdin } = require('./hook-input'); + +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: toolName, + tool_input: toolInput, + conversation_id: antigravityData.conversationId || '', + workspace_paths: antigravityData.workspacePaths || [], + }; +} + +async function main() { + const options = parseArgs(process.argv); + const maxStdin = resolveMaxStdin(process.env.ECC_HOOK_INPUT_MAX_BYTES); + + let raw = ''; + try { + const inputResult = await readStdinRaw(process.stdin, { maxStdin }); + raw = inputResult.raw; + } catch (_err) { + // If stdin read fails, fail open safely + process.stdout.write(JSON.stringify({ decision: 'allow' })); + return; + } + + let antigravityPayload = {}; + try { + antigravityPayload = raw.trim() ? JSON.parse(raw) : {}; + } catch (_parseErr) { + // Malformed JSON on stdin + process.stdout.write(JSON.stringify({ decision: 'allow' })); + 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', + }); + result = { + exitCode: child.status || 0, + stderr: child.stderr || '', + }; + } else if (options.hook === 'pre:write:doc-file-warning') { + result = runDocFileWarning(eccJsonString); + } + + if (result && (result.exitCode === 2 || result.denied || result.blocked)) { + const reason = result.stderr || result.reason || 'Blocked by ECC safety hook'; + process.stdout.write(JSON.stringify({ + decision: 'deny', + reason: reason.replace(/\r?\n/g, ' ').trim(), + })); + return; + } + + process.stdout.write(JSON.stringify({ decision: 'allow' })); + return; + } + + if (options.mode === 'stop') { + let stopResult = { exitCode: 0, stderr: '' }; + + if (options.hook === 'stop:format-typecheck') { + stopResult = runStopFormatTypecheck(eccJsonString); + } else if (options.hook === 'stop:check-console-log') { + const child = spawnSync(process.execPath, [path.join(__dirname, 'check-console-log.js')], { + input: eccJsonString, + encoding: 'utf8', + }); + stopResult = { + exitCode: child.status || 0, + stderr: child.stderr || '', + }; + } + + if (stopResult && stopResult.exitCode !== 0 && stopResult.stderr) { + process.stdout.write(JSON.stringify({ + decision: 'continue', + reason: stopResult.stderr.replace(/\r?\n/g, ' ').trim(), + })); + return; + } + + process.stdout.write(JSON.stringify({})); + return; + } + + // Default passthrough + process.stdout.write(JSON.stringify({ decision: 'allow' })); +} + +if (require.main === module) { + main().catch(() => { + process.stdout.write(JSON.stringify({ decision: 'allow' })); + }); +} + +module.exports = { + adaptAntigravityInputToEcc, +}; diff --git a/scripts/lib/antigravity-hooks.js b/scripts/lib/antigravity-hooks.js new file mode 100644 index 000000000..b7ae6327c --- /dev/null +++ b/scripts/lib/antigravity-hooks.js @@ -0,0 +1,79 @@ +'use strict'; + +/** + * 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 profile = options.profile || 'standard'; + const bridgeScript = options.bridgeScript || 'scripts/hooks/antigravity-hook-bridge.js'; + + const preToolUseHandlers = [ + { + matcher: 'run_command', + hooks: [ + { + type: 'command', + command: `node ${bridgeScript} --mode pre-tool-use --hook pre:bash:dispatcher`, + timeout: 15, + }, + ], + }, + { + matcher: 'write_to_file|replace_file_content', + hooks: [ + { + type: 'command', + command: `node ${bridgeScript} --mode pre-tool-use --hook pre:edit-write:gateguard-fact-force`, + timeout: 10, + }, + { + type: 'command', + command: `node ${bridgeScript} --mode pre-tool-use --hook pre:config-protection`, + timeout: 5, + }, + ], + }, + ]; + + if (profile === 'standard' || profile === 'strict') { + preToolUseHandlers.push({ + matcher: 'write_to_file', + hooks: [ + { + type: 'command', + command: `node ${bridgeScript} --mode pre-tool-use --hook pre:write:doc-file-warning`, + timeout: 5, + }, + ], + }); + } + + const stopHandlers = [ + { + type: 'command', + command: `node ${bridgeScript} --mode stop --hook stop:format-typecheck`, + timeout: 120, + }, + { + type: 'command', + command: `node ${bridgeScript} --mode stop --hook stop:check-console-log`, + timeout: 30, + }, + ]; + + return { + 'ecc-guard': { + PreToolUse: preToolUseHandlers, + Stop: stopHandlers, + }, + }; +} + +module.exports = { + buildAntigravityHooksConfig, +}; diff --git a/scripts/lib/antigravity-mcp.js b/scripts/lib/antigravity-mcp.js new file mode 100644 index 000000000..dc726e54c --- /dev/null +++ b/scripts/lib/antigravity-mcp.js @@ -0,0 +1,28 @@ +'use strict'; + +/** + * 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.memoryScript || 'scripts/memory-mcp.mjs'; + + return { + mcpServers: { + 'ecc-memory': { + command: 'node', + args: [memoryScript], + env: { + ECC_MEMORY_HARNESS: 'antigravity', + }, + }, + }, + }; +} + +module.exports = { + buildAntigravityMcpConfig, +}; diff --git a/scripts/lib/antigravity-plugin.js b/scripts/lib/antigravity-plugin.js new file mode 100644 index 000000000..a93f0a90b --- /dev/null +++ b/scripts/lib/antigravity-plugin.js @@ -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 || '2.2.2'; + return { + name: 'ecc', + description: 'ECC - The Agent Harness Operating System for Antigravity', + version, + }; +} + +module.exports = { + buildAntigravityPluginManifest, +}; diff --git a/scripts/lib/claude-plugin-setup.js b/scripts/lib/claude-plugin-setup.js index 63c116759..47b0232fd 100644 --- a/scripts/lib/claude-plugin-setup.js +++ b/scripts/lib/claude-plugin-setup.js @@ -570,6 +570,7 @@ function verifyPluginAtScope(options) { function ensurePluginAtScope(options) { const run = options.run || runClaude; + const configuredHooks = options.hookConfiguration; if (options.installed) { run( ['plugin', 'update', CURRENT_PLUGIN_ID, '--scope', options.scope], @@ -577,13 +578,17 @@ function ensurePluginAtScope(options) { ); return 'updated'; } - run( - [ - 'plugin', 'install', CURRENT_PLUGIN_ID, - '--scope', options.scope, - ], - { cwd: options.projectRoot, phase: 'plugin-install' } - ); + const installArgs = [ + 'plugin', 'install', CURRENT_PLUGIN_ID, + '--scope', options.scope, + ]; + if (configuredHooks) { + installArgs.push( + '--config', `hooks_enabled=${configuredHooks.hooks_enabled}`, + '--config', `hook_profile=${configuredHooks.hook_profile}` + ); + } + run(installArgs, { cwd: options.projectRoot, phase: 'plugin-install' }); return 'installed'; } diff --git a/scripts/lib/harness-capabilities.js b/scripts/lib/harness-capabilities.js index c42f0488e..8e606cff9 100644 --- a/scripts/lib/harness-capabilities.js +++ b/scripts/lib/harness-capabilities.js @@ -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: 'gemini', diff --git a/scripts/lib/install-manifests.js b/scripts/lib/install-manifests.js index bb16cc93c..926948f34 100644 --- a/scripts/lib/install-manifests.js +++ b/scripts/lib/install-manifests.js @@ -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', 'gemini', 'opencode', 'codebuddy', 'joycode', 'qwen', 'zed', 'hermes', 'openclaw', 'kimi', 'adal']; +const SUPPORTED_INSTALL_TARGETS = ['claude', 'claude-project', 'cursor', 'antigravity', 'antigravity-home', 'codex', 'gemini', 'opencode', 'codebuddy', 'joycode', 'qwen', 'zed', 'hermes', 'openclaw', 'kimi', 'adal']; const COMPONENT_FAMILY_PREFIXES = { baseline: 'baseline:', language: 'lang:', @@ -71,6 +71,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', diff --git a/scripts/lib/install-targets/antigravity-home.js b/scripts/lib/install-targets/antigravity-home.js new file mode 100644 index 000000000..553ebd175 --- /dev/null +++ b/scripts/lib/install-targets/antigravity-home.js @@ -0,0 +1,209 @@ +'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 } = require('../antigravity-mcp'); +const { buildAntigravityPluginManifest } = require('../antigravity-plugin'); + +function readJsonObject(filePath, label) { + let parsed; + try { + parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch (error) { + throw new Error(`Failed to parse ${label} at ${filePath}: ${error.message}`); + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`Invalid ${label} at ${filePath}: expected a JSON object`); + } + + return parsed; +} + +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, + 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); + return [ + createManagedScaffoldOperation( + module.id, + normalizedSourcePath, + path.join(targetRoot, 'workflows', 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' + ) { + return [ + 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: input.hookProfile || 'standard', + }), + }), + ]; + } + + if ( + module.id === 'platform-configs' + && (normalizedSourcePath === 'mcp-configs' || normalizedSourcePath === '.mcp.json') + ) { + const baseMcp = (repoRoot && fs.existsSync(path.join(repoRoot, '.mcp.json'))) + ? readJsonObject(path.join(repoRoot, '.mcp.json'), '.mcp.json') + : { mcpServers: {} }; + const antigravityMcp = buildAntigravityMcpConfig(); + const mergedMcp = { + mcpServers: { + ...(baseMcp.mcpServers || {}), + ...(antigravityMcp.mcpServers || {}), + }, + }; + + 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: mergedMcp, + }), + 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( + createManagedScaffoldOperation( + module.id, + 'scripts/memory-mcp.mjs', + path.join(targetRoot, 'scripts', 'memory-mcp.mjs'), + 'preserve-relative-path' + ) + ); + } + + return operations; + } + + if (normalizedSourcePath === 'scripts/hooks' || normalizedSourcePath === 'scripts/lib') { + return [adapter.createScaffoldOperation(module.id, normalizedSourcePath, planningInput)]; + } + + return []; + }); + }); + }, +}); diff --git a/scripts/lib/install-targets/antigravity-project.js b/scripts/lib/install-targets/antigravity-project.js index 7861bbc25..9f5b8a8fd 100644 --- a/scripts/lib/install-targets/antigravity-project.js +++ b/scripts/lib/install-targets/antigravity-project.js @@ -1,3 +1,4 @@ +const fs = require('fs'); const path = require('path'); const { @@ -7,8 +8,21 @@ const { createManagedScaffoldOperation, normalizeRelativePath, } = require('./helpers'); +const { buildAntigravityHooksConfig } = require('../antigravity-hooks'); +const { buildAntigravityMcpConfig } = require('../antigravity-mcp'); +const { buildAntigravityPluginManifest } = require('../antigravity-plugin'); -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); @@ -17,12 +31,28 @@ function supportsAntigravitySourcePath(sourceRelativePath) { )); } +function readJsonObject(filePath, label) { + let parsed; + try { + parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch (error) { + throw new Error(`Failed to parse ${label} at ${filePath}: ${error.message}`); + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`Invalid ${label} at ${filePath}: expected a JSON object`); + } + + return parsed; +} + module.exports = createInstallTargetAdapter({ id: 'antigravity-project', target: 'antigravity', 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; @@ -114,6 +144,82 @@ module.exports = createInstallTargetAdapter({ ]; } + if ( + module.id === 'hooks-runtime' + && normalizedSourcePath === 'hooks' + ) { + return [ + 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: input.hookProfile || 'standard', + }), + }), + ]; + } + + if ( + module.id === 'platform-configs' + && (normalizedSourcePath === 'mcp-configs' || normalizedSourcePath === '.mcp.json') + ) { + const baseMcp = (repoRoot && fs.existsSync(path.join(repoRoot, '.mcp.json'))) + ? readJsonObject(path.join(repoRoot, '.mcp.json'), '.mcp.json') + : { mcpServers: {} }; + const antigravityMcp = buildAntigravityMcpConfig(); + const mergedMcp = { + mcpServers: { + ...(baseMcp.mcpServers || {}), + ...(antigravityMcp.mcpServers || {}), + }, + }; + + 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: mergedMcp, + }), + 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( + createManagedScaffoldOperation( + module.id, + 'scripts/memory-mcp.mjs', + path.join(targetRoot, 'scripts', 'memory-mcp.mjs'), + 'preserve-relative-path' + ) + ); + } + + return operations; + } + + if (normalizedSourcePath === 'scripts/hooks' || normalizedSourcePath === 'scripts/lib') { + return [adapter.createScaffoldOperation(module.id, normalizedSourcePath, planningInput)]; + } + return []; }); }); diff --git a/scripts/lib/install-targets/registry.js b/scripts/lib/install-targets/registry.js index 8dd7cf848..864a91a22 100644 --- a/scripts/lib/install-targets/registry.js +++ b/scripts/lib/install-targets/registry.js @@ -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'); @@ -19,6 +20,7 @@ const ADAPTERS = Object.freeze([ claudeHome, claudeProject, cursorProject, + antigravityHome, antigravityProject, codexHome, geminiProject, diff --git a/scripts/lib/install/codex-user-config.js b/scripts/lib/install/codex-user-config.js index 5b7aa612c..a4e95df05 100644 --- a/scripts/lib/install/codex-user-config.js +++ b/scripts/lib/install/codex-user-config.js @@ -6,7 +6,7 @@ const path = require('path'); const { assertWithinTrustedRoot } = require('../path-safety'); function isCodexUserConfig(plan, operation) { - if (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); diff --git a/scripts/lib/install/hook-consent.js b/scripts/lib/install/hook-consent.js index 883c121d7..4b84a6b4e 100644 --- a/scripts/lib/install/hook-consent.js +++ b/scripts/lib/install/hook-consent.js @@ -60,6 +60,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/') ); diff --git a/scripts/lib/install/plan.js b/scripts/lib/install/plan.js index 1400557c7..91774b6e0 100644 --- a/scripts/lib/install/plan.js +++ b/scripts/lib/install/plan.js @@ -167,8 +167,10 @@ 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) } ]; } diff --git a/scripts/lib/resolve-ecc-root.js b/scripts/lib/resolve-ecc-root.js index c9b8ee423..1b2da3684 100644 --- a/scripts/lib/resolve-ecc-root.js +++ b/scripts/lib/resolve-ecc-root.js @@ -55,7 +55,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(); @@ -80,6 +80,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) => diff --git a/scripts/plan-canvas.js b/scripts/plan-canvas.js index 6ecefe49a..9b692821a 100755 --- a/scripts/plan-canvas.js +++ b/scripts/plan-canvas.js @@ -17,6 +17,7 @@ * so stdout stays parseable. */ +const { spawn } = require('child_process'); const fs = require('fs'); const http = require('http'); const path = require('path'); diff --git a/tests/lib/antigravity-tier1.test.js b/tests/lib/antigravity-tier1.test.js new file mode 100644 index 000000000..145947bcd --- /dev/null +++ b/tests/lib/antigravity-tier1.test.js @@ -0,0 +1,356 @@ +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +const { adaptAntigravityInputToEcc } = require('../../scripts/hooks/antigravity-hook-bridge'); +const { buildAntigravityHooksConfig } = require('../../scripts/lib/antigravity-hooks'); +const { buildAntigravityMcpConfig } = require('../../scripts/lib/antigravity-mcp'); +const { buildAntigravityPluginManifest } = require('../../scripts/lib/antigravity-plugin'); +const { getInstallTargetAdapter, listInstallTargetAdapters } = require('../../scripts/lib/install-targets/registry'); +const { resolveInstallPlan } = require('../../scripts/lib/install-manifests'); +const { resolveEccRoot } = require('../../scripts/lib/resolve-ecc-root'); + +let passed = 0; +let failed = 0; + +function test(name, fn) { + try { + fn(); + console.log(` ✓ ${name}`); + passed += 1; + return true; + } catch (error) { + console.log(` ✗ ${name}`); + console.log(` Error: ${error.message}`); + failed += 1; + return false; + } +} + +function createTempDir(prefix) { + return fs.mkdtempSync(path.join(os.tmpdir(), prefix)); +} + +function cleanup(dirPath) { + fs.rmSync(dirPath, { recursive: true, force: true }); +} + +function runTests() { + console.log('\n=== Testing Antigravity Tier 1 Parity ===\n'); + + test('adaptAntigravityInputToEcc normalizes run_command tool calls', () => { + const rawInput = { + conversationId: 'conv-1234', + workspacePaths: ['/workspace/app'], + stepIdx: 5, + toolCall: { + name: 'run_command', + args: { + CommandLine: 'npm test', + Cwd: '/workspace/app', + }, + }, + }; + + const adapted = adaptAntigravityInputToEcc(rawInput); + assert.strictEqual(adapted.tool_name, 'run_command'); + assert.strictEqual(adapted.tool_input.command, 'npm test'); + assert.strictEqual(adapted.tool_input.CommandLine, 'npm test'); + assert.strictEqual(adapted.conversation_id, 'conv-1234'); + assert.deepStrictEqual(adapted.workspace_paths, ['/workspace/app']); + }); + + test('adaptAntigravityInputToEcc normalizes write_to_file and replace_file_content tool calls', () => { + const writeInput = { + toolCall: { + name: 'write_to_file', + args: { + TargetFile: '/workspace/app/src/index.js', + CodeContent: 'console.log("hello");', + }, + }, + }; + const adaptedWrite = adaptAntigravityInputToEcc(writeInput); + assert.strictEqual(adaptedWrite.tool_name, 'write_to_file'); + assert.strictEqual(adaptedWrite.tool_input.file_path, '/workspace/app/src/index.js'); + + const replaceInput = { + toolCall: { + name: 'replace_file_content', + args: { + TargetFile: '/workspace/app/src/index.js', + TargetContent: 'hello', + ReplacementContent: 'world', + }, + }, + }; + const adaptedReplace = adaptAntigravityInputToEcc(replaceInput); + assert.strictEqual(adaptedReplace.tool_name, 'replace_file_content'); + assert.strictEqual(adaptedReplace.tool_input.file_path, '/workspace/app/src/index.js'); + }); + + test('adaptAntigravityInputToEcc handles malformed or empty payloads safely', () => { + const emptyAdapted = adaptAntigravityInputToEcc(null); + assert.strictEqual(emptyAdapted.tool_name, ''); + assert.deepStrictEqual(emptyAdapted.tool_input, {}); + + const emptyObjAdapted = adaptAntigravityInputToEcc({}); + assert.strictEqual(emptyObjAdapted.tool_name, ''); + assert.deepStrictEqual(emptyObjAdapted.tool_input, { command: '', file_path: '' }); + }); + + test('buildAntigravityHooksConfig generates valid Antigravity hooks specification', () => { + const config = buildAntigravityHooksConfig({ profile: 'standard' }); + assert.ok(config['ecc-guard'], 'Should have ecc-guard hook entry'); + const guard = config['ecc-guard']; + + assert.ok(Array.isArray(guard.PreToolUse), 'PreToolUse should be an array'); + assert.ok(Array.isArray(guard.Stop), 'Stop should be an array'); + + const commandMatcher = guard.PreToolUse.find(entry => entry.matcher === 'run_command'); + assert.ok(commandMatcher, 'Should have run_command matcher in PreToolUse'); + assert.ok( + commandMatcher.hooks.some(h => h.command.includes('pre:bash:dispatcher')), + 'Should invoke pre:bash:dispatcher on run_command' + ); + + const editMatcher = guard.PreToolUse.find(entry => entry.matcher === 'write_to_file|replace_file_content'); + assert.ok(editMatcher, 'Should have write_to_file|replace_file_content matcher'); + assert.ok( + editMatcher.hooks.some(h => h.command.includes('pre:edit-write:gateguard-fact-force')), + 'Should invoke GateGuard on write operations' + ); + }); + + test('buildAntigravityMcpConfig generates valid stdio MCP configuration for ecc-memory', () => { + const config = buildAntigravityMcpConfig(); + assert.ok(config.mcpServers, 'Should declare mcpServers'); + assert.ok(config.mcpServers['ecc-memory'], 'Should declare ecc-memory server'); + const memoryServer = config.mcpServers['ecc-memory']; + assert.strictEqual(memoryServer.command, 'node'); + assert.strictEqual(memoryServer.env.ECC_MEMORY_HARNESS, 'antigravity'); + }); + + test('buildAntigravityPluginManifest generates valid Antigravity plugin manifest', () => { + const manifest = buildAntigravityPluginManifest({ version: '2.2.2' }); + assert.strictEqual(manifest.name, 'ecc'); + assert.strictEqual(manifest.version, '2.2.2'); + assert.ok(manifest.description.includes('Antigravity')); + }); + + test('antigravity-home adapter resolves root to ~/.gemini/config/plugins/ecc', () => { + const homeDir = '/home/testuser'; + const adapter = getInstallTargetAdapter('antigravity-home'); + assert.strictEqual(adapter.id, 'antigravity-home'); + assert.strictEqual(adapter.kind, 'home'); + assert.strictEqual( + adapter.resolveRoot({ homeDir }), + path.join(homeDir, '.gemini', 'config', 'plugins', 'ecc') + ); + }); + + test('antigravity-home plans complete native plugin structure for core profile', () => { + const homeDir = createTempDir('antigravity-home-test-'); + const projectRoot = createTempDir('antigravity-proj-test-'); + + try { + const plan = resolveInstallPlan({ + profileId: 'core', + target: 'antigravity-home', + homeDir, + projectRoot, + enableHooks: true, + }); + + assert.strictEqual(plan.targetAdapterId, 'antigravity-home'); + assert.strictEqual( + plan.targetRoot, + path.join(homeDir, '.gemini', 'config', 'plugins', 'ecc') + ); + + const targetRoot = plan.targetRoot; + + // Check plugin.json + assert.ok( + plan.operations.some(op => ( + op.destinationPath === path.join(targetRoot, 'plugin.json') + && op.kind === 'merge-json' + )), + 'Should plan plugin.json merge' + ); + + // Check mcp_config.json + assert.ok( + plan.operations.some(op => ( + op.destinationPath === path.join(targetRoot, 'mcp_config.json') + && op.kind === 'merge-json' + )), + 'Should plan mcp_config.json merge' + ); + + // Check hooks.json + assert.ok( + plan.operations.some(op => ( + op.destinationPath === path.join(targetRoot, 'hooks.json') + && op.kind === 'merge-json' + )), + 'Should plan hooks.json merge' + ); + + // Check rules + assert.ok( + plan.operations.some(op => ( + op.destinationPath.startsWith(path.join(targetRoot, 'rules')) + )), + 'Should plan rules into plugin rules directory' + ); + + // Check workflows + assert.ok( + plan.operations.some(op => ( + op.destinationPath.startsWith(path.join(targetRoot, 'workflows')) + )), + 'Should plan workflows' + ); + } finally { + cleanup(homeDir); + cleanup(projectRoot); + } + }); + + test('antigravity-hook-bridge handles allow decision for safe command', () => { + const bridgePath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'antigravity-hook-bridge.js'); + const input = JSON.stringify({ + conversationId: 'test-conv', + workspacePaths: ['/tmp'], + toolCall: { + name: 'run_command', + args: { + CommandLine: 'echo "hello from safe command"', + }, + }, + }); + + const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:bash:dispatcher'], { + input, + encoding: 'utf8', + }); + + assert.strictEqual(run.status, 0); + const output = JSON.parse(run.stdout); + assert.strictEqual(output.decision, 'allow'); + }); + + test('antigravity-hook-bridge returns deny for blocked git push --no-verify', () => { + const bridgePath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'antigravity-hook-bridge.js'); + const input = JSON.stringify({ + conversationId: 'test-conv', + workspacePaths: ['/tmp'], + toolCall: { + name: 'run_command', + args: { + CommandLine: 'git push origin main --no-verify', + }, + }, + }); + + const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:bash:dispatcher'], { + input, + encoding: 'utf8', + }); + + assert.strictEqual(run.status, 0); + const output = JSON.parse(run.stdout); + assert.strictEqual(output.decision, 'deny'); + assert.match(output.reason, /no-verify/i); + }); + + test('antigravity-project plans mcp_config.json when platform configs are selected', () => { + const projectRoot = createTempDir('antigravity-proj-mcp-'); + try { + const plan = resolveInstallPlan({ + moduleIds: ['platform-configs'], + target: 'antigravity', + projectRoot, + }); + + assert.strictEqual(plan.targetAdapterId, 'antigravity-project'); + const targetRoot = path.join(projectRoot, '.agents'); + + assert.ok( + plan.operations.some(op => op.destinationPath === path.join(targetRoot, 'mcp_config.json') && op.kind === 'merge-json'), + 'Should plan mcp_config.json in project .agents' + ); + } finally { + cleanup(projectRoot); + } + }); + + test('antigravity-home end-to-end install applies complete plugin directory and install state', () => { + const homeDir = createTempDir('antigravity-home-e2e-'); + const projectDir = createTempDir('antigravity-proj-e2e-'); + + try { + const { createManifestInstallPlan } = require('../../scripts/lib/install/plan'); + const { applyInstallPlan } = require('../../scripts/lib/install/apply'); + const { withHookConsent } = require('../../scripts/lib/install/hook-consent'); + const plan = withHookConsent(createManifestInstallPlan({ + profileId: 'core', + target: 'antigravity-home', + homeDir, + projectRoot: projectDir, + }), 'enabled'); + + const result = applyInstallPlan(plan); + const pluginDir = path.join(homeDir, '.gemini', 'config', 'plugins', 'ecc'); + + assert.ok(fs.existsSync(path.join(pluginDir, 'plugin.json')), 'plugin.json should exist'); + assert.ok(fs.existsSync(path.join(pluginDir, 'hooks.json')), 'hooks.json should exist'); + assert.ok(fs.existsSync(path.join(pluginDir, 'mcp_config.json')), 'mcp_config.json should exist'); + assert.ok(fs.existsSync(path.join(pluginDir, 'ecc-install-state.json')), 'install-state should exist'); + assert.ok(fs.existsSync(path.join(pluginDir, 'rules', 'common-coding-style.md')), 'rules should exist'); + assert.ok(fs.existsSync(path.join(pluginDir, 'skills', 'tdd-workflow', 'SKILL.md')), 'skills should exist'); + assert.ok(fs.existsSync(path.join(pluginDir, 'scripts', 'hooks', 'antigravity-hook-bridge.js')), 'hook bridge should exist'); + + const pluginJson = JSON.parse(fs.readFileSync(path.join(pluginDir, 'plugin.json'), 'utf8')); + assert.strictEqual(pluginJson.name, 'ecc'); + + const hooksJson = JSON.parse(fs.readFileSync(path.join(pluginDir, 'hooks.json'), 'utf8')); + assert.ok(hooksJson['ecc-guard']); + assert.ok(Array.isArray(hooksJson['ecc-guard'].PreToolUse)); + assert.ok(Array.isArray(hooksJson['ecc-guard'].Stop)); + + const mcpConfig = JSON.parse(fs.readFileSync(path.join(pluginDir, 'mcp_config.json'), 'utf8')); + assert.ok(mcpConfig.mcpServers['ecc-memory']); + } finally { + cleanup(homeDir); + cleanup(projectDir); + } + }); + + test('resolveEccRoot recognizes Antigravity global plugin install', () => { + const tempHome = createTempDir('ecc-root-test-'); + try { + const pluginDir = path.join(tempHome, '.gemini', 'config', 'plugins', 'ecc'); + fs.mkdirSync(path.join(pluginDir, 'scripts', 'lib'), { recursive: true }); + fs.mkdirSync(path.join(pluginDir, 'skills', 'continuous-learning-v2'), { recursive: true }); + fs.writeFileSync(path.join(pluginDir, 'scripts', 'lib', 'utils.js'), '// utils'); + + const resolved = resolveEccRoot({ homeDir: tempHome }); + assert.strictEqual(resolved, pluginDir); + } finally { + cleanup(tempHome); + } + }); + + console.log(`\nResults: Passed: ${passed}, Failed: ${failed}\n`); + if (failed > 0) { + process.exit(1); + } +} + +runTests(); diff --git a/tests/lib/harness-capabilities.test.js b/tests/lib/harness-capabilities.test.js index 4591403d4..35d1abb8b 100644 --- a/tests/lib/harness-capabilities.test.js +++ b/tests/lib/harness-capabilities.test.js @@ -33,12 +33,12 @@ function runTests() { let passed = 0; let failed = 0; - if (test('represents all 15 registered targets exactly once across 14 harnesses', () => { + if (test('represents all 16 registered targets exactly once across 14 harnesses', () => { const catalogTargetIds = HARNESS_CAPABILITIES.flatMap(harness => harness.targetIds); const adapterTargetIds = listInstallTargetAdapters().map(adapter => adapter.target); assert.strictEqual(HARNESS_CAPABILITIES.length, 14); - assert.strictEqual(new Set(catalogTargetIds).size, 15); + assert.strictEqual(new Set(catalogTargetIds).size, 16); assert.deepStrictEqual([...catalogTargetIds].sort(), [...SUPPORTED_INSTALL_TARGETS].sort()); assert.deepStrictEqual([...catalogTargetIds].sort(), [...adapterTargetIds].sort()); })) passed++; else failed++; @@ -84,6 +84,16 @@ function runTests() { { id: 'project', targetId: 'kimi', root: './.kimi-code' }, ]); + const antigravity = getHarnessCapability('antigravity'); + assert.deepStrictEqual(antigravity.targetIds, ['antigravity-home', 'antigravity']); + assert.strictEqual(antigravity.channel, 'native-plugin'); + assert.strictEqual(antigravity.installMode, 'native-plugin'); + assert.match(antigravity.destination, /selected Antigravity scope/i); + assert.deepStrictEqual(antigravity.scopes, [ + { id: 'user', targetId: 'antigravity-home', root: '~/.gemini/config/plugins/ecc' }, + { id: 'project', targetId: 'antigravity', root: './.agents' }, + ]); + const opencode = getHarnessCapability('opencode'); assert.match(opencode.destinationResolution, /OPENCODE_CONFIG_DIR/); assert.match(opencode.destinationResolution, /XDG_CONFIG_HOME/); @@ -93,7 +103,6 @@ function runTests() { if (test('keeps every advanced target attached to its registered root and scope', () => { const expected = { cursor: ['project', './.cursor'], - antigravity: ['project', './.agents'], gemini: ['project', './.gemini'], opencode: ['home', '~/.config/opencode'], codebuddy: ['project', './.codebuddy'], diff --git a/tests/scripts/codex-hooks.test.js b/tests/scripts/codex-hooks.test.js index c47f6d986..17efc10b4 100644 --- a/tests/scripts/codex-hooks.test.js +++ b/tests/scripts/codex-hooks.test.js @@ -406,6 +406,7 @@ function runHermeticPythonPrePush({ HOME: process.env.HOME ?? '', ECC_SKIP_GIT_HOOKS: '0', ECC_SKIP_PREPUSH: '0', + ECC_PREPUSH_RUN_CHECKS: '1', MSYS_NO_PATHCONV: '1', ...(venvDir === null || trackVenv ? {} : { VIRTUAL_ENV: toBashPath(venvDir) }), ...(override === null ? {} : { ECC_PYTEST_CMD: override }), @@ -452,7 +453,7 @@ else failed++; // A case-folded spelling, because macOS resolves `$venv/bin/python` to a committed // `Python` while git matches index pathspecs case-sensitively. Skipped where the // filesystem is case-sensitive and the two names cannot collide. -if (fs.existsSync(__filename.toUpperCase()) || fs.existsSync(__filename.toLowerCase())) { +if (fs.existsSync(__filename.toUpperCase()) && fs.existsSync(__filename.toLowerCase())) { if ( test('pre-push refuses a tracked interpreter committed under a folded case', () => { const { result, calls } = runHermeticPythonPrePush({ diff --git a/tests/scripts/control-pane.test.js b/tests/scripts/control-pane.test.js index 5503bcf95..406e09c72 100644 --- a/tests/scripts/control-pane.test.js +++ b/tests/scripts/control-pane.test.js @@ -603,7 +603,10 @@ async function runTests() { if ( await test('CLI browser opener handles spawn errors', async () => { - const source = fs.readFileSync(SCRIPT, 'utf8'); + const source = fs.readFileSync( + path.join(REPO_ROOT, 'scripts', 'lib', 'platform-launch.js'), + 'utf8' + ); assert.match(source, /child\.on\('error'/); assert.match(source, /child\.unref\(\)/); From 689160048ad51361e6b4d86d6173409a9f0179a5 Mon Sep 17 00:00:00 2001 From: MohamedAfrash Date: Wed, 23 Sep 2026 11:15:35 +0100 Subject: [PATCH 02/13] docs(readme): document Antigravity native plugin and global install target --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 9156c729a..6c284c359 100644 --- a/README.md +++ b/README.md @@ -136,7 +136,7 @@ Instead of rebuilding that process in every prompt, you install it once and make > Optimize the context window. Persist everything else. -ECC is MIT-licensed open source. It works best with Claude Code today, has a supported Codex sync path, and provides capability-limited adapters for Cursor, OpenCode, Gemini, Zed, GitHub Copilot, Antigravity, Qwen, and other harnesses. See the [support status matrix](#platform-support) before assuming feature parity. +ECC is MIT-licensed open source. It works best with Claude Code today, has supported native plugin paths for Codex and Antigravity, and provides capability-limited adapters for Cursor, OpenCode, Gemini, Zed, GitHub Copilot, Qwen, and other harnesses. See the [support status matrix](#platform-support) before assuming feature parity. Access to 68 agents, 292 skills, and 94 legacy command shims, plus hooks, rules, memory, continuous learning, and AgentShield security scanning. The agents are specialized for planning, review, build repair, security, architecture, and domain work. @@ -259,7 +259,7 @@ npx ecc-universal@2.2.2 doctor --target kimi Do not use `npx ecc-install --profile minimal --target claude`: `ecc-install` is a binary name inside `ecc-universal`, not a separately published npm package. -ECC also ships advanced managed adapters for `cursor`, `antigravity`, `gemini`, `opencode`, `codebuddy`, `joycode`, `qwen`, `zed`, `hermes`, and `openclaw`. Those targets still use their documented `ecc install --target ...` paths until each adapter has passed the guided collision, update, repair, and uninstall lifecycle matrix. Neither wizard silently installs into every detected harness. +ECC also ships advanced managed adapters for `cursor`, `antigravity`, `antigravity-home`, `gemini`, `opencode`, `codebuddy`, `joycode`, `qwen`, `zed`, `hermes`, and `openclaw`. Those targets still use their documented `ecc install --target ...` paths until each adapter has passed the guided collision, update, repair, and uninstall lifecycle matrix. Neither wizard silently installs into every detected harness. ### Pick one path only (per harness) @@ -399,7 +399,8 @@ cd ECC | OpenCode | `npm install && npm run build:opencode && ./install.sh --profile full --target opencode --enable-hooks` | Builds the plugin payload before the full install | | Gemini CLI | `./install.sh --profile minimal --target gemini` | Project-local `.gemini/` config | | Zed | `./install.sh --profile minimal --target zed` | Project-local `.zed/` adapter | -| Antigravity | `./install.sh --profile minimal --target antigravity` | See the [Antigravity guide](docs/ANTIGRAVITY-GUIDE.md) | +| Antigravity (Global Plugin) | `./install.sh --target antigravity-home --profile core --enable-hooks` | Native Tier 1 global plugin (`~/.gemini/config/plugins/ecc/`) with lifecycle hooks · [Guide](docs/ANTIGRAVITY-GUIDE.md) | +| Antigravity (Project-Local) | `./install.sh --target antigravity --profile minimal` | Project-local `.agents/` adapter · [Guide](docs/ANTIGRAVITY-GUIDE.md) | | Qwen CLI | `./install.sh --profile minimal --target qwen` | See the [Qwen guide](docs/QWEN-GUIDE.md) | | Hermes | `./install.sh --profile minimal --target hermes` | See the [Hermes setup guide](docs/HERMES-SETUP.md) | | OpenClaw | `./install.sh --profile minimal --target openclaw` | Managed home-directory install | @@ -1284,10 +1285,11 @@ Treat `stable`, `beta`, `experimental`, and `instruction-only` below as capabili |---|---|---|---| | Claude Code | Stable primary | Plugin or selective installer | The plugin advertises the installed catalog to the model; use a selective/manual profile when context footprint matters. Optional shell-backed skills are not portable to every OS. | | Codex | Supported native plugin | Codex marketplace plugin or repo config | Native hooks require an explicit trust decision and do not use Claude's hook profiles. The legacy sync is compatibility-only. | +| Antigravity | Supported native plugin | Native plugin (`~/.gemini/config/plugins/ecc`) or project `.agents/` | Global native plugin with lifecycle hooks (`PreToolUse`, `Stop`) via protojson bridge, rules, workflows, skills, and memory MCP. | | Cursor | Beta project adapter | Selective installer into `.cursor/` | Agent discovery varies by Cursor build, and ECC's installer paths do not yet expose identical hook sets ([#2419](https://github.com/affaan-m/ECC/issues/2419)). | | OpenCode | Beta built plugin | Build plugin, then selective installer | ECC ships a subset of the catalog; connect a provider and select a model in OpenCode ([#2617](https://github.com/affaan-m/ECC/issues/2617)). | | GitHub Copilot | Instruction-only | Checked-in instructions and prompt files | No ECC hooks, runtime agents, delegation, or native skill discovery. | -| Gemini, Zed, Antigravity, Qwen, Hermes, OpenClaw, Kimi, CodeBuddy, JoyCode | Experimental/minimal adapters | Harness-specific selective target | File placement and instruction portability are tested; full Claude feature parity is not claimed. | +| Gemini, Zed, Qwen, Hermes, OpenClaw, Kimi, CodeBuddy, JoyCode | Experimental/minimal adapters | Harness-specific selective target | File placement and instruction portability are tested; full Claude feature parity is not claimed. |
Package manager detection From aa457babfc787fd647f61e3130398fefbbb7a7f8 Mon Sep 17 00:00:00 2001 From: MohamedAfrash Date: Thu, 24 Sep 2026 03:01:29 +0100 Subject: [PATCH 03/13] fix(antigravity): resolve PR review comments on hooks bridge, mcp runtime, and quoting --- docs/ANTIGRAVITY-GUIDE.md | 16 +- manifests/install-modules.json | 1 + scripts/hooks/antigravity-hook-bridge.js | 83 +++++-- scripts/lib/antigravity-hooks.js | 41 +++- scripts/lib/antigravity-mcp.js | 44 +++- scripts/lib/antigravity-plugin.js | 2 +- scripts/lib/claude-plugin-setup.js | 1 + .../lib/install-targets/antigravity-home.js | 17 +- .../install-targets/antigravity-project.js | 17 +- tests/lib/antigravity-tier1.test.js | 229 +++++++++++++++++- tests/lib/claude-plugin-setup.test.js | 17 ++ tests/lib/install-manifests.test.js | 4 +- tests/scripts/antigravity-hook-bridge.test.js | 102 ++++++++ tests/scripts/install-apply.test.js | 6 +- 14 files changed, 507 insertions(+), 73 deletions(-) create mode 100644 tests/scripts/antigravity-hook-bridge.test.js diff --git a/docs/ANTIGRAVITY-GUIDE.md b/docs/ANTIGRAVITY-GUIDE.md index 80c03fa27..2637f1acd 100644 --- a/docs/ANTIGRAVITY-GUIDE.md +++ b/docs/ANTIGRAVITY-GUIDE.md @@ -153,8 +153,9 @@ node "$EccRoot\scripts\uninstall.js" --target antigravity --dry-run ## Tier 1 Native Plugin and Global Installation (`antigravity-home`) Antigravity supports global plugins located in `~/.gemini/config/plugins//`. Installing ECC as a native Antigravity plugin enables: + 1. **Global Scope**: ECC rules, skills, agents, workflows, and memory MCP are active across all projects automatically, without requiring a `.agents/` folder in every repository. -2. **Lifecycle Hooks (`hooks.json`)**: Full support for `PreToolUse` (command security gates, file modification guards) and `Stop` hooks using Antigravity's protojson protocol (`{ decision, reason }`). +2. **Lifecycle Hooks (`hooks.json`)**: Full support for `PreToolUse` (command security gates, file modification guards) `PostToolUse` edit tracking, and `Stop` formatting and diagnostics using Antigravity's protojson protocol (`{ decision, reason }`). 3. **Shared Memory Vault (`mcp_config.json`)**: Direct integration with `ecc-memory-mcp` across all Antigravity sessions. 4. **Native Plugin Manifest (`plugin.json`)**: Declares the ECC plugin metadata. @@ -171,17 +172,25 @@ PowerShell: & "$EccRoot\install.ps1" --target antigravity-home --profile core --enable-hooks ``` +The installer copies the memory server and its runtime dependencies into the +managed target. Generated hook and MCP commands use absolute installed paths, +so they also work when Antigravity runs from another workspace. + +Project-local hooks use the same runtime; select `--profile core --enable-hooks` +with `--target antigravity`. Use `--no-hooks` to omit automatic hooks. + ### Global Plugin Structure ```text ~/.gemini/config/plugins/ecc/ ├── plugin.json # Antigravity plugin manifest -├── hooks.json # PreToolUse and Stop lifecycle hooks +├── hooks.json # PreToolUse, PostToolUse, and Stop hooks ├── mcp_config.json # Shared ECC Memory Vault MCP server ├── rules/ # Rules applied to all workspaces ├── workflows/ # Global slash workflows ├── skills/ # Global Agent Skills -└── scripts/hooks/ # Antigravity hook bridge +├── scripts/ # Hook bridge and memory runtime +└── node_modules/ # Memory server dependencies ``` ## Official Antigravity references @@ -190,6 +199,7 @@ PowerShell: - [Rules and workflows](https://antigravity.google/docs/rules-workflows) - [Custom agents and subagents](https://antigravity.google/docs/subagents) - [Plugins](https://antigravity.google/docs/plugins) +- [Lifecycle hooks](https://antigravity.google/docs/hooks) See [CONTRIBUTING.md](../CONTRIBUTING.md) for ECC contribution guidance and [SELECTIVE-INSTALL-ARCHITECTURE.md](SELECTIVE-INSTALL-ARCHITECTURE.md) for the diff --git a/manifests/install-modules.json b/manifests/install-modules.json index 85ebc638c..6484fa7a7 100644 --- a/manifests/install-modules.json +++ b/manifests/install-modules.json @@ -103,6 +103,7 @@ "cursor", "opencode", "codebuddy", + "antigravity", "antigravity-home" ], "dependencies": [], diff --git a/scripts/hooks/antigravity-hook-bridge.js b/scripts/hooks/antigravity-hook-bridge.js index f0dc01dea..9fa65d7d8 100644 --- a/scripts/hooks/antigravity-hook-bridge.js +++ b/scripts/hooks/antigravity-hook-bridge.js @@ -14,7 +14,7 @@ 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: runStopFormatTypecheck } = require('./stop-format-typecheck'); +const { run: runPostEditAccumulator } = require('./post-edit-accumulator'); const { readStdinRaw, resolveMaxStdin } = require('./hook-input'); function parseArgs(argv) { @@ -53,13 +53,22 @@ function adaptAntigravityInputToEcc(antigravityData) { }; return { - tool_name: toolName, + 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); const maxStdin = resolveMaxStdin(process.env.ECC_HOOK_INPUT_MAX_BYTES); @@ -67,19 +76,21 @@ async function main() { let raw = ''; try { const inputResult = await readStdinRaw(process.stdin, { maxStdin }); + if (inputResult.truncated) throw new Error('Incomplete hook input'); raw = inputResult.raw; } catch (_err) { - // If stdin read fails, fail open safely - process.stdout.write(JSON.stringify({ decision: 'allow' })); + writeFailure(options.mode, 'ECC hook input could not be read completely'); return; } let antigravityPayload = {}; try { - antigravityPayload = raw.trim() ? JSON.parse(raw) : {}; + antigravityPayload = JSON.parse(raw); + if (!antigravityPayload || typeof antigravityPayload !== 'object' || Array.isArray(antigravityPayload)) { + throw new Error('Invalid hook input'); + } } catch (_parseErr) { - // Malformed JSON on stdin - process.stdout.write(JSON.stringify({ decision: 'allow' })); + writeFailure(options.mode, 'ECC hook input must be a valid JSON object'); return; } @@ -97,45 +108,65 @@ async function main() { const child = spawnSync(process.execPath, [path.join(__dirname, 'config-protection.js')], { input: eccJsonString, encoding: 'utf8', + timeout: 4000, }); result = { - exitCode: child.status || 0, + exitCode: child.error || child.status === null ? 2 : child.status, stderr: child.stderr || '', }; } else if (options.hook === 'pre:write:doc-file-warning') { result = runDocFileWarning(eccJsonString); } - if (result && (result.exitCode === 2 || result.denied || result.blocked)) { - const reason = result.stderr || result.reason || 'Blocked by ECC safety hook'; - process.stdout.write(JSON.stringify({ - decision: 'deny', - reason: reason.replace(/\r?\n/g, ' ').trim(), - })); - return; - } + const output = result && (result.stdout || result.output); + const hookOutput = output ? JSON.parse(output).hookSpecificOutput : null; + const denied = 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; + } - process.stdout.write(JSON.stringify({ decision: 'allow' })); + // 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: '' }; - if (options.hook === 'stop:format-typecheck') { - stopResult = runStopFormatTypecheck(eccJsonString); - } else if (options.hook === 'stop:check-console-log') { - const child = spawnSync(process.execPath, [path.join(__dirname, 'check-console-log.js')], { + 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, encoding: 'utf8', + timeout: options.hook === 'stop:format-typecheck' ? 280000 : 25000, }); stopResult = { - exitCode: child.status || 0, - stderr: child.stderr || '', + stderr: child.stderr || (child.error ? 'ECC stop hook failed: ' + child.error.message : ''), }; } - if (stopResult && stopResult.exitCode !== 0 && stopResult.stderr) { + if (stopResult && stopResult.stderr) { process.stdout.write(JSON.stringify({ decision: 'continue', reason: stopResult.stderr.replace(/\r?\n/g, ' ').trim(), @@ -143,7 +174,7 @@ async function main() { return; } - process.stdout.write(JSON.stringify({})); + process.stdout.write(JSON.stringify({ decision: 'allow' })); return; } @@ -153,7 +184,7 @@ async function main() { if (require.main === module) { main().catch(() => { - process.stdout.write(JSON.stringify({ decision: 'allow' })); + writeFailure(parseArgs(process.argv).mode, 'ECC safety hook failed unexpectedly'); }); } diff --git a/scripts/lib/antigravity-hooks.js b/scripts/lib/antigravity-hooks.js index b7ae6327c..9b301b6b9 100644 --- a/scripts/lib/antigravity-hooks.js +++ b/scripts/lib/antigravity-hooks.js @@ -1,5 +1,8 @@ 'use strict'; +const path = require('path'); +const { shellQuote } = require('./control-pane/actions'); + /** * Antigravity Hooks Generator * @@ -10,7 +13,19 @@ function buildAntigravityHooksConfig(options = {}) { const profile = options.profile || 'standard'; - const bridgeScript = options.bridgeScript || 'scripts/hooks/antigravity-hook-bridge.js'; + 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.includes(' ') ? `"${bridgeScript}"` : bridgeScript; + } else { + quotedBridgeScript = shellQuote(bridgeScript); + } const preToolUseHandlers = [ { @@ -18,22 +33,22 @@ function buildAntigravityHooksConfig(options = {}) { hooks: [ { type: 'command', - command: `node ${bridgeScript} --mode pre-tool-use --hook pre:bash:dispatcher`, + command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:bash:dispatcher`, timeout: 15, }, ], }, { - matcher: 'write_to_file|replace_file_content', + matcher: 'write_to_file|replace_file_content|multi_replace_file_content', hooks: [ { type: 'command', - command: `node ${bridgeScript} --mode pre-tool-use --hook pre:edit-write:gateguard-fact-force`, + command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:edit-write:gateguard-fact-force`, timeout: 10, }, { type: 'command', - command: `node ${bridgeScript} --mode pre-tool-use --hook pre:config-protection`, + command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:config-protection`, timeout: 5, }, ], @@ -46,7 +61,7 @@ function buildAntigravityHooksConfig(options = {}) { hooks: [ { type: 'command', - command: `node ${bridgeScript} --mode pre-tool-use --hook pre:write:doc-file-warning`, + command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:write:doc-file-warning`, timeout: 5, }, ], @@ -56,12 +71,12 @@ function buildAntigravityHooksConfig(options = {}) { const stopHandlers = [ { type: 'command', - command: `node ${bridgeScript} --mode stop --hook stop:format-typecheck`, - timeout: 120, + command: `node ${quotedBridgeScript} --mode stop --hook stop:format-typecheck`, + timeout: 300, }, { type: 'command', - command: `node ${bridgeScript} --mode stop --hook stop:check-console-log`, + command: `node ${quotedBridgeScript} --mode stop --hook stop:check-console-log`, timeout: 30, }, ]; @@ -69,6 +84,14 @@ function buildAntigravityHooksConfig(options = {}) { 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, }, }; diff --git a/scripts/lib/antigravity-mcp.js b/scripts/lib/antigravity-mcp.js index dc726e54c..a8689630a 100644 --- a/scripts/lib/antigravity-mcp.js +++ b/scripts/lib/antigravity-mcp.js @@ -1,5 +1,9 @@ 'use strict'; +const fs = require('fs'); +const path = require('path'); +const { createManagedScaffoldOperation } = require('./install-targets/helpers'); + /** * Antigravity MCP Configuration Generator * @@ -8,7 +12,10 @@ */ function buildAntigravityMcpConfig(options = {}) { - const memoryScript = options.memoryScript || 'scripts/memory-mcp.mjs'; + const { memoryScript } = options; + if (typeof memoryScript !== 'string' || !path.isAbsolute(memoryScript) || memoryScript.includes('\0')) { + throw new Error('memoryScript must be an absolute path'); + } return { mcpServers: { @@ -23,6 +30,41 @@ function buildAntigravityMcpConfig(options = {}) { }; } +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 = []) { + 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); + operations.push(createManagedScaffoldOperation( + moduleId, path.relative(repoRoot, packageRoot), 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]); + } + } + addDependency('ajv', repoRoot, targetRoot); + return operations; +} + module.exports = { buildAntigravityMcpConfig, + planAntigravityMemoryRuntime, }; diff --git a/scripts/lib/antigravity-plugin.js b/scripts/lib/antigravity-plugin.js index a93f0a90b..92b43c120 100644 --- a/scripts/lib/antigravity-plugin.js +++ b/scripts/lib/antigravity-plugin.js @@ -7,7 +7,7 @@ */ function buildAntigravityPluginManifest(options = {}) { - const version = options.version || '2.2.2'; + const version = options.version || require('../../package.json').version; return { name: 'ecc', description: 'ECC - The Agent Harness Operating System for Antigravity', diff --git a/scripts/lib/claude-plugin-setup.js b/scripts/lib/claude-plugin-setup.js index 47b0232fd..dd59cbbcd 100644 --- a/scripts/lib/claude-plugin-setup.js +++ b/scripts/lib/claude-plugin-setup.js @@ -658,6 +658,7 @@ function setupClaudePlugin(options = {}, dependencies = {}) { spawnSync: dependencies.spawnSync, }); const action = ensurePluginAtScope({ + hookConfiguration: hookOptions(hooks), hooks, installed: inventory.installed, projectRoot: paths.projectRoot, diff --git a/scripts/lib/install-targets/antigravity-home.js b/scripts/lib/install-targets/antigravity-home.js index 553ebd175..5e362718d 100644 --- a/scripts/lib/install-targets/antigravity-home.js +++ b/scripts/lib/install-targets/antigravity-home.js @@ -13,7 +13,7 @@ const { normalizeRelativePath, } = require('./helpers'); const { buildAntigravityHooksConfig } = require('../antigravity-hooks'); -const { buildAntigravityMcpConfig } = require('../antigravity-mcp'); +const { buildAntigravityMcpConfig, planAntigravityMemoryRuntime } = require('../antigravity-mcp'); const { buildAntigravityPluginManifest } = require('../antigravity-plugin'); function readJsonObject(filePath, label) { @@ -131,6 +131,7 @@ module.exports = createInstallTargetAdapter({ && normalizedSourcePath === 'hooks' ) { return [ + createManagedScaffoldOperation(module.id, 'package.json', path.join(targetRoot, 'package.json'), 'preserve-relative-path'), createManagedOperation({ kind: 'merge-json', moduleId: module.id, @@ -141,6 +142,7 @@ module.exports = createInstallTargetAdapter({ scaffoldOnly: false, mergePayload: buildAntigravityHooksConfig({ profile: input.hookProfile || 'standard', + bridgeScript: path.join(targetRoot, 'scripts', 'hooks', 'antigravity-hook-bridge.js'), }), }), ]; @@ -153,7 +155,9 @@ module.exports = createInstallTargetAdapter({ const baseMcp = (repoRoot && fs.existsSync(path.join(repoRoot, '.mcp.json'))) ? readJsonObject(path.join(repoRoot, '.mcp.json'), '.mcp.json') : { mcpServers: {} }; - const antigravityMcp = buildAntigravityMcpConfig(); + const antigravityMcp = buildAntigravityMcpConfig({ + memoryScript: path.join(targetRoot, 'scripts', 'memory-mcp.mjs'), + }); const mergedMcp = { mcpServers: { ...(baseMcp.mcpServers || {}), @@ -185,14 +189,7 @@ module.exports = createInstallTargetAdapter({ ]; if (repoRoot && fs.existsSync(path.join(repoRoot, 'scripts', 'memory-mcp.mjs'))) { - operations.push( - createManagedScaffoldOperation( - module.id, - 'scripts/memory-mcp.mjs', - path.join(targetRoot, 'scripts', 'memory-mcp.mjs'), - 'preserve-relative-path' - ) - ); + operations.push(...planAntigravityMemoryRuntime(module.id, repoRoot, targetRoot)); } return operations; diff --git a/scripts/lib/install-targets/antigravity-project.js b/scripts/lib/install-targets/antigravity-project.js index 9f5b8a8fd..647c4eb7d 100644 --- a/scripts/lib/install-targets/antigravity-project.js +++ b/scripts/lib/install-targets/antigravity-project.js @@ -9,7 +9,7 @@ const { normalizeRelativePath, } = require('./helpers'); const { buildAntigravityHooksConfig } = require('../antigravity-hooks'); -const { buildAntigravityMcpConfig } = require('../antigravity-mcp'); +const { buildAntigravityMcpConfig, planAntigravityMemoryRuntime } = require('../antigravity-mcp'); const { buildAntigravityPluginManifest } = require('../antigravity-plugin'); const SUPPORTED_SOURCE_PREFIXES = [ @@ -149,6 +149,7 @@ module.exports = createInstallTargetAdapter({ && normalizedSourcePath === 'hooks' ) { return [ + createManagedScaffoldOperation(module.id, 'package.json', path.join(targetRoot, 'package.json'), 'preserve-relative-path'), createManagedOperation({ kind: 'merge-json', moduleId: module.id, @@ -159,6 +160,7 @@ module.exports = createInstallTargetAdapter({ scaffoldOnly: false, mergePayload: buildAntigravityHooksConfig({ profile: input.hookProfile || 'standard', + bridgeScript: path.join(targetRoot, 'scripts', 'hooks', 'antigravity-hook-bridge.js'), }), }), ]; @@ -171,7 +173,9 @@ module.exports = createInstallTargetAdapter({ const baseMcp = (repoRoot && fs.existsSync(path.join(repoRoot, '.mcp.json'))) ? readJsonObject(path.join(repoRoot, '.mcp.json'), '.mcp.json') : { mcpServers: {} }; - const antigravityMcp = buildAntigravityMcpConfig(); + const antigravityMcp = buildAntigravityMcpConfig({ + memoryScript: path.join(targetRoot, 'scripts', 'memory-mcp.mjs'), + }); const mergedMcp = { mcpServers: { ...(baseMcp.mcpServers || {}), @@ -203,14 +207,7 @@ module.exports = createInstallTargetAdapter({ ]; if (repoRoot && fs.existsSync(path.join(repoRoot, 'scripts', 'memory-mcp.mjs'))) { - operations.push( - createManagedScaffoldOperation( - module.id, - 'scripts/memory-mcp.mjs', - path.join(targetRoot, 'scripts', 'memory-mcp.mjs'), - 'preserve-relative-path' - ) - ); + operations.push(...planAntigravityMemoryRuntime(module.id, repoRoot, targetRoot)); } return operations; diff --git a/tests/lib/antigravity-tier1.test.js b/tests/lib/antigravity-tier1.test.js index 145947bcd..e8e8fa98a 100644 --- a/tests/lib/antigravity-tier1.test.js +++ b/tests/lib/antigravity-tier1.test.js @@ -10,7 +10,7 @@ const { adaptAntigravityInputToEcc } = require('../../scripts/hooks/antigravity- const { buildAntigravityHooksConfig } = require('../../scripts/lib/antigravity-hooks'); const { buildAntigravityMcpConfig } = require('../../scripts/lib/antigravity-mcp'); const { buildAntigravityPluginManifest } = require('../../scripts/lib/antigravity-plugin'); -const { getInstallTargetAdapter, listInstallTargetAdapters } = require('../../scripts/lib/install-targets/registry'); +const { getInstallTargetAdapter } = require('../../scripts/lib/install-targets/registry'); const { resolveInstallPlan } = require('../../scripts/lib/install-manifests'); const { resolveEccRoot } = require('../../scripts/lib/resolve-ecc-root'); @@ -57,7 +57,7 @@ function runTests() { }; const adapted = adaptAntigravityInputToEcc(rawInput); - assert.strictEqual(adapted.tool_name, 'run_command'); + assert.strictEqual(adapted.tool_name, 'Bash'); assert.strictEqual(adapted.tool_input.command, 'npm test'); assert.strictEqual(adapted.tool_input.CommandLine, 'npm test'); assert.strictEqual(adapted.conversation_id, 'conv-1234'); @@ -75,7 +75,7 @@ function runTests() { }, }; const adaptedWrite = adaptAntigravityInputToEcc(writeInput); - assert.strictEqual(adaptedWrite.tool_name, 'write_to_file'); + assert.strictEqual(adaptedWrite.tool_name, 'Write'); assert.strictEqual(adaptedWrite.tool_input.file_path, '/workspace/app/src/index.js'); const replaceInput = { @@ -89,7 +89,7 @@ function runTests() { }, }; const adaptedReplace = adaptAntigravityInputToEcc(replaceInput); - assert.strictEqual(adaptedReplace.tool_name, 'replace_file_content'); + assert.strictEqual(adaptedReplace.tool_name, 'Edit'); assert.strictEqual(adaptedReplace.tool_input.file_path, '/workspace/app/src/index.js'); }); @@ -104,12 +104,14 @@ function runTests() { }); test('buildAntigravityHooksConfig generates valid Antigravity hooks specification', () => { - const config = buildAntigravityHooksConfig({ profile: 'standard' }); + const config = buildAntigravityHooksConfig({ profile: 'standard', bridgeScript: path.resolve('scripts/hooks/antigravity-hook-bridge.js') }); assert.ok(config['ecc-guard'], 'Should have ecc-guard hook entry'); const guard = config['ecc-guard']; assert.ok(Array.isArray(guard.PreToolUse), 'PreToolUse should be an array'); assert.ok(Array.isArray(guard.Stop), 'Stop should be an array'); + assert.ok(guard.PostToolUse.some(entry => entry.matcher.includes('multi_replace_file_content') && entry.hooks.some(hook => hook.command.includes('post:edit:accumulator')))); + assert.ok(guard.Stop.find(hook => hook.command.includes('stop:format-typecheck')).timeout >= 270); const commandMatcher = guard.PreToolUse.find(entry => entry.matcher === 'run_command'); assert.ok(commandMatcher, 'Should have run_command matcher in PreToolUse'); @@ -118,7 +120,7 @@ function runTests() { 'Should invoke pre:bash:dispatcher on run_command' ); - const editMatcher = guard.PreToolUse.find(entry => entry.matcher === 'write_to_file|replace_file_content'); + const editMatcher = guard.PreToolUse.find(entry => entry.matcher === 'write_to_file|replace_file_content|multi_replace_file_content'); assert.ok(editMatcher, 'Should have write_to_file|replace_file_content matcher'); assert.ok( editMatcher.hooks.some(h => h.command.includes('pre:edit-write:gateguard-fact-force')), @@ -127,7 +129,7 @@ function runTests() { }); test('buildAntigravityMcpConfig generates valid stdio MCP configuration for ecc-memory', () => { - const config = buildAntigravityMcpConfig(); + const config = buildAntigravityMcpConfig({ memoryScript: path.resolve('scripts/memory-mcp.mjs') }); assert.ok(config.mcpServers, 'Should declare mcpServers'); assert.ok(config.mcpServers['ecc-memory'], 'Should declare ecc-memory server'); const memoryServer = config.mcpServers['ecc-memory']; @@ -142,6 +144,146 @@ function runTests() { assert.ok(manifest.description.includes('Antigravity')); }); + test('generators reject missing, relative, and malformed executable paths', () => { + for (const value of [undefined, '', 'relative/script.js', 7, '/tmp/bad\0path']) { + assert.throws(() => buildAntigravityHooksConfig({ bridgeScript: value }), /absolute path/); + assert.throws(() => buildAntigravityMcpConfig({ memoryScript: value }), /absolute path/); + } + assert.strictEqual(buildAntigravityPluginManifest().version, require('../../package.json').version); + }); + + test('hook commands preserve shell metacharacters in the installed path', () => { + const dir = createTempDir("ecc space ' $HOME `echo x` "); + try { + const script = path.join(dir, 'bridge.js'); + fs.writeFileSync(script, 'process.stdout.write(JSON.stringify(process.argv.slice(2)))'); + const config = buildAntigravityHooksConfig({ bridgeScript: script }); + const command = config['ecc-guard'].PreToolUse[0].hooks[0].command; + const run = spawnSync(command, { shell: true, encoding: 'utf8' }); + assert.strictEqual(run.status, 0, run.stderr); + assert.deepStrictEqual(JSON.parse(run.stdout), ['--mode', 'pre-tool-use', '--hook', 'pre:bash:dispatcher']); + } finally { + cleanup(dir); + } + }); + + for (const target of ['antigravity', 'antigravity-home']) { + test(`${target} installed memory server starts outside the source checkout`, () => { + const root = createTempDir('ecc-memory-install-'); + try { + const projectRoot = path.join(root, 'project'); + fs.mkdirSync(projectRoot); + fs.writeFileSync(path.join(projectRoot, 'package.json'), '{"type":"module"}'); + const { createManifestInstallPlan } = require('../../scripts/lib/install/plan'); + const { applyInstallPlan } = require('../../scripts/lib/install/apply'); + const plan = createManifestInstallPlan({ moduleIds: ['platform-configs'], target, homeDir: root, projectRoot }); + applyInstallPlan(plan); + const config = JSON.parse(fs.readFileSync(path.join(plan.targetRoot, 'mcp_config.json'), 'utf8')); + const server = config.mcpServers['ecc-memory']; + assert.strictEqual(server.args[0], path.join(plan.targetRoot, 'scripts', 'memory-mcp.mjs')); + const run = spawnSync(process.execPath, server.args, { + cwd: root, + env: { ...process.env, ...server.env, NODE_PATH: '' }, + input: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'test', version: '1' } } }) + '\n', + encoding: 'utf8', + timeout: 10000, + }); + assert.strictEqual(run.status, 0, run.stderr); + assert.strictEqual(JSON.parse(run.stdout.trim()).id, 1); + } finally { + cleanup(root); + } + }); + } + + test('project hooks install and run with explicit consent in an ESM project', () => { + const root = createTempDir('ecc-project-hooks-'); + try { + fs.writeFileSync(path.join(root, 'package.json'), '{"type":"module"}'); + const { createManifestInstallPlan } = require('../../scripts/lib/install/plan'); + const { applyInstallPlan } = require('../../scripts/lib/install/apply'); + const { withHookConsent } = require('../../scripts/lib/install/hook-consent'); + const plan = withHookConsent(createManifestInstallPlan({ moduleIds: ['hooks-runtime'], target: 'antigravity', projectRoot: root }), 'enabled'); + applyInstallPlan(plan); + const config = JSON.parse(fs.readFileSync(path.join(plan.targetRoot, 'hooks.json'), 'utf8')); + const run = spawnSync(config['ecc-guard'].PreToolUse[0].hooks[0].command, { + cwd: root, + shell: true, + env: { ...process.env, GATEGUARD_BASH_ROUTINE_DISABLED: '1' }, + input: JSON.stringify({ workspacePaths: [root], toolCall: { name: 'run_command', args: { CommandLine: 'pwd' } } }), + encoding: 'utf8', + timeout: 10000, + }); + assert.strictEqual(run.status, 0, run.stderr); + assert.strictEqual(JSON.parse(run.stdout).decision, 'allow', run.stdout); + } finally { + cleanup(root); + } + }); + + test('memory runtime installs from npm-hoisted dependencies', () => { + const root = createTempDir('ecc-hoisted-memory-'); + try { + const sourceRoot = path.join(root, 'node_modules', 'ecc-universal'); + const repoRoot = path.resolve(__dirname, '../..'); + for (const relative of ['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 destination = path.join(sourceRoot, relative); + fs.mkdirSync(path.dirname(destination), { recursive: true }); + fs.copyFileSync(path.join(repoRoot, relative), destination); + } + const ajvManifest = require('ajv/package.json'); + for (const name of ['ajv', ...Object.keys(ajvManifest.dependencies)]) { + fs.cpSync(path.dirname(require.resolve(`${name}/package.json`)), path.join(root, 'node_modules', name), { recursive: true }); + } + fs.cpSync(path.join(repoRoot, 'manifests'), path.join(sourceRoot, 'manifests'), { recursive: true }); + const projectRoot = path.join(root, 'app'); + const { createManifestInstallPlan } = require('../../scripts/lib/install/plan'); + const { applyInstallPlan } = require('../../scripts/lib/install/apply'); + const plan = createManifestInstallPlan({ sourceRoot, moduleIds: ['platform-configs'], target: 'antigravity', projectRoot }); + applyInstallPlan(plan); + fs.rmSync(path.join(root, 'node_modules'), { recursive: true }); + const run = spawnSync(process.execPath, [path.join(plan.targetRoot, 'scripts/memory-mcp.mjs')], { + cwd: root, + env: { ...process.env, ECC_MEMORY_HARNESS: 'antigravity', NODE_PATH: '' }, + input: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'test', version: '1' } } }) + '\n', + encoding: 'utf8', + timeout: 10000, + }); + assert.strictEqual(run.status, 0, run.stderr); + assert.strictEqual(JSON.parse(run.stdout.trim()).id, 1); + } finally { + cleanup(root); + } + }); + + test('missing memory dependencies give installation instructions', () => { + const root = createTempDir('ecc-missing-memory-dependency-'); + try { + const ajvRoot = path.join(root, 'node_modules', 'ajv'); + fs.mkdirSync(ajvRoot, { recursive: true }); + fs.writeFileSync(path.join(ajvRoot, 'package.json'), JSON.stringify({ dependencies: { 'ecc-test-nonexistent-dependency': '1.0.0' } })); + const { planAntigravityMemoryRuntime } = require('../../scripts/lib/antigravity-mcp'); + assert.throws(() => planAntigravityMemoryRuntime('platform-configs', root, path.join(root, 'target')), /Run npm install/); + } finally { + cleanup(root); + } + }); + + test('Windows hook commands quote spaces and reject shell expansion characters', () => { + const descriptor = Object.getOwnPropertyDescriptor(process, 'platform'); + try { + Object.defineProperty(process, 'platform', { value: 'win32' }); + const bridgeScript = path.resolve('folder with spaces/bridge.js'); + const config = buildAntigravityHooksConfig({ bridgeScript }); + assert.ok(config['ecc-guard'].PreToolUse[0].hooks[0].command.startsWith(`node "${bridgeScript}" `)); + for (const character of ['"', '%', '!', '$', '`', '\r', '\n']) { + assert.throws(() => buildAntigravityHooksConfig({ bridgeScript: bridgeScript + character }), /shell/); + } + } finally { + Object.defineProperty(process, 'platform', descriptor); + } + }); + test('antigravity-home adapter resolves root to ~/.gemini/config/plugins/ecc', () => { const homeDir = '/home/testuser'; const adapter = getInstallTargetAdapter('antigravity-home'); @@ -163,7 +305,6 @@ function runTests() { target: 'antigravity-home', homeDir, projectRoot, - enableHooks: true, }); assert.strictEqual(plan.targetAdapterId, 'antigravity-home'); @@ -230,7 +371,7 @@ function runTests() { toolCall: { name: 'run_command', args: { - CommandLine: 'echo "hello from safe command"', + CommandLine: 'pwd', }, }, }); @@ -269,6 +410,72 @@ function runTests() { assert.match(output.reason, /no-verify/i); }); + test('antigravity-hook-bridge returns deny for GateGuard write_to_file on first touch', () => { + const bridgePath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'antigravity-hook-bridge.js'); + const root = createTempDir('ecc-bridge-deny-'); + try { + const targetFile = path.join(root, 'index.js'); + const input = JSON.stringify({ + conversationId: path.basename(root), + workspacePaths: [root], + toolCall: { + name: 'write_to_file', + args: { + TargetFile: targetFile, + CodeContent: 'console.log("hello");', + }, + }, + }); + + const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:edit-write:gateguard-fact-force'], { + input, + encoding: 'utf8', + env: { + ...process.env, + GATEGUARD_STATE_DIR: root, + GATEGUARD_DISABLED: '0', + GATEGUARD_EXEMPT_PATHS: '', + GATEGUARD_EXEMPT_GLOBS: '', + }, + }); + + assert.strictEqual(run.status, 0); + const output = JSON.parse(run.stdout); + assert.strictEqual(output.decision, 'deny'); + assert.ok(output.reason); + } finally { + cleanup(root); + } + }); + + test('antigravity-hook-bridge returns deny for oversized input in pre-tool-use', () => { + const bridgePath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'antigravity-hook-bridge.js'); + const input = JSON.stringify({ + conversationId: 'test-oversized', + workspacePaths: ['/tmp'], + toolCall: { + name: 'run_command', + args: { + CommandLine: 'echo ' + 'x'.repeat(100), + }, + }, + }); + + const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:bash:dispatcher'], { + input, + encoding: 'utf8', + env: { + ...process.env, + ECC_HOOK_INPUT_MAX_BYTES: '10', + }, + }); + + assert.strictEqual(run.status, 0); + const output = JSON.parse(run.stdout); + assert.strictEqual(output.decision, 'deny'); + assert.match(output.reason, /completely|input/i); + }); + test('antigravity-project plans mcp_config.json when platform configs are selected', () => { const projectRoot = createTempDir('antigravity-proj-mcp-'); try { @@ -305,7 +512,7 @@ function runTests() { projectRoot: projectDir, }), 'enabled'); - const result = applyInstallPlan(plan); + applyInstallPlan(plan); const pluginDir = path.join(homeDir, '.gemini', 'config', 'plugins', 'ecc'); assert.ok(fs.existsSync(path.join(pluginDir, 'plugin.json')), 'plugin.json should exist'); @@ -326,6 +533,8 @@ function runTests() { const mcpConfig = JSON.parse(fs.readFileSync(path.join(pluginDir, 'mcp_config.json'), 'utf8')); assert.ok(mcpConfig.mcpServers['ecc-memory']); + const hookCommand = hooksJson['ecc-guard'].PreToolUse[0].hooks[0].command; + assert.ok(hookCommand.includes(path.join(pluginDir, 'scripts', 'hooks', 'antigravity-hook-bridge.js'))); } finally { cleanup(homeDir); cleanup(projectDir); diff --git a/tests/lib/claude-plugin-setup.test.js b/tests/lib/claude-plugin-setup.test.js index cdda9f5f0..700ec1a3f 100644 --- a/tests/lib/claude-plugin-setup.test.js +++ b/tests/lib/claude-plugin-setup.test.js @@ -294,6 +294,8 @@ test('fresh install uses supported Claude arguments and follows the verification [ 'plugin', 'install', 'ecc@ecc', '--scope', 'project', + '--config', 'hooks_enabled=true', + '--config', 'hook_profile=strict', ], ['plugin', 'list', '--json'], ]); @@ -324,6 +326,19 @@ test('fresh installs support all Claude scopes while hook preferences stay user- } }); +test('fresh installs pass disabled hooks to the provider before activation', () => { + withFixture({}, fixture => { + setupClaudePlugin(setupOptions(fixture, { scope: 'user', hooks: 'off' })); + const install = readCalls(fixture).find(argv => argv[1] === 'install'); + assert.deepStrictEqual(install, [ + 'plugin', 'install', 'ecc@ecc', '--scope', 'user', + '--config', 'hooks_enabled=false', '--config', 'hook_profile=standard', + ]); + const settings = JSON.parse(fs.readFileSync(fixture.settingsPath, 'utf8')); + assert.strictEqual(settings.pluginConfigs['ecc@ecc'].options.hooks_enabled, false); + }); +}); + test('same-scope repeat setup updates ECC and changes durable user hook preferences', () => { withFixture({ plugins: [installedPlugin('local')], @@ -722,6 +737,8 @@ test('provider failures stop later operations and leave settings untouched', () const installArgv = [ 'plugin', 'install', 'ecc@ecc', '--scope', 'user', + '--config', 'hooks_enabled=true', + '--config', 'hook_profile=standard', ]; withFixture({ failures: [{ diff --git a/tests/lib/install-manifests.test.js b/tests/lib/install-manifests.test.js index cd91e6e3a..bf6fe62b8 100644 --- a/tests/lib/install-manifests.test.js +++ b/tests/lib/install-manifests.test.js @@ -280,12 +280,14 @@ function runTests() { 'rules-core', 'agents-core', 'commands-core', + 'hooks-runtime', 'platform-configs', 'skill-unified-memory', 'workflow-quality' ] ); - assert.ok(plan.skippedModuleIds.includes('hooks-runtime')); + assert.ok(!plan.skippedModuleIds.includes('hooks-runtime')); + assert.ok(plan.operations.some(operation => operation.destinationPath === path.join(projectRoot, '.agents', 'hooks.json'))); assert.ok(!plan.skippedModuleIds.includes('platform-configs')); assert.ok(!plan.skippedModuleIds.includes('workflow-quality')); assert.strictEqual(plan.targetAdapterId, 'antigravity-project'); diff --git a/tests/scripts/antigravity-hook-bridge.test.js b/tests/scripts/antigravity-hook-bridge.test.js new file mode 100644 index 000000000..d967bbd63 --- /dev/null +++ b/tests/scripts/antigravity-hook-bridge.test.js @@ -0,0 +1,102 @@ +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); +const os = require('os'); +const { spawnSync } = require('child_process'); +const { adaptAntigravityInputToEcc } = require('../../scripts/hooks/antigravity-hook-bridge'); + +const bridgePath = path.resolve(__dirname, '../../scripts/hooks/antigravity-hook-bridge.js'); +async function invoke({ hook = 'pre:edit-write:gateguard-fact-force', mode = 'pre-tool-use', raw = '{}', truncated = false, result = {}, child, readError = false, hookError = false } = {}) { + let output = ''; + let spawnOptions; + let hookCalls = 0; + const module = { exports: {} }; + const run = () => { hookCalls += 1; if (hookError) throw new Error('hook failed'); return result; }; + const imports = { + path, + child_process: { spawnSync: (_file, _args, options) => { spawnOptions = options; return child; } }, + './bash-hook-dispatcher': { runPreBash: run }, + './gateguard-fact-force': { run }, + './doc-file-warning': { run }, + './post-edit-accumulator': { run }, + './stop-format-typecheck': { run }, + './hook-input': { + resolveMaxStdin: () => 1024, + readStdinRaw: async () => { if (readError) throw new Error('read failed'); return { raw, truncated }; }, + }, + }; + const requireStub = name => imports[name]; + requireStub.main = module; + vm.runInNewContext(fs.readFileSync(bridgePath, 'utf8'), { + require: requireStub, module, __dirname: path.dirname(bridgePath), + process: { argv: ['node', bridgePath, '--mode', mode, '--hook', hook], env: {}, execPath: process.execPath, stdin: {}, stdout: { write: text => { output += text; } } }, + }); + await new Promise(resolve => setImmediate(resolve)); + return { response: JSON.parse(output), spawnOptions, hookCalls }; +} + +async function main() { + for (const [native, expected] of [['run_command', 'Bash'], ['write_to_file', 'Write'], ['replace_file_content', 'Edit'], ['multi_replace_file_content', 'Edit']]) { + const input = adaptAntigravityInputToEcc({ toolCall: { name: native, args: { CommandLine: 'echo ok', TargetFile: '/tmp/code.js' } } }); + assert.strictEqual(input.tool_name, expected); + assert.strictEqual(input.tool_input.command, 'echo ok'); + assert.strictEqual(input.tool_input.file_path, '/tmp/code.js'); + } + const session = adaptAntigravityInputToEcc({ conversationId: 'session-a', workspacePaths: ['/workspace/app'] }); + assert.strictEqual(session.session_id, 'session-a'); + assert.strictEqual(session.cwd, '/workspace/app'); + const denial = { hookSpecificOutput: { permissionDecision: 'deny', permissionDecisionReason: 'Inspect first\nThen retry' } }; + assert.deepStrictEqual((await invoke({ result: { exitCode: 0, stdout: JSON.stringify(denial) } })).response, { decision: 'deny', reason: 'Inspect first Then retry' }); + assert.strictEqual((await invoke({ hook: 'pre:bash:dispatcher', result: { exitCode: 0, output: JSON.stringify(denial) } })).response.decision, 'deny'); + assert.match((await invoke({ hook: 'pre:write:doc-file-warning', result: { exitCode: 0, additionalContext: ['warning one', 'warning two'] } })).response.reason, /warning one.*warning two/); + for (const failure of [{ raw: '{' }, { raw: '' }, { raw: 'null' }, { raw: '[]' }, { truncated: true }, { readError: true }, { hookError: true }]) { + assert.strictEqual((await invoke(failure)).response.decision, 'deny', JSON.stringify(failure)); + } + for (const child of [{ status: null, error: new Error('timed out') }, { status: 1, stderr: 'failed' }, { status: 2, stderr: 'blocked' }]) { + const result = await invoke({ hook: 'pre:config-protection', child }); + assert.strictEqual(result.response.decision, 'deny'); + assert.ok(result.spawnOptions.timeout > 0 && result.spawnOptions.timeout <= 10000); + } + assert.strictEqual((await invoke({ hook: 'pre:config-protection', child: { status: 0, stderr: '' } })).response.decision, 'allow'); + assert.strictEqual((await invoke({ result: '{}' })).response.decision, 'allow'); + assert.strictEqual((await invoke({ mode: 'stop', raw: '{' })).response.decision, 'allow'); + assert.strictEqual((await invoke({ mode: 'post-tool-use', hook: 'post:edit:accumulator' })).hookCalls, 1); + assert.strictEqual((await invoke({ mode: 'post-tool-use', hook: 'post:edit:accumulator', raw: JSON.stringify({ error: 'write failed' }) })).hookCalls, 0); + assert.deepStrictEqual((await invoke({ mode: 'stop', hook: 'stop:format-typecheck', raw: JSON.stringify({ fullyIdle: false }) })).response, { decision: 'allow' }); + assert.deepStrictEqual((await invoke({ mode: 'stop', hook: 'stop:format-typecheck', child: { status: 0, stderr: '' } })).response, { decision: 'allow' }); + for (const hook of ['stop:check-console-log', 'stop:format-typecheck']) { + const stop = await invoke({ mode: 'stop', hook, child: { status: 0, stderr: 'Remove console.log' } }); + assert.deepStrictEqual(stop.response, { decision: 'continue', reason: 'Remove console.log' }); + } + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-bridge-')); + const conversationId = path.basename(root); + const accumulator = path.join(os.tmpdir(), `ecc-edited-${conversationId}.txt`); + const target = path.join(root, 'component.js'); + const payload = { conversationId, workspacePaths: [root], toolCall: { name: 'multi_replace_file_content', args: { TargetFile: target } } }; + const cli = (mode, hook, input = payload, extraEnv = {}) => { + const child = spawnSync(process.execPath, [bridgePath, '--mode', mode, '--hook', hook], { + input: JSON.stringify(input), encoding: 'utf8', + env: { ...process.env, GATEGUARD_STATE_DIR: root, GATEGUARD_DISABLED: '0', GATEGUARD_EXEMPT_PATHS: '', ...extraEnv }, + }); + assert.strictEqual(child.status, 0, child.stderr); + return JSON.parse(child.stdout); + }; + try { + assert.strictEqual(cli('pre-tool-use', 'pre:edit-write:gateguard-fact-force').decision, 'deny'); + const warning = cli('pre-tool-use', 'pre:write:doc-file-warning', { toolCall: { name: 'write_to_file', args: { TargetFile: path.join(root, 'NOTES.md') } } }); + assert.match(warning.reason, /Ad-hoc documentation/); + assert.strictEqual(cli('pre-tool-use', 'pre:config-protection', payload, { ECC_HOOK_INPUT_MAX_BYTES: '2' }).decision, 'deny'); + cli('post-tool-use', 'post:edit:accumulator'); + assert.strictEqual(fs.readFileSync(accumulator, 'utf8').trim(), target); + cli('stop', 'stop:format-typecheck', { conversationId }); + assert.ok(!fs.existsSync(accumulator) || fs.readFileSync(accumulator, 'utf8') === ''); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + fs.rmSync(accumulator, { force: true }); + } + console.log('antigravity-hook-bridge regression checks passed'); +} +main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/tests/scripts/install-apply.test.js b/tests/scripts/install-apply.test.js index f2846495f..c072d6f31 100644 --- a/tests/scripts/install-apply.test.js +++ b/tests/scripts/install-apply.test.js @@ -891,7 +891,7 @@ function runTests() { const projectDir = createTempDir('install-apply-project-'); try { - const result = run(['--target', 'antigravity', '--profile', 'core'], { cwd: projectDir, homeDir }); + const result = run(['--target', 'antigravity', '--profile', 'core', '--enable-hooks'], { cwd: projectDir, homeDir }); assert.strictEqual(result.code, 0, result.stderr); assert.ok(fs.existsSync(path.join(projectDir, '.agents', 'rules', 'common-coding-style.md'))); @@ -902,6 +902,7 @@ function runTests() { assert.ok(fs.existsSync(path.join(projectDir, '.agents', 'agents', 'architect.md'))); assert.ok(fs.existsSync(path.join(projectDir, '.agents', 'workflows', 'plan.md'))); assert.ok(fs.existsSync(path.join(projectDir, '.agents', 'skills', 'tdd-workflow', 'SKILL.md'))); + assert.ok(fs.existsSync(path.join(projectDir, '.agents', 'hooks.json')), 'hooks.json should exist'); const state = readJson(path.join(projectDir, '.agents', 'ecc-install-state.json')); assert.strictEqual(state.request.profile, 'core'); @@ -912,12 +913,13 @@ function runTests() { 'rules-core', 'agents-core', 'commands-core', + 'hooks-runtime', 'platform-configs', 'skill-unified-memory', 'workflow-quality' ] ); - assert.ok(state.resolution.skippedModules.includes('hooks-runtime')); + assert.ok(!state.resolution.skippedModules.includes('hooks-runtime')); assert.ok(!state.resolution.skippedModules.includes('workflow-quality')); assert.ok(!state.resolution.skippedModules.includes('platform-configs')); } finally { From 9dfa26f24d9f03cec33a49cff429cbdfb9168a8a Mon Sep 17 00:00:00 2001 From: MohamedAfrash Date: Thu, 24 Sep 2026 03:36:29 +0100 Subject: [PATCH 04/13] fix(antigravity): route global workflows to config dir and quote bridgeScript on windows --- docs/ANTIGRAVITY-GUIDE.md | 19 ++++++++++--------- docs/releases/2.2.0/release-notes.md | 2 +- scripts/lib/antigravity-hooks.js | 2 +- scripts/lib/install-lifecycle.js | 13 ++++++++++--- scripts/lib/install-manifests.js | 1 + .../lib/install-targets/antigravity-home.js | 13 ++++++++++++- scripts/lib/install-targets/helpers.js | 7 +++++++ scripts/lib/install-targets/registry.js | 4 ++++ scripts/lib/install/apply.js | 14 ++++++++++++-- scripts/lib/install/plan.js | 1 + scripts/lib/multi-harness-setup.js | 8 ++++++-- tests/lib/antigravity-tier1.test.js | 4 +++- 12 files changed, 68 insertions(+), 20 deletions(-) diff --git a/docs/ANTIGRAVITY-GUIDE.md b/docs/ANTIGRAVITY-GUIDE.md index 2637f1acd..b498492e7 100644 --- a/docs/ANTIGRAVITY-GUIDE.md +++ b/docs/ANTIGRAVITY-GUIDE.md @@ -155,7 +155,7 @@ node "$EccRoot\scripts\uninstall.js" --target antigravity --dry-run Antigravity supports global plugins located in `~/.gemini/config/plugins//`. Installing ECC as a native Antigravity plugin enables: 1. **Global Scope**: ECC rules, skills, agents, workflows, and memory MCP are active across all projects automatically, without requiring a `.agents/` folder in every repository. -2. **Lifecycle Hooks (`hooks.json`)**: Full support for `PreToolUse` (command security gates, file modification guards) `PostToolUse` edit tracking, and `Stop` formatting and diagnostics using Antigravity's protojson protocol (`{ decision, reason }`). +2. **Lifecycle Hooks (`hooks.json`)**: Full support for `PreToolUse` (command security gates, file modification guards), `PostToolUse` edit tracking, and `Stop` formatting and diagnostics using Antigravity's protojson protocol (`{ decision, reason }`). 3. **Shared Memory Vault (`mcp_config.json`)**: Direct integration with `ecc-memory-mcp` across all Antigravity sessions. 4. **Native Plugin Manifest (`plugin.json`)**: Declares the ECC plugin metadata. @@ -182,15 +182,16 @@ with `--target antigravity`. Use `--no-hooks` to omit automatic hooks. ### Global Plugin Structure ```text -~/.gemini/config/plugins/ecc/ -├── plugin.json # Antigravity plugin manifest -├── hooks.json # PreToolUse, PostToolUse, and Stop hooks -├── mcp_config.json # Shared ECC Memory Vault MCP server -├── rules/ # Rules applied to all workspaces +~/.gemini/config/ ├── workflows/ # Global slash workflows -├── skills/ # Global Agent Skills -├── scripts/ # Hook bridge and memory runtime -└── node_modules/ # Memory server dependencies +└── plugins/ecc/ + ├── plugin.json # Antigravity plugin manifest + ├── hooks.json # PreToolUse, PostToolUse, and Stop hooks + ├── mcp_config.json # Shared ECC Memory Vault MCP server + ├── rules/ # Rules applied to all workspaces + ├── skills/ # Global Agent Skills + ├── scripts/ # Hook bridge and memory runtime + └── node_modules/ # Memory server dependencies ``` ## Official Antigravity references diff --git a/docs/releases/2.2.0/release-notes.md b/docs/releases/2.2.0/release-notes.md index 6aa336ddf..447cd6379 100644 --- a/docs/releases/2.2.0/release-notes.md +++ b/docs/releases/2.2.0/release-notes.md @@ -32,7 +32,7 @@ Install or update the published package, then run the same ECC install command y ```bash npm install -g ecc-universal@2.2.0 -ecc install --target antigravity --profile full +ecc install --target antigravity --profile full --enable-hooks ``` Use `ecc doctor --target ` after installation. For Antigravity, start a new conversation and verify workspace skills under Settings > Customizations. diff --git a/scripts/lib/antigravity-hooks.js b/scripts/lib/antigravity-hooks.js index 9b301b6b9..cc496665c 100644 --- a/scripts/lib/antigravity-hooks.js +++ b/scripts/lib/antigravity-hooks.js @@ -22,7 +22,7 @@ function buildAntigravityHooksConfig(options = {}) { if (/[%"!$`\r\n]/.test(bridgeScript)) { throw new Error('bridgeScript contains unsafe shell expansion characters'); } - quotedBridgeScript = bridgeScript.includes(' ') ? `"${bridgeScript}"` : bridgeScript; + quotedBridgeScript = `"${bridgeScript}"`; } else { quotedBridgeScript = shellQuote(bridgeScript); } diff --git a/scripts/lib/install-lifecycle.js b/scripts/lib/install-lifecycle.js index 7da0ae78a..f54809513 100644 --- a/scripts/lib/install-lifecycle.js +++ b/scripts/lib/install-lifecycle.js @@ -7,7 +7,7 @@ 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 { createInstallPlanFromRequest } = require('./install/runtime'); const { assertNoNewUserOwnedFile, prepareUserOwnedFileGuard } = require('./install/ownership-guard'); const { isCodexUserConfig } = require('./install/codex-user-config'); @@ -2364,8 +2364,14 @@ function uninstallInstalledStates(options = {}) { ); } + const adapter = record.adapter && getInstallTargetAdapter(record.adapter.id || record.adapter.target); + const trustedRoots = adapter && typeof adapter.resolveTrustedRoots === 'function' + ? adapter.resolveTrustedRoots({ homeDir: options.homeDir, projectRoot: options.projectRoot }) + : [record.targetRoot]; + for (const operation of operations) { - const outcome = executeUninstallOperation(operation, record.targetRoot, { + const matchingRoot = trustedRoots.find(root => isWithinRoot(operation.destinationPath, root)) || record.targetRoot; + const outcome = executeUninstallOperation(operation, matchingRoot, { preserveDriftedCopies: true, target: record.adapter.target, settingsLockHeld: Boolean(releaseSettingsLock), @@ -2389,7 +2395,8 @@ function uninstallInstalledStates(options = {}) { } for (const cleanupTarget of cleanupTargets) { - cleanupEmptyParentDirs(cleanupTarget, record.targetRoot); + const matchingRoot = trustedRoots.find(root => isWithinRoot(cleanupTarget, root)) || record.targetRoot; + cleanupEmptyParentDirs(cleanupTarget, matchingRoot); } return { diff --git a/scripts/lib/install-manifests.js b/scripts/lib/install-manifests.js index 926948f34..f77a476d5 100644 --- a/scripts/lib/install-manifests.js +++ b/scripts/lib/install-manifests.js @@ -741,6 +741,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 : [], }; diff --git a/scripts/lib/install-targets/antigravity-home.js b/scripts/lib/install-targets/antigravity-home.js index 5e362718d..2be18d0d9 100644 --- a/scripts/lib/install-targets/antigravity-home.js +++ b/scripts/lib/install-targets/antigravity-home.js @@ -39,6 +39,13 @@ module.exports = createInstallTargetAdapter({ installStatePathSegments: ['ecc-install-state.json'], nativeRootRelativePath: '.gemini', excludedSourcePaths: HOME_INSTALL_EXCLUDED_SOURCE_PATHS, + resolveTrustedRoots(input, targetRoot) { + const workflowsRoot = path.join( + path.dirname(path.dirname(targetRoot)), + 'workflows' + ); + return [targetRoot, workflowsRoot]; + }, planOperations(input, adapter) { const modules = Array.isArray(input.modules) ? input.modules @@ -81,11 +88,15 @@ module.exports = createInstallTargetAdapter({ 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(targetRoot, 'workflows', commandRelativePath), + path.join(workflowsRoot, commandRelativePath), 'preserve-relative-path' ), ]; diff --git a/scripts/lib/install-targets/helpers.js b/scripts/lib/install-targets/helpers.js index 5df5ae1c4..dca6b4481 100644 --- a/scripts/lib/install-targets/helpers.js +++ b/scripts/lib/install-targets/helpers.js @@ -329,6 +329,13 @@ function createInstallTargetAdapter(config) { } return path.join(baseRoot, ...config.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, ...config.installStatePathSegments); diff --git a/scripts/lib/install-targets/registry.js b/scripts/lib/install-targets/registry.js index 864a91a22..f50d973db 100644 --- a/scripts/lib/install-targets/registry.js +++ b/scripts/lib/install-targets/registry.js @@ -68,6 +68,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, @@ -80,6 +83,7 @@ function planInstallTargetScaffold(options = {}) { kind: adapter.kind, }, targetRoot, + trustedRoots, installStatePath, validationIssues, operations, diff --git a/scripts/lib/install/apply.js b/scripts/lib/install/apply.js index 1776cb6ca..f08b7f7eb 100644 --- a/scripts/lib/install/apply.js +++ b/scripts/lib/install/apply.js @@ -21,7 +21,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, @@ -248,12 +248,22 @@ function isMcpConfigPath(filePath) { return basename === '.mcp.json' || basename === 'mcp.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 assertSafeInstallOperation(plan, operation) { if (!operation || typeof operation.destinationPath !== 'string') { 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); diff --git a/scripts/lib/install/plan.js b/scripts/lib/install/plan.js index 91774b6e0..64d376ddd 100644 --- a/scripts/lib/install/plan.js +++ b/scripts/lib/install/plan.js @@ -328,6 +328,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] : [], diff --git a/scripts/lib/multi-harness-setup.js b/scripts/lib/multi-harness-setup.js index 141eb4206..2367ac838 100644 --- a/scripts/lib/multi-harness-setup.js +++ b/scripts/lib/multi-harness-setup.js @@ -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; diff --git a/tests/lib/antigravity-tier1.test.js b/tests/lib/antigravity-tier1.test.js index e8e8fa98a..c274f513b 100644 --- a/tests/lib/antigravity-tier1.test.js +++ b/tests/lib/antigravity-tier1.test.js @@ -153,6 +153,7 @@ function runTests() { }); test('hook commands preserve shell metacharacters in the installed path', () => { + if (process.platform === 'win32') return; const dir = createTempDir("ecc space ' $HOME `echo x` "); try { const script = path.join(dir, 'bridge.js'); @@ -353,7 +354,7 @@ function runTests() { // Check workflows assert.ok( plan.operations.some(op => ( - op.destinationPath.startsWith(path.join(targetRoot, 'workflows')) + op.destinationPath.startsWith(path.join(homeDir, '.gemini', 'config', 'workflows')) )), 'Should plan workflows' ); @@ -522,6 +523,7 @@ function runTests() { assert.ok(fs.existsSync(path.join(pluginDir, 'rules', 'common-coding-style.md')), 'rules should exist'); assert.ok(fs.existsSync(path.join(pluginDir, 'skills', 'tdd-workflow', 'SKILL.md')), 'skills should exist'); assert.ok(fs.existsSync(path.join(pluginDir, 'scripts', 'hooks', 'antigravity-hook-bridge.js')), 'hook bridge should exist'); + assert.ok(fs.existsSync(path.join(homeDir, '.gemini', 'config', 'workflows', 'plan.md')), 'workflow plan.md should exist in global workflows dir'); const pluginJson = JSON.parse(fs.readFileSync(path.join(pluginDir, 'plugin.json'), 'utf8')); assert.strictEqual(pluginJson.name, 'ecc'); From 611ec0d3abd59fcfc6d70c7a19030dd4f38ef0a2 Mon Sep 17 00:00:00 2001 From: MohamedAfrash Date: Fri, 25 Sep 2026 03:19:35 +0100 Subject: [PATCH 05/13] fix(antigravity): guard hook stdout json parse to prevent false denials --- scripts/hooks/antigravity-hook-bridge.js | 25 ++++++++++++++----- tests/lib/antigravity-tier1.test.js | 23 +++++++++++++++++ tests/scripts/antigravity-hook-bridge.test.js | 3 +++ 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/scripts/hooks/antigravity-hook-bridge.js b/scripts/hooks/antigravity-hook-bridge.js index 9fa65d7d8..177a0ae0f 100644 --- a/scripts/hooks/antigravity-hook-bridge.js +++ b/scripts/hooks/antigravity-hook-bridge.js @@ -113,19 +113,32 @@ async function main() { 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 = result && (result.stdout || result.output); - const hookOutput = output ? JSON.parse(output).hookSpecificOutput : null; - const denied = result && ((result.exitCode !== undefined && result.exitCode !== 0) || result.denied || result.blocked) - || hookOutput?.permissionDecision === 'deny'; + 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; + ? 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() } : {}), diff --git a/tests/lib/antigravity-tier1.test.js b/tests/lib/antigravity-tier1.test.js index c274f513b..56725d202 100644 --- a/tests/lib/antigravity-tier1.test.js +++ b/tests/lib/antigravity-tier1.test.js @@ -477,6 +477,29 @@ function runTests() { assert.match(output.reason, /completely|input/i); }); + test('antigravity-hook-bridge safely ignores non-JSON hook stdout and allows safe tool call', () => { + const bridgePath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'antigravity-hook-bridge.js'); + const input = JSON.stringify({ + conversationId: 'test-conv', + workspacePaths: ['/tmp'], + toolCall: { + name: 'run_command', + args: { + CommandLine: 'echo safe', + }, + }, + }); + + const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:write:doc-file-warning'], { + input, + encoding: 'utf8', + }); + + assert.strictEqual(run.status, 0); + const output = JSON.parse(run.stdout); + assert.strictEqual(output.decision, 'allow'); + }); + test('antigravity-project plans mcp_config.json when platform configs are selected', () => { const projectRoot = createTempDir('antigravity-proj-mcp-'); try { diff --git a/tests/scripts/antigravity-hook-bridge.test.js b/tests/scripts/antigravity-hook-bridge.test.js index d967bbd63..2393607ba 100644 --- a/tests/scripts/antigravity-hook-bridge.test.js +++ b/tests/scripts/antigravity-hook-bridge.test.js @@ -62,6 +62,9 @@ async function main() { } assert.strictEqual((await invoke({ hook: 'pre:config-protection', child: { status: 0, stderr: '' } })).response.decision, 'allow'); assert.strictEqual((await invoke({ result: '{}' })).response.decision, 'allow'); + assert.strictEqual((await invoke({ result: { exitCode: 0, stdout: 'warning: non-json line' } })).response.decision, 'allow'); + assert.strictEqual((await invoke({ result: { exitCode: 0, output: ['ignored', 'output array'] } })).response.decision, 'allow'); + assert.strictEqual((await invoke({ hook: 'pre:config-protection', child: { status: 0, stdout: 'non-json warning', stderr: '' } })).response.decision, 'allow'); assert.strictEqual((await invoke({ mode: 'stop', raw: '{' })).response.decision, 'allow'); assert.strictEqual((await invoke({ mode: 'post-tool-use', hook: 'post:edit:accumulator' })).hookCalls, 1); assert.strictEqual((await invoke({ mode: 'post-tool-use', hook: 'post:edit:accumulator', raw: JSON.stringify({ error: 'write failed' }) })).hookCalls, 0); From 6443b39a7ae0e7c3d302e0b72c039708a836a440 Mon Sep 17 00:00:00 2001 From: MohamedAfrash Date: Tue, 13 Oct 2026 14:52:53 +0100 Subject: [PATCH 06/13] test: cover Antigravity runtime profile overrides RED: minimal installs omit the warning handler, so selecting strict at runtime cannot enable it. Existing suppression, formatting and managed-profile tests pass. --- tests/scripts/antigravity-hook-policy.test.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/scripts/antigravity-hook-policy.test.js b/tests/scripts/antigravity-hook-policy.test.js index 27a32ab39..0bd564ac9 100644 --- a/tests/scripts/antigravity-hook-policy.test.js +++ b/tests/scripts/antigravity-hook-policy.test.js @@ -6,6 +6,7 @@ const os = require('node:os'); const path = require('node:path'); const { spawnSync } = require('node:child_process'); const { test } = require('node:test'); +const { buildAntigravityHooksConfig } = require('../../scripts/lib/antigravity-hooks'); const bridge = path.resolve(__dirname, '../../scripts/hooks/antigravity-hook-bridge.js'); const controls = [ @@ -15,6 +16,12 @@ const controls = [ { ECC_DRY_RUN: '1' }, ]; +test('minimal installs retain warning handlers for explicit runtime profile overrides', () => { + const config = buildAntigravityHooksConfig({ profile: 'minimal', bridgeScript: bridge }); + assert.ok(config['ecc-guard'].PreToolUse.some(entry => + entry.hooks.some(hook => hook.command.includes('pre:write:doc-file-warning')))); +}); + function invoke(mode, hook, payload, env = {}) { const child = spawnSync(process.execPath, [bridge, '--mode', mode, '--hook', hook], { input: JSON.stringify(payload), encoding: 'utf8', timeout: 15000, From 31ecd4b1c3459c6f1ff9e4e002fec064f33d7ac0 Mon Sep 17 00:00:00 2001 From: MohamedAfrash Date: Tue, 13 Oct 2026 16:23:24 +0100 Subject: [PATCH 07/13] fix: honor Antigravity runtime policy and contain managed installs GREEN: hook policy 4/4, MCP policy 8/8, native Antigravity 1.2.9 import, tier suite 24/24, lifecycle 5/5 plus 73 existing checks. Use shared enable/profile/dry-run decisions and managed setup; stop importing source MCP definitions and filter mcp_config.json. Derive sibling workflow roots for doctor/repair/uninstall and refuse escapes. Restore upstream Claude setup behavior after four migration regressions. Update module targets, carrier schema, unchanged trigger binding, and native validation limits. --- README.md | 2 +- docs/ANTIGRAVITY-GUIDE.md | 52 +++++++++++++- manifests/context-packs/skill-triggers@1.json | 2 +- manifests/install-modules.json | 5 ++ schemas/context-carrier.schema.json | 2 +- scripts/hooks/antigravity-hook-bridge.js | 7 ++ scripts/lib/antigravity-hooks.js | 8 +-- scripts/lib/claude-plugin-setup.js | 20 ++---- scripts/lib/install-lifecycle.js | 3 +- .../lib/install-targets/antigravity-home.js | 50 ++++++-------- .../install-targets/antigravity-project.js | 40 ++++------- scripts/lib/install/apply.js | 2 +- scripts/plan-canvas.js | 1 - tests/lib/antigravity-lifecycle.test.js | 67 +++++++++++++------ tests/lib/antigravity-tier1.test.js | 1 + tests/lib/claude-plugin-setup.test.js | 17 ----- tests/scripts/antigravity-hook-bridge.test.js | 1 + .../scripts/antigravity-native-plugin.test.js | 16 +++-- tests/scripts/codex-hooks.test.js | 1 - 19 files changed, 169 insertions(+), 128 deletions(-) diff --git a/README.md b/README.md index bd9f1f22b..3f0c9e2a6 100644 --- a/README.md +++ b/README.md @@ -1325,7 +1325,7 @@ Treat `stable`, `beta`, `experimental`, and `instruction-only` below as capabili |---|---|---|---| | Claude Code | Stable primary | Plugin or selective installer | The plugin advertises the installed catalog to the model; use a selective/manual profile when context footprint matters. Optional shell-backed skills are not portable to every OS. | | Codex | Supported native plugin | Codex marketplace plugin or repo config | Native hooks require an explicit trust decision and do not use Claude's hook profiles. The legacy sync is compatibility-only. | -| Antigravity | Supported native plugin | Native plugin (`~/.gemini/config/plugins/ecc`) or project `.agents/` | Global native plugin with lifecycle hooks (`PreToolUse`, `PostToolUse`, `Stop`) via protojson bridge, rules, workflows, skills, and memory MCP. | +| Antigravity | Native plugin adapter | Antigravity 2.0/IDE plugin (`~/.gemini/config/plugins/ecc`) or project `.agents/` | Profile-gated lifecycle hooks, rules, workflows, skills, and memory MCP. CLI 1.2.9 validates local import; authenticated native tool and Stop execution remain unverified. | | Qoder | Supported native plugin | Local plugin directory in Qoder CLI or ZIP upload in Qoder IDE | Loads the canonical skills, agents, commands, and MCP config; only the reviewed SessionStart hook is enabled, and Node.js 18+ must be on the non-interactive PATH. | | Cursor | Beta project adapter | Selective installer into `.cursor/` | Agent discovery varies by Cursor build; hook events use profile-gated dispatchers, but full Claude feature parity is not claimed. | | OpenCode | Beta built plugin | Build plugin, then selective installer | ECC ships a subset of the catalog; connect a provider and select a model in OpenCode ([#2617](https://github.com/affaan-m/ECC/issues/2617)). | diff --git a/docs/ANTIGRAVITY-GUIDE.md b/docs/ANTIGRAVITY-GUIDE.md index b498492e7..0ca21be6a 100644 --- a/docs/ANTIGRAVITY-GUIDE.md +++ b/docs/ANTIGRAVITY-GUIDE.md @@ -150,12 +150,12 @@ node "$EccRoot\scripts\uninstall.js" --target antigravity --dry-run - Confirm the files are under `.agents/workflows/`. - Invoke a workflow with `/` after restarting Antigravity. -## Tier 1 Native Plugin and Global Installation (`antigravity-home`) +## Native Plugin and Global Installation (`antigravity-home`) Antigravity supports global plugins located in `~/.gemini/config/plugins//`. Installing ECC as a native Antigravity plugin enables: 1. **Global Scope**: ECC rules, skills, agents, workflows, and memory MCP are active across all projects automatically, without requiring a `.agents/` folder in every repository. -2. **Lifecycle Hooks (`hooks.json`)**: Full support for `PreToolUse` (command security gates, file modification guards), `PostToolUse` edit tracking, and `Stop` formatting and diagnostics using Antigravity's protojson protocol (`{ decision, reason }`). +2. **Lifecycle Hooks (`hooks.json`)**: Handlers for `PreToolUse` command and file guards, `PostToolUse` edit tracking, and `Stop` formatting and diagnostics using Antigravity's protojson protocol (`{ decision, reason }`). 3. **Shared Memory Vault (`mcp_config.json`)**: Direct integration with `ecc-memory-mcp` across all Antigravity sessions. 4. **Native Plugin Manifest (`plugin.json`)**: Declares the ECC plugin metadata. @@ -173,11 +173,23 @@ PowerShell: ``` The installer copies the memory server and its runtime dependencies into the -managed target. Generated hook and MCP commands use absolute installed paths, +managed target. Only ECC memory is included in the generated MCP configuration; +repository `.mcp.json` commands are not imported automatically. Set +`ECC_DISABLED_MCPS=ecc-memory` during installation to omit that server. +Existing MCP entries are preserved on upgrades, including servers generated by +older ECC versions. Review `mcp_config.json` and remove any unwanted existing +entries explicitly; installation does not delete user configuration. +Generated hook and MCP commands use absolute installed paths, so they also work when Antigravity runs from another workspace. Project-local hooks use the same runtime; select `--profile core --enable-hooks` with `--target antigravity`. Use `--no-hooks` to omit automatic hooks. +Choose a hook profile at installation with the existing environment setting, for +example `ECC_HOOK_PROFILE=minimal "$ECC_ROOT/install.sh" --target antigravity-home --profile core --enable-hooks`. +The installer retains it in managed `ecc/setup.json` for runtime execution. +`ECC_HOOK_PROFILE` overrides that profile; `ECC_DISABLED_HOOKS` disables individual +hook IDs, and `ECC_DRY_RUN=1` suppresses hook execution. These controls also apply +to the Antigravity bridge. ### Global Plugin Structure @@ -188,12 +200,46 @@ with `--target antigravity`. Use `--no-hooks` to omit automatic hooks. ├── plugin.json # Antigravity plugin manifest ├── hooks.json # PreToolUse, PostToolUse, and Stop hooks ├── mcp_config.json # Shared ECC Memory Vault MCP server + ├── ecc/setup.json # Managed hook enable/profile configuration ├── rules/ # Rules applied to all workspaces ├── skills/ # Global Agent Skills ├── scripts/ # Hook bridge and memory runtime └── node_modules/ # Memory server dependencies ``` +### Native validation and limits + +Run the optional native check from the ECC source checkout: + +```bash +node tests/scripts/antigravity-native-plugin.test.js +``` + +The test requires an already installed **Antigravity CLI 1.2.9** and skips with an +explicit message if that version is unavailable. It does not download the CLI. +It installs ECC into one temporary home, runs `agy plugin validate`, imports the +local plugin into a separate disposable CLI home with `agy plugin install`, and +checks `agy plugin list --json`. +Every CLI subprocess uses disposable home and configuration directories without +inheriting authentication credentials. The test makes no model requests. + +This validates the CLI's local plugin importer and component registration. +CLI 1.2.9 does not list a manually placed `~/.gemini/config/plugins/ecc` plugin +until explicitly imported; its CLI staging location differs from the Antigravity +2.0 and IDE global location. Importing directly from the same home plugin directory +fails in CLI 1.2.9 because its importer attempts to copy onto the source directory. +The test uses separate install and loader homes to exercise the importer without +that collision; this does not establish in-place CLI activation of the home target. + +The CLI exposes no standalone tool-event or Stop-event runner. The existing +bridge tests check allowed and denied tool payloads and Stop behavior directly; +they do **not** establish native loader execution. Automatic IDE discovery, +allowed and denied tool execution, and Stop execution still require a real +Antigravity session. In Settings > Customizations, verify ECC appears, then use +a disposable workspace to verify an ordinary command proceeds, a destructive +command is denied before execution, and an edit triggers the expected Stop +formatting or diagnostics. Never use valuable files for the denial check. + ## Official Antigravity references - [Skills](https://antigravity.google/docs/skills) diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index a49a8c824..5d980781e 100644 --- a/manifests/context-packs/skill-triggers@1.json +++ b/manifests/context-packs/skill-triggers@1.json @@ -10,7 +10,7 @@ "id": "hand-seeded", "source": "manual-curation-pending-regeneration" }, - "registryDigest": "498caee2738006d64530e9be34883111cf67742d8c4389f39d61299e1a1c4400", + "registryDigest": "25fdb7f75a02286ffddaa5902c0803be09d7e5a9a55797bb9f0224816e3d18e7", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [ diff --git a/manifests/install-modules.json b/manifests/install-modules.json index bf6e9f38b..a26e24358 100644 --- a/manifests/install-modules.json +++ b/manifests/install-modules.json @@ -372,6 +372,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -453,6 +454,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -1397,6 +1399,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -1428,6 +1431,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -1461,6 +1465,7 @@ "cursor", "copilot", "antigravity", + "antigravity-home", "opencode", "codebuddy", "joycode", diff --git a/schemas/context-carrier.schema.json b/schemas/context-carrier.schema.json index 03a48ce67..87905bf48 100644 --- a/schemas/context-carrier.schema.json +++ b/schemas/context-carrier.schema.json @@ -10,7 +10,7 @@ "active": { "const": false }, "disposition": { "const": "proposed" }, "nativeSupport": { "const": "unobserved" }, - "target": { "enum": ["adal", "antigravity", "claude", "claude-project", "codebuddy", "codex", "copilot", "cursor", "gemini", "hermes", "joycode", "kimi", "openclaw", "opencode", "pi", "qwen", "zed"] }, + "target": { "enum": ["adal", "antigravity", "antigravity-home", "claude", "claude-project", "codebuddy", "codex", "copilot", "cursor", "gemini", "hermes", "joycode", "kimi", "openclaw", "opencode", "pi", "qwen", "zed"] }, "profileId": { "enum": ["lean@1", "full@1"] }, "selectionMode": { "enum": ["manual", "suggest", "auto"] }, "registryDigest": { "$ref": "#/definitions/digest" }, diff --git a/scripts/hooks/antigravity-hook-bridge.js b/scripts/hooks/antigravity-hook-bridge.js index 177a0ae0f..5d2699298 100644 --- a/scripts/hooks/antigravity-hook-bridge.js +++ b/scripts/hooks/antigravity-hook-bridge.js @@ -16,6 +16,7 @@ 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 = { @@ -71,6 +72,12 @@ function writeFailure(mode, 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 = ''; diff --git a/scripts/lib/antigravity-hooks.js b/scripts/lib/antigravity-hooks.js index cc496665c..d5977fea7 100644 --- a/scripts/lib/antigravity-hooks.js +++ b/scripts/lib/antigravity-hooks.js @@ -12,7 +12,6 @@ const { shellQuote } = require('./control-pane/actions'); */ function buildAntigravityHooksConfig(options = {}) { - const profile = options.profile || 'standard'; const { bridgeScript } = options; if (typeof bridgeScript !== 'string' || !path.isAbsolute(bridgeScript) || bridgeScript.includes('\0')) { throw new Error('bridgeScript must be an absolute path'); @@ -55,8 +54,8 @@ function buildAntigravityHooksConfig(options = {}) { }, ]; - if (profile === 'standard' || profile === 'strict') { - preToolUseHandlers.push({ + // Runtime hook flags select the profile, including explicit environment overrides. + preToolUseHandlers.push({ matcher: 'write_to_file', hooks: [ { @@ -65,8 +64,7 @@ function buildAntigravityHooksConfig(options = {}) { timeout: 5, }, ], - }); - } + }); const stopHandlers = [ { diff --git a/scripts/lib/claude-plugin-setup.js b/scripts/lib/claude-plugin-setup.js index bde0f3ff6..97f5969b2 100644 --- a/scripts/lib/claude-plugin-setup.js +++ b/scripts/lib/claude-plugin-setup.js @@ -572,7 +572,6 @@ function verifyPluginAtScope(options) { function ensurePluginAtScope(options) { const run = options.run || runClaude; - const configuredHooks = options.hookConfiguration; if (options.installed) { run( ['plugin', 'update', CURRENT_PLUGIN_ID, '--scope', options.scope], @@ -580,17 +579,13 @@ function ensurePluginAtScope(options) { ); return 'updated'; } - const installArgs = [ - 'plugin', 'install', CURRENT_PLUGIN_ID, - '--scope', options.scope, - ]; - if (configuredHooks) { - installArgs.push( - '--config', `hooks_enabled=${configuredHooks.hooks_enabled}`, - '--config', `hook_profile=${configuredHooks.hook_profile}` - ); - } - run(installArgs, { cwd: options.projectRoot, phase: 'plugin-install' }); + run( + [ + 'plugin', 'install', CURRENT_PLUGIN_ID, + '--scope', options.scope, + ], + { cwd: options.projectRoot, phase: 'plugin-install' } + ); return 'installed'; } @@ -660,7 +655,6 @@ function setupClaudePlugin(options = {}, dependencies = {}) { spawnSync: dependencies.spawnSync, }); const action = ensurePluginAtScope({ - hookConfiguration: hookOptions(hooks), hooks, installed: inventory.installed, projectRoot: paths.projectRoot, diff --git a/scripts/lib/install-lifecycle.js b/scripts/lib/install-lifecycle.js index f4fba36b7..76805cfc6 100644 --- a/scripts/lib/install-lifecycle.js +++ b/scripts/lib/install-lifecycle.js @@ -874,7 +874,8 @@ function inspectManagedOperation(repoRoot, trustedRoot, operation, linkIndex = n } function trustedRootForDestination(destinationPath, targetRoot, trustedRoots = [targetRoot]) { - return trustedRoots.find(root => isWithinRoot(destinationPath, root)) || 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]) { diff --git a/scripts/lib/install-targets/antigravity-home.js b/scripts/lib/install-targets/antigravity-home.js index 2be18d0d9..c3a53372a 100644 --- a/scripts/lib/install-targets/antigravity-home.js +++ b/scripts/lib/install-targets/antigravity-home.js @@ -15,21 +15,8 @@ const { const { buildAntigravityHooksConfig } = require('../antigravity-hooks'); const { buildAntigravityMcpConfig, planAntigravityMemoryRuntime } = require('../antigravity-mcp'); const { buildAntigravityPluginManifest } = require('../antigravity-plugin'); - -function readJsonObject(filePath, label) { - let parsed; - try { - parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); - } catch (error) { - throw new Error(`Failed to parse ${label} at ${filePath}: ${error.message}`); - } - - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { - throw new Error(`Invalid ${label} at ${filePath}: expected a JSON object`); - } - - return parsed; -} +const { getHookProfile } = require('../hook-flags'); +const { isWithinRoot } = require('../path-safety'); module.exports = createInstallTargetAdapter({ id: 'antigravity-home', @@ -40,10 +27,11 @@ module.exports = createInstallTargetAdapter({ nativeRootRelativePath: '.gemini', excludedSourcePaths: HOME_INSTALL_EXCLUDED_SOURCE_PATHS, resolveTrustedRoots(input, targetRoot) { - const workflowsRoot = path.join( - path.dirname(path.dirname(targetRoot)), - 'workflows' - ); + 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) { @@ -141,6 +129,7 @@ module.exports = createInstallTargetAdapter({ 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({ @@ -152,10 +141,20 @@ module.exports = createInstallTargetAdapter({ ownership: 'managed', scaffoldOnly: false, mergePayload: buildAntigravityHooksConfig({ - profile: input.hookProfile || 'standard', + 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 } }, + }), ]; } @@ -163,18 +162,9 @@ module.exports = createInstallTargetAdapter({ module.id === 'platform-configs' && (normalizedSourcePath === 'mcp-configs' || normalizedSourcePath === '.mcp.json') ) { - const baseMcp = (repoRoot && fs.existsSync(path.join(repoRoot, '.mcp.json'))) - ? readJsonObject(path.join(repoRoot, '.mcp.json'), '.mcp.json') - : { mcpServers: {} }; const antigravityMcp = buildAntigravityMcpConfig({ memoryScript: path.join(targetRoot, 'scripts', 'memory-mcp.mjs'), }); - const mergedMcp = { - mcpServers: { - ...(baseMcp.mcpServers || {}), - ...(antigravityMcp.mcpServers || {}), - }, - }; const operations = [ createManagedOperation({ @@ -185,7 +175,7 @@ module.exports = createInstallTargetAdapter({ strategy: 'merge-json', ownership: 'managed', scaffoldOnly: false, - mergePayload: mergedMcp, + mergePayload: antigravityMcp, }), createManagedOperation({ kind: 'merge-json', diff --git a/scripts/lib/install-targets/antigravity-project.js b/scripts/lib/install-targets/antigravity-project.js index 647c4eb7d..375976844 100644 --- a/scripts/lib/install-targets/antigravity-project.js +++ b/scripts/lib/install-targets/antigravity-project.js @@ -11,6 +11,7 @@ const { 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', @@ -31,21 +32,6 @@ function supportsAntigravitySourcePath(sourceRelativePath) { )); } -function readJsonObject(filePath, label) { - let parsed; - try { - parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); - } catch (error) { - throw new Error(`Failed to parse ${label} at ${filePath}: ${error.message}`); - } - - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { - throw new Error(`Invalid ${label} at ${filePath}: expected a JSON object`); - } - - return parsed; -} - module.exports = createInstallTargetAdapter({ id: 'antigravity-project', target: 'antigravity', @@ -148,6 +134,7 @@ module.exports = createInstallTargetAdapter({ 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({ @@ -159,10 +146,20 @@ module.exports = createInstallTargetAdapter({ ownership: 'managed', scaffoldOnly: false, mergePayload: buildAntigravityHooksConfig({ - profile: input.hookProfile || 'standard', + 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 } }, + }), ]; } @@ -170,18 +167,9 @@ module.exports = createInstallTargetAdapter({ module.id === 'platform-configs' && (normalizedSourcePath === 'mcp-configs' || normalizedSourcePath === '.mcp.json') ) { - const baseMcp = (repoRoot && fs.existsSync(path.join(repoRoot, '.mcp.json'))) - ? readJsonObject(path.join(repoRoot, '.mcp.json'), '.mcp.json') - : { mcpServers: {} }; const antigravityMcp = buildAntigravityMcpConfig({ memoryScript: path.join(targetRoot, 'scripts', 'memory-mcp.mjs'), }); - const mergedMcp = { - mcpServers: { - ...(baseMcp.mcpServers || {}), - ...(antigravityMcp.mcpServers || {}), - }, - }; const operations = [ createManagedOperation({ @@ -192,7 +180,7 @@ module.exports = createInstallTargetAdapter({ strategy: 'merge-json', ownership: 'managed', scaffoldOnly: false, - mergePayload: mergedMcp, + mergePayload: antigravityMcp, }), createManagedOperation({ kind: 'merge-json', diff --git a/scripts/lib/install/apply.js b/scripts/lib/install/apply.js index cec446c98..82fef1ffd 100644 --- a/scripts/lib/install/apply.js +++ b/scripts/lib/install/apply.js @@ -254,7 +254,7 @@ 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) { diff --git a/scripts/plan-canvas.js b/scripts/plan-canvas.js index 96d075e93..bc8f49d45 100755 --- a/scripts/plan-canvas.js +++ b/scripts/plan-canvas.js @@ -17,7 +17,6 @@ * so stdout stays parseable. */ -const { spawn } = require('child_process'); const fs = require('fs'); const http = require('http'); const path = require('path'); diff --git a/tests/lib/antigravity-lifecycle.test.js b/tests/lib/antigravity-lifecycle.test.js index 84c0692ec..0851c3019 100644 --- a/tests/lib/antigravity-lifecycle.test.js +++ b/tests/lib/antigravity-lifecycle.test.js @@ -8,7 +8,7 @@ const path = require('path'); const { createManifestInstallPlan } = require('../../scripts/lib/install/plan'); const { applyInstallPlan } = require('../../scripts/lib/install/apply'); const { withHookConsent } = require('../../scripts/lib/install/hook-consent'); -const { buildDoctorReport, repairInstalledStates } = require('../../scripts/lib/install-lifecycle'); +const { buildDoctorReport, repairInstalledStates, uninstallInstalledStates } = require('../../scripts/lib/install-lifecycle'); const repoRoot = path.join(__dirname, '..', '..'); const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'antigravity-lifecycle-')); @@ -25,24 +25,7 @@ try { projectRoot, }), 'enabled'); const workflowPath = path.join(homeDir, '.gemini', 'config', 'workflows', 'plan.md'); - const workflowOperation = { - kind: 'copy-file', - moduleId: 'commands-core', - sourcePath: path.join(repoRoot, 'commands', 'plan.md'), - sourceRelativePath: 'commands/plan.md', - destinationPath: workflowPath, - strategy: 'preserve-relative-path', - ownership: 'managed', - scaffoldOnly: false, - }; - applyInstallPlan({ - ...plan, - operations: [...plan.operations, workflowOperation], - statePreview: { - ...plan.statePreview, - operations: [...plan.statePreview.operations, workflowOperation], - }, - }); + applyInstallPlan(plan); const original = fs.readFileSync(workflowPath, 'utf8'); fs.unlinkSync(workflowPath); @@ -77,7 +60,51 @@ try { assert.strictEqual(refused.status, 'error'); assert.match(refused.error, /unsafe managed destination|symlink/i); assert.strictEqual(fs.readFileSync(outsidePath, 'utf8'), 'user content'); - console.log('Results: Passed: 3, Failed: 0'); + + const uninstalled = uninstallInstalledStates({ + homeDir, + projectRoot, + targets: ['antigravity-home'], + }).results[0]; + assert.strictEqual(uninstalled.status, 'partial', uninstalled.error); + assert.ok(uninstalled.retainedPaths.includes(workflowPath)); + assert.ok(fs.lstatSync(workflowPath).isSymbolicLink()); + assert.strictEqual(fs.readFileSync(outsidePath, 'utf8'), 'user content'); + + const symlinkHome = path.join(fixtureRoot, 'symlink-home'); + const symlinkProject = path.join(fixtureRoot, 'symlink-project'); + fs.mkdirSync(symlinkHome); + fs.mkdirSync(symlinkProject); + const symlinkPlan = withHookConsent(createManifestInstallPlan({ + profileId: 'core', + target: 'antigravity-home', + homeDir: symlinkHome, + projectRoot: symlinkProject, + }), 'enabled'); + applyInstallPlan(symlinkPlan); + const workflowsRoot = path.join(symlinkHome, '.gemini', 'config', 'workflows'); + const externalRoot = path.join(fixtureRoot, 'external-workflows'); + fs.renameSync(workflowsRoot, externalRoot); + fs.symlinkSync(externalRoot, workflowsRoot, 'dir'); + const externalWorkflow = path.join(externalRoot, 'plan.md'); + const externalContent = fs.readFileSync(externalWorkflow, 'utf8'); + + assert.throws(() => applyInstallPlan(symlinkPlan), /outside|symlink|trusted/i); + const rootSymlinkRepair = repairInstalledStates({ + repoRoot, + homeDir: symlinkHome, + projectRoot: symlinkProject, + targets: ['antigravity-home'], + }).results[0]; + const rootSymlinkUninstall = uninstallInstalledStates({ + homeDir: symlinkHome, + projectRoot: symlinkProject, + targets: ['antigravity-home'], + }).results[0]; + assert.strictEqual(rootSymlinkRepair.status, 'error'); + assert.strictEqual(rootSymlinkUninstall.status, 'error'); + assert.strictEqual(fs.readFileSync(externalWorkflow, 'utf8'), externalContent); + console.log('Results: Passed: 5, Failed: 0'); } finally { fs.rmSync(fixtureRoot, { recursive: true, force: true }); } diff --git a/tests/lib/antigravity-tier1.test.js b/tests/lib/antigravity-tier1.test.js index 56725d202..1d5ca5034 100644 --- a/tests/lib/antigravity-tier1.test.js +++ b/tests/lib/antigravity-tier1.test.js @@ -380,6 +380,7 @@ function runTests() { const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:bash:dispatcher'], { input, encoding: 'utf8', + env: { ...process.env, GATEGUARD_BASH_ROUTINE_DISABLED: '1' }, }); assert.strictEqual(run.status, 0); diff --git a/tests/lib/claude-plugin-setup.test.js b/tests/lib/claude-plugin-setup.test.js index fa752342b..f80014a45 100644 --- a/tests/lib/claude-plugin-setup.test.js +++ b/tests/lib/claude-plugin-setup.test.js @@ -295,8 +295,6 @@ test('fresh install uses supported Claude arguments and follows the verification [ 'plugin', 'install', 'ecc@ecc', '--scope', 'project', - '--config', 'hooks_enabled=true', - '--config', 'hook_profile=strict', ], ['plugin', 'list', '--json'], ]); @@ -327,19 +325,6 @@ test('fresh installs support all Claude scopes while hook preferences stay user- } }); -test('fresh installs pass disabled hooks to the provider before activation', () => { - withFixture({}, fixture => { - setupClaudePlugin(setupOptions(fixture, { scope: 'user', hooks: 'off' })); - const install = readCalls(fixture).find(argv => argv[1] === 'install'); - assert.deepStrictEqual(install, [ - 'plugin', 'install', 'ecc@ecc', '--scope', 'user', - '--config', 'hooks_enabled=false', '--config', 'hook_profile=standard', - ]); - const settings = JSON.parse(fs.readFileSync(fixture.settingsPath, 'utf8')); - assert.strictEqual(settings.pluginConfigs['ecc@ecc'].options.hooks_enabled, false); - }); -}); - test('same-scope repeat setup updates ECC and changes durable user hook preferences', () => { withFixture({ plugins: [installedPlugin('local')], @@ -747,8 +732,6 @@ test('provider failures stop later operations and leave settings untouched', () const installArgv = [ 'plugin', 'install', 'ecc@ecc', '--scope', 'user', - '--config', 'hooks_enabled=true', - '--config', 'hook_profile=standard', ]; withFixture({ failures: [{ diff --git a/tests/scripts/antigravity-hook-bridge.test.js b/tests/scripts/antigravity-hook-bridge.test.js index 2393607ba..2566de33b 100644 --- a/tests/scripts/antigravity-hook-bridge.test.js +++ b/tests/scripts/antigravity-hook-bridge.test.js @@ -23,6 +23,7 @@ async function invoke({ hook = 'pre:edit-write:gateguard-fact-force', mode = 'pr './doc-file-warning': { run }, './post-edit-accumulator': { run }, './stop-format-typecheck': { run }, + '../lib/hook-flags': { isHookEnabled: () => true, isDryRun: () => false }, './hook-input': { resolveMaxStdin: () => 1024, readStdinRaw: async () => { if (readError) throw new Error('read failed'); return { raw, truncated }; }, diff --git a/tests/scripts/antigravity-native-plugin.test.js b/tests/scripts/antigravity-native-plugin.test.js index 26d1706c3..28f069127 100644 --- a/tests/scripts/antigravity-native-plugin.test.js +++ b/tests/scripts/antigravity-native-plugin.test.js @@ -10,15 +10,17 @@ const { applyInstallPlan } = require('../../scripts/lib/install/apply'); const { withHookConsent } = require('../../scripts/lib/install/hook-consent'); const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-agy-native-')); +const loaderHome = path.join(root, 'loader-home'); +fs.mkdirSync(loaderHome); // Only pass filesystem locations owned by this test; never inherit authentication. const env = { PATH: process.env.PATH, - HOME: root, - USERPROFILE: root, - XDG_CONFIG_HOME: path.join(root, '.config'), - XDG_DATA_HOME: path.join(root, '.local', 'share'), - XDG_CACHE_HOME: path.join(root, '.cache'), - ...(process.platform === 'win32' ? { SystemRoot: process.env.SystemRoot, APPDATA: root, LOCALAPPDATA: root } : {}), + HOME: loaderHome, + USERPROFILE: loaderHome, + XDG_CONFIG_HOME: path.join(loaderHome, '.config'), + XDG_DATA_HOME: path.join(loaderHome, '.local', 'share'), + XDG_CACHE_HOME: path.join(loaderHome, '.cache'), + ...(process.platform === 'win32' ? { SystemRoot: process.env.SystemRoot, APPDATA: loaderHome, LOCALAPPDATA: loaderHome } : {}), }; function agy(args) { @@ -42,7 +44,7 @@ try { profileId: 'core', target: 'antigravity-home', projectRoot: path.join(root, 'workspace'), - homeDir: root, + homeDir: path.join(root, 'install-home'), }), 'enabled'); applyInstallPlan(plan); assert.ok(fs.existsSync(path.join(plan.targetRoot, 'plugin.json'))); diff --git a/tests/scripts/codex-hooks.test.js b/tests/scripts/codex-hooks.test.js index fc31f103d..85e2f31af 100644 --- a/tests/scripts/codex-hooks.test.js +++ b/tests/scripts/codex-hooks.test.js @@ -493,7 +493,6 @@ function runHermeticPythonPrePush({ ECC_PREPUSH_RUN_CHECKS: '1', ECC_SKIP_GIT_HOOKS: '0', ECC_SKIP_PREPUSH: '0', - ECC_PREPUSH_RUN_CHECKS: '1', MSYS_NO_PATHCONV: '1', ...(venvDir === null || trackVenv ? {} : { VIRTUAL_ENV: toBashPath(venvDir) }), ...(override === null ? {} : { ECC_PYTEST_CMD: override }), From dcacfd6eab249d2242be9810567c716d58fffb5a Mon Sep 17 00:00:00 2001 From: MohamedAfrash Date: Tue, 13 Oct 2026 16:44:26 +0100 Subject: [PATCH 08/13] test: reproduce Antigravity opt-out and Stop workspace regressions RED: enabled-to-declined reinstalls retain executable hooks for both targets, including legacy bridges; Stop diagnostics inspect launch cwd instead of payload workspace. Add current/legacy/re-enable/fresh consent controls and disposable workspace diagnostics. --- tests/lib/antigravity-hook-consent.test.js | 102 ++++++++++++++++++ tests/scripts/antigravity-hook-policy.test.js | 35 +++++- 2 files changed, 136 insertions(+), 1 deletion(-) create mode 100644 tests/lib/antigravity-hook-consent.test.js diff --git a/tests/lib/antigravity-hook-consent.test.js b/tests/lib/antigravity-hook-consent.test.js new file mode 100644 index 000000000..97570ac5d --- /dev/null +++ b/tests/lib/antigravity-hook-consent.test.js @@ -0,0 +1,102 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); +const { test } = require('node:test'); +const { createManifestInstallPlan } = require('../../scripts/lib/install/plan'); +const { applyInstallPlan } = require('../../scripts/lib/install/apply'); +const { withHookConsent } = require('../../scripts/lib/install/hook-consent'); + +for (const target of ['antigravity', 'antigravity-home']) { + for (const legacy of [false, true]) { + test(`${target} revokes ${legacy ? 'legacy' : 'current'} hooks and can re-enable them`, () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-hook-consent-')); + try { + const options = { moduleIds: ['hooks-runtime'], target, homeDir: root, projectRoot: root }; + const enabled = withHookConsent(createManifestInstallPlan(options), 'enabled'); + applyInstallPlan(enabled); + const hooksPath = path.join(enabled.targetRoot, 'hooks.json'); + const setupPath = path.join(enabled.targetRoot, 'ecc', 'setup.json'); + const bridgePath = path.join(enabled.targetRoot, 'scripts', 'hooks', 'antigravity-hook-bridge.js'); + const marker = path.join(root, 'hook-ran'); + // Simulate an already installed bridge that predates managed flag support. + if (legacy) { + fs.rmSync(setupPath); + fs.writeFileSync(bridgePath, `require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'ran');`); + } + const config = JSON.parse(fs.readFileSync(hooksPath, 'utf8')); + const userHook = { Stop: [{ type: 'command', command: 'user-selected-hook' }] }; + fs.writeFileSync(hooksPath, JSON.stringify({ ...config, 'user-hook': userHook })); + applyInstallPlan(withHookConsent(createManifestInstallPlan(options), 'declined')); + const declined = JSON.parse(fs.readFileSync(hooksPath, 'utf8')); + assert.deepEqual(declined['user-hook'], userHook); + for (const handler of declined['ecc-guard']?.PostToolUse || []) { + for (const hook of handler.hooks || []) { + const result = spawnSync(hook.command, { + shell: true, cwd: root, encoding: 'utf8', + input: JSON.stringify({ toolCall: { name: 'write_to_file', args: { TargetFile: path.join(root, 'file.js') } } }), + }); + assert.equal(result.status, 0, result.stderr); + } + } + assert.equal(fs.existsSync(marker), false, 'Declined legacy hook must not execute'); + assert.equal(Object.hasOwn(declined, 'ecc-guard'), false); + assert.equal(JSON.parse(fs.readFileSync(setupPath, 'utf8')).hooks.enabled, false); + applyInstallPlan(withHookConsent(createManifestInstallPlan(options), 'declined')); + assert.deepEqual(JSON.parse(fs.readFileSync(hooksPath, 'utf8'))['user-hook'], userHook); + applyInstallPlan(withHookConsent(createManifestInstallPlan(options), 'enabled')); + assert.ok(JSON.parse(fs.readFileSync(hooksPath, 'utf8'))['ecc-guard']); + assert.equal(JSON.parse(fs.readFileSync(setupPath, 'utf8')).hooks.enabled, true); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + } + + for (const unsafe of ['modified-hooks', 'symlinked-setup']) { + test(`${target} refuses ${unsafe} before recording declined consent`, () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-unsafe-revocation-')); + try { + const options = { moduleIds: ['hooks-runtime'], target, homeDir: root, projectRoot: root }; + const enabled = withHookConsent(createManifestInstallPlan(options), 'enabled'); + applyInstallPlan(enabled); + const hooksPath = path.join(enabled.targetRoot, 'hooks.json'); + const setupPath = path.join(enabled.targetRoot, 'ecc', 'setup.json'); + const original = fs.readFileSync(hooksPath, 'utf8'); + if (unsafe === 'modified-hooks') { + const hooks = JSON.parse(original); + fs.writeFileSync(hooksPath, JSON.stringify({ + ...hooks, 'ecc-guard': { ...hooks['ecc-guard'], Stop: [{ command: 'user-customized-hook' }] }, + })); + } else { + fs.rmSync(setupPath); + fs.symlinkSync(path.join(root, 'outside.json'), setupPath); + } + const before = fs.readFileSync(hooksPath, 'utf8'); + assert.throws(() => applyInstallPlan(withHookConsent(createManifestInstallPlan(options), 'declined')), + /modified Antigravity hooks|symlink|outside the install root/i); + assert.equal(fs.readFileSync(hooksPath, 'utf8'), before); + assert.equal(fs.existsSync(path.join(root, 'outside.json')), false); + assert.equal(JSON.parse(fs.readFileSync(enabled.installStatePath, 'utf8')).request.hookConsent, 'enabled'); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + } + + test(`${target} fresh declined installation creates no hook runtime`, () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-fresh-declined-')); + try { + const plan = withHookConsent(createManifestInstallPlan({ moduleIds: ['hooks-runtime'], target, homeDir: root, projectRoot: root }), 'declined'); + applyInstallPlan(plan); + assert.equal(fs.existsSync(path.join(plan.targetRoot, 'hooks.json')), false); + assert.equal(fs.existsSync(path.join(plan.targetRoot, 'ecc', 'setup.json')), false); + assert.equal(fs.existsSync(path.join(plan.targetRoot, 'scripts', 'hooks')), false); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); +} diff --git a/tests/scripts/antigravity-hook-policy.test.js b/tests/scripts/antigravity-hook-policy.test.js index 0bd564ac9..0d791fdf1 100644 --- a/tests/scripts/antigravity-hook-policy.test.js +++ b/tests/scripts/antigravity-hook-policy.test.js @@ -4,7 +4,7 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); -const { spawnSync } = require('node:child_process'); +const { spawnSync, execFileSync } = require('node:child_process'); const { test } = require('node:test'); const { buildAntigravityHooksConfig } = require('../../scripts/lib/antigravity-hooks'); @@ -109,3 +109,36 @@ test('managed profile is used unless an explicit environment choice overrides it fs.rmSync(root, { recursive: true, force: true }); } }); + +test('Stop diagnostics inspect the payload workspace rather than the launch directory', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-agy-stop-cwd-')); + try { + const workspace = path.join(root, 'workspace'); + const unrelated = path.join(root, 'unrelated'); + const env = { + ...process.env, ECC_HOOK_PROFILE: 'standard', ECC_HOOKS_ENABLED: 'true', + ECC_DISABLED_HOOKS: '', ECC_DRY_RUN: '0', ECC_HOOK_CONFIG: '', + GIT_CONFIG_GLOBAL: path.join(root, 'no-global-config'), GIT_CONFIG_NOSYSTEM: '1', + }; + for (const [dir, name] of [[workspace, 'intended.js'], [unrelated, 'unrelated.js']]) { + fs.mkdirSync(dir); + execFileSync('git', ['init', '--quiet', dir], { env }); + fs.writeFileSync(path.join(dir, name), 'const value = 1;\n'); + execFileSync('git', ['-C', dir, 'add', name], { env }); + fs.appendFileSync(path.join(dir, name), 'console.log(value);\n'); + } + for (const cwd of [root, unrelated]) { + const child = spawnSync(process.execPath, [bridge, '--mode', 'stop', '--hook', 'stop:check-console-log'], { + cwd, env, encoding: 'utf8', timeout: 15000, + input: JSON.stringify({ workspacePaths: [workspace], fullyIdle: true }), + }); + assert.equal(child.status, 0, child.stderr); + const response = JSON.parse(child.stdout); + assert.equal(response.decision, 'continue'); + assert.match(response.reason, /intended\.js/); + assert.doesNotMatch(response.reason, /unrelated\.js/); + } + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); From 80558fe144e8de82fd74426c09bc54f38b3a6e7d Mon Sep 17 00:00:00 2001 From: MohamedAfrash Date: Tue, 13 Oct 2026 16:55:26 +0100 Subject: [PATCH 09/13] fix: deactivate opted-out Antigravity hooks and use workspace diagnostics GREEN: 14 consent cases cover current/legacy upgrades, fresh decline, re-enable, retry, dry-run and symlink races; 48 installer checks and 8 MCP policy cases pass. Stop workspace regression fails under original execution and passes with payload cwd; uninstall defaults match discovery. Keep deactivation operations ephemeral and use guarded no-follow CAS writes before recording declined consent. Preserve custom user namespaces and refuse modified ECC registrations. Native test emits countable pass/skip summaries. --- docs/ANTIGRAVITY-GUIDE.md | 4 + scripts/hooks/antigravity-hook-bridge.js | 1 + scripts/lib/install-lifecycle.js | 13 ++- scripts/lib/install/apply.js | 97 ++++++++++++++++++- scripts/lib/install/hook-consent.js | 6 ++ tests/lib/antigravity-hook-consent.test.js | 54 +++++++++-- tests/lib/antigravity-lifecycle.test.js | 26 ++++- tests/scripts/antigravity-hook-policy.test.js | 2 + .../scripts/antigravity-native-plugin.test.js | 2 + 9 files changed, 190 insertions(+), 15 deletions(-) diff --git a/docs/ANTIGRAVITY-GUIDE.md b/docs/ANTIGRAVITY-GUIDE.md index 0ca21be6a..87e16b584 100644 --- a/docs/ANTIGRAVITY-GUIDE.md +++ b/docs/ANTIGRAVITY-GUIDE.md @@ -184,6 +184,10 @@ so they also work when Antigravity runs from another workspace. Project-local hooks use the same runtime; select `--profile core --enable-hooks` with `--target antigravity`. Use `--no-hooks` to omit automatic hooks. +On reinstall, `--no-hooks` also deactivates previously installed ECC hooks, +including legacy bridges. Other hook namespaces are preserved. If the managed +`ecc-guard` registration was customized, installation refuses the change; +review that customization before retrying. Choose a hook profile at installation with the existing environment setting, for example `ECC_HOOK_PROFILE=minimal "$ECC_ROOT/install.sh" --target antigravity-home --profile core --enable-hooks`. The installer retains it in managed `ecc/setup.json` for runtime execution. diff --git a/scripts/hooks/antigravity-hook-bridge.js b/scripts/hooks/antigravity-hook-bridge.js index 5d2699298..485a2c457 100644 --- a/scripts/hooks/antigravity-hook-bridge.js +++ b/scripts/hooks/antigravity-hook-bridge.js @@ -178,6 +178,7 @@ async function main() { 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, }); diff --git a/scripts/lib/install-lifecycle.js b/scripts/lib/install-lifecycle.js index 76805cfc6..391d1bc0b 100644 --- a/scripts/lib/install-lifecycle.js +++ b/scripts/lib/install-lifecycle.js @@ -1951,11 +1951,14 @@ function repairInstalledStates(options = {}) { 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 => { @@ -2014,7 +2017,7 @@ function uninstallInstalledStates(options = {}) { const adapter = record.adapter && getInstallTargetAdapter(record.adapter.id || record.adapter.target); const trustedRoots = adapter && typeof adapter.resolveTrustedRoots === 'function' - ? adapter.resolveTrustedRoots({ homeDir: options.homeDir, projectRoot: options.projectRoot }) + ? adapter.resolveTrustedRoots(context) : [record.targetRoot]; const { isScriptBoundary, retainScriptBoundary } = require('./install/opencode-script-boundary'); diff --git a/scripts/lib/install/apply.js b/scripts/lib/install/apply.js index 82fef1ffd..9c955029d 100644 --- a/scripts/lib/install/apply.js +++ b/scripts/lib/install/apply.js @@ -3,6 +3,7 @@ const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); +const { isDeepStrictEqual } = require('util'); const { hasExplicitCommitAttributionPreference, @@ -18,6 +19,7 @@ const { getOpenCodeSourceActivationKind, planMaterializesHookRuntime, shouldDisableOpenCodeHooks, + shouldDisableAntigravityHooks, } = require('./hook-consent'); const { getClaudeSettingsPath, @@ -83,10 +85,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; @@ -629,6 +631,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); @@ -658,6 +722,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') @@ -845,6 +912,32 @@ function applyInstallPlanLocked(plan, dependencies = {}, settingsLockHeld = fals } 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' diff --git a/scripts/lib/install/hook-consent.js b/scripts/lib/install/hook-consent.js index c7a82a227..9fcc0a49f 100644 --- a/scripts/lib/install/hook-consent.js +++ b/scripts/lib/install/hook-consent.js @@ -216,6 +216,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; @@ -340,5 +345,6 @@ module.exports = { planMaterializesHookRuntime, resolveHookConsentFlags, shouldDisableOpenCodeHooks, + shouldDisableAntigravityHooks, withHookConsent, }; diff --git a/tests/lib/antigravity-hook-consent.test.js b/tests/lib/antigravity-hook-consent.test.js index 97570ac5d..88ad5f163 100644 --- a/tests/lib/antigravity-hook-consent.test.js +++ b/tests/lib/antigravity-hook-consent.test.js @@ -7,7 +7,8 @@ const path = require('node:path'); const { spawnSync } = require('node:child_process'); const { test } = require('node:test'); const { createManifestInstallPlan } = require('../../scripts/lib/install/plan'); -const { applyInstallPlan } = require('../../scripts/lib/install/apply'); +const { applyInstallPlan, previewInstallPlan } = require('../../scripts/lib/install/apply'); +const { readInstallState } = require('../../scripts/lib/install-state'); const { withHookConsent } = require('../../scripts/lib/install/hook-consent'); for (const target of ['antigravity', 'antigravity-home']) { @@ -30,7 +31,13 @@ for (const target of ['antigravity', 'antigravity-home']) { const config = JSON.parse(fs.readFileSync(hooksPath, 'utf8')); const userHook = { Stop: [{ type: 'command', command: 'user-selected-hook' }] }; fs.writeFileSync(hooksPath, JSON.stringify({ ...config, 'user-hook': userHook })); - applyInstallPlan(withHookConsent(createManifestInstallPlan(options), 'declined')); + const declinePlan = withHookConsent(createManifestInstallPlan(options), 'declined'); + const beforePreview = fs.readFileSync(hooksPath, 'utf8'); + const preview = previewInstallPlan(declinePlan); + assert.ok(preview.operations.some(operation => operation.kind === 'remove-antigravity-hooks')); + assert.ok(preview.warnings.some(warning => /disabl.*Antigravity hooks/i.test(warning))); + assert.equal(fs.readFileSync(hooksPath, 'utf8'), beforePreview); + applyInstallPlan(declinePlan); const declined = JSON.parse(fs.readFileSync(hooksPath, 'utf8')); assert.deepEqual(declined['user-hook'], userHook); for (const handler of declined['ecc-guard']?.PostToolUse || []) { @@ -45,6 +52,7 @@ for (const target of ['antigravity', 'antigravity-home']) { assert.equal(fs.existsSync(marker), false, 'Declined legacy hook must not execute'); assert.equal(Object.hasOwn(declined, 'ecc-guard'), false); assert.equal(JSON.parse(fs.readFileSync(setupPath, 'utf8')).hooks.enabled, false); + assert.equal(readInstallState(enabled.installStatePath).request.hookConsent, 'declined'); applyInstallPlan(withHookConsent(createManifestInstallPlan(options), 'declined')); assert.deepEqual(JSON.parse(fs.readFileSync(hooksPath, 'utf8'))['user-hook'], userHook); applyInstallPlan(withHookConsent(createManifestInstallPlan(options), 'enabled')); @@ -56,8 +64,11 @@ for (const target of ['antigravity', 'antigravity-home']) { }); } - for (const unsafe of ['modified-hooks', 'symlinked-setup']) { - test(`${target} refuses ${unsafe} before recording declined consent`, () => { + for (const unsafe of ['modified-hooks', 'symlinked-setup', 'swapped-setup']) { + test(`${target} refuses ${unsafe} before recording declined consent`, { + skip: process.platform === 'win32' && unsafe !== 'modified-hooks' + ? 'Creating file symlinks requires Windows developer mode or elevation' : false, + }, () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-unsafe-revocation-')); try { const options = { moduleIds: ['hooks-runtime'], target, homeDir: root, projectRoot: root }; @@ -71,14 +82,21 @@ for (const target of ['antigravity', 'antigravity-home']) { fs.writeFileSync(hooksPath, JSON.stringify({ ...hooks, 'ecc-guard': { ...hooks['ecc-guard'], Stop: [{ command: 'user-customized-hook' }] }, })); - } else { + } else if (unsafe === 'symlinked-setup') { fs.rmSync(setupPath); fs.symlinkSync(path.join(root, 'outside.json'), setupPath); } const before = fs.readFileSync(hooksPath, 'utf8'); - assert.throws(() => applyInstallPlan(withHookConsent(createManifestInstallPlan(options), 'declined')), + assert.throws(() => applyInstallPlan(withHookConsent(createManifestInstallPlan(options), 'declined'), { + beforeOperationWrite({ operation }) { + if (unsafe === 'swapped-setup' && operation.destinationPath === setupPath) { + fs.rmSync(setupPath); + fs.symlinkSync(path.join(root, 'outside.json'), setupPath); + } + }, + }), /modified Antigravity hooks|symlink|outside the install root/i); - assert.equal(fs.readFileSync(hooksPath, 'utf8'), before); + if (unsafe !== 'swapped-setup') assert.equal(fs.readFileSync(hooksPath, 'utf8'), before); assert.equal(fs.existsSync(path.join(root, 'outside.json')), false); assert.equal(JSON.parse(fs.readFileSync(enabled.installStatePath, 'utf8')).request.hookConsent, 'enabled'); } finally { @@ -99,4 +117,26 @@ for (const target of ['antigravity', 'antigravity-home']) { fs.rmSync(root, { recursive: true, force: true }); } }); + + test(`${target} failed deactivation does not record declined consent`, () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-decline-failure-')); + try { + const options = { moduleIds: ['hooks-runtime'], target, homeDir: root, projectRoot: root }; + const enabled = withHookConsent(createManifestInstallPlan(options), 'enabled'); + applyInstallPlan(enabled); + const declined = withHookConsent(createManifestInstallPlan(options), 'declined'); + assert.throws(() => applyInstallPlan(declined, { + beforeOperationWrite({ operation }) { + if (operation.destinationPath === path.join(enabled.targetRoot, 'ecc', 'setup.json')) { + throw new Error('injected setup write failure'); + } + }, + }), /injected setup write failure/); + assert.equal(readInstallState(enabled.installStatePath).request.hookConsent, 'enabled'); + applyInstallPlan(declined); + assert.equal(readInstallState(enabled.installStatePath).request.hookConsent, 'declined'); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); } diff --git a/tests/lib/antigravity-lifecycle.test.js b/tests/lib/antigravity-lifecycle.test.js index 0851c3019..4ee9801b8 100644 --- a/tests/lib/antigravity-lifecycle.test.js +++ b/tests/lib/antigravity-lifecycle.test.js @@ -104,7 +104,31 @@ try { assert.strictEqual(rootSymlinkRepair.status, 'error'); assert.strictEqual(rootSymlinkUninstall.status, 'error'); assert.strictEqual(fs.readFileSync(externalWorkflow, 'utf8'), externalContent); - console.log('Results: Passed: 5, Failed: 0'); + + const defaultHome = path.join(fixtureRoot, 'default-home'); + const defaultProject = path.join(fixtureRoot, 'default-project'); + fs.mkdirSync(defaultHome); + fs.mkdirSync(defaultProject); + applyInstallPlan(withHookConsent(createManifestInstallPlan({ + profileId: 'core', + target: 'antigravity', + homeDir: defaultHome, + projectRoot: defaultProject, + }), 'enabled')); + const previousHome = process.env.HOME; + const previousCwd = process.cwd(); + try { + process.env.HOME = defaultHome; + process.chdir(defaultProject); + const defaultUninstall = uninstallInstalledStates({ targets: ['antigravity'] }).results[0]; + assert.strictEqual(defaultUninstall.status, 'uninstalled', defaultUninstall.error); + assert.ok(!fs.existsSync(path.join(defaultProject, '.agents', 'ecc-install-state.json'))); + } finally { + process.chdir(previousCwd); + if (previousHome === undefined) delete process.env.HOME; + else process.env.HOME = previousHome; + } + console.log('Results: Passed: 6, Failed: 0'); } finally { fs.rmSync(fixtureRoot, { recursive: true, force: true }); } diff --git a/tests/scripts/antigravity-hook-policy.test.js b/tests/scripts/antigravity-hook-policy.test.js index 0d791fdf1..f232c269f 100644 --- a/tests/scripts/antigravity-hook-policy.test.js +++ b/tests/scripts/antigravity-hook-policy.test.js @@ -125,6 +125,8 @@ test('Stop diagnostics inspect the payload workspace rather than the launch dire execFileSync('git', ['init', '--quiet', dir], { env }); fs.writeFileSync(path.join(dir, name), 'const value = 1;\n'); execFileSync('git', ['-C', dir, 'add', name], { env }); + execFileSync('git', ['-C', dir, '-c', 'user.name=ECC fixture', '-c', 'user.email=fixture@example.invalid', + '-c', 'commit.gpgSign=false', 'commit', '--quiet', '-m', 'fixture'], { env }); fs.appendFileSync(path.join(dir, name), 'console.log(value);\n'); } for (const cwd of [root, unrelated]) { diff --git a/tests/scripts/antigravity-native-plugin.test.js b/tests/scripts/antigravity-native-plugin.test.js index 28f069127..241e1d1d3 100644 --- a/tests/scripts/antigravity-native-plugin.test.js +++ b/tests/scripts/antigravity-native-plugin.test.js @@ -37,6 +37,7 @@ try { const version = agy(['--version']); if (version.error?.code === 'ENOENT' || (version.status === 0 && version.stdout.trim() !== '1.2.9')) { console.log(`SKIP: native plugin validation requires installed agy 1.2.9 (found ${version.stdout?.trim() || 'none'}); no download attempted.`); + console.log('Results: Passed: 0, Failed: 0'); } else { assert.strictEqual(version.status, 0, version.error?.message || version.stderr); const plan = withHookConsent(createManifestInstallPlan({ @@ -58,6 +59,7 @@ try { assert.ok(plugin.components.includes('mcpServers'), 'Native importer must register ECC memory'); console.log('PASS: agy 1.2.9 validates and imports the generated ECC plugin in a disposable HOME.'); console.log('NOT CHECKED: authenticated tool execution, Stop execution, and automatic IDE discovery.'); + console.log('Results: Passed: 1, Failed: 0'); } } finally { fs.rmSync(root, { recursive: true, force: true }); From f8a10d84ff7e9f5681dfcbf16c10356633be9a23 Mon Sep 17 00:00:00 2001 From: MohamedAfrash Date: Thu, 15 Oct 2026 17:44:17 +0100 Subject: [PATCH 10/13] test: pin Antigravity native validation to CLI 1.3.5 --- docs/ANTIGRAVITY-GUIDE.md | 2 +- tests/scripts/antigravity-native-plugin.test.js | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/ANTIGRAVITY-GUIDE.md b/docs/ANTIGRAVITY-GUIDE.md index 87e16b584..aab304dd6 100644 --- a/docs/ANTIGRAVITY-GUIDE.md +++ b/docs/ANTIGRAVITY-GUIDE.md @@ -219,7 +219,7 @@ Run the optional native check from the ECC source checkout: node tests/scripts/antigravity-native-plugin.test.js ``` -The test requires an already installed **Antigravity CLI 1.2.9** and skips with an +The test requires an already installed **Antigravity CLI 1.3.5** and skips with an explicit message if that version is unavailable. It does not download the CLI. It installs ECC into one temporary home, runs `agy plugin validate`, imports the local plugin into a separate disposable CLI home with `agy plugin install`, and diff --git a/tests/scripts/antigravity-native-plugin.test.js b/tests/scripts/antigravity-native-plugin.test.js index 241e1d1d3..e2515b338 100644 --- a/tests/scripts/antigravity-native-plugin.test.js +++ b/tests/scripts/antigravity-native-plugin.test.js @@ -35,8 +35,8 @@ function checked(args) { try { const version = agy(['--version']); - if (version.error?.code === 'ENOENT' || (version.status === 0 && version.stdout.trim() !== '1.2.9')) { - console.log(`SKIP: native plugin validation requires installed agy 1.2.9 (found ${version.stdout?.trim() || 'none'}); no download attempted.`); + if (version.error?.code === 'ENOENT' || (version.status === 0 && version.stdout.trim() !== '1.3.5')) { + console.log(`SKIP: native plugin validation requires installed agy 1.3.5 (found ${version.stdout?.trim() || 'none'}); no download attempted.`); console.log('Results: Passed: 0, Failed: 0'); } else { assert.strictEqual(version.status, 0, version.error?.message || version.stderr); @@ -53,11 +53,11 @@ try { assert.match(validation, /\[ok\]/); checked(['plugin', 'install', plan.targetRoot]); const listed = JSON.parse(checked(['plugin', 'list', '--json'])); - const plugin = listed.imports.find(entry => entry.name === 'ecc'); + const plugin = listed.find(entry => entry.name === 'ecc'); assert.ok(plugin, 'Native CLI must discover ECC after explicit local import'); - assert.ok(plugin.components.includes('hooks'), 'Native importer must register lifecycle hooks'); - assert.ok(plugin.components.includes('mcpServers'), 'Native importer must register ECC memory'); - console.log('PASS: agy 1.2.9 validates and imports the generated ECC plugin in a disposable HOME.'); + assert.ok(plugin.hooks.includes('ecc-guard'), 'Native importer must register lifecycle hooks'); + assert.ok(plugin.mcpServers.includes('ecc-memory'), 'Native importer must register ECC memory'); + console.log('PASS: agy 1.3.5 validates and imports the generated ECC plugin in a disposable HOME.'); console.log('NOT CHECKED: authenticated tool execution, Stop execution, and automatic IDE discovery.'); console.log('Results: Passed: 1, Failed: 0'); } From ca70aa2ff3c7162a8f1ab13f59913edf48e15666 Mon Sep 17 00:00:00 2001 From: MohamedAfrash Date: Mon, 26 Oct 2026 12:59:08 +0000 Subject: [PATCH 11/13] fix: record Antigravity memory dependencies as repairable package sources When npm hoists ajv beside ecc-universal, path.relative(repoRoot, ...) recorded sources like ../ajv/..., which doctor flags as unsafe-repair-source and repair refuses. Record dependency sources as node_modules/[/node_modules/...]/, mirroring the installed layout, and resolve each package from the repository with Node module resolution at plan and repair time. Paths still reject traversal, absolute paths, and malformed package names, and resolved files must stay inside their package root. Co-Authored-By: Claude Opus 5.5 --- scripts/lib/antigravity-mcp.js | 8 ++- scripts/lib/install-lifecycle.js | 12 ++++ scripts/lib/install/package-source.js | 64 ++++++++++++++++++++ scripts/lib/install/plan.js | 7 ++- tests/lib/antigravity-tier1.test.js | 19 ++++++ tests/lib/package-source.test.js | 85 +++++++++++++++++++++++++++ 6 files changed, 190 insertions(+), 5 deletions(-) create mode 100644 scripts/lib/install/package-source.js create mode 100644 tests/lib/package-source.test.js diff --git a/scripts/lib/antigravity-mcp.js b/scripts/lib/antigravity-mcp.js index a8689630a..54a347931 100644 --- a/scripts/lib/antigravity-mcp.js +++ b/scripts/lib/antigravity-mcp.js @@ -3,6 +3,7 @@ const fs = require('fs'); const path = require('path'); const { createManagedScaffoldOperation } = require('./install-targets/helpers'); +const { formatPackageSourcePath } = require('./install/package-source'); /** * Antigravity MCP Configuration Generator @@ -42,7 +43,7 @@ function planAntigravityMemoryRuntime(moduleId, repoRoot, targetRoot) { const operations = sourcePaths.map(sourcePath => createManagedScaffoldOperation( moduleId, sourcePath, path.join(targetRoot, sourcePath), 'preserve-relative-path' )); - function addDependency(name, fromRoot, destinationRoot, ancestors = []) { + function addDependency(name, fromRoot, destinationRoot, ancestors = [], packageChain = []) { let manifestPath; try { manifestPath = require.resolve(`${name}/package.json`, { paths: [fromRoot] }); @@ -52,12 +53,13 @@ function planAntigravityMemoryRuntime(moduleId, repoRoot, targetRoot) { 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, path.relative(repoRoot, packageRoot), destinationPath, 'preserve-relative-path' + 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]); + addDependency(dependency, packageRoot, destinationPath, [...ancestors, manifestPath], sourceChain); } } addDependency('ajv', repoRoot, targetRoot); diff --git a/scripts/lib/install-lifecycle.js b/scripts/lib/install-lifecycle.js index 74e69f3a3..a4d0854bc 100644 --- a/scripts/lib/install-lifecycle.js +++ b/scripts/lib/install-lifecycle.js @@ -8,6 +8,7 @@ const { isDeepStrictEqual } = require('util'); const { loadInstallManifests } = require('./install-manifests'); const { readInstallState, validateInstallState } = require('./install-state'); 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'); @@ -194,6 +195,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 diff --git a/scripts/lib/install/package-source.js b/scripts/lib/install/package-source.js new file mode 100644 index 000000000..744a2f334 --- /dev/null +++ b/scripts/lib/install/package-source.js @@ -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/[/node_modules/...]/` 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, +}; diff --git a/scripts/lib/install/plan.js b/scripts/lib/install/plan.js index 0f4df094a..624ffaf52 100644 --- a/scripts/lib/install/plan.js +++ b/scripts/lib/install/plan.js @@ -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'); @@ -181,8 +182,10 @@ function materializeScaffoldOperation(sourceRoot, operation) { ]; } - 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 []; } diff --git a/tests/lib/antigravity-tier1.test.js b/tests/lib/antigravity-tier1.test.js index 1d5ca5034..6cf035f7c 100644 --- a/tests/lib/antigravity-tier1.test.js +++ b/tests/lib/antigravity-tier1.test.js @@ -242,6 +242,25 @@ function runTests() { const { applyInstallPlan } = require('../../scripts/lib/install/apply'); const plan = createManifestInstallPlan({ sourceRoot, moduleIds: ['platform-configs'], target: 'antigravity', projectRoot }); applyInstallPlan(plan); + + const state = JSON.parse(fs.readFileSync(plan.installStatePath, 'utf8')); + const dependencySources = state.operations + .map(operation => operation.sourceRelativePath || '') + .filter(source => source.split(/[/\\]+/)[0] === 'node_modules'); + assert.ok(dependencySources.length > 0); + assert.ok(state.operations.every(operation => !String(operation.sourceRelativePath || '').split(/[/\\]+/).includes('..'))); + + const { buildDoctorReport, repairInstalledStates } = require('../../scripts/lib/install-lifecycle'); + const lifecycleOptions = { repoRoot: sourceRoot, homeDir: path.join(root, 'home'), projectRoot, targets: ['antigravity'] }; + const doctor = buildDoctorReport(lifecycleOptions).results[0]; + assert.ok(!doctor.issues.some(issue => issue.code === 'unsafe-repair-source'), JSON.stringify(doctor.issues)); + const installedAjv = path.join(plan.targetRoot, 'node_modules', 'ajv', 'package.json'); + const originalAjv = fs.readFileSync(installedAjv, 'utf8'); + fs.unlinkSync(installedAjv); + const repaired = repairInstalledStates(lifecycleOptions).results[0]; + assert.strictEqual(repaired.status, 'repaired', repaired.error); + assert.strictEqual(fs.readFileSync(installedAjv, 'utf8'), originalAjv); + fs.rmSync(path.join(root, 'node_modules'), { recursive: true }); const run = spawnSync(process.execPath, [path.join(plan.targetRoot, 'scripts/memory-mcp.mjs')], { cwd: root, diff --git a/tests/lib/package-source.test.js b/tests/lib/package-source.test.js new file mode 100644 index 000000000..b5ed1fc59 --- /dev/null +++ b/tests/lib/package-source.test.js @@ -0,0 +1,85 @@ +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const { + formatPackageSourcePath, + isPackageSourcePath, + parsePackageSourcePath, + resolvePackageSourcePath, +} = require('../../scripts/lib/install/package-source'); + +let passed = 0; +let failed = 0; + +function test(name, fn) { + try { + fn(); + console.log(` ✓ ${name}`); + passed += 1; + } catch (error) { + console.log(` ✗ ${name}`); + console.log(` Error: ${error.message}`); + failed += 1; + } +} + +function writePackage(packageRoot, name, files = {}) { + fs.mkdirSync(packageRoot, { recursive: true }); + fs.writeFileSync(path.join(packageRoot, 'package.json'), JSON.stringify({ name, version: '1.0.0' })); + for (const [relativePath, content] of Object.entries(files)) { + fs.mkdirSync(path.dirname(path.join(packageRoot, relativePath)), { recursive: true }); + fs.writeFileSync(path.join(packageRoot, relativePath), content); + } +} + +console.log('\n=== Testing install/package-source.js ===\n'); + +test('formats package chains as the installed node_modules layout', () => { + assert.strictEqual(formatPackageSourcePath(['ajv']), 'node_modules/ajv'); + assert.strictEqual( + formatPackageSourcePath(['ajv', '@scope/dep'], 'dist\\index.js'), + 'node_modules/ajv/node_modules/@scope/dep/dist/index.js' + ); +}); + +test('recognizes only node_modules-rooted sources', () => { + assert.strictEqual(isPackageSourcePath('node_modules/ajv/package.json'), true); + assert.strictEqual(isPackageSourcePath('scripts/node_modules/x.js'), false); + assert.strictEqual(isPackageSourcePath(undefined), false); +}); + +test('rejects traversal and malformed package names', () => { + for (const source of [ + 'node_modules/ajv/../../secret', + 'node_modules/../etc/passwd', + 'node_modules/ajv/./x', + 'node_modules/Bad Name/x', + 'node_modules/@scope', + 'node_modules', + ]) { + assert.throws(() => parsePackageSourcePath(source), /Invalid package source path/, source); + } +}); + +test('resolves hoisted sibling packages through Node resolution', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-package-source-')); + try { + const repoRoot = path.join(root, 'node_modules', 'ecc-universal'); + writePackage(repoRoot, 'ecc-universal'); + writePackage(path.join(root, 'node_modules', 'dep-a'), 'dep-a', { 'lib/a.js': 'a' }); + writePackage(path.join(root, 'node_modules', 'dep-b'), 'dep-b', { 'b.js': 'b' }); + + const resolved = resolvePackageSourcePath(repoRoot, 'node_modules/dep-a/node_modules/dep-b/b.js'); + assert.strictEqual(fs.realpathSync(resolved), fs.realpathSync(path.join(root, 'node_modules', 'dep-b', 'b.js'))); + assert.strictEqual(resolvePackageSourcePath(repoRoot, 'node_modules/ecc-missing-package/x.js'), null); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`); +process.exit(failed > 0 ? 1 : 0); From f98320f140d784be90e7bce30d64f07ead6a4fd3 Mon Sep 17 00:00:00 2001 From: haelyra Date: Mon, 16 Nov 2026 21:02:31 -0500 Subject: [PATCH 12/13] fix(antigravity): keep doctor reporting when one target root is unsafe An Antigravity home whose workflows directory resolves outside the trusted config root made resolveTrustedRoots throw out of the doctor loop, hiding results for every other installed target. Report it as an unsafe-trusted-root error for that target instead, with a regression. Also align the README support row with the pinned CLI 1.3.5 validation and leave the shipped 2.2.0 release notes unchanged. --- README.md | 2 +- docs/releases/2.2.0/release-notes.md | 2 +- scripts/lib/install-lifecycle.js | 11 +++++++++-- tests/lib/antigravity-lifecycle.test.js | 21 ++++++++++++++++++++- 4 files changed, 31 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 559c3448d..823d1dc9d 100644 --- a/README.md +++ b/README.md @@ -1331,7 +1331,7 @@ Treat `stable`, `beta`, `experimental`, and `instruction-only` below as capabili |---|---|---|---| | Claude Code | Stable primary | Plugin or selective installer | The plugin advertises the installed catalog to the model; use a selective/manual profile when context footprint matters. Optional shell-backed skills are not portable to every OS. | | Codex | Supported native plugin | Codex marketplace plugin or repo config | Native hooks require an explicit trust decision and do not use Claude's hook profiles. The legacy sync is compatibility-only. | -| Antigravity | Native plugin adapter | Antigravity 2.0/IDE plugin (`~/.gemini/config/plugins/ecc`) or project `.agents/` | Profile-gated lifecycle hooks, rules, workflows, skills, and memory MCP. CLI 1.2.9 validates local import; authenticated native tool and Stop execution remain unverified. | +| Antigravity | Native plugin adapter | Antigravity 2.0/IDE plugin (`~/.gemini/config/plugins/ecc`) or project `.agents/` | Profile-gated lifecycle hooks, rules, workflows, skills, and memory MCP. CLI 1.3.5 validates local import; authenticated native tool and Stop execution remain unverified. | | Qoder | Supported native plugin | Local plugin directory in Qoder CLI or ZIP upload in Qoder IDE | Loads the canonical skills, agents, commands, and MCP config; only the reviewed SessionStart hook is enabled, and Node.js 18+ must be on the non-interactive PATH. | | Cursor | Beta project adapter | Selective installer into `.cursor/` | Agent discovery varies by Cursor build; hook events use profile-gated dispatchers, but full Claude feature parity is not claimed. | | OpenCode | Beta built plugin | Build plugin, then selective installer | ECC ships a subset of the catalog; connect a provider and select a model in OpenCode ([#2617](https://github.com/affaan-m/ECC/issues/2617)). | diff --git a/docs/releases/2.2.0/release-notes.md b/docs/releases/2.2.0/release-notes.md index 447cd6379..6aa336ddf 100644 --- a/docs/releases/2.2.0/release-notes.md +++ b/docs/releases/2.2.0/release-notes.md @@ -32,7 +32,7 @@ Install or update the published package, then run the same ECC install command y ```bash npm install -g ecc-universal@2.2.0 -ecc install --target antigravity --profile full --enable-hooks +ecc install --target antigravity --profile full ``` Use `ecc doctor --target ` after installation. For Antigravity, start a new conversation and verify workspace skills under Settings > Customizations. diff --git a/scripts/lib/install-lifecycle.js b/scripts/lib/install-lifecycle.js index e36002d78..b6a141920 100644 --- a/scripts/lib/install-lifecycle.js +++ b/scripts/lib/install-lifecycle.js @@ -1127,8 +1127,15 @@ function collectTargetPathIssues(record, state, issues) { } function collectOperationHealthIssues(record, context, state, issues) { - const trustedRoots = getInstallTargetAdapter(record.adapter.id || record.adapter.target) - .resolveTrustedRoots(context); + 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, diff --git a/tests/lib/antigravity-lifecycle.test.js b/tests/lib/antigravity-lifecycle.test.js index 4ee9801b8..03f90a1b3 100644 --- a/tests/lib/antigravity-lifecycle.test.js +++ b/tests/lib/antigravity-lifecycle.test.js @@ -90,6 +90,25 @@ try { const externalContent = fs.readFileSync(externalWorkflow, 'utf8'); assert.throws(() => applyInstallPlan(symlinkPlan), /outside|symlink|trusted/i); + // One unsafe target root must not hide doctor results for other targets. + applyInstallPlan(withHookConsent(createManifestInstallPlan({ + profileId: 'core', + target: 'antigravity', + homeDir: symlinkHome, + projectRoot: symlinkProject, + }), 'enabled')); + const unsafeRootDoctor = buildDoctorReport({ + repoRoot, + homeDir: symlinkHome, + projectRoot: symlinkProject, + targets: ['antigravity-home', 'antigravity'], + }).results; + const homeDoctor = unsafeRootDoctor.find(result => result.adapter.target === 'antigravity-home'); + const projectDoctor = unsafeRootDoctor.find(result => result.adapter.target === 'antigravity'); + assert.strictEqual(homeDoctor.status, 'error'); + assert.ok(homeDoctor.issues.some(issue => issue.code === 'unsafe-trusted-root')); + assert.ok(projectDoctor, 'project target must still be reported'); + assert.notStrictEqual(projectDoctor.status, 'error'); const rootSymlinkRepair = repairInstalledStates({ repoRoot, homeDir: symlinkHome, @@ -128,7 +147,7 @@ try { if (previousHome === undefined) delete process.env.HOME; else process.env.HOME = previousHome; } - console.log('Results: Passed: 6, Failed: 0'); + console.log('Results: Passed: 7, Failed: 0'); } finally { fs.rmSync(fixtureRoot, { recursive: true, force: true }); } From 35335c95f4669262c699637f49cbf64cc7449734 Mon Sep 17 00:00:00 2001 From: haelyra Date: Mon, 16 Nov 2026 21:22:26 -0500 Subject: [PATCH 13/13] docs(antigravity): label the native plugin adapter experimental Native validation proves plugin import with CLI 1.3.5, but authenticated tool and Stop execution through the native host is not yet verified. Keep the README install table and support matrix at experimental until a pinned native loader receipt covers lifecycle execution. --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 823d1dc9d..1c88c91ed 100644 --- a/README.md +++ b/README.md @@ -140,7 +140,7 @@ Instead of rebuilding that process in every prompt, you install it once and make > Optimize the context window. Persist everything else. -ECC is MIT-licensed open source. It works best with Claude Code today, has native Codex, Qoder, and Antigravity plugin paths, and provides capability-limited adapters for Cursor, OpenCode, Gemini, Zed, GitHub Copilot, Qwen, and other harnesses. See the [support status matrix](#platform-support) before assuming feature parity. +ECC is MIT-licensed open source. It works best with Claude Code today, has native Codex and Qoder plugin paths, and provides capability-limited adapters for Cursor, OpenCode, Gemini, Zed, GitHub Copilot, Antigravity, Qwen, and other harnesses. See the [support status matrix](#platform-support) before assuming feature parity. Access to 72 agents, 327 skills, and 98 legacy command shims, plus hooks, rules, memory, continuous learning, and AgentShield security scanning. The agents are specialized for planning, review, build repair, security, architecture, and domain work. @@ -428,7 +428,7 @@ cd ECC | OpenCode | `npm install && npm run build:opencode && ./install.sh --profile full --target opencode --enable-hooks` | Builds the plugin payload before the full install | | Gemini CLI | `./install.sh --profile minimal --target gemini` | Project-local `.gemini/` config | | Zed | `./install.sh --profile minimal --target zed` | Project-local `.zed/` adapter | -| Antigravity (Global Plugin) | `./install.sh --target antigravity-home --profile core --enable-hooks` | Native Tier 1 global plugin (`~/.gemini/config/plugins/ecc/`) with lifecycle hooks · [Guide](docs/ANTIGRAVITY-GUIDE.md) | +| Antigravity (Global Plugin) | `./install.sh --target antigravity-home --profile core --enable-hooks` | Experimental global plugin (`~/.gemini/config/plugins/ecc/`) with lifecycle hooks · [Guide](docs/ANTIGRAVITY-GUIDE.md) | | Antigravity (Project-Local) | `./install.sh --target antigravity --profile minimal` | Project-local `.agents/` adapter · [Guide](docs/ANTIGRAVITY-GUIDE.md) | | Qwen CLI | `./install.sh --profile minimal --target qwen` | See the [Qwen guide](docs/QWEN-GUIDE.md) | | Hermes | `./install.sh --profile minimal --target hermes` | See the [Hermes setup guide](docs/HERMES-SETUP.md) | @@ -1331,7 +1331,7 @@ Treat `stable`, `beta`, `experimental`, and `instruction-only` below as capabili |---|---|---|---| | Claude Code | Stable primary | Plugin or selective installer | The plugin advertises the installed catalog to the model; use a selective/manual profile when context footprint matters. Optional shell-backed skills are not portable to every OS. | | Codex | Supported native plugin | Codex marketplace plugin or repo config | Native hooks require an explicit trust decision and do not use Claude's hook profiles. The legacy sync is compatibility-only. | -| Antigravity | Native plugin adapter | Antigravity 2.0/IDE plugin (`~/.gemini/config/plugins/ecc`) or project `.agents/` | Profile-gated lifecycle hooks, rules, workflows, skills, and memory MCP. CLI 1.3.5 validates local import; authenticated native tool and Stop execution remain unverified. | +| Antigravity | Experimental native plugin adapter | Antigravity 2.0/IDE plugin (`~/.gemini/config/plugins/ecc`) or project `.agents/` | Profile-gated lifecycle hooks, rules, workflows, skills, and memory MCP. CLI 1.3.5 validates local import; authenticated native tool and Stop execution remain unverified. | | Qoder | Supported native plugin | Local plugin directory in Qoder CLI or ZIP upload in Qoder IDE | Loads the canonical skills, agents, commands, and MCP config; only the reviewed SessionStart hook is enabled, and Node.js 18+ must be on the non-interactive PATH. | | Cursor | Beta project adapter | Selective installer into `.cursor/` | Agent discovery varies by Cursor build; hook events use profile-gated dispatchers, but full Claude feature parity is not claimed. | | OpenCode | Beta built plugin | Build plugin, then selective installer | ECC ships a subset of the catalog; connect a provider and select a model in OpenCode ([#2617](https://github.com/affaan-m/ECC/issues/2617)). |