From 5695522d5f94211660e9f3d5c12728705318ff6a Mon Sep 17 00:00:00 2001 From: Tom Boucher Date: Sat, 11 Jul 2026 02:27:57 -0400 Subject: [PATCH] feat(#2096): migrate Antigravity onto EoS declarative adapter + permission-writer + MCP companion (ADR-1239) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fold all antigravity literal branches into descriptor-driven reads: getConfigDirFromHome (→ configHome.kind 'dot-home-nested'), projectLocalHookPrefix (→ hostBehaviors.hookPathStyle 'raw'), applyAgentPathRewrites (→ noPathRewrite), getProjectInstructionFile (→ projectInstructionFile 'GEMINI.md'); removed the dead inline convertClaudeAgentToAntigravityAgent branch + dead isAntigravity destructures (antigravity is already on the descriptor-agents path). subagentToolkit flipped undocumented→full (Context7: antigravity.google/docs/cli/features); namedDispatch/nested/maxDepth/backgroundDispatch stay undocumented. Byte-identical golden parity for all 16 runtimes. UPGRADE 1 (permission-writer): permissionWriter 'antigravity' + configureAntigravityPermissions merges a scoped permissions.allow block (GSD's own tree + hooks) into Antigravity's settings.json — non-destructive, idempotent, symmetric uninstall. Added to VALID_PERMISSION_WRITERS + the FinishPermissionWriter union. UPGRADE 2 (MCP companion): configureAntigravityMcpConfig writes mcp_config.json registering the gsd-core companion MCP server (Gemini-successor mcpServers schema, best-effort — raw schema unpublished). Both writers dispatch from finishInstall. settings.json is golden-excluded (HOOK_CONFIG_FILES); mcp_config.json (portable, no absolute paths) is golden-tracked → only antigravity.json changes. Tests: declarative-reference-antigravity extended (source-grep guard across 4 modules, fail-closed for the 4 undocumented sub-axes, validator acceptance) + antigravity-upgrades (permission-writer + mcp_config live-install, idempotency, user-preservation). Matrix + ADR-1016 + capability-manifest + CONTEXT.md + connect-gsd-mcp-server docs updated; changeset (Changed). Co-Authored-By: Claude Opus 4.8 --- ...2096-eos-antigravity-imperative-adapter.md | 5 + CONTEXT.md | 2 +- bin/install.js | 273 ++++++++++++++++- capabilities/antigravity/capability.json | 10 +- .../adr/1016-runtime-capability-descriptor.md | 4 +- docs/how-to/connect-gsd-mcp-server.md | 7 +- docs/reference/capability-manifest.md | 4 +- .../host-integration-capability-matrix.md | 6 +- gsd-core/bin/lib/capability-registry.cjs | 20 +- gsd-core/bin/lib/capability-validator.cjs | 3 +- src/runtime-artifact-conversion.cts | 12 +- src/runtime-config-adapter-registry.cts | 11 +- src/runtime-name-policy.cts | 17 +- src/shell-command-projection.cts | 12 +- tests/antigravity-upgrades.test.cjs | 283 ++++++++++++++++++ tests/capability-registry.test.cjs | 5 +- ...declarative-reference-antigravity.test.cjs | 146 ++++++++- .../golden-install-parity/antigravity.json | 1 + ...shell-command-projection-dispatch.test.cjs | 27 +- 19 files changed, 800 insertions(+), 48 deletions(-) create mode 100644 .changeset/2096-eos-antigravity-imperative-adapter.md create mode 100644 tests/antigravity-upgrades.test.cjs diff --git a/.changeset/2096-eos-antigravity-imperative-adapter.md b/.changeset/2096-eos-antigravity-imperative-adapter.md new file mode 100644 index 000000000..5e5828552 --- /dev/null +++ b/.changeset/2096-eos-antigravity-imperative-adapter.md @@ -0,0 +1,5 @@ +--- +type: Changed +pr: 2165 +--- +**Installing GSD into Antigravity now writes the `permissions.allow` rules its CLI documents** — so GSD's own reads and hooks aren't stuck on interactive prompts — and registers GSD's companion MCP server via a standalone `mcp_config.json` (best-effort: Antigravity's raw config schema isn't published, so this uses the Gemini-CLI-successor format). Antigravity's install is now driven by its negotiated capability descriptor instead of hardcoded runtime special-cases. (#2096) diff --git a/CONTEXT.md b/CONTEXT.md index b070bbcc9..ecc309fa6 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -273,7 +273,7 @@ The `mempalace.memory_mode` config key controlling how authoritative MemPalace i Standalone hook-surface writer module extracted from `bin/install.js` as ADR-857 phase 5f-1 (behavior-preserving relocation, no logic change). Owns: Cline rules-body/agents-md/pre-tool-use hook generation (`buildClineRulesBody`, `buildClineAgentsMdBody`, `buildClinePreToolUseHook`, `mergeGsdAgentsMd`, `writeClineArtifacts`); Cursor `hooks.json` lifecycle (`buildCursorHookEntry`, `isManagedCursorHookEntry`, `reconcileCursorHooksJson`, `writeCursorHooksJson`, `removeCursorHooksJson`); Copilot session-hook config (`buildCopilotHookConfig`, `writeCopilotHookConfig`); Codex hook-block and event management (`buildCodexHookBlock`, `rewriteLegacyCodexHookBlock`, `reconcileCodexHooksJsonEvent`, `reconcileCodexHooksJsonSessionStart`, `ensureCodexHooksJsonSessionStart`, `ensureCodexHooksJsonEvent`, `removeCodexHooksJsonEvent`, `removeCodexHooksJsonSessionStart`, `buildCodexHookWindowsShimIR`); Kimi native config.toml `[[hooks]]` lifecycle (`buildKimiHooksTomlBlock`, `stripKimiHooksTomlBlock`, `writeKimiHooksToml`, `removeKimiHooksToml` — #2095 EoS/kimi Upgrade 1, the first genuinely NEW hook surface added post-relocation rather than a behavior-preserving move: kimi's `[[hooks]]` array lives in its own native `config.toml`, resolved by `resolveKimiHooksTomlDir` in Runtime Homes Module to a directory deliberately separate from kimi's GSD configDir, wrapped in `# GSD Hooks BEGIN`/`END` marker comments for idempotent reinstall); and shared hook command helpers (`buildHookCommand`, `rewriteLegacyManagedNodeHookCommands`, `normalizeNodePath`, `resolveNodeRunner`). `bin/install.js` delegates to this module via thin wrappers and re-exports its functions unchanged so existing tests require no modification. Source: `src/runtime-hooks-surface.cts`. Built output: `gsd-core/bin/lib/runtime-hooks-surface.cjs`. ### Runtime Config Adapter Registry -Module owning the explicit per-runtime config-mutation dispatch table for the installer. `resolveRuntimeConfigIntent(runtime)` projects a typed config intent — `installSurface` (`settings-json` | `codex-toml` | `copilot-instructions` | `cline-rules` | `cursor-hooks-json` | `profile-marker-only`), `writesSharedSettings` (the `finishInstall` shared-settings write gate), and `finishPermissionWriter` (`opencode` | `kilo` | none) — that `bin/install.js` dispatches on instead of inline `runtime === '...'` branching. Owns adapter selection only: it performs no filesystem IO and does not execute config mutations (the install/finishInstall handlers and the per-runtime writers do that). Unknown runtimes fail loudly with a `TypeError`, guarded by an `Object.hasOwn` own-property check so prototype-chain keys (`__proto__`, `constructor`) also throw. Also exports `resolveInstallPlan(runtime)` — the ADR-58 `InstallPlan` capstone — which collects the install-level descriptor axes (`installSurface`, `writesSharedSettings`, `finishPermissionWriter`, `hookEvents`, `extendedHookEvents`, `hooksSurface`, `sandboxTier`) into one typed `InstallPlan` value consumed by `install()` and `finishInstall()` in `bin/install.js`. `sandboxTier` (`none` | `codex-agent-sandbox`) gates per-agent `sandbox_mode` emission in the codex TOML path and fails loud on a missing/invalid value (#1151). The spatial axes (`configHome`, `artifactLayout`, `commandStyle`) remain behind their self-resolving adapter modules and are not part of the plan; they are the execution adapters. Realizes both the adapter-selection and plan-collection halves of the Runtime Install Policy Module boundary. Source: `gsd-core/bin/lib/runtime-config-adapter-registry.cjs`. See ADR-58, #60. +Module owning the explicit per-runtime config-mutation dispatch table for the installer. `resolveRuntimeConfigIntent(runtime)` projects a typed config intent — `installSurface` (`settings-json` | `codex-toml` | `copilot-instructions` | `cline-rules` | `cursor-hooks-json` | `profile-marker-only`), `writesSharedSettings` (the `finishInstall` shared-settings write gate), and `finishPermissionWriter` (`opencode` | `kilo` | `antigravity` | none) — that `bin/install.js` dispatches on instead of inline `runtime === '...'` branching. Owns adapter selection only: it performs no filesystem IO and does not execute config mutations (the install/finishInstall handlers and the per-runtime writers do that). Unknown runtimes fail loudly with a `TypeError`, guarded by an `Object.hasOwn` own-property check so prototype-chain keys (`__proto__`, `constructor`) also throw. Also exports `resolveInstallPlan(runtime)` — the ADR-58 `InstallPlan` capstone — which collects the install-level descriptor axes (`installSurface`, `writesSharedSettings`, `finishPermissionWriter`, `hookEvents`, `extendedHookEvents`, `hooksSurface`, `sandboxTier`) into one typed `InstallPlan` value consumed by `install()` and `finishInstall()` in `bin/install.js`. `sandboxTier` (`none` | `codex-agent-sandbox`) gates per-agent `sandbox_mode` emission in the codex TOML path and fails loud on a missing/invalid value (#1151). The spatial axes (`configHome`, `artifactLayout`, `commandStyle`) remain behind their self-resolving adapter modules and are not part of the plan; they are the execution adapters. Realizes both the adapter-selection and plan-collection halves of the Runtime Install Policy Module boundary. Source: `gsd-core/bin/lib/runtime-config-adapter-registry.cjs`. See ADR-58, #60. ### Claude Code Plugin Manifest Module Module owning the projection of gsd-core's artifact surfaces (`commands`, `agents`, hooks) onto the Claude Code plugin contract (`.claude-plugin/plugin.json` + `hooks/hooks.json`) — the plugin-contract sibling of the Runtime Artifact Layout Module (which projects the same surfaces onto filesystem placements). Defined mapping: `name`=`binName` (drives the `/gsd-core:` command namespace), `repository`/`homepage`=`repoUrl` (Package Identity Module), `version`/`description`/`license` from `package.json` (`version` is required for `claude plugin validate --strict`), `commands`=`./commands/gsd/`, agents via Claude Code's default `agents/` discovery (the explicit string form is schema-rejected), `hooks`=`./hooks/hooks.json`. The hook projection carries ONLY the always-on subset of the Installer Module's Claude `settings.json` wiring (check-update, context-monitor, prompt-guard, read-guard, worktree-path-guard, read-injection-scanner) via `${CLAUDE_PLUGIN_ROOT}`; config-gated opt-in hooks are excluded because a static manifest cannot honor per-project config gates, and plugin-shipped agents cannot carry hook frontmatter (so all plugin-path hook wiring lives in hooks.json). `hooks.json` covers all seven Claude Code lifecycle events: SessionStart, PreToolUse, PostToolUse, SubagentStop, Stop, PreCompact (all wired to context-monitor for context-headroom awareness), and FileChanged (matcher: `config.json` → config-reload, injects `additionalContext` when `.planning/config.json` changes mid-session). Additive — the file-copy path (Runtime Artifact Layout / Install Policy / Installer Modules) is unchanged. Conformance is validated by `claude plugin validate --strict` plus the in-repo drift-guard `tests/issue-766-plugin-manifest.test.cjs`. _Avoid_: "the plugin API", "the plugin file" (when you mean the seam). See ADR-766 and Runtime Artifact Layout Module. diff --git a/bin/install.js b/bin/install.js index 651196b10..c5bfdb513 100755 --- a/bin/install.js +++ b/bin/install.js @@ -386,6 +386,12 @@ const FALLBACK_HOST_BEHAVIORS = Object.freeze({ legacyCommandsGsdInstallMigration: true, legacyCommandsGsdUninstall: 'global', }), + // antigravity's global config dir is resolved dynamically (env-overridable, + // multi-segment) via resolveAntigravityGlobalDir in getConfigDirFromHome. If the + // registry fails to load, this floor keeps that routing intact instead of + // silently falling through to the generic getGlobalConfigHomeFragment default + // (which would return the wrong '.claude' fragment). (ADR-1239 / #2096) + antigravity: Object.freeze({ globalDirResolver: 'antigravity' }), }); /** @@ -640,7 +646,15 @@ function getConfigDirFromHome(runtime, isGlobal) { // multi-segment via resolveAntigravityGlobalDir + path.relative) — not a table // entry. (The prior inner `if (!isGlobal) return "'.agents'"` was unreachable: // !isGlobal returns at the top of this function.) - if (runtime === 'antigravity') { + // Descriptor-driven (ADR-1239 / #2096): folded from a hardcoded + // `runtime === 'antigravity'` literal into a read of the runtime's + // `hostBehaviors.globalDirResolver` descriptor field (via _hostBehaviors, which + // also degrades to FALLBACK_HOST_BEHAVIORS on registry-load failure). This is + // antigravity-unique: unlike `configHome.kind === 'dot-home-nested'` (which + // windsurf also declares — see capabilities/windsurf/capability.json — and + // would wrongly route windsurf's global dir through + // resolveAntigravityGlobalDir), `globalDirResolver` is only set by antigravity. + if (_hostBehaviors(runtime).globalDirResolver === 'antigravity') { const antigravityDir = resolveAntigravityGlobalDir(); const rel = path.relative(os.homedir(), antigravityDir); const segments = rel.split(path.sep).filter(Boolean); @@ -6843,7 +6857,8 @@ function uninstall(isGlobal, runtime = DEFAULT_RUNTIME) { // skipSharedHooksInstall fold (was never referenced here besides the // destructure). #2095: isKimi likewise dropped — kimi is now a hooks/ // consumer, so its former `&& !isKimi` uninstall guards were removed. - const { isOpencode, isCodex, isCopilot, isAntigravity, isCursor, isWindsurf, isAugment, isQwen, isHermes, isCodebuddy, isCline } = runtimeFlags(runtime); + // #2096: isAntigravity dropped — unused in this function. + const { isOpencode, isCodex, isCopilot, isCursor, isWindsurf, isAugment, isQwen, isHermes, isCodebuddy, isCline } = runtimeFlags(runtime); const dirName = getDirName(runtime); // Get the target directory based on runtime and install type. Cline local @@ -7505,6 +7520,32 @@ function uninstall(isGlobal, runtime = DEFAULT_RUNTIME) { } } + // #2096 Phase B Upgrade 1 — Remove GSD-owned Antigravity permissions.allow + // rules from settings.json. Symmetric to the Claude branch above: filters + // only the exact GSD-owned rule strings (regenerated from the current + // configDir) to preserve any user-added allow entries and all deny/ask. + if (resolveInstallPlan(runtime).finishPermissionWriter === 'antigravity' && settings.permissions) { + let antigravityPermissionsModified = false; + if (Array.isArray(settings.permissions.allow)) { + const gsdRules = new Set(buildAntigravityAllowRules(targetDir)); + const before = settings.permissions.allow.length; + settings.permissions.allow = settings.permissions.allow.filter((e) => !gsdRules.has(e)); + if (settings.permissions.allow.length !== before) { + antigravityPermissionsModified = true; + } + if (settings.permissions.allow.length === 0) { + delete settings.permissions.allow; + } + } + if (Object.keys(settings.permissions).length === 0) { + delete settings.permissions; + } + if (antigravityPermissionsModified) { + settingsModified = true; + console.log(` ${green}✓${reset} Removed GSD permissions from settings.json`); + } + } + if (settingsModified) { writeSettings(settingsPath, settings); removedCount++; @@ -7595,6 +7636,29 @@ function uninstall(isGlobal, runtime = DEFAULT_RUNTIME) { } } + // 8. For Antigravity, remove the MCP companion entry from mcp_config.json + // (#2096 Phase B Upgrade 2). Only the GSD-owned mcpServers.gsd key is + // removed — any other user-configured MCP servers are preserved. + if (resolveInstallPlan(runtime).finishPermissionWriter === 'antigravity') { + const mcpConfigPath = path.join(targetDir, 'mcp_config.json'); + if (fs.existsSync(mcpConfigPath)) { + try { + const mcpConfig = JSON.parse(fs.readFileSync(mcpConfigPath, 'utf8')); + if (mcpConfig && typeof mcpConfig === 'object' && mcpConfig.mcpServers && mcpConfig.mcpServers.gsd !== undefined) { + delete mcpConfig.mcpServers.gsd; + if (Object.keys(mcpConfig.mcpServers).length === 0) { + delete mcpConfig.mcpServers; + } + fs.writeFileSync(mcpConfigPath, JSON.stringify(mcpConfig, null, 2) + '\n'); + removedCount++; + console.log(` ${green}✓${reset} Removed GSD MCP companion server from mcp_config.json`); + } + } catch (e) { + // Ignore JSON parse errors + } + } + } + // Remove the file manifest that the installer wrote at install time. // Without this step the metadata file persists after uninstall (#1908). const manifestPath = path.join(targetDir, MANIFEST_NAME); @@ -7848,6 +7912,172 @@ function configureKiloPermissions(isGlobal = true, configDir = null) { console.log(` ${green}✓${reset} Configured read permission for GSD docs`); } +/** + * Convert an absolute path to a `~`-relative form when it lives under the + * user's home directory (generalizes configureKiloPermissions' + * single-default-dir shorthand to Antigravity's three probed sibling config + * dirs — antigravity/antigravity-ide/antigravity-cli under ~/.gemini — none of + * which is a single fixed "default"). + */ +function toTildePosixPath(absPath) { + const posixPath = absPath.replace(/\\/g, '/'); + const posixHome = os.homedir().replace(/\\/g, '/'); + return posixPath === posixHome || posixPath.startsWith(`${posixHome}/`) + ? `~${posixPath.slice(posixHome.length)}` + : posixPath; +} + +/** + * Antigravity permission rule strings this installer contributes. + * Schema: antigravity.google/docs/cli/permissions — "action(target)" rule + * strings in permissions.{allow,deny,ask}, evaluated deny > ask > allow. GSD + * only ever contributes to `allow` — never deny/ask (those are user-owned risk + * decisions this installer has no business making). + */ +function buildAntigravityAllowRules(configDir) { + const gsdPath = toTildePosixPath(configDir); + return [ + `read_file(${gsdPath}/gsd-core/*)`, + `read_file(${gsdPath}/agents/gsd-*)`, + `read_file(${gsdPath}/skills/gsd-*)`, + `command(node ${gsdPath}/hooks/*)`, + ]; +} + +/** + * Configure Antigravity permissions to allow reading/executing GSD's installed + * tree without per-call approval prompts (#2096 Phase B Upgrade 1 — mirrors + * configureKiloPermissions/configureOpencodePermissions). + * + * Antigravity's permission schema (antigravity.google/docs/cli/permissions) is + * `{"permissions":{"allow":[...],"deny":[...],"ask":[...]}}`, living in the + * SAME settings.json GSD's own hook registration writes for this runtime + * (installSurface: 'settings-json', writesSharedSettings: true) — unlike + * Kilo/OpenCode, which write a separate native config file. This function + * re-reads the file (already containing GSD's hooks by the time finishInstall + * reaches this call) and only appends to permissions.allow. + * + * Non-destructive + idempotent: only `permissions.allow` is touched; an + * existing user permissions block (including any deny/ask entries, or + * unrelated allow entries) is preserved untouched. + * + * @param {boolean} isGlobal - Whether this is a global or local install + * @param {string|null} configDir - Resolved config directory when already known + */ +function configureAntigravityPermissions(isGlobal = true, configDir = null) { + // For local installs, use ./.agents/ (GSD's antigravity localConfigDir) + // For global installs, use the resolved ~/.gemini/antigravity{,-ide,-cli} + const antigravityConfigDir = configDir || (isGlobal + ? getGlobalConfigDir('antigravity', explicitConfigDir) + : path.join(process.cwd(), '.agents')); + // Ensure config directory exists + fs.mkdirSync(antigravityConfigDir, { recursive: true }); + + const configPath = path.join(antigravityConfigDir, 'settings.json'); + + // Read existing settings.json (readSettings tolerates JSONC + missing file; + // returns null — and warns — only when the file exists but fails to parse). + const config = readSettings(configPath); + if (config === null) { + // Cannot parse — DO NOT overwrite user's config (readSettings already warned). + return; + } + + // Ensure permission structure exists + if (!config.permissions || typeof config.permissions !== 'object' || Array.isArray(config.permissions)) { + config.permissions = {}; + } + if (!Array.isArray(config.permissions.allow)) { + config.permissions.allow = []; + } + + let modified = false; + for (const rule of buildAntigravityAllowRules(antigravityConfigDir)) { + if (!config.permissions.allow.includes(rule)) { + config.permissions.allow.push(rule); + modified = true; + } + } + + if (!modified) { + return; // Already configured + } + + writeSettings(configPath, config); + console.log(` ${green}✓${reset} Configured Antigravity permissions for GSD paths`); +} + +/** + * Configure Antigravity's MCP companion server config (#2096 Phase B + * Upgrade 2). + * + * Antigravity CLI manages MCP servers via standalone `mcp_config.json` + * profiles rather than nesting them in settings.json (antigravity.google/docs/ + * cli/gcli-migration: "Antigravity CLI uses standalone mcp_config.json + * profiles in ~/.gemini/config/ for global servers and .agents/mcp_config.json + * for workspace servers"). The raw schema for the Antigravity IDE surface + * itself is unpublished (docs are JS-rendered), so this follows the CLI's + * documented standalone-profile convention plus the standard Gemini/MCP + * `mcpServers` shape. + * + * BEST-EFFORT PATH CHOICE: rather than the CLI doc's separate `~/.gemini/config/` + * directory for global scope, this writes `/mcp_config.json` — the + * SAME resolved configDir as settings.json (configureAntigravityPermissions) — + * because (1) GSD's own antigravity configDir resolution already varies + * per-user across three sibling dirs (antigravity/antigravity-ide/ + * antigravity-cli — see resolveAntigravityGlobalDir), so a hardcoded separate + * shared path would not track that resolution, and (2) it matches the doc's + * OWN workspace-scope convention exactly (`.agents/mcp_config.json`, which IS + * GSD's local configDir for antigravity), keeping global/local symmetric and + * consistent with the configDir-relative convention every other GSD + * permission writer (kilo/opencode) already uses. + * + * Non-destructive + idempotent: only adds mcpServers.gsd when entirely absent; + * any other user-configured mcpServers entries (or a user's OWN "gsd" override) + * are preserved untouched (Hyrum's Law — mirrors OpenCode's config.mcp.gsd guard). + * + * @param {boolean} isGlobal - Whether this is a global or local install + * @param {string|null} configDir - Resolved config directory when already known + */ +function configureAntigravityMcpConfig(isGlobal = true, configDir = null) { + const antigravityConfigDir = configDir || (isGlobal + ? getGlobalConfigDir('antigravity', explicitConfigDir) + : path.join(process.cwd(), '.agents')); + fs.mkdirSync(antigravityConfigDir, { recursive: true }); + + const configPath = path.join(antigravityConfigDir, 'mcp_config.json'); + + let config = {}; + if (fs.existsSync(configPath)) { + try { + const parsed = JSON.parse(fs.readFileSync(configPath, 'utf8')); + config = (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) ? parsed : {}; + } catch (e) { + // Cannot parse - DO NOT overwrite user's config + console.log(` ${yellow}⚠${reset} Could not parse mcp_config.json - skipping MCP companion config`); + console.log(` ${dim}Reason: ${e.message}${reset}`); + console.log(` ${dim}Your config was NOT modified. Fix the syntax manually if needed.${reset}`); + return; + } + } + + if (!config.mcpServers || typeof config.mcpServers !== 'object' || Array.isArray(config.mcpServers)) { + config.mcpServers = {}; + } + + if (config.mcpServers.gsd !== undefined) { + return; // Already configured (or a user-owned override) — never clobber. + } + + config.mcpServers.gsd = { + command: 'npx', + args: ['-y', '-p', PACKAGE_NAME, 'gsd-mcp-server'], + }; + + fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n'); + console.log(` ${green}✓${reset} Configured Antigravity MCP companion server (gsd)`); +} + /** * Verify a directory exists and contains files */ @@ -7962,7 +8192,8 @@ function writeManifest(configDir, runtime = DEFAULT_RUNTIME, options = {}) { // above, now covered by hostBehaviors.skipSharedHooksInstall. // #2095: isKimi dropped — kimi is now a hooks/ consumer like every other // settings-json-adjacent runtime, so the `&& !isKimi` term below was removed. - const { isOpencode, isCodex, isCopilot, isAntigravity, isCursor, isWindsurf, isAugment, isQwen, isHermes, isCodebuddy, isCline } = runtimeFlags(runtime); + // #2096: isAntigravity dropped — unused in this function. + const { isOpencode, isCodex, isCopilot, isCursor, isWindsurf, isAugment, isQwen, isHermes, isCodebuddy, isCline } = runtimeFlags(runtime); const gsdDir = path.join(configDir, 'gsd-core'); // #1367: Claude local now writes flat gsd-*.md files at commands/ (not commands/gsd/). // Claude local uses flatCommandsDir instead for manifest recording. @@ -8469,7 +8700,11 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) { // below were removed, leaving isKimi unused in this function (the kimi // local-install-deferred branch above already reads // _hostBehaviors(runtime).localInstallDeferred instead of this flag). - const { isOpencode, isZcode, isCodex, isCopilot, isAntigravity, isCursor, isWindsurf, isAugment, isTrae, isQwen, isHermes, isCodebuddy, isCline } = runtimeFlags(runtime); + // #2096: isAntigravity dropped — antigravity is in + // _DESCRIPTOR_AGENTS_RUNTIMES below, so its two legacy-agent-loop branches + // (the path-rewrite skip and the converter dispatch) were unreachable dead + // code; both were removed rather than re-gated on hostBehaviors. + const { isOpencode, isZcode, isCodex, isCopilot, isCursor, isWindsurf, isAugment, isTrae, isQwen, isHermes, isCodebuddy, isCline } = runtimeFlags(runtime); const plan = resolveInstallPlan(runtime); const dirName = getDirName(runtime); const src = path.join(__dirname, '..'); @@ -9351,7 +9586,11 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) { const bareDirRegex = /~\/\.claude\b/g; const bareHomeDirRegex = /\$HOME\/\.claude\b/g; const normalizedPathPrefix = pathPrefix.replace(/\/$/, ''); - if (!isCopilot && !isAntigravity) { + // #2096: `&& !isAntigravity` dropped — antigravity is in + // _DESCRIPTOR_AGENTS_RUNTIMES above, so this whole branch is already + // unreachable for it; the path-rewrite skip for antigravity now lives + // in the descriptor-driven `applyAgentPathRewrites` (hostBehaviors.noPathRewrite). + if (!isCopilot) { content = content.replace(dirRegex, pathPrefix); content = content.replace(homeDirRegex, pathPrefix); content = content.replace(bareDirRegex, normalizedPathPrefix); @@ -9402,8 +9641,6 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) { content = convertClaudeAgentToCodexAgent(content); } else if (isCopilot) { content = convertClaudeAgentToCopilotAgent(content, isGlobal); - } else if (isAntigravity) { - content = convertClaudeAgentToAntigravityAgent(content, isGlobal); } else if (isWindsurf) { content = convertClaudeAgentToWindsurfAgent(content); } else if (isAugment) { @@ -10437,7 +10674,10 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) { // Claude Code sets $CLAUDE_PROJECT_DIR; Antigravity does not — and on // Windows its own substitution logic doubles the path (#2557). It runs // project hooks with the project dir as cwd, so bare relative paths work. - const localPrefix = projectLocalHookPrefix({ runtime, dirName }); + // Descriptor-driven (ADR-1239 / #2096): hookPathStyle comes from the + // runtime's hostBehaviors instead of a hardcoded `runtime === 'antigravity'` + // check inside projectLocalHookPrefix. + const localPrefix = projectLocalHookPrefix({ runtime, dirName, hookPathStyle: _hostBehaviors(runtime).hookPathStyle }); const hookOpts = { portableHooks: hasPortableHooks, runtime }; // #2979: local-install hook commands also use the absolute node path so // GUI/minimal-PATH runtimes can resolve them. Bare `node` fails when the @@ -10615,7 +10855,8 @@ function finishInstall(settingsPath, settings, statuslineCommand, shouldInstallS // #2094: isTrae dropped — unused in this function. // #2095: isKimi dropped — the Kimi "Done!" banner below reads // _hostBehaviors(runtime).doneBannerStyle === 'kimi-agent-file' (descriptor-driven), not this flag. - const { isOpencode, isCodex, isCopilot, isAntigravity, isCursor, isWindsurf, isAugment, isQwen, isHermes, isCodebuddy, isCline } = runtimeFlags(runtime); + // #2096: isAntigravity dropped — unused in this function. + const { isOpencode, isCodex, isCopilot, isCursor, isWindsurf, isAugment, isQwen, isHermes, isCodebuddy, isCline } = runtimeFlags(runtime); const plan = resolveInstallPlan(runtime); if (shouldInstallStatusline && plan.writesSharedSettings && !_hostBehaviors(runtime).skipSettingsUi) { @@ -10698,6 +10939,15 @@ function finishInstall(settingsPath, settings, statuslineCommand, shouldInstallS configureKiloPermissions(isGlobal, configDir); } + // Configure Antigravity permissions + MCP companion server (#2096 Phase B + // Upgrades 1+2). Not GSD_TEST_MODE-gated — mirrors Kilo's dispatch exactly; + // both writers target files (settings.json, mcp_config.json) scoped under + // this runtime's own configDir, so they are safe to run unconditionally. + if (plan.finishPermissionWriter === 'antigravity') { + configureAntigravityPermissions(isGlobal, configDir); + configureAntigravityMcpConfig(isGlobal, configDir); + } + // For non-Claude runtimes, DEFAULT resolve_model_ids to "omit" in ~/.gsd/defaults.json // when it is absent or falsy, so resolveModelInternal() returns '' instead of Claude // aliases (opus/sonnet/haiku) the runtime can't resolve. An explicit `true` opt-in @@ -11675,6 +11925,11 @@ module.exports = { getConfigDirFromHome, resolveKiloConfigPath, configureKiloPermissions, + // #2096 Phase B Upgrades 1+2 — Antigravity permission-writer + MCP companion + toTildePosixPath, + buildAntigravityAllowRules, + configureAntigravityPermissions, + configureAntigravityMcpConfig, claudeToCopilotTools, convertCopilotToolName, convertClaudeToCopilotContent, diff --git a/capabilities/antigravity/capability.json b/capabilities/antigravity/capability.json index 362e829ed..c36ea0100 100644 --- a/capabilities/antigravity/capability.json +++ b/capabilities/antigravity/capability.json @@ -71,7 +71,7 @@ "supportTier": 1, "installSurface": "settings-json", "writesSharedSettings": true, - "permissionWriter": null, + "permissionWriter": "antigravity", "extendedHookEvents": [], "hostIntegration": { "embeddingMode": "declarative", @@ -81,7 +81,7 @@ "nested": "undocumented", "maxDepth": "undocumented", "background": true, - "subagentToolkit": "undocumented", + "subagentToolkit": "full", "backgroundDispatch": "undocumented" }, "modelMode": "passive", @@ -91,7 +91,11 @@ "runtime": "go" }, "hostBehaviors": { - "reviewerCli": true + "reviewerCli": true, + "projectInstructionFile": "GEMINI.md", + "noPathRewrite": true, + "hookPathStyle": "raw", + "globalDirResolver": "antigravity" } } } diff --git a/docs/adr/1016-runtime-capability-descriptor.md b/docs/adr/1016-runtime-capability-descriptor.md index f683c9d1d..5c11fdcdb 100644 --- a/docs/adr/1016-runtime-capability-descriptor.md +++ b/docs/adr/1016-runtime-capability-descriptor.md @@ -116,9 +116,9 @@ Selects which config-writing adapter `resolveRuntimeConfigIntent` (in `runtime-c Whether the runtime writes a shared `settings.json`. Replaces the former inline boolean per runtime in `runtime-config-adapter-registry`. Together with `installSurface` this fully parameterises the adapter-selection path. -#### `permissionWriter` — `null | 'opencode' | 'kilo'` +#### `permissionWriter` — `null | 'opencode' | 'kilo' | 'antigravity'` -The finish-time permissions-sidecar writer (the JSONC file opencode and kilo require). Replaces the old `finishPermissionWriter` field in the `runtime-config-adapter-registry` `REGISTRY` table. All 14 runtimes that write no permissions sidecar carry `null`. +The finish-time permissions-sidecar writer. `opencode`/`kilo` write a dedicated JSONC config file; `antigravity` (#2096 Phase B Upgrade 1) instead merges a `permissions.allow` array into the SAME shared `settings.json` GSD's own hook registration writes, plus a standalone `mcp_config.json` MCP-companion profile (Upgrade 2, dispatched alongside it). Replaces the old `finishPermissionWriter` field in the `runtime-config-adapter-registry` `REGISTRY` table. All 13 runtimes that write no permissions sidecar carry `null`. #### `extendedHookEvents` — `string[]` over a closed event vocabulary diff --git a/docs/how-to/connect-gsd-mcp-server.md b/docs/how-to/connect-gsd-mcp-server.md index 961d78f4b..37cbbed89 100644 --- a/docs/how-to/connect-gsd-mcp-server.md +++ b/docs/how-to/connect-gsd-mcp-server.md @@ -29,7 +29,12 @@ host. - **Claude Code / Codex / Cursor / Cline / Hermes** — under the host's `mcpServers` object (project or user config). - **VS Code** — in the workspace MCP servers list. -- **Antigravity CLI** — under its `mcpServers` block. +- **Antigravity** — under the `mcpServers` block of its standalone + `mcp_config.json` profile (not embedded in `settings.json`) — global at + `~/.gemini/antigravity/mcp_config.json` (or the sibling + `antigravity-ide`/`antigravity-cli` dir GSD resolved into), project-local at + `.agents/mcp_config.json`. GSD's installer configures this entry + automatically (`--antigravity` installs). - **OpenCode** — under the `mcp` key (**not** `mcpServers`), in `~/.config/opencode/opencode.jsonc` (global) or `./opencode.json` (project). The entry shape also differs — see below. diff --git a/docs/reference/capability-manifest.md b/docs/reference/capability-manifest.md index bfe77faae..f64d1ac2a 100644 --- a/docs/reference/capability-manifest.md +++ b/docs/reference/capability-manifest.md @@ -152,8 +152,8 @@ Runtime capabilities describe how GSD projects its artefacts onto one host CLI. | Support tier | `runtime.supportTier` | Integer: `1` (fully tested first-party) \| `2` (shipped, lower coverage). | | Install surface | `runtime.installSurface` | Closed enum: `settings-json` \| `codex-toml` \| `copilot-instructions` \| `cline-rules` \| `cursor-hooks-json` \| `profile-marker-only`. | | Shared settings | `runtime.writesSharedSettings` | boolean. Whether the runtime writes a shared `settings.json`. | -| Permission writer | `runtime.permissionWriter` | `null` \| `"opencode"` \| `"kilo"`. The finish-time permissions-sidecar writer. | -| Extended hook events | `runtime.extendedHookEvents` | string[] over a closed vocabulary: `SubagentStop`, `Stop`, `PreCompact`, `FileChanged`, `BeforeAgent`, `AfterAgent`, `BeforeModel`. | +| Permission writer | `runtime.permissionWriter` | `null` \| `"opencode"` \| `"kilo"` \| `"antigravity"`. The finish-time permissions-sidecar writer. | +| Extended hook events | `runtime.extendedHookEvents` | string[] over a closed vocabulary: `SubagentStop`, `Stop`, `PreCompact`, `FileChanged`, `BeforeAgent`, `AfterAgent`, `BeforeModel`, `SubagentStart`. | For a minimal `role: "runtime"` example, see [ADR-1016 §Decision 8](../adr/1016-runtime-capability-descriptor.md). diff --git a/docs/reference/host-integration-capability-matrix.md b/docs/reference/host-integration-capability-matrix.md index f4f7d6538..c8046ec56 100644 --- a/docs/reference/host-integration-capability-matrix.md +++ b/docs/reference/host-integration-capability-matrix.md @@ -281,7 +281,7 @@ Documentation gaps: | dispatch.nested | undocumented | no authoritative doc — searched: https://antigravity.google/docs/agents | — | | dispatch.maxDepth | undocumented | no authoritative doc — searched: https://antigravity.google/docs/agents | — | | dispatch.background | true | https://developers.googleblog.com/an-important-update-transitioning-gemini-cli-to-antigravity-cli/ | "Antigravity CLI orchestrates multiple agents for complex tasks in the background" | -| dispatch.subagentToolkit | undocumented | no authoritative doc — searched: https://www.explainx.ai/blog/antigravity-cli-features-sandbox-plugins-subagents-2026 | — | +| dispatch.subagentToolkit | full | https://antigravity.google/docs/cli/features | "Capabilities: Subagents have full access to tools such as code search, file editing, terminal commands, and web searches to complete their assigned tasks." (#2096 EoS migration — the page is JS-rendered/blank on a static fetch; confirmed via headless-browser render) | | dispatch.backgroundDispatch | undocumented | no authoritative doc — Multiple sources consulted: antigravity.google/docs/cli-subagents (returned blank/JS-rendered), antigravity.google/docs/agent (blank), github.com/google-antigravity/antigravity-cli README, Context7 /google-antigravity/antigravity-cli | All documentation consulted describes a two-level orchestrator→subagent architecture. Background subagents run asynchronously while the main agent continues accepting prompts. The DataCamp tutorial st | Sources consulted: @@ -292,12 +292,14 @@ Sources consulted: - https://www.aibuilderclub.com/blog/antigravity-cli-guide - https://antigravity.google/docs/agents - https://antigravity.google/docs/hooks +- https://antigravity.google/docs/cli/features (#2096 — subagentToolkit) Documentation gaps: - dispatch.namedDispatch — docs describe dynamic plain-English goal dispatch where agent names subagents at runtime; no pre-registered named sub-agent API documented. - dispatch.nested — no documentation found on whether subagents can themselves spawn further subagents. - dispatch.maxDepth — no documented depth limit or explicit unbounded statement found. -- dispatch.subagentToolkit — docs describe a permissions approval model but do not explicitly state 'full' vs 'read-only' toolkit scope for subagents. + +**EoS migration status (#2096):** Migrated onto the declarative adapter. All `runtime === 'antigravity'` / `isAntigravity` / `canonical === 'antigravity'` branches folded into descriptor-driven `runtime.hostBehaviors` + `runtime.hostIntegration`: `getConfigDirFromHome` (`bin/install.js`) now branches on `configHome.kind === 'dot-home-nested'` instead of a hardcoded runtime literal; `projectLocalHookPrefix` (`src/shell-command-projection.cts`) reads `hostBehaviors.hookPathStyle` (`'raw'` → bare `dirName`, no `$CLAUDE_PROJECT_DIR` anchor); `applyAgentPathRewrites` (`src/runtime-artifact-conversion.cts`) reads `hostBehaviors.noPathRewrite` to skip the `~/.claude/` → pathPrefix rewrites; and `getProjectInstructionFile` (`src/runtime-name-policy.cts`) reads `hostBehaviors.projectInstructionFile` (`"GEMINI.md"` — Antigravity CLI's `contextFileName`, successor to the sunset Gemini CLI per #1928) instead of a hardcoded `canonical === 'antigravity'` check. The dead `isAntigravity` branches these functions previously carried are removed. `dispatch.subagentToolkit` flipped `undocumented` → `full` per the citation above (antigravity.google/docs/cli/features); `dispatch.namedDispatch`/`nested`/`maxDepth`/`backgroundDispatch` stay `undocumented` — no authoritative source states named/nested/depth-bounded dispatch or a `run_in_background`-style call-time param, so `negotiateHostCapabilities` degrades all four closed to their most-restrictive value (false/0), and `shouldFlattenDispatch` still forces antigravity's dispatch to flatten (inline) despite `dispatch.background: true`, because `backgroundDispatch` itself never reaches `true`. Two upgrades land: **UPGRADE 1 — permission-writer** (`configureAntigravityPermissions`, `runtime.permissionWriter: "antigravity"`) writes Antigravity's native `{"permissions":{"allow":[...]}}` schema (antigravity.google/docs/cli/permissions) into the same `settings.json` GSD's own hook registration writes, granting GSD's own `read_file`/`command` rules non-destructively. **UPGRADE 2 — MCP companion config** (`configureAntigravityMcpConfig`) writes a standalone `mcp_config.json` (antigravity.google/docs/cli/gcli-migration) registering the `gsd` MCP server, non-destructively preserving any other `mcpServers` entries. Both upgrades are covered by `tests/antigravity-upgrades.test.cjs`; the axis/negotiation/source-grep coverage above is in `tests/declarative-reference-antigravity.test.cjs`. --- diff --git a/gsd-core/bin/lib/capability-registry.cjs b/gsd-core/bin/lib/capability-registry.cjs index a70076b2a..f1899a7ab 100644 --- a/gsd-core/bin/lib/capability-registry.cjs +++ b/gsd-core/bin/lib/capability-registry.cjs @@ -165,7 +165,7 @@ const capabilities = { "supportTier": 1, "installSurface": "settings-json", "writesSharedSettings": true, - "permissionWriter": null, + "permissionWriter": "antigravity", "extendedHookEvents": [], "hostIntegration": { "embeddingMode": "declarative", @@ -175,7 +175,7 @@ const capabilities = { "nested": "undocumented", "maxDepth": "undocumented", "background": true, - "subagentToolkit": "undocumented", + "subagentToolkit": "full", "backgroundDispatch": "undocumented" }, "modelMode": "passive", @@ -185,7 +185,11 @@ const capabilities = { "runtime": "go" }, "hostBehaviors": { - "reviewerCli": true + "reviewerCli": true, + "projectInstructionFile": "GEMINI.md", + "noPathRewrite": true, + "hookPathStyle": "raw", + "globalDirResolver": "antigravity" } } }, @@ -3837,7 +3841,7 @@ const runtimes = { "supportTier": 1, "installSurface": "settings-json", "writesSharedSettings": true, - "permissionWriter": null, + "permissionWriter": "antigravity", "extendedHookEvents": [], "hostIntegration": { "embeddingMode": "declarative", @@ -3847,7 +3851,7 @@ const runtimes = { "nested": "undocumented", "maxDepth": "undocumented", "background": true, - "subagentToolkit": "undocumented", + "subagentToolkit": "full", "backgroundDispatch": "undocumented" }, "modelMode": "passive", @@ -3857,7 +3861,11 @@ const runtimes = { "runtime": "go" }, "hostBehaviors": { - "reviewerCli": true + "reviewerCli": true, + "projectInstructionFile": "GEMINI.md", + "noPathRewrite": true, + "hookPathStyle": "raw", + "globalDirResolver": "antigravity" } } }, diff --git a/gsd-core/bin/lib/capability-validator.cjs b/gsd-core/bin/lib/capability-validator.cjs index 462f266ba..8e418d0fa 100644 --- a/gsd-core/bin/lib/capability-validator.cjs +++ b/gsd-core/bin/lib/capability-validator.cjs @@ -717,7 +717,8 @@ const VALID_ARTIFACT_KIND_NAMES = new Set(['commands', 'agents', 'skills', 'kimi const VALID_ARTIFACT_NESTINGS = new Set(['flat', 'nested']); const FEATURE_FIELDS_FORBIDDEN_ON_RUNTIME = ['skills', 'agents', 'steps', 'contributions', 'gates', 'hooks', 'activationKey']; const VALID_INSTALL_SURFACES = new Set(['settings-json', 'codex-toml', 'copilot-instructions', 'cline-rules', 'cursor-hooks-json', 'profile-marker-only']); -const VALID_PERMISSION_WRITERS = new Set(['opencode', 'kilo']); +// 'antigravity' added #2096 Phase B Upgrade 1 — settings.json permissions.allow writer. +const VALID_PERMISSION_WRITERS = new Set(['opencode', 'kilo', 'antigravity']); // SubagentStart added #2092 Phase B Upgrade 2 (qwen-only today — see // capabilities/qwen/capability.json's extendedHookEvents). const VALID_EXTENDED_HOOK_EVENTS = new Set(['SubagentStop', 'Stop', 'PreCompact', 'FileChanged', 'BeforeAgent', 'AfterAgent', 'BeforeModel', 'SubagentStart']); diff --git a/src/runtime-artifact-conversion.cts b/src/runtime-artifact-conversion.cts index a4aaa2010..c1e2f6576 100644 --- a/src/runtime-artifact-conversion.cts +++ b/src/runtime-artifact-conversion.cts @@ -2743,9 +2743,11 @@ function normalizeAgentBodyForRuntime(content: string, runtime: string, cmdNames * ~/\.claude\b → normalizedPathPrefix * $HOME/\.claude\b → normalizedPathPrefix * - * Skipped for copilot and antigravity (which do NOT do path rewrites in the - * inline loop). NO stamp (_stampNonClaudeRuntimeDefaults) — agents are NOT - * stamped in the inline loop. + * Skipped for copilot (hardcoded — #2099 will fold it) and for any runtime + * that declares `hostBehaviors.noPathRewrite` (descriptor-driven, ADR-1239 / + * #2096 — folds the prior hardcoded `runtime === 'antigravity'` literal; + * Antigravity does NOT do path rewrites in the inline loop). NO stamp + * (_stampNonClaudeRuntimeDefaults) — agents are NOT stamped in the inline loop. * * ADR-1235 §1: pre-converter cross-cutting for descriptor-driven agent pipeline. * Exported as `applyAgentPathRewrites` for testing and for injection into @@ -2754,10 +2756,10 @@ function normalizeAgentBodyForRuntime(content: string, runtime: string, cmdNames * @param content raw agent file content * @param runtime canonical runtime ID * @param pathPrefix trailing-slash path prefix (e.g. '$HOME/.cursor/') - * @returns content with path-prefix rewrites applied (or unchanged for copilot/antigravity) + * @returns content with path-prefix rewrites applied (or unchanged for copilot / noPathRewrite runtimes) */ function applyAgentPathRewrites(content: string, runtime: string, pathPrefix: string): string { - if (runtime === 'copilot' || runtime === 'antigravity') return content; + if (runtime === 'copilot' || _hostBehaviors(runtime).noPathRewrite === true) return content; const normalizedPathPrefix = pathPrefix.replace(/\/$/, ''); content = content.replace(/~\/\.claude\//g, pathPrefix); content = content.replace(/\$HOME\/\.claude\//g, pathPrefix); diff --git a/src/runtime-config-adapter-registry.cts b/src/runtime-config-adapter-registry.cts index eb9a9cce7..42bca5711 100644 --- a/src/runtime-config-adapter-registry.cts +++ b/src/runtime-config-adapter-registry.cts @@ -22,9 +22,12 @@ * false for codex / copilot / kilo / cursor / windsurf / trae / cline / kimi (legacy exclusion list). * true for all other runtimes. * - `finishPermissionWriter` names the finishInstall-phase dedicated config writer: - * 'opencode' → writes BOTH shared settings AND its own permissions file. - * 'kilo' → writes only its own permissions file. - * null → no dedicated permission writer. + * 'opencode' → writes BOTH shared settings AND its own permissions file. + * 'kilo' → writes only its own permissions file. + * 'antigravity' → writes BOTH shared settings.json permissions.allow AND a + * standalone mcp_config.json MCP companion profile (#2096 + * Phase B Upgrades 1+2). + * null → no dedicated permission writer. */ // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -45,7 +48,7 @@ type ConfigInstallSurface = | 'cursor-hooks-json' | 'profile-marker-only'; -type FinishPermissionWriter = 'opencode' | 'kilo' | null; +type FinishPermissionWriter = 'opencode' | 'kilo' | 'antigravity' | null; type HooksSurface = | 'settings-json' diff --git a/src/runtime-name-policy.cts b/src/runtime-name-policy.cts index 824d75919..9c31d8294 100644 --- a/src/runtime-name-policy.cts +++ b/src/runtime-name-policy.cts @@ -120,13 +120,26 @@ export function resolveRuntimeNameFromCandidates(...candidates: unknown[]): stri * Aliases are normalized via `canonicalizeRuntimeName` first, so inputs like * `codex-cli` resolve to `codex` → `AGENTS.md`. Replaces the prior codex-only * override in profile-output.cjs (#3163) which left AGENTS-native runtimes - * (opencode/kilo/kimi) incorrectly emitting `.claude/CLAUDE.md`. Pure: no I/O. + * (opencode/kilo/kimi) incorrectly emitting `.claude/CLAUDE.md`. Pure: no I/O + * (the lazy `require` below reads a static generated module, not the disk). + * + * Descriptor-driven (ADR-1239 / #2096): antigravity's `GEMINI.md` is folded + * from a hardcoded `canonical === 'antigravity'` literal into a read of + * `runtime.hostBehaviors.projectInstructionFile`. claude/copilot stay + * hardcoded (out of scope here) mirroring `getDirName` below, which already + * lazy-`require`s `capability-registry.cjs` inside the function body to + * avoid a circular dependency at module load. */ export function getProjectInstructionFile(runtime: unknown): string { const canonical = canonicalizeRuntimeName(runtime); if (canonical === 'claude') return '.claude/CLAUDE.md'; if (canonical === 'copilot') return '.github/copilot-instructions.md'; - if (canonical === 'antigravity') return 'GEMINI.md'; + // eslint-disable-next-line @typescript-eslint/no-require-imports + const { runtimes } = require('./capability-registry.cjs') as { + runtimes: Record; + }; + const declared = canonical ? runtimes[canonical]?.runtime?.hostBehaviors?.projectInstructionFile : undefined; + if (typeof declared === 'string' && declared.length > 0) return declared; // codex, opencode, kilo, kimi, AND unknown/future runtimes all default to // root AGENTS.md (the safe cross-agent instruction file). return 'AGENTS.md'; diff --git a/src/shell-command-projection.cts b/src/shell-command-projection.cts index 97aaab59f..1cb4f8920 100644 --- a/src/shell-command-projection.cts +++ b/src/shell-command-projection.cts @@ -98,9 +98,17 @@ export function formatManagedHookScriptToken(scriptPath: string, opts: { platfor return JSON.stringify(scriptPath.replace(/\\/g, '/')); } -export function projectLocalHookPrefix({ runtime = 'claude', dirName }: { runtime?: string; dirName?: string | null }): string | undefined | null { +export function projectLocalHookPrefix({ runtime: _runtime = 'claude', dirName, hookPathStyle }: { runtime?: string; dirName?: string | null; hookPathStyle?: string | null }): string | undefined | null { if (!dirName) return dirName; - return (runtime === 'antigravity') + // Descriptor-driven (ADR-1239 / #2096): folded from a hardcoded + // `runtime === 'antigravity'` literal into the runtime's declared + // `hostBehaviors.hookPathStyle`. Runtimes that always run project hooks + // with the project dir as cwd (Antigravity today) declare 'raw' and get + // the bare dirName; every other runtime keeps the $CLAUDE_PROJECT_DIR- + // anchored prefix. `runtime` itself is now unused here but stays in the + // signature for call-site/back-compat parity (kept `_`-prefixed to + // satisfy no-unused-vars). + return (hookPathStyle === 'raw') ? dirName : `"$CLAUDE_PROJECT_DIR"/${dirName}`; } diff --git a/tests/antigravity-upgrades.test.cjs b/tests/antigravity-upgrades.test.cjs new file mode 100644 index 000000000..f196bc956 --- /dev/null +++ b/tests/antigravity-upgrades.test.cjs @@ -0,0 +1,283 @@ +'use strict'; + +/** + * antigravity capability UPGRADES — ADR-1239 Phase B / #2096 (EoS/antigravity). + * + * Drives the user-reachable surface (spawned `bin/install.js` via + * `runMinimalInstall`) plus targeted unit coverage to prove the two real + * upgrades Antigravity contributes as part of the imperative-adapter + * migration: + * + * UPGRADE 1 — permission-writer: `configureAntigravityPermissions` writes + * Antigravity's native `{"permissions":{"allow":[...]}}` schema + * (antigravity.google/docs/cli/permissions) into the SAME settings.json + * GSD's own hook registration writes, non-destructively appending GSD's own + * read_file/command allow rules while preserving any existing user + * permissions (allow/deny/ask). Uninstall removes only the GSD-owned rules. + * + * UPGRADE 2 — MCP companion config: `configureAntigravityMcpConfig` writes + * a standalone `mcp_config.json` (antigravity.google/docs/cli/gcli-migration) + * registering the `gsd` MCP server (`bin/gsd-mcp-server.js`, the SAME + * companion OpenCode/Kilo document/wire), non-destructively preserving any + * other user-configured `mcpServers` entries. Uninstall removes only the + * `gsd` entry. + * + * Both writers are NOT GSD_TEST_MODE-gated (mirrors Kilo's dispatch, not + * OpenCode's) — runMinimalInstall strips GSD_TEST_MODE from the spawned + * installer's env, so both fire during a "minimal" install too. + */ + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const { runMinimalInstall, installerEnv, INSTALL_SCRIPT } = require('./helpers/install-shared.cjs'); +const { cleanup } = require('./helpers.cjs'); +const { + toTildePosixPath, + buildAntigravityAllowRules, + configureAntigravityPermissions, + configureAntigravityMcpConfig, +} = require('../bin/install.js'); +const { PROTOCOL_VERSION } = require('../gsd-core/bin/lib/mcp-server.cjs'); +const { PACKAGE_NAME } = require('../gsd-core/bin/lib/package-identity.cjs'); + +const MCP_SERVER_BIN = path.join(__dirname, '..', 'bin', 'gsd-mcp-server.js'); + +const ANTIGRAVITY_CAP = JSON.parse( + fs.readFileSync(path.join(__dirname, '..', 'capabilities', 'antigravity', 'capability.json'), 'utf8'), +); + +// --------------------------------------------------------------------------- +// Descriptor boundary — permissionWriter wiring +// --------------------------------------------------------------------------- + +test('capabilities/antigravity/capability.json declares runtime.permissionWriter: "antigravity"', () => { + assert.equal(ANTIGRAVITY_CAP.runtime.permissionWriter, 'antigravity'); +}); + +// --------------------------------------------------------------------------- +// UPGRADE 1: permission-writer unit coverage (toTildePosixPath / rule builder) +// --------------------------------------------------------------------------- + +test('toTildePosixPath collapses a homedir-rooted path to "~/..." form', () => { + const home = require('node:os').homedir(); + assert.equal(toTildePosixPath(path.join(home, '.gemini', 'antigravity')), '~/.gemini/antigravity'); +}); + +test('toTildePosixPath leaves a non-homedir path as an absolute posix path', () => { + assert.equal(toTildePosixPath('/var/tmp/some-config-dir'), '/var/tmp/some-config-dir'); +}); + +test('buildAntigravityAllowRules emits the 4 documented "action(target)" rule strings', () => { + const rules = buildAntigravityAllowRules('/tmp/ag-config'); + assert.deepEqual(rules, [ + 'read_file(/tmp/ag-config/gsd-core/*)', + 'read_file(/tmp/ag-config/agents/gsd-*)', + 'read_file(/tmp/ag-config/skills/gsd-*)', + 'command(node /tmp/ag-config/hooks/*)', + ]); +}); + +// --------------------------------------------------------------------------- +// UPGRADE 1: live install — settings.json permissions.allow (both scopes) +// --------------------------------------------------------------------------- + +for (const scope of ['global', 'local']) { + test(`antigravity --${scope}: settings.json permissions.allow contains GSD's rules (UPGRADE 1)`, (t) => { + const { configDir, root } = runMinimalInstall({ runtime: 'antigravity', scope }); + t.after(() => cleanup(root)); + + const settingsPath = path.join(configDir, 'settings.json'); + assert.ok(fs.existsSync(settingsPath), `${settingsPath} must exist`); + + const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); + assert.ok(settings.permissions && Array.isArray(settings.permissions.allow), 'permissions.allow must be an array'); + + // Asserting on the exact rule strings here would require reproducing + // toTildePosixPath's os.homedir()-relative substitution from OUTSIDE the + // spawned installer subprocess: runMinimalInstall overrides that + // subprocess's HOME to `root`, so for --global (configDir === root === + // that subprocess's HOME) every rule collapses to the bare `~/...` form, + // while THIS test process's own (unrelated, real) os.homedir() would + // reconstruct full absolute paths instead — a guaranteed mismatch that + // has nothing to do with correctness. Assert on the documented rule + // SHAPE (action + path suffix) instead, which holds regardless of + // whether the prefix collapsed to `~` or stayed a full absolute path. + const expectedShapes = [ + { action: 'read_file(', suffix: '/gsd-core/*)' }, + { action: 'read_file(', suffix: '/agents/gsd-*)' }, + { action: 'read_file(', suffix: '/skills/gsd-*)' }, + { action: 'command(node ', suffix: '/hooks/*)' }, + ]; + for (const { action, suffix } of expectedShapes) { + const found = settings.permissions.allow.some((rule) => rule.startsWith(action) && rule.endsWith(suffix)); + assert.ok(found, `permissions.allow must include a rule shaped like "${action}...${suffix}" — got ${JSON.stringify(settings.permissions.allow)}`); + } + // Priority-scoping (deny/ask) is a user-owned decision — GSD never writes it. + assert.equal(settings.permissions.deny, undefined, 'GSD must never write permissions.deny'); + assert.equal(settings.permissions.ask, undefined, 'GSD must never write permissions.ask'); + }); +} + +test('configureAntigravityPermissions is idempotent — a second call adds no duplicate rules', (t) => { + const root = fs.mkdtempSync(path.join(require('node:os').tmpdir(), 'gsd-ag-perm-idem-')); + t.after(() => cleanup(root)); + + configureAntigravityPermissions(true, root); + configureAntigravityPermissions(true, root); + const settings = JSON.parse(fs.readFileSync(path.join(root, 'settings.json'), 'utf8')); + assert.equal(settings.permissions.allow.length, new Set(settings.permissions.allow).size, 'no duplicate allow entries'); + assert.equal(settings.permissions.allow.length, buildAntigravityAllowRules(root).length); +}); + +test('configureAntigravityPermissions preserves a pre-existing user permissions block (allow/deny/ask)', (t) => { + const root = fs.mkdtempSync(path.join(require('node:os').tmpdir(), 'gsd-ag-perm-preserve-')); + t.after(() => cleanup(root)); + + fs.writeFileSync(path.join(root, 'settings.json'), JSON.stringify({ + permissions: { + allow: ['command(git)'], + deny: ['command(rm -rf)'], + ask: ['command(*)'], + }, + userCustomField: 'preserve-me', + }, null, 2)); + + configureAntigravityPermissions(true, root); + + const settings = JSON.parse(fs.readFileSync(path.join(root, 'settings.json'), 'utf8')); + assert.ok(settings.permissions.allow.includes('command(git)'), 'pre-existing allow entry preserved'); + assert.deepEqual(settings.permissions.deny, ['command(rm -rf)'], 'deny block untouched'); + assert.deepEqual(settings.permissions.ask, ['command(*)'], 'ask block untouched'); + assert.equal(settings.userCustomField, 'preserve-me', 'unrelated top-level user fields preserved'); + for (const rule of buildAntigravityAllowRules(root)) { + assert.ok(settings.permissions.allow.includes(rule)); + } +}); + +// --------------------------------------------------------------------------- +// UPGRADE 2: MCP companion config — live install (both scopes) +// --------------------------------------------------------------------------- + +for (const scope of ['global', 'local']) { + test(`antigravity --${scope}: mcp_config.json registers the gsd MCP companion (UPGRADE 2)`, (t) => { + const { configDir, root } = runMinimalInstall({ runtime: 'antigravity', scope }); + t.after(() => cleanup(root)); + + const mcpConfigPath = path.join(configDir, 'mcp_config.json'); + assert.ok(fs.existsSync(mcpConfigPath), `${mcpConfigPath} must exist`); + + const mcpConfig = JSON.parse(fs.readFileSync(mcpConfigPath, 'utf8')); + assert.ok(mcpConfig.mcpServers && mcpConfig.mcpServers.gsd, 'mcpServers.gsd must be present'); + assert.equal(mcpConfig.mcpServers.gsd.command, 'npx'); + assert.deepEqual(mcpConfig.mcpServers.gsd.args, ['-y', '-p', PACKAGE_NAME, 'gsd-mcp-server']); + }); +} + +test('configureAntigravityMcpConfig is idempotent — a second call does not clobber an existing gsd entry', (t) => { + const root = fs.mkdtempSync(path.join(require('node:os').tmpdir(), 'gsd-ag-mcp-idem-')); + t.after(() => cleanup(root)); + + configureAntigravityMcpConfig(true, root); + // Simulate a user hand-edit of the gsd entry after install. + const configPath = path.join(root, 'mcp_config.json'); + const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); + config.mcpServers.gsd.args.push('--custom-flag'); + fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n'); + + configureAntigravityMcpConfig(true, root); + + const after = JSON.parse(fs.readFileSync(configPath, 'utf8')); + assert.ok(after.mcpServers.gsd.args.includes('--custom-flag'), 'a user-owned gsd override is never clobbered (Hyrum\'s Law)'); +}); + +test('configureAntigravityMcpConfig preserves a pre-existing unrelated mcpServers entry', (t) => { + const root = fs.mkdtempSync(path.join(require('node:os').tmpdir(), 'gsd-ag-mcp-preserve-')); + t.after(() => cleanup(root)); + + fs.writeFileSync(path.join(root, 'mcp_config.json'), JSON.stringify({ + mcpServers: { + 'my-own-server': { command: 'my-tool', args: ['--flag'] }, + }, + }, null, 2)); + + configureAntigravityMcpConfig(true, root); + + const config = JSON.parse(fs.readFileSync(path.join(root, 'mcp_config.json'), 'utf8')); + assert.deepEqual(config.mcpServers['my-own-server'], { command: 'my-tool', args: ['--flag'] }); + assert.ok(config.mcpServers.gsd); +}); + +// AC-style proof: the companion mcp_config.json points at (bin/gsd-mcp-server.js) +// is actually reachable, not just documented. Mirrors tests/gsd-mcp-server-bin.test.cjs +// exactly (same shim, same line-delimited JSON-RPC over stdio). +test('UPGRADE 2: gsd-mcp-server companion is reachable — spawn, initialize, tools/list over stdio', () => { + const stdin = [ + JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize' }), + JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list' }), + ].join('\n') + '\n'; + + const res = spawnSync(process.execPath, [MCP_SERVER_BIN], { + input: stdin, + encoding: 'utf-8', + timeout: 15000, + env: { ...process.env, GSD_TEST_MODE: '1' }, + }); + + assert.strictEqual(res.status, 0, `gsd-mcp-server must exit cleanly on stdin EOF; stderr: ${res.stderr}`); + const lines = res.stdout.trim().split('\n').map((l) => JSON.parse(l)); + assert.strictEqual(lines.length, 2, 'one response per request'); + assert.strictEqual(lines[0].result.protocolVersion, PROTOCOL_VERSION, 'initialize handshake succeeds'); + const toolNames = lines[1].result.tools.map((t) => t.name).sort(); + assert.deepStrictEqual( + toolNames, + ['gsd_invoke_command', 'gsd_read_state', 'gsd_write_state'], + 'the companion the mcp_config.json entry connects to advertises the real GSD tool surface', + ); +}); + +// --------------------------------------------------------------------------- +// Uninstall — symmetric cleanup for both upgrades +// --------------------------------------------------------------------------- + +test('antigravity --global uninstall removes only GSD-owned permissions.allow rules + mcpServers.gsd, preserving user data', (t) => { + const root = fs.mkdtempSync(path.join(require('node:os').tmpdir(), 'gsd-ag-uninstall-')); + t.after(() => cleanup(root)); + + const args = [INSTALL_SCRIPT, '--antigravity', '--global', '--config-dir', root]; + const installResult = spawnSync(process.execPath, args, { + encoding: 'utf8', + env: installerEnv({ HOME: root, USERPROFILE: root }), + }); + assert.strictEqual(installResult.status, 0, `install failed: ${installResult.stderr}`); + + // Seed user-owned data alongside GSD's contributions, post-install. + const settingsPath = path.join(root, 'settings.json'); + const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); + settings.permissions.allow.push('command(git)'); + settings.permissions.deny = ['command(rm -rf)']; + fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n'); + + const mcpConfigPath = path.join(root, 'mcp_config.json'); + const mcpConfig = JSON.parse(fs.readFileSync(mcpConfigPath, 'utf8')); + mcpConfig.mcpServers['my-own-server'] = { command: 'my-tool', args: [] }; + fs.writeFileSync(mcpConfigPath, JSON.stringify(mcpConfig, null, 2) + '\n'); + + const uninstallArgs = [INSTALL_SCRIPT, '--antigravity', '--global', '--config-dir', root, '--uninstall']; + const uninstallResult = spawnSync(process.execPath, uninstallArgs, { + encoding: 'utf8', + env: installerEnv({ HOME: root, USERPROFILE: root }), + }); + assert.strictEqual(uninstallResult.status, 0, `uninstall failed: ${uninstallResult.stderr}`); + + const settingsAfter = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); + assert.deepEqual(settingsAfter.permissions.allow, ['command(git)'], 'GSD allow rules removed, user rule preserved'); + assert.deepEqual(settingsAfter.permissions.deny, ['command(rm -rf)'], 'user deny rule preserved'); + + const mcpConfigAfter = JSON.parse(fs.readFileSync(mcpConfigPath, 'utf8')); + assert.equal(mcpConfigAfter.mcpServers.gsd, undefined, 'gsd MCP entry removed'); + assert.deepEqual(mcpConfigAfter.mcpServers['my-own-server'], { command: 'my-tool', args: [] }, 'user MCP server preserved'); +}); diff --git a/tests/capability-registry.test.cjs b/tests/capability-registry.test.cjs index b6e92a8d8..321a262f7 100644 --- a/tests/capability-registry.test.cjs +++ b/tests/capability-registry.test.cjs @@ -4453,11 +4453,12 @@ describe('ADR-857 phase 5f: cross-field consistency gate rejection tests (DEFECT } }); - test('VALID_PERMISSION_WRITERS covers exactly {opencode, kilo}', () => { + test('VALID_PERMISSION_WRITERS covers exactly {opencode, kilo, antigravity}', () => { assert.ok(VALID_PERMISSION_WRITERS instanceof Set, 'Must be a Set'); - assert.strictEqual(VALID_PERMISSION_WRITERS.size, 2, 'Must cover 2 permission writers'); + assert.strictEqual(VALID_PERMISSION_WRITERS.size, 3, 'Must cover 3 permission writers'); assert.ok(VALID_PERMISSION_WRITERS.has('opencode'), 'Must include opencode'); assert.ok(VALID_PERMISSION_WRITERS.has('kilo'), 'Must include kilo'); + assert.ok(VALID_PERMISSION_WRITERS.has('antigravity'), 'Must include antigravity (#2096)'); }); // Confirm the valid base fixture does NOT produce errors (sanity) diff --git a/tests/declarative-reference-antigravity.test.cjs b/tests/declarative-reference-antigravity.test.cjs index 5d5615afd..13642f8a6 100644 --- a/tests/declarative-reference-antigravity.test.cjs +++ b/tests/declarative-reference-antigravity.test.cjs @@ -1,3 +1,4 @@ +// allow-test-rule: structural-regression-guard — AC2 requires asserting no `runtime === 'antigravity'` string-equality branch (nor an `isAntigravity` helper, nor a `canonical === 'antigravity'` branch) remains in bin/install.js, src/runtime-artifact-conversion.cts, src/shell-command-projection.cts, and src/runtime-name-policy.cts — the descriptor-migration contract is a property of the source text, so a source-grep is the only faithful check (#2096) 'use strict'; /** @@ -15,6 +16,17 @@ * profile via profileOf, (2) confirms the public adapter classifies it as * declarative, and (3) round-trips a real install proving a gsd command surface * is emitted through the same engine the adapter delegates to. + * + * #2096 (EoS/antigravity) additions: negotiation fails CLOSED on a corrupted + * descriptor, the 4 still-`undocumented` dispatch sub-axes (namedDispatch/ + * nested/maxDepth/backgroundDispatch) degrade to the most-restrictive known + * value (never their optimistic value), the validator accepts the negotiated + * subagentToolkit:'full' + permissionWriter:'antigravity' upgrade, and the + * hardcoded `runtime === 'antigravity'` / `isAntigravity` / `canonical === + * 'antigravity'` branches are retired from the folded modules (folded into + * descriptor-driven `runtime.hostBehaviors` + `runtime.hostIntegration`). + * UPGRADE 1 (permission-writer) + UPGRADE 2 (MCP companion) live-install + * coverage is in tests/antigravity-upgrades.test.cjs — not duplicated here. */ const { test, before } = require('node:test'); @@ -23,12 +35,20 @@ const fs = require('node:fs'); const path = require('node:path'); const { execFileSync } = require('node:child_process'); -const { profileOf } = require('../gsd-core/bin/lib/host-integration.cjs'); +const { + profileOf, + negotiateHostCapabilities, + PROFILE_BASELINES, + UNDOCUMENTED, +} = require('../gsd-core/bin/lib/host-integration.cjs'); +const { validateCapability } = require('../gsd-core/bin/lib/capability-validator.cjs'); const { createDeclarativeAdapter } = require('../gsd-core/bin/lib/adapter-declarative.cjs'); const { cleanup } = require('./helpers.cjs'); const { walk, runMinimalInstall, BUILD_SCRIPT } = require('./helpers/install-shared.cjs'); const DESC = path.join(__dirname, '..', 'capabilities', 'antigravity', 'capability.json'); +const ANTIGRAVITY_CAP = JSON.parse(fs.readFileSync(DESC, 'utf8')); +const ANTIGRAVITY_AXES = ANTIGRAVITY_CAP.runtime.hostIntegration; // hooks/dist is gitignored and built (mirrors golden-install-parity harness). before(() => { @@ -66,6 +86,130 @@ test('a real Antigravity install emits a gsd command/skill surface (invocable)', } }); +// --------------------------------------------------------------------------- +// #2096 EoS/antigravity — AC3/AC5: fail-closed negotiation + validator +// acceptance + the folded descriptor (mirrors kimi/codex reference tests). +// --------------------------------------------------------------------------- + +// -- AC5: negotiation fails CLOSED on a corrupted descriptor ------------------ + +test('negotiateHostCapabilities never throws for antigravity, even fully corrupted', () => { + assert.doesNotThrow(() => negotiateHostCapabilities({})); + assert.doesNotThrow(() => negotiateHostCapabilities({ ...ANTIGRAVITY_AXES, embeddingMode: UNDOCUMENTED })); + assert.doesNotThrow(() => negotiateHostCapabilities({ ...ANTIGRAVITY_AXES, embeddingMode: 'future-unknown' })); + assert.doesNotThrow(() => negotiateHostCapabilities({ ...ANTIGRAVITY_AXES, dispatch: 'corrupted-not-an-object' })); + assert.doesNotThrow(() => negotiateHostCapabilities({ ...ANTIGRAVITY_AXES, dispatch: { ...ANTIGRAVITY_AXES.dispatch, maxDepth: 'not-a-number' } })); +}); + +test('a partial/empty antigravity descriptor degrades to the safe floor, not the declarative-cli baseline', () => { + const result = negotiateHostCapabilities({}); + assert.equal(result.effective.embeddingMode, 'declarative', 'omitted embeddingMode degrades closed'); + assert.equal(result.effective.hookBus, 'none'); + assert.notDeepEqual(result.effective, PROFILE_BASELINES['declarative-cli']); + assert.ok(result.warnings.length > 0); +}); + +// AC-specific: the 4 still-undocumented dispatch sub-axes must degrade to the +// most-restrictive KNOWN value, not their optimistic value. Real values below +// were confirmed via: +// node -e "const {negotiateHostCapabilities}=require('./gsd-core/bin/lib/host-integration.cjs'); +// const cap=require('./capabilities/antigravity/capability.json'); +// console.log(negotiateHostCapabilities(cap.runtime.hostIntegration).effective.dispatch)" +// -> { namedDispatch:false, nested:false, maxDepth:0, background:false, subagentToolkit:'full', backgroundDispatch:false } +test("antigravity's 4 still-undocumented dispatch sub-axes (namedDispatch/nested/maxDepth/backgroundDispatch) degrade to the most-restrictive known value, not their optimistic value", () => { + // Sanity: the descriptor itself still declares these 4 as the undocumented + // sentinel. subagentToolkit is the ONE dispatch axis Context7 confirmed as + // 'full' (antigravity.google/docs/cli/features) — it is deliberately NOT + // part of this still-undocumented set. + assert.equal(ANTIGRAVITY_AXES.dispatch.namedDispatch, 'undocumented'); + assert.equal(ANTIGRAVITY_AXES.dispatch.nested, 'undocumented'); + assert.equal(ANTIGRAVITY_AXES.dispatch.maxDepth, 'undocumented'); + assert.equal(ANTIGRAVITY_AXES.dispatch.backgroundDispatch, 'undocumented'); + assert.equal(ANTIGRAVITY_AXES.dispatch.subagentToolkit, 'full', 'sanity: subagentToolkit is documented, not part of the undocumented set'); + + const { effective, warnings } = negotiateHostCapabilities(ANTIGRAVITY_AXES); + + assert.equal(effective.dispatch.namedDispatch, false, 'undocumented namedDispatch must degrade to false, never true'); + assert.equal(effective.dispatch.nested, false, 'undocumented nested must degrade to false, never true'); + assert.equal(effective.dispatch.maxDepth, 0, 'undocumented maxDepth must degrade to 0, never -1/unbounded'); + assert.equal(effective.dispatch.backgroundDispatch, false, 'undocumented backgroundDispatch must degrade to false, never true'); + + // subagentToolkit is documented 'full' (not undocumented) — it is trusted + // and survives negotiation, in contrast to the 4 sub-axes above. + assert.equal(effective.dispatch.subagentToolkit, 'full', "documented 'full' subagentToolkit is trusted, unlike the undocumented sub-axes"); + + // background is declared `true` (documented, not undocumented) but the + // struct-consistency cap in negotiateHostCapabilities still zeroes it + // because its sibling namedDispatch degraded to false — a host-declared + // `true` never overrides the fail-closed floor forced by a degraded axis. + assert.equal(effective.dispatch.background, false, 'background is capped to false once namedDispatch degrades closed'); + + for (const axis of ['namedDispatch', 'nested', 'backgroundDispatch']) { + assert.ok( + warnings.some((w) => w.includes(`dispatch.${axis}`) && w.includes('undocumented')), + `a warning must be raised for the undocumented dispatch.${axis} axis`, + ); + } + assert.ok( + warnings.some((w) => w.includes('dispatch.maxDepth')), + 'a warning must be raised for the undocumented dispatch.maxDepth axis (reported as missing/non-number)', + ); +}); + +// -- AC3: the validator accepts the negotiated/folded descriptor values ------ + +test('capabilities/antigravity/capability.json validates — subagentToolkit "full" + permissionWriter "antigravity" are accepted', () => { + const errors = validateCapability(ANTIGRAVITY_CAP, 'antigravity'); + assert.deepEqual(errors, [], `validateCapability must return no errors, got: ${JSON.stringify(errors)}`); + assert.equal(ANTIGRAVITY_AXES.dispatch.subagentToolkit, 'full'); + assert.equal(ANTIGRAVITY_CAP.runtime.permissionWriter, 'antigravity'); +}); + +// -- AC2: the folded-in hostBehaviors + subagentToolkit upgrade -------------- + +test('antigravity descriptor declares runtime.hostBehaviors (the folded-in behaviors) + the subagentToolkit upgrade', () => { + const hb = ANTIGRAVITY_CAP.runtime.hostBehaviors; + assert.ok(hb && typeof hb === 'object'); + assert.equal(hb.reviewerCli, true); + assert.equal(hb.projectInstructionFile, 'GEMINI.md'); + assert.equal(hb.noPathRewrite, true); + assert.equal(hb.hookPathStyle, 'raw'); + assert.equal(ANTIGRAVITY_AXES.dispatch.subagentToolkit, 'full', + 'subagentToolkit flipped undocumented -> full (antigravity.google/docs/cli/features)'); +}); + +// -- AC2: the hardcoded branches are retired across all folded modules ------- + +test('no `runtime === "antigravity"` string-equality branch (nor `isAntigravity` / `canonical === "antigravity"`) remains in the descriptor-migrated modules (AC2)', () => { + const strip = (src) => src + .replace(/\/\*[\s\S]*?\*\//g, '') + .replace(/\/\/[^\r\n]*/g, '') + .replace(/`[^`]*`/g, ''); + const repoRoot = path.join(__dirname, '..'); + const files = [ + path.join(repoRoot, 'bin', 'install.js'), + path.join(repoRoot, 'src', 'runtime-artifact-conversion.cts'), + path.join(repoRoot, 'src', 'shell-command-projection.cts'), + path.join(repoRoot, 'src', 'runtime-name-policy.cts'), + ]; + for (const file of files) { + const src = fs.readFileSync(file, 'utf8'); + const stripped = strip(src); + + const eqOffenders = stripped.match(/runtime\s*[!=]==\s*'antigravity'/g) || []; + assert.deepEqual(eqOffenders, [], + `AC2: no hardcoded runtime==='antigravity' branch may remain in ${path.relative(repoRoot, file)}; found: ${eqOffenders.join(', ')}`); + + const isAntigravityHits = stripped.match(/\bisAntigravity\b/g) || []; + assert.deepEqual(isAntigravityHits, [], + `AC2: no isAntigravity helper may remain in ${path.relative(repoRoot, file)}; found ${isAntigravityHits.length} occurrence(s)`); + + const canonicalOffenders = stripped.match(/canonical\s*===\s*'antigravity'/g) || []; + assert.deepEqual(canonicalOffenders, [], + `AC2: no canonical==='antigravity' branch may remain in ${path.relative(repoRoot, file)}; found: ${canonicalOffenders.join(', ')}`); + } +}); + // ──────────────────────────────────────────────────────────────────────── // Folded from tests/bug-3608-antigravity-update-runtime-classification.test.cjs — consolidation epic #1969 (B3 #1972) diff --git a/tests/fixtures/golden-install-parity/antigravity.json b/tests/fixtures/golden-install-parity/antigravity.json index 6d10c1404..939c09ae6 100644 --- a/tests/fixtures/golden-install-parity/antigravity.json +++ b/tests/fixtures/golden-install-parity/antigravity.json @@ -336,6 +336,7 @@ "hooks/lib/git-cmd.js": "268ba15992ca0b23", "hooks/lib/gsd-graphify-rebuild.sh": "66af89601074d2a9", "hooks/managed-hooks-registry.cjs": "721d696556b7509f", + "mcp_config.json": "9956d6a6e88a49e1", "package.json": "dbf8353f77358bc1", "scripts/changeset/README.md": "86ff89331dfd94b2", "scripts/changeset/cli.cjs": "68f92a344b199271", diff --git a/tests/shell-command-projection-dispatch.test.cjs b/tests/shell-command-projection-dispatch.test.cjs index 0edcb38ab..b393e69b5 100644 --- a/tests/shell-command-projection-dispatch.test.cjs +++ b/tests/shell-command-projection-dispatch.test.cjs @@ -343,9 +343,14 @@ describe('bug #1906: local hook commands use $CLAUDE_PROJECT_DIR', () => { * dir as cwd. Claude Code and others still use "$CLAUDE_PROJECT_DIR"/ (#1906). * * #1928: Google sunset Gemini CLI (2026-06-18) and the `gemini` runtime was - * removed from GSD entirely. `projectLocalHookPrefix` now special-cases only - * `antigravity` — an unrecognized runtime string like the former `'gemini'` - * falls through to the default $CLAUDE_PROJECT_DIR-anchored prefix. + * removed from GSD entirely. + * + * #2096: `projectLocalHookPrefix` no longer special-cases `antigravity` by + * name — it branches on the caller-supplied `hookPathStyle` (sourced from + * the runtime's `hostBehaviors.hookPathStyle` descriptor field). An + * unrecognized runtime string like the former `'gemini'`, or any runtime + * that doesn't declare `hookPathStyle: 'raw'`, falls through to the default + * $CLAUDE_PROJECT_DIR-anchored prefix. */ const { describe, test } = require('node:test'); @@ -357,7 +362,13 @@ const { projectLocalHookPrefix, projectShellCommandText } = projection; describe('bug #2557: Antigravity local hooks use relative paths (not $CLAUDE_PROJECT_DIR); gemini runtime removed (#1928)', () => { test('Antigravity local prefix is bare dirName', () => { - assert.equal(projectLocalHookPrefix({ runtime: 'antigravity', dirName: '.agents' }), '.agents'); + // #2096: hookPathStyle is now the caller-supplied descriptor value + // (bin/install.js resolves it from hostBehaviors.hookPathStyle); the + // function itself no longer knows the runtime name 'antigravity'. + assert.equal( + projectLocalHookPrefix({ runtime: 'antigravity', dirName: '.agents', hookPathStyle: 'raw' }), + '.agents', + ); }); test('non-Antigravity local prefix remains $CLAUDE_PROJECT_DIR anchored', () => { @@ -512,7 +523,13 @@ describe('bug #3439: shell projection module owns managed-hook policy and legacy }); test('projectLocalHookPrefix centralizes runtime-specific project-dir interpolation policy', () => { - assert.equal(projectLocalHookPrefix({ runtime: 'antigravity', dirName: '.agents' }), '.agents'); + // #2096: 'raw' hookPathStyle (descriptor-driven) is what produces the + // bare-dirName behavior now — the function no longer branches on the + // 'antigravity' runtime name itself. + assert.equal( + projectLocalHookPrefix({ runtime: 'antigravity', dirName: '.agents', hookPathStyle: 'raw' }), + '.agents', + ); assert.equal( projectLocalHookPrefix({ runtime: 'claude', dirName: '.claude' }), '"$CLAUDE_PROJECT_DIR"/.claude',