diff --git a/README.md b/README.md index 30b8a7a31..1c88c91ed 100644 --- a/README.md +++ b/README.md @@ -263,7 +263,7 @@ npx ecc-universal@2.2.3 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) @@ -428,7 +428,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` | 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) | | OpenClaw | `./install.sh --profile minimal --target openclaw` | Managed home-directory install | @@ -1330,12 +1331,13 @@ 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 | 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)). | | GitHub Copilot Chat | Instruction-only | Checked-in instructions and prompt files | ECC hooks are not adapted. | | GitHub Copilot CLI | Beta project adapter | `--target copilot` places skills, adapted agents, and converted rules in `.github/` | ECC hooks and command shims are not installed by this target. | -| 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 diff --git a/docs/ANTIGRAVITY-GUIDE.md b/docs/ANTIGRAVITY-GUIDE.md index 427e9a0c4..e7388af75 100644 --- a/docs/ANTIGRAVITY-GUIDE.md +++ b/docs/ANTIGRAVITY-GUIDE.md @@ -155,12 +155,107 @@ node "$EccRoot\scripts\uninstall.js" --target antigravity --dry-run - Confirm the files are under `.agents/workflows/`. - Invoke a workflow with `/` after restarting Antigravity. +## 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`)**: 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. + +### 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 +``` + +The installer copies the memory server and its runtime dependencies into the +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. +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. +`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 + +```text +~/.gemini/config/ +├── workflows/ # Global slash workflows +└── plugins/ecc/ + ├── 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.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 +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) - [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/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index 91b727422..8f50f94fb 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": "23bd986cff96ea33424b1a461461a70e3194582ce01927145fd3f956daeebf7f", + "registryDigest": "79f94a9e247632fee0967983fb80ba85c3a76e6440d1cf2cd97fc73198472b8e", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [ diff --git a/manifests/install-modules.json b/manifests/install-modules.json index d16c7c6b8..1b14e4135 100644 --- a/manifests/install-modules.json +++ b/manifests/install-modules.json @@ -14,6 +14,7 @@ "cursor", "copilot", "antigravity", + "antigravity-home", "codebuddy", "joycode", "qwen", @@ -42,6 +43,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "codebuddy", @@ -78,6 +80,7 @@ "cursor", "copilot", "antigravity", + "antigravity-home", "opencode", "codebuddy", "joycode", @@ -109,7 +112,9 @@ "claude-project", "cursor", "opencode", - "codebuddy" + "codebuddy", + "antigravity", + "antigravity-home" ], "dependencies": [], "defaultInstall": true, @@ -161,6 +166,7 @@ "cursor", "copilot", "antigravity", + "antigravity-home", "codex", "gemini", "opencode", @@ -267,6 +273,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -309,6 +316,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -336,6 +344,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "gemini", @@ -368,6 +377,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -449,6 +459,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -480,6 +491,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -517,6 +529,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -568,6 +581,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -605,6 +619,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -645,6 +660,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -692,6 +708,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -721,6 +738,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -753,6 +771,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -768,7 +787,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", @@ -779,6 +798,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "gemini", @@ -811,6 +831,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "gemini", @@ -845,6 +866,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -943,6 +965,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -1028,6 +1051,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -1073,6 +1097,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -1103,6 +1128,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -1141,6 +1167,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -1169,6 +1196,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "opencode", @@ -1404,6 +1432,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -1464,6 +1493,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "opencode", "codebuddy", @@ -1526,6 +1556,7 @@ "cursor", "copilot", "antigravity", + "antigravity-home", "opencode", "codebuddy", "joycode", diff --git a/schemas/context-carrier.schema.json b/schemas/context-carrier.schema.json index 1289e0e9c..9e5b7fa37 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", "grok", "hermes", "joycode", "kimi", "openclaw", "opencode", "pi", "qwen", "zed"] }, + "target": { "enum": ["adal", "antigravity", "antigravity-home", "claude", "claude-project", "codebuddy", "codex", "copilot", "cursor", "gemini", "grok", "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/schemas/ecc-install-config.schema.json b/schemas/ecc-install-config.schema.json index 1ff1d4716..a59c8ab7e 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", "copilot", "gemini", diff --git a/schemas/install-modules.schema.json b/schemas/install-modules.schema.json index 617a5359d..a1a55e2f5 100644 --- a/schemas/install-modules.schema.json +++ b/schemas/install-modules.schema.json @@ -52,6 +52,7 @@ "claude-project", "cursor", "antigravity", + "antigravity-home", "codex", "copilot", "gemini", diff --git a/scripts/hooks/antigravity-hook-bridge.js b/scripts/hooks/antigravity-hook-bridge.js new file mode 100644 index 000000000..485a2c457 --- /dev/null +++ b/scripts/hooks/antigravity-hook-bridge.js @@ -0,0 +1,214 @@ +#!/usr/bin/env node +'use strict'; + +/** + * Antigravity Lifecycle Hook Bridge + * + * Bridges Google Antigravity's protojson hook contract (stdin/stdout JSON with + * camelCase keys and { decision, reason } responses) to ECC's internal hook + * runtime (exit-code/stderr based). + */ + +const path = require('path'); +const { spawnSync } = require('child_process'); +const { runPreBash } = require('./bash-hook-dispatcher'); +const { run: runGateGuard } = require('./gateguard-fact-force'); +const { run: runDocFileWarning } = require('./doc-file-warning'); +const { run: runPostEditAccumulator } = require('./post-edit-accumulator'); +const { readStdinRaw, resolveMaxStdin } = require('./hook-input'); +const { isHookEnabled, isDryRun } = require('../lib/hook-flags'); + +function parseArgs(argv) { + const options = { + mode: 'pre-tool-use', + hook: null, + }; + + for (let i = 2; i < argv.length; i += 1) { + if (argv[i] === '--mode') { + options.mode = argv[i + 1] || options.mode; + i += 1; + } else if (argv[i] === '--hook') { + options.hook = argv[i + 1] || options.hook; + i += 1; + } + } + + return options; +} + +function adaptAntigravityInputToEcc(antigravityData) { + if (!antigravityData || typeof antigravityData !== 'object') { + return { tool_name: '', tool_input: {} }; + } + + const toolCall = antigravityData.toolCall || {}; + const toolName = toolCall.name || antigravityData.tool_name || ''; + const args = toolCall.args || antigravityData.tool_input || {}; + + // Normalize Antigravity tools to ECC tool conventions + const toolInput = { + ...args, + command: args.CommandLine || args.command || '', + file_path: args.TargetFile || args.file_path || args.path || '', + }; + + return { + tool_name: ({ run_command: 'Bash', write_to_file: 'Write', replace_file_content: 'Edit', multi_replace_file_content: 'Edit' })[toolName] || toolName, + tool_input: toolInput, + session_id: antigravityData.conversationId || antigravityData.session_id || '', + cwd: args.Cwd || antigravityData.cwd || antigravityData.workspacePaths?.[0] || '', + conversation_id: antigravityData.conversationId || '', + workspace_paths: antigravityData.workspacePaths || [], + }; +} + +function writeFailure(mode, reason) { + process.stdout.write(JSON.stringify({ + decision: mode === 'pre-tool-use' ? 'deny' : 'allow', + ...(mode === 'pre-tool-use' ? { reason } : {}), + })); +} + +async function main() { + const options = parseArgs(process.argv); + process.env.ECC_HOOK_CONFIG ||= path.resolve(__dirname, '../../ecc/setup.json'); + const profiles = options.hook === 'pre:bash:dispatcher' ? 'minimal,standard,strict' : undefined; + if (!isHookEnabled(options.hook, { profiles }) || isDryRun()) { + process.stdout.write(JSON.stringify(options.mode === 'post-tool-use' ? {} : { decision: 'allow' })); + return; + } + const maxStdin = resolveMaxStdin(process.env.ECC_HOOK_INPUT_MAX_BYTES); + + let raw = ''; + try { + const inputResult = await readStdinRaw(process.stdin, { maxStdin }); + if (inputResult.truncated) throw new Error('Incomplete hook input'); + raw = inputResult.raw; + } catch (_err) { + writeFailure(options.mode, 'ECC hook input could not be read completely'); + return; + } + + let antigravityPayload = {}; + try { + antigravityPayload = JSON.parse(raw); + if (!antigravityPayload || typeof antigravityPayload !== 'object' || Array.isArray(antigravityPayload)) { + throw new Error('Invalid hook input'); + } + } catch (_parseErr) { + writeFailure(options.mode, 'ECC hook input must be a valid JSON object'); + return; + } + + const eccPayload = adaptAntigravityInputToEcc(antigravityPayload); + const eccJsonString = JSON.stringify(eccPayload); + + if (options.mode === 'pre-tool-use') { + let result = { exitCode: 0, stderr: '' }; + + if (options.hook === 'pre:bash:dispatcher') { + result = runPreBash(eccJsonString); + } else if (options.hook === 'pre:edit-write:gateguard-fact-force') { + result = runGateGuard(eccJsonString); + } else if (options.hook === 'pre:config-protection') { + const child = spawnSync(process.execPath, [path.join(__dirname, 'config-protection.js')], { + input: eccJsonString, + encoding: 'utf8', + timeout: 4000, + }); + result = { + exitCode: child.error || child.status === null ? 2 : child.status, + stderr: child.stderr || '', + stdout: typeof child.stdout === 'string' ? child.stdout : '', + }; + } else if (options.hook === 'pre:write:doc-file-warning') { + result = runDocFileWarning(eccJsonString); + } + + const output = typeof result?.stdout === 'string' + ? result.stdout + : (typeof result?.output === 'string' ? result.output : null); + let hookOutput = null; + if (output) { + try { + const parsed = JSON.parse(output); + hookOutput = parsed && typeof parsed === 'object' ? parsed.hookSpecificOutput : null; + } catch { + hookOutput = null; + } + } + const denied = Boolean( + (result && ((result.exitCode !== undefined && result.exitCode !== 0) || result.denied || result.blocked)) + || hookOutput?.permissionDecision === 'deny' + ); + const context = result?.additionalContext || hookOutput?.additionalContext; + const reason = denied + ? hookOutput?.permissionDecisionReason || result?.stderr || result?.reason || 'Blocked by ECC safety hook' + : (Array.isArray(context) ? context.join(' ') : context); + process.stdout.write(JSON.stringify({ + decision: denied ? 'deny' : 'allow', + ...(reason ? { reason: String(reason).replace(/\r?\n/g, ' ').trim() } : {}), + })); + return; + } + + // Both accumulator and batch formatter use the same session-scoped temp file. + if (eccPayload.session_id) process.env.CLAUDE_SESSION_ID = String(eccPayload.session_id); + + if (options.mode === 'post-tool-use') { + if (options.hook === 'post:edit:accumulator' && !antigravityPayload.error) { + runPostEditAccumulator(eccJsonString); + } + process.stdout.write(JSON.stringify({})); + return; + } + + if (options.mode === 'stop') { + if (antigravityPayload.fullyIdle === false) { + process.stdout.write(JSON.stringify({ decision: 'allow' })); + return; + } + let stopResult = { exitCode: 0, stderr: '' }; + + const stopScript = { + 'stop:format-typecheck': 'stop-format-typecheck.js', + 'stop:check-console-log': 'check-console-log.js', + }[options.hook]; + if (stopScript) { + const child = spawnSync(process.execPath, [path.join(__dirname, stopScript)], { + input: eccJsonString, + cwd: eccPayload.cwd || undefined, + encoding: 'utf8', + timeout: options.hook === 'stop:format-typecheck' ? 280000 : 25000, + }); + stopResult = { + stderr: child.stderr || (child.error ? 'ECC stop hook failed: ' + child.error.message : ''), + }; + } + + if (stopResult && stopResult.stderr) { + process.stdout.write(JSON.stringify({ + decision: 'continue', + reason: stopResult.stderr.replace(/\r?\n/g, ' ').trim(), + })); + return; + } + + process.stdout.write(JSON.stringify({ decision: 'allow' })); + return; + } + + // Default passthrough + process.stdout.write(JSON.stringify({ decision: 'allow' })); +} + +if (require.main === module) { + main().catch(() => { + writeFailure(parseArgs(process.argv).mode, 'ECC safety hook failed unexpectedly'); + }); +} + +module.exports = { + adaptAntigravityInputToEcc, +}; diff --git a/scripts/lib/antigravity-hooks.js b/scripts/lib/antigravity-hooks.js new file mode 100644 index 000000000..d5977fea7 --- /dev/null +++ b/scripts/lib/antigravity-hooks.js @@ -0,0 +1,100 @@ +'use strict'; + +const path = require('path'); +const { shellQuote } = require('./control-pane/actions'); + +/** + * Antigravity Hooks Generator + * + * Generates valid Antigravity hooks.json configuration matching Antigravity's + * lifecycle schema (PreToolUse, PostToolUse, Stop) and pointing to the ECC + * hook bridge. + */ + +function buildAntigravityHooksConfig(options = {}) { + const { bridgeScript } = options; + if (typeof bridgeScript !== 'string' || !path.isAbsolute(bridgeScript) || bridgeScript.includes('\0')) { + throw new Error('bridgeScript must be an absolute path'); + } + let quotedBridgeScript; + if (process.platform === 'win32') { + if (/[%"!$`\r\n]/.test(bridgeScript)) { + throw new Error('bridgeScript contains unsafe shell expansion characters'); + } + quotedBridgeScript = `"${bridgeScript}"`; + } else { + quotedBridgeScript = shellQuote(bridgeScript); + } + + const preToolUseHandlers = [ + { + matcher: 'run_command', + hooks: [ + { + type: 'command', + command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:bash:dispatcher`, + timeout: 15, + }, + ], + }, + { + matcher: 'write_to_file|replace_file_content|multi_replace_file_content', + hooks: [ + { + type: 'command', + command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:edit-write:gateguard-fact-force`, + timeout: 10, + }, + { + type: 'command', + command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:config-protection`, + timeout: 5, + }, + ], + }, + ]; + + // Runtime hook flags select the profile, including explicit environment overrides. + preToolUseHandlers.push({ + matcher: 'write_to_file', + hooks: [ + { + type: 'command', + command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:write:doc-file-warning`, + timeout: 5, + }, + ], + }); + + const stopHandlers = [ + { + type: 'command', + command: `node ${quotedBridgeScript} --mode stop --hook stop:format-typecheck`, + timeout: 300, + }, + { + type: 'command', + command: `node ${quotedBridgeScript} --mode stop --hook stop:check-console-log`, + timeout: 30, + }, + ]; + + return { + 'ecc-guard': { + PreToolUse: preToolUseHandlers, + PostToolUse: [{ + matcher: 'write_to_file|replace_file_content|multi_replace_file_content', + hooks: [{ + type: 'command', + command: `node ${quotedBridgeScript} --mode post-tool-use --hook post:edit:accumulator`, + timeout: 10, + }], + }], + Stop: stopHandlers, + }, + }; +} + +module.exports = { + buildAntigravityHooksConfig, +}; diff --git a/scripts/lib/antigravity-mcp.js b/scripts/lib/antigravity-mcp.js new file mode 100644 index 000000000..54a347931 --- /dev/null +++ b/scripts/lib/antigravity-mcp.js @@ -0,0 +1,72 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { createManagedScaffoldOperation } = require('./install-targets/helpers'); +const { formatPackageSourcePath } = require('./install/package-source'); + +/** + * Antigravity MCP Configuration Generator + * + * Generates valid Antigravity mcp_config.json containing the ECC Memory Vault + * stdio server so that Antigravity agents have native access to .ecc/memory/. + */ + +function buildAntigravityMcpConfig(options = {}) { + const { memoryScript } = options; + if (typeof memoryScript !== 'string' || !path.isAbsolute(memoryScript) || memoryScript.includes('\0')) { + throw new Error('memoryScript must be an absolute path'); + } + + return { + mcpServers: { + 'ecc-memory': { + command: 'node', + args: [memoryScript], + env: { + ECC_MEMORY_HARNESS: 'antigravity', + }, + }, + }, + }; +} + +function planAntigravityMemoryRuntime(moduleId, repoRoot, targetRoot) { + const sourcePaths = [ + 'package.json', + 'scripts/memory-mcp.mjs', + 'scripts/lib/missing-dependency.js', + 'scripts/lib/memory-vault.js', + 'scripts/lib/memory-vault-format.js', + 'scripts/lib/path-safety.js', + ]; + const operations = sourcePaths.map(sourcePath => createManagedScaffoldOperation( + moduleId, sourcePath, path.join(targetRoot, sourcePath), 'preserve-relative-path' + )); + function addDependency(name, fromRoot, destinationRoot, ancestors = [], packageChain = []) { + let manifestPath; + try { + manifestPath = require.resolve(`${name}/package.json`, { paths: [fromRoot] }); + } catch (error) { + throw new Error(`Cannot install Antigravity memory dependency ${name}. Run npm install in ${repoRoot}: ${error.message}`); + } + if (ancestors.includes(manifestPath)) return; + const packageRoot = path.dirname(manifestPath); + const destinationPath = path.join(destinationRoot, 'node_modules', name); + const sourceChain = [...packageChain, name]; + operations.push(createManagedScaffoldOperation( + moduleId, formatPackageSourcePath(sourceChain), destinationPath, 'preserve-relative-path' + )); + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + for (const dependency of Object.keys(manifest.dependencies || {})) { + addDependency(dependency, packageRoot, destinationPath, [...ancestors, manifestPath], sourceChain); + } + } + addDependency('ajv', repoRoot, targetRoot); + return operations; +} + +module.exports = { + buildAntigravityMcpConfig, + planAntigravityMemoryRuntime, +}; diff --git a/scripts/lib/antigravity-plugin.js b/scripts/lib/antigravity-plugin.js new file mode 100644 index 000000000..92b43c120 --- /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 || require('../../package.json').version; + return { + name: 'ecc', + description: 'ECC - The Agent Harness Operating System for Antigravity', + version, + }; +} + +module.exports = { + buildAntigravityPluginManifest, +}; diff --git a/scripts/lib/harness-capabilities.js b/scripts/lib/harness-capabilities.js index 071deedf4..81ee1113b 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: 'copilot', diff --git a/scripts/lib/install-lifecycle.js b/scripts/lib/install-lifecycle.js index 7574a3a04..b6a141920 100644 --- a/scripts/lib/install-lifecycle.js +++ b/scripts/lib/install-lifecycle.js @@ -7,7 +7,8 @@ const { isDeepStrictEqual } = require('util'); const { loadInstallManifests } = require('./install-manifests'); const { readInstallState, validateInstallState } = require('./install-state'); -const { assertWithinTrustedRoot } = require('./path-safety'); +const { assertWithinTrustedRoot, isWithinRoot } = require('./path-safety'); +const { isPackageSourcePath, resolvePackageSourcePath } = require('./install/package-source'); const { createInstallPlanFromRequest } = require('./install/runtime'); const { assertNoNewUserOwnedFile, prepareUserOwnedFileGuard } = require('./install/ownership-guard'); const { withOpenCodeInstallLocks } = require('./install/opencode-install-lock'); @@ -198,6 +199,17 @@ function resolveOperationSourcePath(repoRoot, operation) { throw createUnsafeRepairSourceError(); } + if (isPackageSourcePath(sourceRelativePath)) { + let packageSourcePath; + try { + packageSourcePath = resolvePackageSourcePath(repoRoot, sourceRelativePath); + } catch { + throw createUnsafeRepairSourceError(); + } + // An unresolvable package reports as a missing source, not an unsafe one. + return packageSourcePath || path.resolve(repoRoot, sourceRelativePath); + } + return assertSafeRepairSourcePath( path.resolve(repoRoot, sourceRelativePath), repoRoot @@ -788,13 +800,18 @@ function inspectManagedOperation(repoRoot, trustedRoot, operation, linkIndex = n } } -function summarizeManagedOperationHealth(repoRoot, trustedRoot, operations, target = null) { +function trustedRootForDestination(destinationPath, targetRoot, trustedRoots = [targetRoot]) { + const parent = typeof destinationPath === 'string' ? path.dirname(destinationPath) : destinationPath; + return trustedRoots.find(root => isWithinRoot(parent, root)) || targetRoot; +} + +function summarizeManagedOperationHealth(repoRoot, trustedRoot, operations, target = null, trustedRoots = [trustedRoot]) { const linkIndex = buildLinkIndexForOperations(operations, trustedRoot); return operations.reduce( (summary, operation) => { const inspection = inspectManagedOperation( repoRoot, - trustedRoot, + trustedRootForDestination(operation.destinationPath, trustedRoot, trustedRoots), operation, linkIndex, target @@ -1110,11 +1127,21 @@ function collectTargetPathIssues(record, state, issues) { } function collectOperationHealthIssues(record, context, state, issues) { + let trustedRoots; + try { + trustedRoots = getInstallTargetAdapter(record.adapter.id || record.adapter.target) + .resolveTrustedRoots(context); + } catch (error) { + // Report an unsafe root for this target without aborting the other targets. + issues.push(buildIssue('error', 'unsafe-trusted-root', error.message)); + return; + } const operationHealth = summarizeManagedOperationHealth( context.repoRoot, record.targetRoot, getManagedOperations(state), - record.adapter.target + record.adapter.target, + trustedRoots ); const destinationPaths = entries => entries.map(entry => entry.destinationPath); @@ -1594,7 +1621,8 @@ function planOpencodeBuildRepair(repair, build) { desiredPlan.sourceRoot || context.repoRoot, record.targetRoot, desiredPlan.operations, - record.adapter.target + record.adapter.target, + repair.trustedRoots ); const unsafeOperationResult = getUnsafeOperationResult(record, operationHealth); if (unsafeOperationResult) return unsafeOperationResult; @@ -1657,12 +1685,12 @@ function executeGuardedRepairOperation(repair, plan, operation, repairedPaths) { const repairedPath = executeRepairOperation( desiredPlan.sourceRoot || context.repoRoot, operation, - record.targetRoot, + trustedRootForDestination(operation.destinationPath, record.targetRoot, repair.trustedRoots), { - linkIndex: repairLinkIndex, - target: record.adapter.target, - settingsLockHeld, - writeOptions: apply.getOpenCodeActivationWriteOptions(operation, activationSnapshot), + linkIndex: repairLinkIndex, + target: record.adapter.target, + settingsLockHeld, + writeOptions: apply.getOpenCodeActivationWriteOptions(operation, activationSnapshot), } ); if (repairedPath) { @@ -1749,7 +1777,8 @@ function repairManagedRecord(repair, build) { repairSourceRoot, record.targetRoot, desiredPlan.operations, - record.adapter.target + record.adapter.target, + repair.trustedRoots ); const unsafeOperationResult = getUnsafeOperationResult(record, operationHealth); @@ -1802,7 +1831,8 @@ function repairManagedRecord(repair, build) { // Repair one discovered record. `repair` carries the record, lifecycle // context, caller options, the OpenCode build runner, an optional OpenCode -// lease, and whether the Claude settings lock is already held. +// lease, whether the Claude settings lock is already held, and the adapter's +// trusted roots for destinations outside the target root. function runRecordRepair(repair) { const { record, context, options } = repair; const needsOpencodeBuild = record.adapter.target === 'opencode' @@ -1852,6 +1882,8 @@ function repairInstalledStates(options = {}) { let releaseSettingsLock = null; try { + const trustedRoots = getInstallTargetAdapter(record.adapter.id || record.adapter.target) + .resolveTrustedRoots(context); preflightOpenCodeHookDeactivation(record, context); releaseSettingsLock = acquireRepairSettingsLock(record, options); return runRecordRepair({ @@ -1861,6 +1893,7 @@ function repairInstalledStates(options = {}) { buildOpencodeRunner, opencodeLease, settingsLockHeld: Boolean(releaseSettingsLock), + trustedRoots, }); } catch (error) { return repairErrorResult(record, error.message); @@ -1922,12 +1955,22 @@ function repairInstalledStates(options = {}) { } +function resolveRecordTrustedRoots(record, context) { + const adapter = record.adapter && getInstallTargetAdapter(record.adapter.id || record.adapter.target); + return adapter && typeof adapter.resolveTrustedRoots === 'function' + ? adapter.resolveTrustedRoots(context) + : [record.targetRoot]; +} + function uninstallInstalledStates(options = {}) { - const records = discoverInstalledStates({ - homeDir: options.homeDir, - projectRoot: options.projectRoot, - targets: options.targets, + const context = { + homeDir: options.homeDir || process.env.HOME || os.homedir(), + projectRoot: options.projectRoot || process.cwd(), env: resolveInvocationEnvironment(options), + }; + const records = discoverInstalledStates({ + ...context, + targets: options.targets, }).filter(record => record.exists); const results = records.map(record => { @@ -1984,6 +2027,8 @@ function uninstallInstalledStates(options = {}) { ); } + const trustedRoots = resolveRecordTrustedRoots(record, context); + const { isScriptBoundary, retainScriptBoundary } = require('./install/opencode-script-boundary'); // Remove owned script bodies first. Keep their CommonJS scope while any // retained or user-created JavaScript still relies on that boundary. @@ -1996,7 +2041,7 @@ function uninstallInstalledStates(options = {}) { retainedPaths.push(operation.destinationPath); continue; } - const outcome = executeUninstallOperation(operation, record.targetRoot, { + const outcome = executeUninstallOperation(operation, trustedRootForDestination(operation.destinationPath, record.targetRoot, trustedRoots), { preserveDriftedCopies: true, target: record.adapter.target, settingsLockHeld: Boolean(releaseSettingsLock), @@ -2020,7 +2065,8 @@ function uninstallInstalledStates(options = {}) { } for (const cleanupTarget of cleanupTargets) { - cleanupEmptyParentDirs(cleanupTarget, record.targetRoot); + const matchingRoot = trustedRootForDestination(cleanupTarget, record.targetRoot, trustedRoots); + cleanupEmptyParentDirs(cleanupTarget, matchingRoot); } return { diff --git a/scripts/lib/install-manifests.js b/scripts/lib/install-manifests.js index 324d69c7f..e380dd9a3 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', 'copilot', 'gemini', 'opencode', 'codebuddy', 'joycode', 'qwen', 'zed', 'hermes', 'openclaw', 'kimi', 'adal', 'grok']; +const SUPPORTED_INSTALL_TARGETS = ['claude', 'claude-project', 'cursor', 'antigravity', 'antigravity-home', 'codex', 'copilot', 'gemini', 'opencode', 'codebuddy', 'joycode', 'qwen', 'zed', 'hermes', 'openclaw', 'kimi', 'adal', 'grok']; const COMPONENT_FAMILY_PREFIXES = { baseline: 'baseline:', language: 'lang:', @@ -77,6 +77,14 @@ const LEGACY_COMPAT_BASE_MODULE_IDS_BY_TARGET = Object.freeze({ 'skill-unified-memory', 'workflow-quality', ], + 'antigravity-home': [ + 'rules-core', + 'agents-core', + 'commands-core', + 'hooks-runtime', + 'platform-configs', + 'workflow-quality', + ], zed: [ 'rules-core', 'agents-core', @@ -765,6 +773,7 @@ function resolveInstallPlan(options = {}) { targetAdapterId: scaffoldPlan ? scaffoldPlan.adapter.id : null, homeDir: targetPlanningInput ? targetPlanningInput.homeDir : null, targetRoot: scaffoldPlan ? scaffoldPlan.targetRoot : null, + trustedRoots: scaffoldPlan ? scaffoldPlan.trustedRoots : (scaffoldPlan?.targetRoot ? [scaffoldPlan.targetRoot] : []), installStatePath: scaffoldPlan ? scaffoldPlan.installStatePath : null, operations: scaffoldPlan ? scaffoldPlan.operations : [], }; diff --git a/scripts/lib/install-targets/antigravity-home.js b/scripts/lib/install-targets/antigravity-home.js new file mode 100644 index 000000000..c3a53372a --- /dev/null +++ b/scripts/lib/install-targets/antigravity-home.js @@ -0,0 +1,207 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const { + HOME_INSTALL_EXCLUDED_SOURCE_PATHS, + createFlatRuleOperations, + createInstallTargetAdapter, + createManagedOperation, + createManagedScaffoldOperation, + isForeignPlatformPath, + normalizeRelativePath, +} = require('./helpers'); +const { buildAntigravityHooksConfig } = require('../antigravity-hooks'); +const { buildAntigravityMcpConfig, planAntigravityMemoryRuntime } = require('../antigravity-mcp'); +const { buildAntigravityPluginManifest } = require('../antigravity-plugin'); +const { getHookProfile } = require('../hook-flags'); +const { isWithinRoot } = require('../path-safety'); + +module.exports = createInstallTargetAdapter({ + id: 'antigravity-home', + target: 'antigravity-home', + kind: 'home', + rootSegments: ['.gemini', 'config', 'plugins', 'ecc'], + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.gemini', + excludedSourcePaths: HOME_INSTALL_EXCLUDED_SOURCE_PATHS, + resolveTrustedRoots(input, targetRoot) { + const configRoot = path.dirname(path.dirname(targetRoot)); + const workflowsRoot = path.join(configRoot, 'workflows'); + if (!isWithinRoot(workflowsRoot, configRoot)) { + throw new Error('Refusing Antigravity workflows outside the trusted config root.'); + } + return [targetRoot, workflowsRoot]; + }, + planOperations(input, adapter) { + const modules = Array.isArray(input.modules) + ? input.modules + : (input.module ? [input.module] : []); + const { + repoRoot, + projectRoot, + homeDir, + } = input; + const planningInput = { + repoRoot, + projectRoot, + homeDir, + }; + const targetRoot = adapter.resolveRoot(planningInput); + + return modules.flatMap(module => { + const paths = Array.isArray(module.paths) ? module.paths : []; + return paths + .filter(p => !isForeignPlatformPath(p, 'antigravity') && !adapter.excludesSourcePath(p)) + .flatMap(sourceRelativePath => { + const normalizedSourcePath = normalizeRelativePath(sourceRelativePath); + + if ( + normalizedSourcePath === 'rules' + || normalizedSourcePath.startsWith('rules/') + ) { + return createFlatRuleOperations({ + moduleId: module.id, + repoRoot, + sourceRelativePath: normalizedSourcePath, + destinationDir: path.join(targetRoot, 'rules'), + }); + } + + if ( + normalizedSourcePath === 'commands' + || normalizedSourcePath.startsWith('commands/') + ) { + const commandRelativePath = normalizedSourcePath === 'commands' + ? '' + : normalizedSourcePath.slice('commands/'.length); + const workflowsRoot = path.join( + path.dirname(path.dirname(targetRoot)), + 'workflows' + ); + return [ + createManagedScaffoldOperation( + module.id, + normalizedSourcePath, + path.join(workflowsRoot, commandRelativePath), + 'preserve-relative-path' + ), + ]; + } + + if ( + normalizedSourcePath === 'agents' + || normalizedSourcePath.startsWith('agents/') + ) { + const agentRelativePath = normalizedSourcePath === 'agents' + ? '' + : normalizedSourcePath.slice('agents/'.length); + return [ + createManagedOperation({ + moduleId: module.id, + sourceRelativePath: normalizedSourcePath, + destinationPath: path.join(targetRoot, 'agents', agentRelativePath), + strategy: 'preserve-relative-path', + contentTransform: 'antigravity-agent-frontmatter', + }), + ]; + } + + if ( + normalizedSourcePath === 'skills' + || normalizedSourcePath.startsWith('skills/') + ) { + const skillRelativePath = normalizedSourcePath === 'skills' + ? '' + : normalizedSourcePath.slice('skills/'.length); + return [ + createManagedScaffoldOperation( + module.id, + normalizedSourcePath, + path.join(targetRoot, 'skills', skillRelativePath), + 'preserve-relative-path' + ), + ]; + } + + if ( + module.id === 'hooks-runtime' + && normalizedSourcePath === 'hooks' + ) { + const profile = getHookProfile(input.env); + return [ + createManagedScaffoldOperation(module.id, 'package.json', path.join(targetRoot, 'package.json'), 'preserve-relative-path'), + createManagedOperation({ + kind: 'merge-json', + moduleId: module.id, + sourceRelativePath: 'hooks/hooks.json', + destinationPath: path.join(targetRoot, 'hooks.json'), + strategy: 'merge-json', + ownership: 'managed', + scaffoldOnly: false, + mergePayload: buildAntigravityHooksConfig({ + profile, + bridgeScript: path.join(targetRoot, 'scripts', 'hooks', 'antigravity-hook-bridge.js'), + }), + }), + createManagedOperation({ + kind: 'merge-json', + moduleId: module.id, + sourceRelativePath: 'hooks/hooks.json', + destinationPath: path.join(targetRoot, 'ecc', 'setup.json'), + strategy: 'merge-json', + ownership: 'managed', + scaffoldOnly: false, + mergePayload: { hooks: { enabled: true, profile } }, + }), + ]; + } + + if ( + module.id === 'platform-configs' + && (normalizedSourcePath === 'mcp-configs' || normalizedSourcePath === '.mcp.json') + ) { + const antigravityMcp = buildAntigravityMcpConfig({ + memoryScript: path.join(targetRoot, 'scripts', 'memory-mcp.mjs'), + }); + + const operations = [ + createManagedOperation({ + kind: 'merge-json', + moduleId: module.id, + sourceRelativePath: '.mcp.json', + destinationPath: path.join(targetRoot, 'mcp_config.json'), + strategy: 'merge-json', + ownership: 'managed', + scaffoldOnly: false, + mergePayload: antigravityMcp, + }), + createManagedOperation({ + kind: 'merge-json', + moduleId: module.id, + sourceRelativePath: 'plugin.json', + destinationPath: path.join(targetRoot, 'plugin.json'), + strategy: 'merge-json', + ownership: 'managed', + scaffoldOnly: false, + mergePayload: buildAntigravityPluginManifest(), + }), + ]; + + if (repoRoot && fs.existsSync(path.join(repoRoot, 'scripts', 'memory-mcp.mjs'))) { + operations.push(...planAntigravityMemoryRuntime(module.id, repoRoot, targetRoot)); + } + + return operations; + } + + if (normalizedSourcePath === 'scripts/hooks' || normalizedSourcePath === 'scripts/lib') { + return [adapter.createScaffoldOperation(module.id, normalizedSourcePath, planningInput)]; + } + + return []; + }); + }); + }, +}); diff --git a/scripts/lib/install-targets/antigravity-project.js b/scripts/lib/install-targets/antigravity-project.js index 40c39e540..3bf7254e6 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,22 @@ const { createManagedScaffoldOperation, normalizeRelativePath, } = require('./helpers'); +const { buildAntigravityHooksConfig } = require('../antigravity-hooks'); +const { buildAntigravityMcpConfig, planAntigravityMemoryRuntime } = require('../antigravity-mcp'); +const { buildAntigravityPluginManifest } = require('../antigravity-plugin'); +const { getHookProfile } = require('../hook-flags'); -const SUPPORTED_SOURCE_PREFIXES = ['rules', 'commands', 'agents', 'skills']; +const SUPPORTED_SOURCE_PREFIXES = [ + 'rules', + 'commands', + 'agents', + 'skills', + 'hooks', + 'scripts/hooks', + 'scripts/lib', + 'mcp-configs', + '.mcp.json', +]; function supportsAntigravitySourcePath(sourceRelativePath) { const normalizedPath = normalizeRelativePath(sourceRelativePath); @@ -39,6 +54,7 @@ module.exports = createInstallTargetAdapter({ kind: 'project', rootSegments: ['.agents'], installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.agents', supportsModule(module) { const paths = Array.isArray(module && module.paths) ? module.paths : []; return paths.length > 0; @@ -130,6 +146,81 @@ module.exports = createInstallTargetAdapter({ ]; } + if ( + module.id === 'hooks-runtime' + && normalizedSourcePath === 'hooks' + ) { + const profile = getHookProfile(input.env); + return [ + createManagedScaffoldOperation(module.id, 'package.json', path.join(targetRoot, 'package.json'), 'preserve-relative-path'), + createManagedOperation({ + kind: 'merge-json', + moduleId: module.id, + sourceRelativePath: 'hooks/hooks.json', + destinationPath: path.join(targetRoot, 'hooks.json'), + strategy: 'merge-json', + ownership: 'managed', + scaffoldOnly: false, + mergePayload: buildAntigravityHooksConfig({ + profile, + bridgeScript: path.join(targetRoot, 'scripts', 'hooks', 'antigravity-hook-bridge.js'), + }), + }), + createManagedOperation({ + kind: 'merge-json', + moduleId: module.id, + sourceRelativePath: 'hooks/hooks.json', + destinationPath: path.join(targetRoot, 'ecc', 'setup.json'), + strategy: 'merge-json', + ownership: 'managed', + scaffoldOnly: false, + mergePayload: { hooks: { enabled: true, profile } }, + }), + ]; + } + + if ( + module.id === 'platform-configs' + && (normalizedSourcePath === 'mcp-configs' || normalizedSourcePath === '.mcp.json') + ) { + const antigravityMcp = buildAntigravityMcpConfig({ + memoryScript: path.join(targetRoot, 'scripts', 'memory-mcp.mjs'), + }); + + const operations = [ + createManagedOperation({ + kind: 'merge-json', + moduleId: module.id, + sourceRelativePath: '.mcp.json', + destinationPath: path.join(targetRoot, 'mcp_config.json'), + strategy: 'merge-json', + ownership: 'managed', + scaffoldOnly: false, + mergePayload: antigravityMcp, + }), + createManagedOperation({ + kind: 'merge-json', + moduleId: module.id, + sourceRelativePath: 'plugin.json', + destinationPath: path.join(targetRoot, 'plugins', 'ecc', 'plugin.json'), + strategy: 'merge-json', + ownership: 'managed', + scaffoldOnly: false, + mergePayload: buildAntigravityPluginManifest(), + }), + ]; + + if (repoRoot && fs.existsSync(path.join(repoRoot, 'scripts', 'memory-mcp.mjs'))) { + operations.push(...planAntigravityMemoryRuntime(module.id, repoRoot, targetRoot)); + } + + return operations; + } + + if (normalizedSourcePath === 'scripts/hooks' || normalizedSourcePath === 'scripts/lib') { + return [adapter.createScaffoldOperation(module.id, normalizedSourcePath, planningInput)]; + } + return []; }); }); diff --git a/scripts/lib/install-targets/helpers.js b/scripts/lib/install-targets/helpers.js index e61925c41..1a8366d08 100644 --- a/scripts/lib/install-targets/helpers.js +++ b/scripts/lib/install-targets/helpers.js @@ -386,6 +386,13 @@ function createInstallTargetAdapter(config) { } return path.join(baseRoot, ...adapter.rootSegments); }, + resolveTrustedRoots(input = {}) { + const root = adapter.resolveRoot(input); + if (typeof config.resolveTrustedRoots === 'function') { + return config.resolveTrustedRoots(input, root); + } + return [root]; + }, getInstallStatePath(input = {}) { const root = adapter.resolveRoot(input); return path.join(root, ...adapter.installStatePathSegments); diff --git a/scripts/lib/install-targets/registry.js b/scripts/lib/install-targets/registry.js index 770096742..299e59557 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'); @@ -21,6 +22,7 @@ const ADAPTERS = Object.freeze([ claudeHome, claudeProject, cursorProject, + antigravityHome, antigravityProject, codexHome, copilotProject, @@ -73,6 +75,9 @@ function planInstallTargetScaffold(options = {}) { } const targetRoot = adapter.resolveRoot(planningInput); const installStatePath = adapter.getInstallStatePath(planningInput); + const trustedRoots = typeof adapter.resolveTrustedRoots === 'function' + ? adapter.resolveTrustedRoots(planningInput) + : [targetRoot]; const operations = adapter.planOperations({ ...planningInput, modules, @@ -85,6 +90,7 @@ function planInstallTargetScaffold(options = {}) { kind: adapter.kind, }, targetRoot, + trustedRoots, installStatePath, validationIssues, operations, diff --git a/scripts/lib/install/apply.js b/scripts/lib/install/apply.js index 4dde6c16b..89af0ca13 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, @@ -21,6 +22,7 @@ const { getOpenCodeSourceActivationKind, planMaterializesHookRuntime, shouldDisableOpenCodeHooks, + shouldDisableAntigravityHooks, } = require('./hook-consent'); const { getClaudeSettingsPath, @@ -33,7 +35,7 @@ const { validateRecordedManagedHooks, } = require('./claude-settings'); const { filterMcpConfig, parseDisabledMcpServers } = require('../mcp-config'); -const { assertWithinTrustedRoot } = require('../path-safety'); +const { assertWithinTrustedRoot, isWithinRoot } = require('../path-safety'); const { assertSafeClaudeSkillOperation, prepareClaudeSkillMigration, @@ -86,10 +88,10 @@ function buildLinkIndexForPlan(plan) { return buildInstallIndex(mappings); } -function readJsonObject(filePath, label) { +function readJsonObject(filePath, label, readContent = () => fs.readFileSync(filePath, 'utf8')) { let parsed; try { - parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + parsed = JSON.parse(readContent()); } catch (error) { const wrappedError = new Error(`Failed to parse ${label} at ${filePath}: ${error.message}`); wrappedError.code = error.code; @@ -257,7 +259,15 @@ function writeClaudeCommitAttributionPreference(settingsPath, options = {}) { function isMcpConfigPath(filePath) { const basename = path.basename(String(filePath || '')); - return basename === '.mcp.json' || basename === 'mcp.json'; + return basename === '.mcp.json' || basename === 'mcp.json' || basename === 'mcp_config.json'; +} + +function getTrustedRootsForPlan(plan) { + if (!plan) return []; + if (Array.isArray(plan.trustedRoots) && plan.trustedRoots.length > 0) { + return plan.trustedRoots; + } + return plan.targetRoot ? [plan.targetRoot] : []; } function withMcpMergeExclusions(plan, disabledServers) { @@ -291,7 +301,9 @@ function assertSafeInstallOperation(plan, operation) { throw new Error('Refusing to apply install operation: missing destination path.'); } - const targetRoot = plan && plan.targetRoot; + const trustedRoots = getTrustedRootsForPlan(plan); + const matchingRoot = trustedRoots.find(root => isWithinRoot(operation.destinationPath, root)); + const targetRoot = matchingRoot || (plan && plan.targetRoot); assertWithinTrustedRoot(operation.destinationPath, targetRoot, 'install ECC file'); const resolvedRoot = path.resolve(targetRoot); @@ -703,6 +715,68 @@ function preflightClaudeSettingsOperations(plan) { })); } +function withoutManagedAntigravityHooks(plan, operation) { + const content = readInstalledFileNoFollow(plan, operation); + const config = content === null ? {} : JSON.parse(content.toString('utf8')); + if (!config || typeof config !== 'object' || Array.isArray(config)) { + throw new Error(`Invalid Antigravity hooks config: ${operation.destinationPath}`); + } + if (Object.hasOwn(config, 'ecc-guard') + && !isDeepStrictEqual(config['ecc-guard'], operation.mergePayload?.['ecc-guard'])) { + throw new Error(`Refusing to disable modified Antigravity hooks in ${operation.destinationPath}.`); + } + const userHooks = Object.fromEntries(Object.entries(config).filter(([name]) => name !== 'ecc-guard')); + return { + content: formatJson(userHooks), + expectedContent: content === null ? { kind: 'absent' } : { + kind: 'sha256', digest: crypto.createHash('sha256').update(content).digest('hex'), + }, + }; +} + +function prepareAntigravityHookDeactivation(plan, migration, previousState) { + if (!shouldDisableAntigravityHooks(plan)) return migration; + const hooksPath = path.join(plan.targetRoot, 'hooks.json'); + const previousHooks = previousState.operations.find(operation => ( + operation.ownership === 'managed' && operation.kind === 'merge-json' + && operation.moduleId === 'hooks-runtime' + && comparablePath(operation.destinationPath) === comparablePath(hooksPath) + )); + if (!previousHooks) return migration; + const removal = { ...previousHooks, kind: 'remove-antigravity-hooks' }; + // Check before ordinary writes, then re-read at the guarded write boundary. + withoutManagedAntigravityHooks(plan, removal); + const disabledSetup = { + ...previousHooks, + kind: 'merge-json', + destinationPath: path.join(plan.targetRoot, 'ecc', 'setup.json'), + mergePayload: { hooks: { enabled: false } }, + }; + assertSafeInstallOperation(plan, disabledSetup); + readOptionalJsonObject(disabledSetup.destinationPath, 'managed hook setup'); + const changed = new Set([hooksPath, disabledSetup.destinationPath].map(comparablePath)); + return { + ...migration, + appliedOperations: [ + ...migration.appliedOperations, removal, + { ...disabledSetup, kind: 'disable-antigravity-hook-setup' }, + ], + warnings: [...migration.warnings, 'Disabling previously installed Antigravity hooks; preserving user hook namespaces.'], + finalState: { + ...migration.finalState, + operations: [ + ...migration.finalState.operations.filter(operation => !changed.has(comparablePath(operation.destinationPath))), + { ...previousHooks, mergePayload: {} }, disabledSetup, + ], + }, + bridgeState: { + ...migration.bridgeState, + request: { ...migration.bridgeState.request, hookConsent: getRecordedHookConsent(previousState) }, + }, + requiresBridgeState: true, + }; +} + function prepareHookConsentMigration(plan, migration) { if (shouldDisableOpenCodeHooks(plan) && migration.requiresBridgeState) { const previousState = readPreviousInstallState(plan); @@ -732,6 +806,9 @@ function prepareHookConsentMigration(plan, migration) { if (!previousState) { return migration; } + if (shouldDisableAntigravityHooks(plan)) { + return prepareAntigravityHookDeactivation(plan, migration, previousState); + } const removals = (previousState.operations || []) .filter(operation => operation.kind === 'update-claude-settings') @@ -926,6 +1003,32 @@ function applyInstallPlanLocked(rawPlan, dependencies = {}, settingsLockHeld = f } assertOpenCodeActivationUnchanged(appliedPlan, operation, activationSnapshot); + if (['remove-antigravity-hooks', 'disable-antigravity-hook-setup'].includes(operation.kind)) { + const current = operation.kind === 'disable-antigravity-hook-setup' + ? readInstalledFileNoFollow(appliedPlan, operation) : null; + const disabled = operation.kind === 'remove-antigravity-hooks' + ? withoutManagedAntigravityHooks(appliedPlan, operation) + : { + content: formatJson(deepMergeJson( + readJsonObject(operation.destinationPath, 'managed hook setup', () => current || '{}'), + operation.mergePayload + )), + expectedContent: current === null ? { kind: 'absent' } : { + kind: 'sha256', digest: crypto.createHash('sha256').update(current).digest('hex'), + }, + }; + writeFileNoFollow(operation.destinationPath, disabled.content, { + action: 'disable Antigravity hooks', + expectedContent: disabled.expectedContent, + validateDestination(destinationPath) { + assertSafeInstallOperation(appliedPlan, { destinationPath }); + return destinationPath; + }, + }); + writtenDestinations.add(operation.destinationPath); + continue; + } + if ( operation.kind === 'update-claude-settings' || operation.kind === 'remove-claude-settings-hooks' diff --git a/scripts/lib/install/codex-user-config.js b/scripts/lib/install/codex-user-config.js index 4dade44f2..9cf429286 100644 --- a/scripts/lib/install/codex-user-config.js +++ b/scripts/lib/install/codex-user-config.js @@ -7,7 +7,7 @@ const { assertWithinTrustedRoot } = require('../path-safety'); const { sameFileIdentity } = require('./claude-settings-lock'); function isCodexUserConfig(plan, operation) { - if (!plan.adapter || plan.adapter.id !== 'codex-home' || operation.kind !== 'copy-file') { + if (plan?.adapter?.id !== 'codex-home' || operation?.kind !== 'copy-file') { return false; } const relativePath = path.relative(plan.targetRoot, operation.destinationPath); diff --git a/scripts/lib/install/hook-consent.js b/scripts/lib/install/hook-consent.js index 2504de499..6d752ad1d 100644 --- a/scripts/lib/install/hook-consent.js +++ b/scripts/lib/install/hook-consent.js @@ -274,6 +274,7 @@ function isHookRuntimeOperation(operation = {}) { || source.startsWith('.cursor/hooks/') || source === '.cursor/hooks.json' || destination.endsWith('/hooks/hooks.json') + || destination.endsWith('/hooks.json') || destination.endsWith('/.cursor/hooks.json') || destination.includes('/.cursor/hooks/') ); @@ -366,6 +367,11 @@ function shouldDisableOpenCodeHooks(plan = {}) { && (plan.hookConsent === 'declined' || !planSelectsHookRuntime(plan)); } +function shouldDisableAntigravityHooks(plan = {}) { + return ['antigravity', 'antigravity-home'].includes(plan.target) + && plan.hookConsent === 'declined'; +} + function setStatePreviewHookConsent(statePreview, hookConsent) { if (!statePreview || !statePreview.request) { return statePreview; @@ -500,5 +506,6 @@ module.exports = { planMaterializesHookRuntime, resolveHookConsentFlags, shouldDisableOpenCodeHooks, + shouldDisableAntigravityHooks, withHookConsent, }; 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 116cf50ed..0979546ca 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'); @@ -176,14 +177,18 @@ function materializeScaffoldOperation(sourceRoot, operation) { destinationPath: operation.destinationPath, strategy: operation.strategy || 'merge-json', ownership: operation.ownership || 'managed', - scaffoldOnly: Object.hasOwn(operation, 'scaffoldOnly') ? operation.scaffoldOnly : false, - mergePayload: readJsonObject(path.join(sourceRoot, operation.sourceRelativePath), operation.sourceRelativePath) + scaffoldOnly: typeof operation.scaffoldOnly === 'boolean' ? operation.scaffoldOnly : false, + mergePayload: operation.mergePayload !== undefined + ? JSON.parse(JSON.stringify(operation.mergePayload)) + : readJsonObject(path.join(sourceRoot, operation.sourceRelativePath), operation.sourceRelativePath) } ]; } - const sourcePath = path.join(sourceRoot, operation.sourceRelativePath); - if (!fs.existsSync(sourcePath)) { + const sourcePath = isPackageSourcePath(operation.sourceRelativePath) + ? resolvePackageSourcePath(sourceRoot, operation.sourceRelativePath) + : path.join(sourceRoot, operation.sourceRelativePath); + if (!sourcePath || !fs.existsSync(sourcePath)) { return []; } @@ -363,6 +368,7 @@ function createManifestInstallPlan(options = {}) { }, homeDir: plan.homeDir, targetRoot: plan.targetRoot, + trustedRoots: plan.trustedRoots || (plan.targetRoot ? [plan.targetRoot] : []), installRoot: plan.targetRoot, installStatePath: plan.installStatePath, warnings: Array.isArray(options.warnings) ? [...options.warnings] : [], 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/scripts/lib/resolve-ecc-root.js b/scripts/lib/resolve-ecc-root.js index d34a42c62..99495106e 100644 --- a/scripts/lib/resolve-ecc-root.js +++ b/scripts/lib/resolve-ecc-root.js @@ -73,7 +73,7 @@ const DEFAULT_SKILL_PROBE = path.join('skills', 'continuous-learning-v2'); function resolveEccRoot(options = {}) { const envRoot = options.envRoot !== undefined ? options.envRoot - : (process.env.CLAUDE_PLUGIN_ROOT || ''); + : (process.env.CLAUDE_PLUGIN_ROOT || process.env.ANTIGRAVITY_PLUGIN_ROOT || process.env.GEMINI_PLUGIN_ROOT || ''); if (envRoot && envRoot.trim()) { return envRoot.trim(); @@ -110,6 +110,12 @@ function resolveEccRoot(options = {}) { return claudeDir; } + // Antigravity global plugin install — ~/.gemini/config/plugins/ecc + const antigravityPluginDir = path.join(homeDir, '.gemini', 'config', 'plugins', 'ecc'); + if (isRoot(antigravityPluginDir)) { + return antigravityPluginDir; + } + // Exact legacy plugin install locations. These preserve backwards // compatibility without scanning arbitrary plugin trees. const legacyPluginRoots = PLUGIN_ROOT_SEGMENTS.map((segments) => diff --git a/tests/lib/antigravity-hook-consent.test.js b/tests/lib/antigravity-hook-consent.test.js new file mode 100644 index 000000000..88ad5f163 --- /dev/null +++ b/tests/lib/antigravity-hook-consent.test.js @@ -0,0 +1,142 @@ +'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, 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']) { + 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 })); + 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 || []) { + 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); + 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')); + 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', '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 }; + 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 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'), { + 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); + 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 { + 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 }); + } + }); + + 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 new file mode 100644 index 000000000..03f90a1b3 --- /dev/null +++ b/tests/lib/antigravity-lifecycle.test.js @@ -0,0 +1,153 @@ +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +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, uninstallInstalledStates } = require('../../scripts/lib/install-lifecycle'); + +const repoRoot = path.join(__dirname, '..', '..'); +const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'antigravity-lifecycle-')); +const homeDir = path.join(fixtureRoot, 'home'); +const projectRoot = path.join(fixtureRoot, 'project'); + +try { + fs.mkdirSync(homeDir); + fs.mkdirSync(projectRoot); + const plan = withHookConsent(createManifestInstallPlan({ + profileId: 'core', + target: 'antigravity-home', + homeDir, + projectRoot, + }), 'enabled'); + const workflowPath = path.join(homeDir, '.gemini', 'config', 'workflows', 'plan.md'); + applyInstallPlan(plan); + + const original = fs.readFileSync(workflowPath, 'utf8'); + fs.unlinkSync(workflowPath); + + const doctor = buildDoctorReport({ + repoRoot, + homeDir, + projectRoot, + targets: ['antigravity-home'], + }).results[0]; + assert.ok(!doctor.issues.some(issue => issue.code === 'unsafe-managed-destination')); + + const repaired = repairInstalledStates({ + repoRoot, + homeDir, + projectRoot, + targets: ['antigravity-home'], + }).results[0]; + assert.strictEqual(repaired.status, 'repaired', repaired.error); + assert.strictEqual(fs.readFileSync(workflowPath, 'utf8'), original); + + const outsidePath = path.join(homeDir, 'outside.md'); + fs.writeFileSync(outsidePath, 'user content'); + fs.unlinkSync(workflowPath); + fs.symlinkSync(outsidePath, workflowPath); + const refused = repairInstalledStates({ + repoRoot, + homeDir, + projectRoot, + targets: ['antigravity-home'], + }).results[0]; + assert.strictEqual(refused.status, 'error'); + assert.match(refused.error, /unsafe managed destination|symlink/i); + assert.strictEqual(fs.readFileSync(outsidePath, 'utf8'), 'user content'); + + 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); + // 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, + 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); + + 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: 7, Failed: 0'); +} finally { + fs.rmSync(fixtureRoot, { recursive: true, force: true }); +} diff --git a/tests/lib/antigravity-mcp-policy.test.js b/tests/lib/antigravity-mcp-policy.test.js new file mode 100644 index 000000000..56603bbde --- /dev/null +++ b/tests/lib/antigravity-mcp-policy.test.js @@ -0,0 +1,75 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { test } = require('node:test'); +const { getInstallTargetAdapter } = require('../../scripts/lib/install-targets/registry'); +const { createManifestInstallPlan } = require('../../scripts/lib/install/plan'); +const { applyInstallPlan } = require('../../scripts/lib/install/apply'); + +for (const target of ['antigravity', 'antigravity-home']) { + test(`${target} persists the selected hook profile in managed setup`, () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-hook-profile-')); + try { + const operations = getInstallTargetAdapter(target).planOperations({ + repoRoot: root, projectRoot: root, homeDir: root, + env: { ECC_HOOK_PROFILE: 'minimal' }, + modules: [{ id: 'hooks-runtime', paths: ['hooks'] }], + }); + const setup = operations.find(op => op.destinationPath.endsWith(path.join('ecc', 'setup.json'))); + assert.ok(setup, 'Hook installation must persist its runtime profile'); + assert.deepEqual(setup.mergePayload, { hooks: { enabled: true, profile: 'minimal' } }); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + test(`${target} does not promote executable repository MCP definitions`, () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-mcp-policy-')); + try { + fs.writeFileSync(path.join(root, '.mcp.json'), JSON.stringify({ + mcpServers: { untrusted: { command: 'untrusted-command', args: ['run'], env: { SOURCE_ONLY: 'value' } } }, + })); + const operations = getInstallTargetAdapter(target).planOperations({ + repoRoot: root, projectRoot: root, homeDir: root, + modules: [{ id: 'platform-configs', paths: ['.mcp.json'] }], + }); + const config = operations.find(op => path.basename(op.destinationPath) === 'mcp_config.json'); + assert.deepEqual(Object.keys(config.mergePayload.mcpServers), ['ecc-memory']); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + for (const disabled of [false, true]) { + test(`${target} preserves user servers and ${disabled ? 'suppresses disabled' : 'adds'} ECC memory`, () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-mcp-install-policy-')); + const previous = process.env.ECC_DISABLED_MCPS; + try { + if (disabled) process.env.ECC_DISABLED_MCPS = 'ecc-memory'; + else delete process.env.ECC_DISABLED_MCPS; + const projectRoot = path.join(root, 'project'); + fs.mkdirSync(projectRoot); + const plan = createManifestInstallPlan({ + moduleIds: ['platform-configs'], target, homeDir: root, projectRoot, + }); + const configPath = path.join(plan.targetRoot, 'mcp_config.json'); + const userServer = { command: 'user-selected-server', args: ['--user-option'] }; + fs.mkdirSync(plan.targetRoot, { recursive: true }); + fs.writeFileSync(configPath, JSON.stringify({ mcpServers: { 'user-server': userServer } })); + applyInstallPlan(plan); + const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); + assert.deepEqual(config.mcpServers['user-server'], userServer); + assert.equal(Object.hasOwn(config.mcpServers, 'ecc-memory'), !disabled); + assert.deepEqual(Object.keys(config.mcpServers).sort(), disabled + ? ['user-server'] : ['ecc-memory', 'user-server']); + } finally { + if (previous === undefined) delete process.env.ECC_DISABLED_MCPS; + else process.env.ECC_DISABLED_MCPS = previous; + fs.rmSync(root, { recursive: true, force: true }); + } + }); + } +} diff --git a/tests/lib/antigravity-tier1.test.js b/tests/lib/antigravity-tier1.test.js new file mode 100644 index 000000000..6cf035f7c --- /dev/null +++ b/tests/lib/antigravity-tier1.test.js @@ -0,0 +1,610 @@ +'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 } = 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, 'Bash'); + 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'); + 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, 'Edit'); + 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', 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'); + 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|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')), + 'Should invoke GateGuard on write operations' + ); + }); + + test('buildAntigravityMcpConfig generates valid stdio MCP configuration for ecc-memory', () => { + 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']; + 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('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', () => { + if (process.platform === 'win32') return; + 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); + + 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, + 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'); + 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, + }); + + 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(homeDir, '.gemini', 'config', '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: 'pwd', + }, + }, + }); + + 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); + 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-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-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 { + 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'); + + 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'); + 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'); + + 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']); + 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); + } + }); + + 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 41d5fe66c..ccc8607b8 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 17 registered targets exactly once across 16 harnesses', () => { + if (test('represents all 18 registered targets exactly once across 16 harnesses', () => { const catalogTargetIds = HARNESS_CAPABILITIES.flatMap(harness => harness.targetIds); const adapterTargetIds = listInstallTargetAdapters().map(adapter => adapter.target); assert.strictEqual(HARNESS_CAPABILITIES.length, 16); - assert.strictEqual(new Set(catalogTargetIds).size, 17); + assert.strictEqual(new Set(catalogTargetIds).size, 18); 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/lib/install-manifests.test.js b/tests/lib/install-manifests.test.js index 0cb0baf46..62a6e3396 100644 --- a/tests/lib/install-manifests.test.js +++ b/tests/lib/install-manifests.test.js @@ -291,13 +291,15 @@ function runTests() { 'rules-core', 'agents-core', 'commands-core', + 'hooks-runtime', 'platform-configs', 'skill-unified-memory', 'workflow-quality', 'shared-script-utils' ] ); - 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/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); diff --git a/tests/scripts/antigravity-hook-bridge.test.js b/tests/scripts/antigravity-hook-bridge.test.js new file mode 100644 index 000000000..2566de33b --- /dev/null +++ b/tests/scripts/antigravity-hook-bridge.test.js @@ -0,0 +1,106 @@ +'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 }, + '../lib/hook-flags': { isHookEnabled: () => true, isDryRun: () => false }, + './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({ 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); + 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/antigravity-hook-policy.test.js b/tests/scripts/antigravity-hook-policy.test.js new file mode 100644 index 000000000..f232c269f --- /dev/null +++ b/tests/scripts/antigravity-hook-policy.test.js @@ -0,0 +1,146 @@ +'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, execFileSync } = 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 = [ + { ECC_HOOKS_ENABLED: 'false' }, + { ECC_HOOK_PROFILE: 'minimal' }, + { ECC_DISABLED_HOOKS: 'stop:format-typecheck' }, + { 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, + env: { + ...process.env, ECC_HOOKS_ENABLED: 'true', ECC_HOOK_PROFILE: 'standard', + ECC_DISABLED_HOOKS: '', ECC_DRY_RUN: '0', ECC_HOOK_CONFIG: '', ...env, + }, + }); + assert.equal(child.status, 0, child.stderr); + return JSON.parse(child.stdout); +} + +test('Stop formatting writes only when enabled; disabled, minimal and dry-run preserve edits', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-agy-policy-')); + const conversationId = path.basename(root); + const accumulator = path.join(os.tmpdir(), `ecc-edited-${conversationId}.txt`); + try { + const target = path.join(root, 'component.js'); + const marker = path.join(root, 'formatter-args.json'); + const binDir = path.join(root, 'node_modules', '.bin'); + fs.mkdirSync(binDir, { recursive: true }); + fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ prettier: {} })); + fs.writeFileSync(target, 'const value = 1;\n'); + const script = path.join(root, 'formatter.cjs'); + fs.writeFileSync(script, `require('fs').writeFileSync(${JSON.stringify(marker)}, JSON.stringify(process.argv.slice(2)));`); + const bin = path.join(binDir, process.platform === 'win32' ? 'prettier.cmd' : 'prettier'); + fs.writeFileSync(bin, process.platform === 'win32' + ? `@echo off\r\n"${process.execPath}" "${script}" %*\r\n` + : `#!/bin/sh\nexec '${process.execPath.replace(/'/g, "'\\''")}' '${script.replace(/'/g, "'\\''")}' "$@"\n`, { mode: 0o755 }); + const payload = { conversationId, workspacePaths: [root], fullyIdle: true }; + for (const env of controls) { + fs.writeFileSync(accumulator, `${target}\n`); + assert.equal(invoke('stop', 'stop:format-typecheck', payload, env).decision, 'allow'); + assert.equal(fs.existsSync(marker), false, JSON.stringify(env)); + assert.equal(fs.readFileSync(accumulator, 'utf8'), `${target}\n`, JSON.stringify(env)); + } + // The upstream Windows formatter deliberately skips shell-unsafe paths. + if (process.platform !== 'win32' || !/[&|<>^%!\s()]/.test(target)) { + invoke('stop', 'stop:format-typecheck', payload); + assert.ok(JSON.parse(fs.readFileSync(marker, 'utf8')).includes('--write')); + assert.ok(!fs.existsSync(accumulator)); + } + } finally { + fs.rmSync(root, { recursive: true, force: true }); + fs.rmSync(accumulator, { force: true }); + } +}); + +test('PostToolUse and warnings honor the same execution controls', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-agy-flags-')); + const conversationId = path.basename(root); + const accumulator = path.join(os.tmpdir(), `ecc-edited-${conversationId}.txt`); + try { + const edit = { conversationId, toolCall: { name: 'write_to_file', args: { TargetFile: path.join(root, 'app.js') } } }; + for (const env of [...controls.slice(0, 2), { ECC_DISABLED_HOOKS: 'post:edit:accumulator' }, controls[3]]) { + assert.deepEqual(invoke('post-tool-use', 'post:edit:accumulator', edit, env), {}); + assert.equal(fs.existsSync(accumulator), false, JSON.stringify(env)); + } + const doc = { toolCall: { name: 'write_to_file', args: { TargetFile: path.join(root, 'NOTES.md') } } }; + for (const env of [...controls.slice(0, 2), { ECC_DISABLED_HOOKS: 'pre:write:doc-file-warning' }, controls[3]]) { + assert.deepEqual(invoke('pre-tool-use', 'pre:write:doc-file-warning', doc, env), { decision: 'allow' }); + } + assert.match(invoke('pre-tool-use', 'pre:write:doc-file-warning', doc).reason, /Ad-hoc documentation/); + invoke('post-tool-use', 'post:edit:accumulator', edit); + assert.equal(fs.readFileSync(accumulator, 'utf8').trim(), edit.toolCall.args.TargetFile); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + fs.rmSync(accumulator, { force: true }); + } +}); + +test('managed profile is used unless an explicit environment choice overrides it', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-agy-config-')); + try { + const config = path.join(root, 'setup.json'); + fs.writeFileSync(config, JSON.stringify({ hooks: { enabled: true, profile: 'minimal' } })); + const payload = { toolCall: { name: 'write_to_file', args: { TargetFile: path.join(root, 'NOTES.md') } } }; + assert.deepEqual(invoke('pre-tool-use', 'pre:write:doc-file-warning', payload, { + ECC_HOOK_PROFILE: undefined, ECC_HOOK_CONFIG: config, + }), { decision: 'allow' }); + assert.match(invoke('pre-tool-use', 'pre:write:doc-file-warning', payload, { + ECC_HOOK_PROFILE: 'strict', ECC_HOOK_CONFIG: config, + }).reason, /Ad-hoc documentation/); + } finally { + 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 }); + 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]) { + 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 }); + } +}); diff --git a/tests/scripts/antigravity-native-plugin.test.js b/tests/scripts/antigravity-native-plugin.test.js new file mode 100644 index 000000000..e2515b338 --- /dev/null +++ b/tests/scripts/antigravity-native-plugin.test.js @@ -0,0 +1,66 @@ +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); +const { createManifestInstallPlan } = require('../../scripts/lib/install/plan'); +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: 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) { + return spawnSync('agy', args, { env, cwd: root, encoding: 'utf8', timeout: 15000 }); +} + +function checked(args) { + const result = agy(args); + assert.strictEqual(result.status, 0, result.error?.message || result.stderr || result.stdout); + return result.stdout; +} + +try { + const version = agy(['--version']); + 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); + const plan = withHookConsent(createManifestInstallPlan({ + sourceRoot: path.resolve(__dirname, '../..'), + profileId: 'core', + target: 'antigravity-home', + projectRoot: path.join(root, 'workspace'), + homeDir: path.join(root, 'install-home'), + }), 'enabled'); + applyInstallPlan(plan); + assert.ok(fs.existsSync(path.join(plan.targetRoot, 'plugin.json'))); + const validation = checked(['plugin', 'validate', plan.targetRoot]); + assert.match(validation, /\[ok\]/); + checked(['plugin', 'install', plan.targetRoot]); + const listed = JSON.parse(checked(['plugin', 'list', '--json'])); + const plugin = listed.find(entry => entry.name === 'ecc'); + assert.ok(plugin, 'Native CLI must discover ECC after explicit local import'); + 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'); + } +} finally { + fs.rmSync(root, { recursive: true, force: true }); +} diff --git a/tests/scripts/install-apply.test.js b/tests/scripts/install-apply.test.js index 6236efa8e..c52c61cbe 100644 --- a/tests/scripts/install-apply.test.js +++ b/tests/scripts/install-apply.test.js @@ -1018,7 +1018,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'))); @@ -1029,6 +1029,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'); @@ -1039,13 +1040,14 @@ function runTests() { 'rules-core', 'agents-core', 'commands-core', + 'hooks-runtime', 'platform-configs', 'skill-unified-memory', 'workflow-quality', 'shared-script-utils' ] ); - 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 {