From 5695522d5f94211660e9f3d5c12728705318ff6a Mon Sep 17 00:00:00 2001 From: Tom Boucher Date: Sat, 11 Jul 2026 02:27:57 -0400 Subject: [PATCH 1/3] 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', From 17aa35fba7f20e6b8dc33e3b992fe1d80382a8a8 Mon Sep 17 00:00:00 2001 From: Tom Boucher Date: Sat, 11 Jul 2026 04:04:48 -0400 Subject: [PATCH 2/3] feat(#2097): migrate Augment onto EoS declarative adapter + settings.json MCP companion (ADR-1239) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fold augment's runtime-literal conversion branches onto descriptor-driven hostBehaviors and delete dead code: - Site A (_applyRuntimeRewrites case 'augment'): the 4 ~/.augment dot-dir regexes now derive from getDirName('augment') via escapeRegExp (byte- identical; getDirName('augment')==='.augment') — no runtime literal. - Site B (applyRuntimeContentRewritesForCommandsInPlace): the `if (runtime==='augment')` markdown-converter branch now reads runtime.hostBehaviors.commandBodyConverter and dispatches through a local COMMAND_BODY_CONVERTERS map (degrade-closed on unknown/absent name). - Deleted dead `claudeToAugmentTools` map (zero refs; orphaned by ADR-1508 single-sourcing) and the unreachable `else if (isAugment)` agent-conversion branch (augment ∈ _DESCRIPTOR_AGENTS_RUNTIMES → gated out upstream). - Incidental orphan cleanup (no-defer): removed the equally-unreachable `else if (isTrae)` agent-conversion arm left behind by trae's already-merged migration #2094 (trae ∈ _DESCRIPTOR_AGENTS_RUNTIMES, same upstream gate). copilot/windsurf/codebuddy arms are removed by their own pending migrations. UPGRADE 3 (transport:mcp): register the GSD companion MCP server in Augment's settings.json under mcpServers.gsd (Augment hosts MCP in settings.json, not a standalone file). mergeGsdMcpServerIntoSettings mutates the in-memory settings object finishInstall already writes (gated on hostBehaviors.mcpCompanion=== 'settings-json'); non-destructive + idempotent; symmetric uninstall removal. settings.json is golden-excluded, so no golden change. UPGRADE 1 (named/ background dispatch) + UPGRADE 2 (settings-json hook bus, Claude dialect) were already live in production — this adds tests exercising both. Golden: byte-identical for all 16 runtimes (folds preserve regex behavior; MCP lives in golden-excluded settings.json) — verified by a real double-install tree diff. Tests: declarative-reference-augment (adapter/axes/fail-closed/ undocumented-sub-axes + source-grep guard scoped to conversion-logic branches) + augment-upgrades (dispatch negotiation, hook-bus live install, MCP add/ idempotent/preserve/uninstall). Matrix + connect-gsd-mcp-server + a stale install-on-your-runtime hook-ownership claim corrected; changeset (Changed). Co-Authored-By: Claude Opus 4.8 --- .../2097-eos-augment-imperative-adapter.md | 6 + bin/install.js | 56 +++- capabilities/augment/capability.json | 4 + docs/how-to/connect-gsd-mcp-server.md | 8 +- docs/how-to/install-on-your-runtime.md | 2 +- .../host-integration-capability-matrix.md | 29 +++ gsd-core/bin/lib/capability-registry.cjs | 8 + src/runtime-artifact-conversion.cts | 27 +- tests/augment-upgrades.test.cjs | 243 ++++++++++++++++++ tests/declarative-reference-augment.test.cjs | 202 +++++++++++++++ 10 files changed, 564 insertions(+), 21 deletions(-) create mode 100644 .changeset/2097-eos-augment-imperative-adapter.md create mode 100644 tests/augment-upgrades.test.cjs create mode 100644 tests/declarative-reference-augment.test.cjs diff --git a/.changeset/2097-eos-augment-imperative-adapter.md b/.changeset/2097-eos-augment-imperative-adapter.md new file mode 100644 index 000000000..fe67b40f2 --- /dev/null +++ b/.changeset/2097-eos-augment-imperative-adapter.md @@ -0,0 +1,6 @@ +--- +type: Changed +pr: 2166 +--- + +**Augment Code now installs through its capability descriptor, with a native MCP companion** — installing GSD into Augment registers the GSD companion server in Augment's `settings.json` `mcpServers` and drives command/skill/agent conversion from Augment's negotiated descriptor instead of hardcoded runtime special-cases. (#2097) diff --git a/bin/install.js b/bin/install.js index c5bfdb513..027c6c8c6 100755 --- a/bin/install.js +++ b/bin/install.js @@ -2606,14 +2606,6 @@ function convertClaudeAgentToWindsurfAgent(content) { // Augment uses a tool set similar to Cursor/Windsurf. // Config lives in .augment/ (local) and ~/.augment/ (global). -const claudeToAugmentTools = { - Bash: 'launch-process', - Edit: 'str-replace-editor', - AskUserQuestion: null, - SlashCommand: null, - TodoWrite: 'add_tasks', -}; - // #1675 (ADR-1508): the augment converter family below was a byte-identical // duplicate of runtime-artifact-conversion.cjs: // convertSlashCommandsToAugmentSkillMentions, convertClaudeToAugmentMarkdown, @@ -7546,6 +7538,21 @@ function uninstall(isGlobal, runtime = DEFAULT_RUNTIME) { } } + // #2097 UPGRADE 3 — Remove the MCP companion entry from settings.json for + // runtimes that host MCP there (Augment), symmetric to the mcp_config.json + // removal for Antigravity below. Only the GSD-owned mcpServers.gsd key is + // removed — any other user-configured MCP servers are preserved. + if (_hostBehaviors(runtime).mcpCompanion === 'settings-json' && + settings.mcpServers && typeof settings.mcpServers === 'object' && + settings.mcpServers.gsd !== undefined) { + delete settings.mcpServers.gsd; + if (Object.keys(settings.mcpServers).length === 0) { + delete settings.mcpServers; + } + settingsModified = true; + console.log(` ${green}✓${reset} Removed GSD MCP companion server from settings.json`); + } + if (settingsModified) { writeSettings(settingsPath, settings); removedCount++; @@ -8078,6 +8085,27 @@ function configureAntigravityMcpConfig(isGlobal = true, configDir = null) { console.log(` ${green}✓${reset} Configured Antigravity MCP companion server (gsd)`); } +/** + * #2097 (ADR-1239 transport:mcp): register the GSD companion MCP server inside a + * runtime's settings.json (Augment hosts MCP in settings.json.mcpServers, unlike + * Antigravity's standalone mcp_config.json). Mutates the in-memory settings object + * that finishInstall already writes — non-destructive + idempotent: only sets + * mcpServers.gsd, preserving any user-defined servers (a user's own `gsd` override + * is respected — Hyrum's Law). + * @param {object} settings - the in-memory settings object finishInstall will write + */ +function mergeGsdMcpServerIntoSettings(settings) { + if (!settings.mcpServers || typeof settings.mcpServers !== 'object' || Array.isArray(settings.mcpServers)) { + settings.mcpServers = {}; + } + if (settings.mcpServers.gsd === undefined) { + settings.mcpServers.gsd = { + command: 'npx', + args: ['-y', '-p', PACKAGE_NAME, 'gsd-mcp-server'], + }; + } +} + /** * Verify a directory exists and contains files */ @@ -9643,10 +9671,6 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) { content = convertClaudeAgentToCopilotAgent(content, isGlobal); } else if (isWindsurf) { content = convertClaudeAgentToWindsurfAgent(content); - } else if (isAugment) { - content = convertClaudeAgentToAugmentAgent(content); - } else if (isTrae) { - content = convertClaudeAgentToTraeAgent(content); } else if (isCodebuddy) { content = convertClaudeAgentToCodebuddyAgent(content); } else if (_hostBehaviors(runtime).frontmatterDialect === 'cline') { @@ -10918,6 +10942,12 @@ function finishInstall(settingsPath, settings, statuslineCommand, shouldInstallS mergeClaudePermissions(settings); } + // #2097 UPGRADE 3 (transport:mcp): companion MCP server for runtimes that host + // MCP in settings.json (Augment). settings.json is golden-excluded, so no golden change. + if (_hostBehaviors(runtime).mcpCompanion === 'settings-json' && settings && plan.writesSharedSettings) { + mergeGsdMcpServerIntoSettings(settings); + } + // Write settings when runtime supports settings.json. // #3002 CR: defense-in-depth — re-run validateHookFields right before // serialization. The push-site guards above already skip null-command @@ -11930,6 +11960,8 @@ module.exports = { buildAntigravityAllowRules, configureAntigravityPermissions, configureAntigravityMcpConfig, + // #2097 UPGRADE 3 — Augment MCP companion (settings.json-hosted) + mergeGsdMcpServerIntoSettings, claudeToCopilotTools, convertCopilotToolName, convertClaudeToCopilotContent, diff --git a/capabilities/augment/capability.json b/capabilities/augment/capability.json index a7e7c5683..a712d16f2 100644 --- a/capabilities/augment/capability.json +++ b/capabilities/augment/capability.json @@ -82,6 +82,10 @@ "writesSharedSettings": true, "permissionWriter": null, "extendedHookEvents": [], + "hostBehaviors": { + "commandBodyConverter": "convertClaudeToAugmentMarkdown", + "mcpCompanion": "settings-json" + }, "hostIntegration": { "embeddingMode": "declarative", "commandSurface": "slash-file", diff --git a/docs/how-to/connect-gsd-mcp-server.md b/docs/how-to/connect-gsd-mcp-server.md index 37cbbed89..468289f8a 100644 --- a/docs/how-to/connect-gsd-mcp-server.md +++ b/docs/how-to/connect-gsd-mcp-server.md @@ -1,7 +1,8 @@ # How to connect a host to the GSD companion MCP server This guide shows you how to make a MCP-capable host (Claude Code, Codex, -OpenCode, VS Code, Antigravity CLI, Cursor, Cline, Hermes) drive GSD — run GSD +OpenCode, VS Code, Antigravity CLI, Cursor, Cline, Hermes, Augment Code) drive +GSD — run GSD commands and read/write `.planning/` state — through the companion MCP server, with no bespoke plugin. @@ -28,6 +29,11 @@ host. - **Claude Code / Codex / Cursor / Cline / Hermes** — under the host's `mcpServers` object (project or user config). +- **Augment Code** — under the `mcpServers` block of its own + `settings.json` (not a standalone MCP config file, unlike Antigravity) + — global at `~/.augment/settings.json`, project-local at + `.augment/settings.json`. GSD's installer configures this entry + automatically (`--augment` installs). - **VS Code** — in the workspace MCP servers list. - **Antigravity** — under the `mcpServers` block of its standalone `mcp_config.json` profile (not embedded in `settings.json`) — global at diff --git a/docs/how-to/install-on-your-runtime.md b/docs/how-to/install-on-your-runtime.md index 6835d0e00..70fc779f6 100644 --- a/docs/how-to/install-on-your-runtime.md +++ b/docs/how-to/install-on-your-runtime.md @@ -397,7 +397,7 @@ Qwen Code supports 15 hook events. GSD registers the following events automatica npx @opengsd/gsd-core@latest --augment --global ``` -Skills land in `~/.augment/skills/` and slash command definitions land in `~/.augment/commands/`. GSD installs skills, agents, and commands (`/gsd-phase`, `/gsd-ship`, etc.). No hook or statusline ownership. +Skills land in `~/.augment/skills/` and slash command definitions land in `~/.augment/commands/`. GSD installs skills, agents, and commands (`/gsd-phase`, `/gsd-ship`, etc.). GSD's managed lifecycle hooks are registered into Augment's own `settings.json` `hooks` block (Claude hook event dialect, covering session-start, tool-use, and phase-boundary events) — no statusline ownership. #2097 also registers the GSD companion MCP server under `settings.json`'s `mcpServers.gsd` (see [Connect a host to the GSD MCP server](connect-gsd-mcp-server.md)). --- diff --git a/docs/reference/host-integration-capability-matrix.md b/docs/reference/host-integration-capability-matrix.md index c8046ec56..1898c9215 100644 --- a/docs/reference/host-integration-capability-matrix.md +++ b/docs/reference/host-integration-capability-matrix.md @@ -334,6 +334,35 @@ Documentation gaps: - dispatch.nested - dispatch.maxDepth +**EoS migration status (#2097):** Folded onto descriptor-driven dispatch. +Augment already installed through the declarative adapter (nested-skill +artifact layout, `settings-json` hook surface, Claude hook event dialect), but +carried two remaining runtime-literal branches in +`src/runtime-artifact-conversion.cts`: the 4 `~/.augment`/`$HOME/.augment` +dot-dir rewrites in `_applyRuntimeRewrites`'s `case 'augment':` block are now +built from `getDirName('augment')` (dirName-derived, byte-identical) instead +of a hardcoded `.augment` literal, and the +`applyRuntimeContentRewritesForCommandsInPlace` command-body conversion +dispatch now reads `runtime.hostBehaviors.commandBodyConverter` +(`"convertClaudeToAugmentMarkdown"`) instead of a hardcoded +`runtime === 'augment'` branch. Two dead-code sites were also removed from +`bin/install.js`: the orphaned `claudeToAugmentTools` map (superseded by the +single-sourced converters per ADR-1508 / #1675) and the unreachable +`else if (isAugment) { content = convertClaudeAgentToAugmentAgent(content); }` +inline agent-conversion branch (augment has been on the descriptor-agents path +since `_DESCRIPTOR_AGENTS_RUNTIMES` was introduced, making that `if`/`else if` +arm dead). **UPGRADE 3 — MCP companion config** +(`mergeGsdMcpServerIntoSettings`) registers the `gsd` MCP server directly +inside the same `settings.json` `mcpServers` block GSD's own hook +registration already writes (Augment hosts MCP in `settings.json`, unlike +Antigravity's standalone `mcp_config.json`) — non-destructively preserving +any other user-configured `mcpServers` entries; uninstall removes only the +GSD-owned `gsd` entry. `settings.json` is golden-excluded +(`HOOK_CONFIG_FILES`), so this upgrade produces no golden fixture change. +Source-grep guard + fail-closed negotiation coverage is in +`tests/declarative-reference-augment.test.cjs`; the dispatch/hook-bus/MCP +upgrade coverage is in `tests/augment-upgrades.test.cjs`. + --- ## qwen diff --git a/gsd-core/bin/lib/capability-registry.cjs b/gsd-core/bin/lib/capability-registry.cjs index f1899a7ab..e5c62b7a7 100644 --- a/gsd-core/bin/lib/capability-registry.cjs +++ b/gsd-core/bin/lib/capability-registry.cjs @@ -360,6 +360,10 @@ const capabilities = { "writesSharedSettings": true, "permissionWriter": null, "extendedHookEvents": [], + "hostBehaviors": { + "commandBodyConverter": "convertClaudeToAugmentMarkdown", + "mcpCompanion": "settings-json" + }, "hostIntegration": { "embeddingMode": "declarative", "commandSurface": "slash-file", @@ -3953,6 +3957,10 @@ const runtimes = { "writesSharedSettings": true, "permissionWriter": null, "extendedHookEvents": [], + "hostBehaviors": { + "commandBodyConverter": "convertClaudeToAugmentMarkdown", + "mcpCompanion": "settings-json" + }, "hostIntegration": { "embeddingMode": "declarative", "commandSurface": "slash-file", diff --git a/src/runtime-artifact-conversion.cts b/src/runtime-artifact-conversion.cts index c1e2f6576..0a235a09b 100644 --- a/src/runtime-artifact-conversion.cts +++ b/src/runtime-artifact-conversion.cts @@ -1107,6 +1107,11 @@ function convertClaudeToAugmentMarkdown(content) { return converted; } +// #2097 (ADR-1239): command-body converters selected by descriptor +// (runtime.hostBehaviors.commandBodyConverter) instead of a runtime-name +// branch. Degrade-closed: unknown/absent name → no conversion. +const COMMAND_BODY_CONVERTERS = { convertClaudeToAugmentMarkdown }; + function getAugmentSkillAdapterHeader(skillName) { return ` ## A. Skill Invocation @@ -2442,19 +2447,24 @@ function _applyRuntimeRewrites(content, runtime, pathPrefix, isGlobal = false, a break; } - case 'augment': + case 'augment': { content = content.replace(/~\/\.claude\//g, pathPrefix); content = content.replace(/\$HOME\/\.claude\//g, pathPrefix); content = content.replace(/\.\/\.claude\//g, `./${dirName}/`); content = content.replace(/~\/\.claude(?![\w-])/g, normalizedPathPrefix); content = content.replace(/\$HOME\/\.claude(?![\w-])/g, normalizedPathPrefix); content = content.replace(/\.\/\.claude(?![\w-])/g, `./${dirName}`); - content = content.replace(/~\/\.augment\//g, pathPrefix); - content = content.replace(/\$HOME\/\.augment\//g, pathPrefix); - content = content.replace(/~\/\.augment(?![\w-])/g, normalizedPathPrefix); - content = content.replace(/\$HOME\/\.augment(?![\w-])/g, normalizedPathPrefix); + // #2097: dot-dir self-references (~/.augment/…) → resolved prefix, + // dirName-derived (no runtime literal). getDirName('augment') resolves + // to '.augment', so this is byte-identical to the prior hardcoded regexes. + const _dd = escapeRegExp(dirName); + content = content.replace(new RegExp('~/' + _dd + '/', 'g'), pathPrefix); + content = content.replace(new RegExp('\\$HOME/' + _dd + '/', 'g'), pathPrefix); + content = content.replace(new RegExp('~/' + _dd + '(?![\\w-])', 'g'), normalizedPathPrefix); + content = content.replace(new RegExp('\\$HOME/' + _dd + '(?![\\w-])', 'g'), normalizedPathPrefix); content = processAttribution(content, attribution); break; + } case 'trae': content = content.replace(/~\/\.claude\//g, pathPrefix); @@ -2631,8 +2641,11 @@ function applyRuntimeContentRewritesForCommandsInPlace(stagedDir, runtime, pathP if (!entry.isFile() || !entry.name.endsWith('.md')) continue; let content = fs.readFileSync(path.join(stagedDir, entry.name), 'utf8'); content = _applyRuntimeRewrites(content, runtime, pathPrefix, isGlobal, attribution); - if (runtime === 'augment') { - content = convertClaudeToAugmentMarkdown(content); + // #2097 (ADR-1239): descriptor-driven — commandBodyConverter name comes + // from runtime.hostBehaviors instead of a hardcoded runtime-name branch. + const _cmdConv = _hostBehaviors(runtime).commandBodyConverter; + if (_cmdConv && COMMAND_BODY_CONVERTERS[_cmdConv]) { + content = COMMAND_BODY_CONVERTERS[_cmdConv](content); } fs.writeFileSync(path.join(tempDir, entry.name), content); } diff --git a/tests/augment-upgrades.test.cjs b/tests/augment-upgrades.test.cjs new file mode 100644 index 000000000..323d902ae --- /dev/null +++ b/tests/augment-upgrades.test.cjs @@ -0,0 +1,243 @@ +'use strict'; + +/** + * Augment Code capability UPGRADES — ADR-1239 / #2097 (EoS/augment migration). + * + * Mirrors tests/antigravity-upgrades.test.cjs's structure. Augment already + * shipped as a declarative-CLI host prior to #2097 (nested-skill artifact + * layout, settings-json hook surface, Claude hook event dialect, dispatch + * namedDispatch/background/subagentToolkit:'full'), so UPGRADE 1 (dispatch) + * and UPGRADE 2 (hook-bus) below are REGRESSION locks on that pre-existing + * wiring, not new capabilities. UPGRADE 3 (MCP companion) IS new: #2097 adds + * `mergeGsdMcpServerIntoSettings`, registering the GSD companion MCP server + * inside Augment's own settings.json `mcpServers` block (Augment hosts MCP + * there, unlike Antigravity's standalone mcp_config.json) — non-destructively + * appending GSD's own entry while preserving any other user-configured + * `mcpServers` entries. Uninstall removes only the GSD-owned `gsd` entry. + */ + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const os = require('node:os'); +const { spawnSync } = require('node:child_process'); + +const { runMinimalInstall, installerEnv, INSTALL_SCRIPT } = require('./helpers/install-shared.cjs'); +const { cleanup } = require('./helpers.cjs'); +const { + mergeGsdMcpServerIntoSettings, +} = require('../bin/install.js'); +const { negotiateHostCapabilities } = require('../gsd-core/bin/lib/host-integration.cjs'); +const { PACKAGE_NAME } = require('../gsd-core/bin/lib/package-identity.cjs'); + +const AUGMENT_CAP = JSON.parse( + fs.readFileSync(path.join(__dirname, '..', 'capabilities', 'augment', 'capability.json'), 'utf8'), +); + +// --------------------------------------------------------------------------- +// UPGRADE 1: dispatch — descriptor + negotiation regression lock +// --------------------------------------------------------------------------- + +test('capabilities/augment/capability.json declares dispatch.namedDispatch/background/subagentToolkit for full subagent support (UPGRADE 1)', () => { + const dispatch = AUGMENT_CAP.runtime.hostIntegration.dispatch; + assert.equal(dispatch.namedDispatch, true); + assert.equal(dispatch.background, true); + assert.equal(dispatch.subagentToolkit, 'full'); +}); + +test('negotiateHostCapabilities does NOT flatten dispatch for augment — namedDispatch/background/subagentToolkit survive negotiation (UPGRADE 1)', () => { + const { effective } = negotiateHostCapabilities(AUGMENT_CAP.runtime.hostIntegration); + assert.equal(effective.dispatch.namedDispatch, true, + 'documented namedDispatch:true must survive negotiation unflattened'); + assert.equal(effective.dispatch.background, true, + 'documented background:true must survive negotiation unflattened (not capped to false)'); + assert.equal(effective.dispatch.subagentToolkit, 'full', + 'documented subagentToolkit:full must survive negotiation unflattened'); +}); + +// --------------------------------------------------------------------------- +// UPGRADE 2: hook-bus — live install proves the settings.json hook surface +// (SessionStart/PostToolUse/PreToolUse) is actually wired for augment. +// --------------------------------------------------------------------------- + +for (const scope of ['global', 'local']) { + test(`augment --${scope}: settings.json contains GSD's managed hook entries (UPGRADE 2)`, (t) => { + const { configDir, root } = runMinimalInstall({ runtime: 'augment', 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.hooks && typeof settings.hooks === 'object', 'settings.hooks must be an object'); + + // Augment's hookEvents dialect is 'claude' (capabilities/augment/capability.json), + // so it gets the Claude-dialect event names (PostToolUse/PreToolUse), not + // antigravity's gemini-dialect (AfterTool/BeforeTool). + assert.ok(Array.isArray(settings.hooks.SessionStart) && settings.hooks.SessionStart.length > 0, + 'settings.hooks.SessionStart must be registered'); + assert.ok(Array.isArray(settings.hooks.PostToolUse) && settings.hooks.PostToolUse.length > 0, + 'settings.hooks.PostToolUse must be registered'); + assert.ok(Array.isArray(settings.hooks.PreToolUse) && settings.hooks.PreToolUse.length > 0, + 'settings.hooks.PreToolUse must be registered'); + + const hasGsdCommand = (entries) => entries.some( + (entry) => entry && Array.isArray(entry.hooks) && + entry.hooks.some((h) => h && typeof h.command === 'string' && h.command.includes('gsd-')), + ); + assert.ok(hasGsdCommand(settings.hooks.SessionStart), 'SessionStart must reference a gsd- managed hook'); + assert.ok(hasGsdCommand(settings.hooks.PostToolUse), 'PostToolUse must reference a gsd- managed hook'); + assert.ok(hasGsdCommand(settings.hooks.PreToolUse), 'PreToolUse must reference a gsd- managed hook'); + }); +} + +// --------------------------------------------------------------------------- +// UPGRADE 3: MCP companion config — direct-unit idempotency + preservation +// (mirrors antigravity's configureAntigravityMcpConfig unit tests exactly, +// scoped to the in-memory settings object mergeGsdMcpServerIntoSettings mutates). +// --------------------------------------------------------------------------- + +test('mergeGsdMcpServerIntoSettings adds mcpServers.gsd with command "npx" and args including gsd-mcp-server + PACKAGE_NAME', () => { + const settings = {}; + mergeGsdMcpServerIntoSettings(settings); + assert.ok(settings.mcpServers && settings.mcpServers.gsd, 'mcpServers.gsd must be present'); + assert.equal(settings.mcpServers.gsd.command, 'npx'); + assert.deepEqual(settings.mcpServers.gsd.args, ['-y', '-p', PACKAGE_NAME, 'gsd-mcp-server']); +}); + +test('mergeGsdMcpServerIntoSettings is idempotent — a second call does not clobber an existing gsd entry', () => { + const settings = {}; + mergeGsdMcpServerIntoSettings(settings); + // Simulate a user hand-edit of the gsd entry after install. + settings.mcpServers.gsd.args.push('--custom-flag'); + + mergeGsdMcpServerIntoSettings(settings); + + assert.ok(settings.mcpServers.gsd.args.includes('--custom-flag'), + "a user-owned gsd override is never clobbered (Hyrum's Law)"); + assert.equal(Object.keys(settings.mcpServers).length, 1, 'exactly one mcpServers entry (gsd)'); +}); + +test('mergeGsdMcpServerIntoSettings preserves a pre-existing unrelated mcpServers entry', () => { + const settings = { + mcpServers: { + 'my-own-server': { command: 'my-tool', args: ['--flag'] }, + }, + }; + mergeGsdMcpServerIntoSettings(settings); + + assert.deepEqual(settings.mcpServers['my-own-server'], { command: 'my-tool', args: ['--flag'] }); + assert.ok(settings.mcpServers.gsd); + assert.equal(Object.keys(settings.mcpServers).length, 2, 'both entries present'); +}); + +test('mergeGsdMcpServerIntoSettings recovers a corrupted (non-object) mcpServers field', () => { + const settingsArrayCase = { mcpServers: ['not', 'an', 'object'] }; + mergeGsdMcpServerIntoSettings(settingsArrayCase); + assert.ok(settingsArrayCase.mcpServers.gsd, 'array mcpServers must be recovered to an object with gsd set'); + + const settingsStringCase = { mcpServers: 'corrupted-string' }; + mergeGsdMcpServerIntoSettings(settingsStringCase); + assert.ok(settingsStringCase.mcpServers.gsd, 'non-object mcpServers must be recovered to an object with gsd set'); +}); + +// --------------------------------------------------------------------------- +// UPGRADE 3: MCP companion config — live install (both scopes) proves the +// end-to-end wiring through finishInstall, not just the unit function. +// --------------------------------------------------------------------------- + +for (const scope of ['global', 'local']) { + test(`augment --${scope}: settings.json registers the gsd MCP companion (UPGRADE 3)`, (t) => { + const { configDir, root } = runMinimalInstall({ runtime: 'augment', 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.mcpServers && settings.mcpServers.gsd, 'mcpServers.gsd must be present'); + assert.equal(settings.mcpServers.gsd.command, 'npx'); + assert.deepEqual(settings.mcpServers.gsd.args, ['-y', '-p', PACKAGE_NAME, 'gsd-mcp-server']); + }); +} + +test('augment --global: reinstalling does not duplicate or clobber the gsd MCP companion entry (live-install idempotency)', (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-augment-mcp-idem-')); + t.after(() => cleanup(root)); + + const args = [INSTALL_SCRIPT, '--augment', '--global', '--config-dir', root]; + const env = installerEnv({ HOME: root, USERPROFILE: root }); + + const first = spawnSync(process.execPath, args, { encoding: 'utf8', env }); + assert.strictEqual(first.status, 0, `first install failed: ${first.stderr}`); + + const settingsPath = path.join(root, 'settings.json'); + const afterFirst = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); + assert.ok(afterFirst.mcpServers.gsd); + // Simulate a user hand-edit of the gsd entry between installs. + afterFirst.mcpServers.gsd.args.push('--custom-flag'); + fs.writeFileSync(settingsPath, JSON.stringify(afterFirst, null, 2) + '\n'); + + const second = spawnSync(process.execPath, args, { encoding: 'utf8', env }); + assert.strictEqual(second.status, 0, `second install failed: ${second.stderr}`); + + const afterSecond = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); + assert.equal(Object.keys(afterSecond.mcpServers).length, 1, 'reinstall must not duplicate the gsd entry'); + assert.ok(afterSecond.mcpServers.gsd.args.includes('--custom-flag'), + "a user-owned gsd override is never clobbered across reinstall (Hyrum's Law)"); +}); + +test('augment --global: installing preserves a pre-existing unrelated mcpServers entry (live-install preservation)', (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-augment-mcp-preserve-')); + fs.mkdirSync(root, { recursive: true }); + t.after(() => cleanup(root)); + + // Pre-seed settings.json with a user's own MCP server BEFORE install runs. + fs.writeFileSync(path.join(root, 'settings.json'), JSON.stringify({ + mcpServers: { + other: { command: 'my-tool', args: ['--flag'] }, + }, + }, null, 2)); + + const args = [INSTALL_SCRIPT, '--augment', '--global', '--config-dir', root]; + const result = spawnSync(process.execPath, args, { + encoding: 'utf8', + env: installerEnv({ HOME: root, USERPROFILE: root }), + }); + assert.strictEqual(result.status, 0, `install failed: ${result.stderr}`); + + const settings = JSON.parse(fs.readFileSync(path.join(root, 'settings.json'), 'utf8')); + assert.deepEqual(settings.mcpServers.other, { command: 'my-tool', args: ['--flag'] }, + "the user's pre-existing mcpServers entry must be preserved"); + assert.ok(settings.mcpServers.gsd, 'the gsd companion entry must also be present'); +}); + +// --------------------------------------------------------------------------- +// Uninstall — symmetric cleanup for the MCP companion entry. +// --------------------------------------------------------------------------- + +test('augment --global uninstall removes only the GSD-owned mcpServers.gsd entry, preserving user data', (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-augment-uninstall-')); + t.after(() => cleanup(root)); + + const env = installerEnv({ HOME: root, USERPROFILE: root }); + const installArgs = [INSTALL_SCRIPT, '--augment', '--global', '--config-dir', root]; + const installResult = spawnSync(process.execPath, installArgs, { encoding: 'utf8', env }); + 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.mcpServers['my-own-server'] = { command: 'my-tool', args: [] }; + fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n'); + + const uninstallArgs = [INSTALL_SCRIPT, '--augment', '--global', '--config-dir', root, '--uninstall']; + const uninstallResult = spawnSync(process.execPath, uninstallArgs, { encoding: 'utf8', env }); + assert.strictEqual(uninstallResult.status, 0, `uninstall failed: ${uninstallResult.stderr}`); + + const settingsAfter = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); + assert.equal(settingsAfter.mcpServers && settingsAfter.mcpServers.gsd, undefined, 'gsd MCP entry removed'); + assert.deepEqual(settingsAfter.mcpServers['my-own-server'], { command: 'my-tool', args: [] }, + 'user MCP server preserved'); +}); diff --git a/tests/declarative-reference-augment.test.cjs b/tests/declarative-reference-augment.test.cjs new file mode 100644 index 000000000..68bfe52e9 --- /dev/null +++ b/tests/declarative-reference-augment.test.cjs @@ -0,0 +1,202 @@ +// allow-test-rule: structural-regression-guard — the descriptor-migration contract (no `runtime === 'augment'` / `isAugment`-as-conversion-branch dispatch logic left in the folded modules) is a property of the source text itself, so a source-grep is the only faithful check (#2097, mirrors tests/declarative-reference-antigravity.test.cjs #2096 AC2 guard). +'use strict'; + +/** + * Declarative reference host coverage — Augment Code (ADR-1239 / #2097 + * EoS/augment migration). + * + * Augment is already a declarative-CLI host (nested-skill artifact layout, + * settings-json hook surface, Claude hook event dialect). #2097 folds its two + * remaining runtime-literal branches in src/runtime-artifact-conversion.cts + * onto descriptor-driven dispatch (runtime.hostBehaviors.commandBodyConverter) + * and deletes 2 dead-code sites in bin/install.js — mirroring the Antigravity + * migration (#2096) structure without duplicating its Antigravity-specific + * (GEMINI.md / reviewerCli / noPathRewrite) assertions. + * + * UPGRADE 3 (MCP companion, settings.json-hosted) live-install coverage is in + * tests/augment-upgrades.test.cjs — not duplicated here. + */ + +const { test, before } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync } = require('node:child_process'); + +const { + profileOf, + negotiateHostCapabilities, + UNDOCUMENTED, +} = require('../gsd-core/bin/lib/host-integration.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', 'augment', 'capability.json'); +const AUGMENT_CAP = JSON.parse(fs.readFileSync(DESC, 'utf8')); +const AUGMENT_AXES = AUGMENT_CAP.runtime.hostIntegration; + +// hooks/dist is gitignored and built (mirrors golden-install-parity harness). +before(() => { + execFileSync(process.execPath, [BUILD_SCRIPT], { encoding: 'utf-8', stdio: 'pipe' }); +}); + +test('Augment classifies as the declarative-cli profile (profileOf)', () => { + const desc = JSON.parse(fs.readFileSync(DESC, 'utf8')); + const axes = desc.runtime.hostIntegration; + assert.ok(axes && axes.embeddingMode, 'augment descriptor declares hostIntegration axes'); + assert.equal(profileOf(axes), 'declarative-cli', 'Augment is a declarative-CLI host'); +}); + +test('the public declarative adapter classifies Augment as a declarative host', () => { + const adapter = createDeclarativeAdapter({ runtime: 'augment' }); + assert.equal(adapter.kind, 'declarative'); + assert.equal(adapter.runtime, 'augment'); + assert.equal(typeof adapter.install, 'function'); + assert.equal(typeof adapter.uninstall, 'function'); +}); + +test('a real Augment install emits a gsd command/skill surface (invocable)', () => { + const { configDir, root } = runMinimalInstall({ runtime: 'augment', scope: 'global' }); + try { + const files = walk(configDir); + assert.ok(files.length > 0, 'install must emit artifacts'); + const gsdSurface = files.filter((f) => /gsd/i.test(path.relative(configDir, f))); + assert.ok(gsdSurface.length > 0, + 'install must emit a gsd command/skill surface (declarative reference)'); + } finally { + cleanup(root); + } +}); + +// --------------------------------------------------------------------------- +// #2097 EoS/augment — fail-closed negotiation + folded dispatch sub-axes +// (mirrors the antigravity/kimi reference tests). +// --------------------------------------------------------------------------- + +test('negotiateHostCapabilities never throws for augment, even fully corrupted', () => { + assert.doesNotThrow(() => negotiateHostCapabilities({})); + assert.doesNotThrow(() => negotiateHostCapabilities({ ...AUGMENT_AXES, embeddingMode: UNDOCUMENTED })); + assert.doesNotThrow(() => negotiateHostCapabilities({ ...AUGMENT_AXES, embeddingMode: 'future-unknown' })); + assert.doesNotThrow(() => negotiateHostCapabilities({ ...AUGMENT_AXES, dispatch: 'corrupted-not-an-object' })); + assert.doesNotThrow(() => negotiateHostCapabilities({ ...AUGMENT_AXES, dispatch: { ...AUGMENT_AXES.dispatch, maxDepth: 'not-a-number' } })); +}); + +// AC-style proof: the 3 still-`undocumented` dispatch sub-axes (nested/ +// maxDepth/backgroundDispatch) must degrade to the most-restrictive KNOWN +// value, never their optimistic value — mirrors antigravity's equivalent +// test, but Augment documents namedDispatch/background (unlike antigravity), +// so only 3 sub-axes are undocumented here, not 4. Real values confirmed via: +// node -e "const {negotiateHostCapabilities}=require('./gsd-core/bin/lib/host-integration.cjs'); +// const cap=require('./capabilities/augment/capability.json'); +// console.log(negotiateHostCapabilities(cap.runtime.hostIntegration).effective.dispatch)" +// -> { namedDispatch:true, nested:false, maxDepth:0, background:true, subagentToolkit:'full', backgroundDispatch:false } +test("augment's 3 still-undocumented dispatch sub-axes (nested/maxDepth/backgroundDispatch) degrade to the most-restrictive known value, not their optimistic value", () => { + // Sanity: the descriptor itself still declares these 3 as the undocumented + // sentinel, while namedDispatch/background/subagentToolkit are documented. + assert.equal(AUGMENT_AXES.dispatch.nested, 'undocumented'); + assert.equal(AUGMENT_AXES.dispatch.maxDepth, 'undocumented'); + assert.equal(AUGMENT_AXES.dispatch.backgroundDispatch, 'undocumented'); + assert.equal(AUGMENT_AXES.dispatch.namedDispatch, true, 'sanity: namedDispatch is documented, not part of the undocumented set'); + assert.equal(AUGMENT_AXES.dispatch.background, true, 'sanity: background is documented, not part of the undocumented set'); + assert.equal(AUGMENT_AXES.dispatch.subagentToolkit, 'full', 'sanity: subagentToolkit is documented, not part of the undocumented set'); + + const { effective, warnings } = negotiateHostCapabilities(AUGMENT_AXES); + + 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'); + + // namedDispatch/background/subagentToolkit are documented — they are + // trusted and survive negotiation unchanged, in contrast to the 3 + // undocumented sub-axes above. Augment's negotiation must NOT flatten + // dispatch the way a fully-undocumented descriptor (e.g. antigravity's + // namedDispatch) would. + assert.equal(effective.dispatch.namedDispatch, true, "documented 'true' namedDispatch is trusted, unlike the undocumented sub-axes"); + assert.equal(effective.dispatch.background, true, "documented 'true' background is trusted — not capped to false, since namedDispatch did not degrade closed"); + assert.equal(effective.dispatch.subagentToolkit, 'full', "documented 'full' subagentToolkit is trusted, unlike the undocumented sub-axes"); + + for (const axis of ['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)', + ); +}); + +// --------------------------------------------------------------------------- +// #2097 AC2-equivalent — the hardcoded conversion-dispatch branches folded by +// this migration are retired from the folded modules. +// +// Unlike antigravity (#2096), where `isAntigravity` was eliminated from +// bin/install.js entirely, Augment's `isAugment` flag legitimately remains +// (destructured from runtimeFlags() and used for non-conversion verification +// logic — e.g. counting installed commands/ files). So this guard does NOT +// assert zero `isAugment` occurrences (that would be a false failure); it +// asserts no `isAugment` occurrence gates a call to an Augment *converter* +// function (the exact shape of the dead branch this migration deleted: +// `else if (isAugment) { content = convertClaudeAgentToAugmentAgent(content); }`). +// The switch `case 'augment':` label in _applyRuntimeRewrites is intentionally +// NOT flagged — it does plain dirName-derived path-prefix rewriting (same as +// the still-`case`-labeled trae/codebuddy/cursor/windsurf branches), not +// conversion-function dispatch, and antigravity's own guard tolerates its +// `case 'antigravity':` label for the identical reason (its regex only +// matches `runtime === 'x'`, never a `case` label). +// --------------------------------------------------------------------------- + +test('no `runtime === "augment"` string-equality branch remains in the descriptor-migrated modules', () => { + 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'), + ]; + for (const file of files) { + const src = fs.readFileSync(file, 'utf8'); + const stripped = strip(src); + const eqOffenders = stripped.match(/runtime\s*[!=]==\s*'augment'/g) || []; + assert.deepEqual(eqOffenders, [], + `no hardcoded runtime==='augment' branch may remain in ${path.relative(repoRoot, file)}; found: ${eqOffenders.join(', ')}`); + } +}); + +test('no `isAugment` occurrence gates a call to an Augment converter function (the deleted dead-code shape)', () => { + const converterNames = [ + 'convertClaudeAgentToAugmentAgent', + 'convertClaudeToAugmentMarkdown', + 'convertClaudeCommandToAugmentSkill', + 'convertSlashCommandsToAugmentSkillMentions', + ]; + const converterCallPattern = new RegExp(`(${converterNames.join('|')})\\s*\\(`); + + const file = path.join(__dirname, '..', 'bin', 'install.js'); + const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/); + const offenders = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + // Only condition-position occurrences count (`if (isAugment)` / `else if + // (isAugment)`), not the runtimeFlags() destructure or unrelated reads. + if (!/(?:if|else if)\s*\(\s*isAugment\s*\)/.test(line)) continue; + const window = lines.slice(i, i + 4).join('\n'); + if (converterCallPattern.test(window)) { + offenders.push(`line ${i + 1}: ${line.trim()}`); + } + } + assert.deepEqual(offenders, [], + `no isAugment-gated call to an Augment converter may remain in bin/install.js; found: ${offenders.join(' | ')}`); +}); + +test('legitimate isAugment destructure/enumeration sites survive (not eliminated, unlike isAntigravity)', () => { + const file = path.join(__dirname, '..', 'bin', 'install.js'); + const src = fs.readFileSync(file, 'utf8'); + assert.ok(/isAugment/.test(src), 'isAugment must still be destructured from runtimeFlags() for non-conversion uses'); + assert.ok(/_DESCRIPTOR_AGENTS_RUNTIMES\s*=\s*new Set\(\[[^\]]*'augment'/.test(src), + 'augment must remain in _DESCRIPTOR_AGENTS_RUNTIMES (descriptor-driven agent layout)'); +}); From 9e1fad1503764f3c55ff358160d72992042f5938 Mon Sep 17 00:00:00 2001 From: Tom Boucher Date: Sat, 11 Jul 2026 09:14:57 -0400 Subject: [PATCH 3/3] feat(#2098): drive CodeBuddy through the EoS descriptor + wire subagent hooks (ADR-1239) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fold CodeBuddy's residual runtime-literal branches onto descriptor-driven hostBehaviors (the issue's "zero branches remain" premise was inaccurate — 2 lived): - Folded the `if (isCodebuddy)` commands/ report duplicate (byte-identical to the generic reportCommandsDir block above it) onto hostBehaviors.reportCommandsDir:true, matching cursor's #2089 precedent. - Deleted the dead `else if (isCodebuddy)` agent-conversion arm (codebuddy ∈ _DESCRIPTOR_AGENTS_RUNTIMES → gated out before the legacy chain, same dead-arm pattern removed for augment/trae in #2097). - Removed isCodebuddy from all 4 destructure sites (now comments only, mirroring the #2096 isAntigravity fold). Zero live isCodebuddy reads remain. UPGRADE 1 (extended hook bus): populate extendedHookEvents with the full extended set SubagentStop/Stop/PreCompact/SubagentStart (qwen #2092 / kimi precedent — codebuddy previously had extendedHookEvents:[] so it got NONE of these). The generic applySettingsJsonHooks loop wires them, so CodeBuddy's settings.json now gains all four subagent-lifecycle + stop/compact hooks it previously lacked, matching Qwen/Kimi coverage. No source change (the HOOK_EVENT_SURFACES SDK catalog is a locked dict; all 4 events are already in the validator enum; hookEvents already 'claude'). settings.json is golden- excluded → no golden change. UPGRADE 2 (background dispatch): surfaced via the negotiated capability contract only. CodeBuddy's dispatch.background:true legitimately exceeds the declarative- cli baseline (false) and survives negotiation with no warning. NO agent-file frontmatter field is emitted: the CodeBuddy CLI (GSD's install target, ~/.codebuddy/agents/) has NO background-dispatch frontmatter field — background is a caller-side run_in_background invocation param (verified against codebuddy.ai/docs/cli/sub-agents); the issue's agentMode/enabledAutoRun are IDE-only (codebuddy.cn, a different product). Emitting them would be a non- functional false-green, so it is deliberately not done. Golden: byte-identical for all 16 runtimes (folds are console/failures-report only; UPGRADE 1 → golden-excluded settings.json; UPGRADE 2 → no artifact change). Tests: declarative-reference-codebuddy (adapter/axes/fail-closed negotiation + AC2 source-grep guard) + codebuddy-upgrades (live install asserts all 4 extended hooks wired; dispatch.background survives negotiation above baseline). Matrix + install-on-your-runtime updated; changeset (Changed). capability-registry regenerated. Co-Authored-By: Claude Opus 4.8 --- .changeset/2098-eos-codebuddy.md | 6 + bin/install.js | 33 ++-- capabilities/codebuddy/capability.json | 10 +- docs/how-to/install-on-your-runtime.md | 16 ++ .../host-integration-capability-matrix.md | 2 + gsd-core/bin/lib/capability-registry.cjs | 20 ++- tests/codebuddy-upgrades.test.cjs | 128 +++++++++++++++ .../declarative-reference-codebuddy.test.cjs | 155 ++++++++++++++++++ 8 files changed, 345 insertions(+), 25 deletions(-) create mode 100644 .changeset/2098-eos-codebuddy.md create mode 100644 tests/codebuddy-upgrades.test.cjs create mode 100644 tests/declarative-reference-codebuddy.test.cjs diff --git a/.changeset/2098-eos-codebuddy.md b/.changeset/2098-eos-codebuddy.md new file mode 100644 index 000000000..66cf3cb78 --- /dev/null +++ b/.changeset/2098-eos-codebuddy.md @@ -0,0 +1,6 @@ +--- +type: Changed +pr: 2169 +--- + +**CodeBuddy now wires GSD's full extended lifecycle hook set and is driven by its capability descriptor** — installing GSD into CodeBuddy now registers `SubagentStart`, `SubagentStop`, `Stop`, and `PreCompact` hooks in its `settings.json` (it previously had none of these), matching the coverage Qwen/Kimi already ship, and CodeBuddy's install is fully descriptor-driven instead of via residual hardcoded runtime branches. (#2098) diff --git a/bin/install.js b/bin/install.js index 027c6c8c6..649bddb22 100755 --- a/bin/install.js +++ b/bin/install.js @@ -6850,7 +6850,8 @@ function uninstall(isGlobal, runtime = DEFAULT_RUNTIME) { // destructure). #2095: isKimi likewise dropped — kimi is now a hooks/ // consumer, so its former `&& !isKimi` uninstall guards were removed. // #2096: isAntigravity dropped — unused in this function. - const { isOpencode, isCodex, isCopilot, isCursor, isWindsurf, isAugment, isQwen, isHermes, isCodebuddy, isCline } = runtimeFlags(runtime); + // #2098: isCodebuddy dropped — unused in this function. + const { isOpencode, isCodex, isCopilot, isCursor, isWindsurf, isAugment, isQwen, isHermes, isCline } = runtimeFlags(runtime); const dirName = getDirName(runtime); // Get the target directory based on runtime and install type. Cline local @@ -8221,7 +8222,8 @@ function writeManifest(configDir, runtime = DEFAULT_RUNTIME, options = {}) { // #2095: isKimi dropped — kimi is now a hooks/ consumer like every other // settings-json-adjacent runtime, so the `&& !isKimi` term below was removed. // #2096: isAntigravity dropped — unused in this function. - const { isOpencode, isCodex, isCopilot, isCursor, isWindsurf, isAugment, isQwen, isHermes, isCodebuddy, isCline } = runtimeFlags(runtime); + // #2098: isCodebuddy dropped — unused in this function. + const { isOpencode, isCodex, isCopilot, isCursor, isWindsurf, isAugment, isQwen, isHermes, 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. @@ -8732,7 +8734,11 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) { // _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); + // #2098: isCodebuddy dropped — codebuddy is also in + // _DESCRIPTOR_AGENTS_RUNTIMES below, so its legacy converter-dispatch branch + // (the `isCodebuddy` arm calling convertClaudeAgentToCodebuddyAgent) was + // unreachable dead code and was removed rather than re-gated. + const { isOpencode, isZcode, isCodex, isCopilot, isCursor, isWindsurf, isAugment, isTrae, isQwen, isHermes, isCline } = runtimeFlags(runtime); const plan = resolveInstallPlan(runtime); const dirName = getDirName(runtime); const src = path.join(__dirname, '..'); @@ -9351,22 +9357,6 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) { failures.push('commands/gsd-*'); } } - - // CodeBuddy only: also report the commands/ output (#789 — slash commands) - if (isCodebuddy) { - const commandsDir = path.join(targetDir, 'commands'); - if (fs.existsSync(commandsDir)) { - const cmdCount = fs.readdirSync(commandsDir) - .filter(f => f.startsWith('gsd-') && f.endsWith('.md')).length; - if (cmdCount > 0) { - console.log(` ${green}✓${reset} Installed ${cmdCount} slash commands to commands/`); - } else { - failures.push('commands/gsd-*'); - } - } else { - failures.push('commands/gsd-*'); - } - } } } else if (_hostBehaviors(runtime).localCommandsViaRules) { // Cline local install: rules-based only — commands are embedded in .clinerules (generated below). @@ -9671,8 +9661,6 @@ function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) { content = convertClaudeAgentToCopilotAgent(content, isGlobal); } else if (isWindsurf) { content = convertClaudeAgentToWindsurfAgent(content); - } else if (isCodebuddy) { - content = convertClaudeAgentToCodebuddyAgent(content); } else if (_hostBehaviors(runtime).frontmatterDialect === 'cline') { // Descriptor-driven (ADR-1239 / #2090): folded from `isCline` into // hostBehaviors.frontmatterDialect === 'cline'. @@ -10880,7 +10868,8 @@ function finishInstall(settingsPath, settings, statuslineCommand, shouldInstallS // #2095: isKimi dropped — the Kimi "Done!" banner below reads // _hostBehaviors(runtime).doneBannerStyle === 'kimi-agent-file' (descriptor-driven), not this flag. // #2096: isAntigravity dropped — unused in this function. - const { isOpencode, isCodex, isCopilot, isCursor, isWindsurf, isAugment, isQwen, isHermes, isCodebuddy, isCline } = runtimeFlags(runtime); + // #2098: isCodebuddy dropped — unused in this function. + const { isOpencode, isCodex, isCopilot, isCursor, isWindsurf, isAugment, isQwen, isHermes, isCline } = runtimeFlags(runtime); const plan = resolveInstallPlan(runtime); if (shouldInstallStatusline && plan.writesSharedSettings && !_hostBehaviors(runtime).skipSettingsUi) { diff --git a/capabilities/codebuddy/capability.json b/capabilities/codebuddy/capability.json index 15d0212a3..c8abf8601 100644 --- a/capabilities/codebuddy/capability.json +++ b/capabilities/codebuddy/capability.json @@ -81,7 +81,12 @@ "installSurface": "settings-json", "writesSharedSettings": true, "permissionWriter": null, - "extendedHookEvents": [], + "extendedHookEvents": [ + "SubagentStop", + "Stop", + "PreCompact", + "SubagentStart" + ], "hostIntegration": { "embeddingMode": "declarative", "commandSurface": "slash-file", @@ -98,6 +103,9 @@ "stateIO": "filesystem", "transport": "mcp", "runtime": "node" + }, + "hostBehaviors": { + "reportCommandsDir": true } } } diff --git a/docs/how-to/install-on-your-runtime.md b/docs/how-to/install-on-your-runtime.md index 70fc779f6..5db6c9f9a 100644 --- a/docs/how-to/install-on-your-runtime.md +++ b/docs/how-to/install-on-your-runtime.md @@ -353,6 +353,22 @@ npx @opengsd/gsd-core@latest --codebuddy --global GSD installs four surfaces. Slash command definitions land in `~/.codebuddy/commands/gsd-*.md` and appear as `/gsd-help`, `/gsd-phase`, `/gsd-ship`, etc. in the `/` menu. Subagents land in `~/.codebuddy/agents/gsd-*.md`. Skills land in `~/.codebuddy/skills/gsd-*/SKILL.md` — emitted with `user-invocable: false` so they stay out of the `/` menu (the commands surface is the sole `/` entry point) and remain available for model invocation. CodeBuddy hooks are written to `settings.json`. No `mcp.json` is written: GSD ships no MCP server. +**Hook coverage** + +GSD registers the following events automatically on install (Claude hook event dialect): + +| Event | Hook | Purpose | +|---|---|---| +| `SessionStart` | `gsd-check-update.js`, `gsd-session-state.sh` | Update check, session orientation | +| `PreToolUse` | `gsd-prompt-guard.js`, `gsd-read-guard.js`, `gsd-workflow-guard.js`, `gsd-worktree-path-guard.js`, `gsd-validate-commit.sh` | Prompt guard, read-before-edit, workflow + worktree safety, commit validation | +| `PostToolUse` | `gsd-context-monitor.js`, `gsd-read-injection-scanner.js`, `gsd-phase-boundary.sh`, `gsd-graphify-update.sh` | Context monitoring, read-time scan, phase boundary detection | +| `SubagentStop` | `gsd-context-monitor.js` | Context headroom tracking after subagent completion | +| `SubagentStart` | `gsd-context-monitor.js` | Context headroom tracking at subagent start | +| `Stop` | `gsd-context-monitor.js` | Context headroom tracking before model stop | +| `PreCompact` | `gsd-context-monitor.js` | Context awareness before conversation compaction | + +CodeBuddy's own [background sub-agent dispatch](https://www.codebuddy.ai/docs/cli/sub-agents) (`run_in_background: true`) is a caller-side invocation parameter, not something GSD's installed agent files control — there is no frontmatter field to set on GSD's agent artifacts to request it. + --- ### Qwen Code diff --git a/docs/reference/host-integration-capability-matrix.md b/docs/reference/host-integration-capability-matrix.md index 1898c9215..375c7e00f 100644 --- a/docs/reference/host-integration-capability-matrix.md +++ b/docs/reference/host-integration-capability-matrix.md @@ -427,6 +427,8 @@ Sources consulted: - https://www.codebuddy.ai/docs/cli/settings - /websites/codebuddy_cn (Context7) +**EoS migration status (#2098):** Migrated onto the declarative adapter (dogfooded in `tests/declarative-reference-codebuddy.test.cjs`). The two remaining `isCodebuddy` branches in `bin/install.js` — a duplicate `commands/` slash-command output report, and a dead legacy agent-converter dispatch arm (unreachable since codebuddy is in `_DESCRIPTOR_AGENTS_RUNTIMES`) — were folded onto the already-generic `runtime.hostBehaviors.reportCommandsDir` (shared with Cursor) and removed outright; `isCodebuddy` no longer appears as a live read anywhere in `bin/install.js`, `src/runtime-artifact-conversion.cts`, `src/shell-command-projection.cts`, or `src/runtime-name-policy.cts`. Two upgrades land: (1) **extended hook events** — codebuddy's `extendedHookEvents` was previously `[]` (none wired); this PR wires all four — `SubagentStop`/`Stop`/`PreCompact`/`SubagentStart` — into `extendedHookEvents` (mirrors qwen/kimi), so an install now registers all four as hooks in `settings.json` alongside the pre-existing base session/tool events (`SessionStart`/`PreToolUse`/`PostToolUse`); cite https://www.codebuddy.ai/docs/cli/hooks. (2) **`dispatch.background`** — the descriptor already declared `true`, exceeding the `declarative-cli` profile baseline of `false`; the negotiation contract (`negotiateHostCapabilities`) now surfaces that value with no downgrade warning, documenting the legitimate deviation. Note: the CodeBuddy CLI has no background-dispatch frontmatter field on sub-agents (`agentMode`/`enabledAutoRun` are IDE-only per https://www.codebuddy.ai/docs/cli/sub-agents) — background dispatch remains a caller-side invocation parameter (`run_in_background: true`), not a field GSD's agent artifacts emit. + --- ## copilot diff --git a/gsd-core/bin/lib/capability-registry.cjs b/gsd-core/bin/lib/capability-registry.cjs index e5c62b7a7..439e4e193 100644 --- a/gsd-core/bin/lib/capability-registry.cjs +++ b/gsd-core/bin/lib/capability-registry.cjs @@ -788,7 +788,12 @@ const capabilities = { "installSurface": "settings-json", "writesSharedSettings": true, "permissionWriter": null, - "extendedHookEvents": [], + "extendedHookEvents": [ + "SubagentStop", + "Stop", + "PreCompact", + "SubagentStart" + ], "hostIntegration": { "embeddingMode": "declarative", "commandSurface": "slash-file", @@ -805,6 +810,9 @@ const capabilities = { "stateIO": "filesystem", "transport": "mcp", "runtime": "node" + }, + "hostBehaviors": { + "reportCommandsDir": true } } }, @@ -4237,7 +4245,12 @@ const runtimes = { "installSurface": "settings-json", "writesSharedSettings": true, "permissionWriter": null, - "extendedHookEvents": [], + "extendedHookEvents": [ + "SubagentStop", + "Stop", + "PreCompact", + "SubagentStart" + ], "hostIntegration": { "embeddingMode": "declarative", "commandSurface": "slash-file", @@ -4254,6 +4267,9 @@ const runtimes = { "stateIO": "filesystem", "transport": "mcp", "runtime": "node" + }, + "hostBehaviors": { + "reportCommandsDir": true } } }, diff --git a/tests/codebuddy-upgrades.test.cjs b/tests/codebuddy-upgrades.test.cjs new file mode 100644 index 000000000..a727258a1 --- /dev/null +++ b/tests/codebuddy-upgrades.test.cjs @@ -0,0 +1,128 @@ +'use strict'; + +/** + * CodeBuddy capability UPGRADES — ADR-1239 / #2098 (EoS/codebuddy). + * + * Drives the user-reachable surface (spawned `bin/install.js` via + * `runMinimalInstall`) plus a direct negotiation-contract check to prove the + * two real upgrades CodeBuddy contributes as part of the EoS migration: + * + * UPGRADE 1 — extended hook events: CodeBuddy's `extendedHookEvents` was + * previously `[]` (none of the 4 extended events were wired). This PR + * wires all four — `SubagentStop`/`Stop`/`PreCompact`/`SubagentStart` — + * into `extendedHookEvents` (mirrors qwen #2092 / kimi exactly — same 4 + * events), so a live install registers all four as hooks in settings.json + * routed through gsd-context-monitor.js, giving CodeBuddy the + * subagent-lifecycle + stop/compact hooks it previously lacked. + * + * UPGRADE 2 — dispatch.background: CodeBuddy's capability.json already + * declares `dispatch.background: true`, which legitimately EXCEEDS the + * `declarative-cli` profile baseline (`false`, per + * `PROFILE_BASELINES['declarative-cli']` in src/host-integration.cts). + * NO agent-file/frontmatter change is involved — the CodeBuddy CLI has no + * background-dispatch frontmatter field (agentMode/enabledAutoRun are + * IDE-only; verified via codebuddy.ai/docs/cli/sub-agents). This is + * surfaced purely through the negotiated contract: a documented `true` + * value must survive negotiation without a downgrade warning. + */ + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const { runMinimalInstall } = require('./helpers/install-shared.cjs'); +const { cleanup } = require('./helpers.cjs'); +const { + profileOf, + negotiateHostCapabilities, + PROFILE_BASELINES, +} = require('../gsd-core/bin/lib/host-integration.cjs'); + +const CODEBUDDY_CAP = JSON.parse( + fs.readFileSync(path.join(__dirname, '..', 'capabilities', 'codebuddy', 'capability.json'), 'utf8'), +); +const CODEBUDDY_AXES = CODEBUDDY_CAP.runtime.hostIntegration; + +// --------------------------------------------------------------------------- +// UPGRADE 1: extended hook events — all 4 newly-wired events' live-install coverage +// --------------------------------------------------------------------------- + +test('capabilities/codebuddy/capability.json extendedHookEvents contains exactly the 4 documented events', () => { + const events = CODEBUDDY_CAP.runtime.extendedHookEvents; + assert.deepEqual(events, ['SubagentStop', 'Stop', 'PreCompact', 'SubagentStart']); + assert.equal(events.length, 4); +}); + +test('codebuddy --global: settings.json wires all 4 newly-added extended hook events to the GSD context-monitor hook (UPGRADE 1)', (t) => { + const { configDir, root } = runMinimalInstall({ runtime: 'codebuddy', scope: 'global' }); + 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')); + + // All 4 events were newly wired by this PR — codebuddy's extendedHookEvents + // was previously [], so none of these existed before #2098. + const NEWLY_WIRED_EXTENDED_EVENTS = ['SubagentStop', 'Stop', 'PreCompact', 'SubagentStart']; + + const entries = NEWLY_WIRED_EXTENDED_EVENTS.map((eventName) => { + const eventHooks = settings.hooks && settings.hooks[eventName]; + assert.ok(Array.isArray(eventHooks) && eventHooks.length > 0, + `settings.hooks.${eventName} must exist and be non-empty`); + const entry = eventHooks[0].hooks[0]; + assert.ok(entry.command.includes('gsd-context-monitor'), + `${eventName} command must reference gsd-context-monitor.js, got: ${entry.command}`); + assert.equal(entry.timeout, 10, `${eventName} entry must have timeout 10`); + return entry; + }); + + const [stopEntry, ...restEntries] = entries; + for (const entry of restEntries) { + assert.equal(entry.command, stopEntry.command, + 'all 4 newly-wired extended events must wire the same gsd-context-monitor command'); + } +}); + +test('a runtime whose extendedHookEvents omits SubagentStart does NOT get one (descriptor-gated, not a global default)', (t) => { + const { configDir, root } = runMinimalInstall({ runtime: 'claude', scope: 'global' }); + t.after(() => cleanup(root)); + + const settingsPath = path.join(configDir, 'settings.json'); + const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); + + assert.ok( + settings.hooks && Array.isArray(settings.hooks.SubagentStop) && settings.hooks.SubagentStop.length > 0, + 'claude must have SubagentStop wired (sanity — proves hooks ARE configured)', + ); + assert.ok( + !settings.hooks || settings.hooks.SubagentStart === undefined, + "claude must NOT have SubagentStart wired — it is not in claude's extendedHookEvents", + ); +}); + +// --------------------------------------------------------------------------- +// UPGRADE 2: dispatch.background negotiation — documented true survives, +// exceeding the declarative-cli profile baseline. No agent-file/frontmatter +// change; caller-side invocation param only (no code path emits it). +// --------------------------------------------------------------------------- + +test("codebuddy classifies as the 'declarative-cli' profile, whose baseline dispatch.background is false", () => { + assert.equal(profileOf(CODEBUDDY_AXES), 'declarative-cli'); + assert.equal(PROFILE_BASELINES['declarative-cli'].dispatch.background, false, + 'sanity: the declarative-cli baseline is false — codebuddy legitimately exceeds it'); +}); + +test('negotiateHostCapabilities surfaces codebuddy\'s documented dispatch.background:true with no downgrade warning (UPGRADE 2)', () => { + assert.equal(CODEBUDDY_AXES.dispatch.background, true, + 'sanity: the descriptor declares dispatch.background: true (documented, not undocumented)'); + + const { effective, warnings } = negotiateHostCapabilities(CODEBUDDY_AXES); + + assert.equal(effective.dispatch.background, true, + 'a documented true value must survive negotiation, exceeding the declarative-cli baseline of false'); + assert.ok( + !warnings.some((w) => w.includes('dispatch.background')), + `no warning may be raised for the documented dispatch.background axis, got: ${JSON.stringify(warnings)}`, + ); +}); diff --git a/tests/declarative-reference-codebuddy.test.cjs b/tests/declarative-reference-codebuddy.test.cjs new file mode 100644 index 000000000..b27a59c38 --- /dev/null +++ b/tests/declarative-reference-codebuddy.test.cjs @@ -0,0 +1,155 @@ +// allow-test-rule: structural-regression-guard — AC2: assert no `runtime === 'codebuddy'` string-equality branch, no `isCodebuddy` conversion helper, no `canonical === 'codebuddy'` branch remains in bin/install.js, src/runtime-artifact-conversion.cts, src/shell-command-projection.cts, src/runtime-name-policy.cts — a source-text property, so source-grep is the faithful check (#2098) +'use strict'; + +/** + * Declarative reference host — CodeBuddy (#2098 / ADR-1239 EoS). + * + * CodeBuddy already installs through the descriptor-driven artifactLayout + * (commands/skills/agents, each with a named `converter`), and its + * capability.json already declares `hostIntegration` + `dispatch` axes. + * Unlike antigravity/qwen (#2096/#2092), CodeBuddy was NOT migrated off a + * legacy runtime-keyed branch chain wholesale — issue #2098 found it was + * already descriptor-driven except for two residual `isCodebuddy` branches + * in bin/install.js: + * 1. a duplicate `commands/` slash-command output report (byte-identical + * to the generic `hostBehaviors.reportCommandsDir` block already used + * by Cursor) — folded onto `hostBehaviors.reportCommandsDir` and deleted. + * 2. a dead legacy agent-converter dispatch arm in the inline agent-copy + * loop, unreachable because codebuddy is a member of + * `_DESCRIPTOR_AGENTS_RUNTIMES` (installRuntimeArtifacts already wrote + * the agents before that loop runs) — deleted outright. + * + * This test is the reference-host dogfood mirroring + * tests/declarative-reference-antigravity.test.cjs: it (1) classifies + * CodeBuddy's profile via profileOf, (2) confirms the public declarative + * adapter classifies it as declarative, (3) round-trips a real install + * proving a gsd command surface is emitted, (4) proves negotiation fails + * CLOSED on a corrupted descriptor, (5) proves the validator accepts the + * descriptor, and (6) source-greps the folded modules for the retired + * `isCodebuddy` branches (AC2). + * + * UPGRADE 1 (extended hook events) + UPGRADE 2 (dispatch.background + * negotiation) live-install coverage is in tests/codebuddy-upgrades.test.cjs + * — not duplicated here. + */ + +const { test, before } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync } = require('node:child_process'); + +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', 'codebuddy', 'capability.json'); +const CODEBUDDY_CAP = JSON.parse(fs.readFileSync(DESC, 'utf8')); +const CODEBUDDY_AXES = CODEBUDDY_CAP.runtime.hostIntegration; + +// hooks/dist is gitignored and built (mirrors golden-install-parity harness). +before(() => { + execFileSync(process.execPath, [BUILD_SCRIPT], { encoding: 'utf-8', stdio: 'pipe' }); +}); + +test('CodeBuddy classifies as the declarative-cli reference profile (profileOf)', () => { + const desc = JSON.parse(fs.readFileSync(DESC, 'utf8')); + const axes = desc.runtime.hostIntegration; + assert.ok(axes && axes.embeddingMode, 'codebuddy descriptor declares hostIntegration axes'); + assert.equal(profileOf(axes), 'declarative-cli', + 'CodeBuddy is a Declarative-CLI host'); +}); + +test('the public declarative adapter classifies CodeBuddy as a declarative host', () => { + const adapter = createDeclarativeAdapter({ runtime: 'codebuddy' }); + assert.equal(adapter.kind, 'declarative'); + assert.equal(adapter.runtime, 'codebuddy'); + assert.equal(typeof adapter.install, 'function'); + assert.equal(typeof adapter.uninstall, 'function'); +}); + +test('a real CodeBuddy install emits a gsd command/skill surface (invocable)', () => { + const { configDir, root } = runMinimalInstall({ runtime: 'codebuddy', scope: 'global' }); + try { + const files = walk(configDir); + assert.ok(files.length > 0, 'install must emit artifacts'); + // CodeBuddy uses a flat commands/gsd-*.md slash-command surface + // (CONTEXT.md installer module; capabilities/codebuddy/capability.json + // artifactLayout `kind: "commands"`). + const gsdSurface = files.filter((f) => /gsd/i.test(path.relative(configDir, f))); + assert.ok(gsdSurface.length > 0, + 'install must emit a gsd command/skill surface (declarative reference)'); + const commandsDir = path.join(configDir, 'commands'); + assert.ok(fs.existsSync(commandsDir), 'commands/ directory must exist'); + const cmdFiles = fs.readdirSync(commandsDir) + .filter((f) => f.startsWith('gsd-') && f.endsWith('.md')); + assert.ok(cmdFiles.length > 0, 'commands/ must contain gsd-*.md slash commands'); + } finally { + cleanup(root); + } +}); + +// --------------------------------------------------------------------------- +// #2098 EoS/codebuddy — fail-closed negotiation + validator acceptance + +// the folded descriptor (mirrors antigravity/qwen reference tests). +// --------------------------------------------------------------------------- + +test('negotiateHostCapabilities never throws for codebuddy, even fully corrupted', () => { + assert.doesNotThrow(() => negotiateHostCapabilities({})); + assert.doesNotThrow(() => negotiateHostCapabilities({ ...CODEBUDDY_AXES, embeddingMode: UNDOCUMENTED })); + assert.doesNotThrow(() => negotiateHostCapabilities({ ...CODEBUDDY_AXES, embeddingMode: 'future-unknown' })); + assert.doesNotThrow(() => negotiateHostCapabilities({ ...CODEBUDDY_AXES, dispatch: 'corrupted-not-an-object' })); + assert.doesNotThrow(() => negotiateHostCapabilities({ ...CODEBUDDY_AXES, dispatch: { ...CODEBUDDY_AXES.dispatch, maxDepth: 'not-a-number' } })); +}); + +test('a partial/empty codebuddy 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); +}); + +test('capabilities/codebuddy/capability.json validates — no errors', () => { + const errors = validateCapability(CODEBUDDY_CAP, 'codebuddy'); + assert.deepEqual(errors, [], `validateCapability must return no errors, got: ${JSON.stringify(errors)}`); +}); + +// -- AC2: the hardcoded branches are retired across all folded modules ------- + +test('no `runtime === "codebuddy"` string-equality branch (nor `isCodebuddy` conversion helper / `canonical === "codebuddy"`) 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*'codebuddy'/g) || []; + assert.deepEqual(eqOffenders, [], + `AC2: no hardcoded runtime==='codebuddy' branch may remain in ${path.relative(repoRoot, file)}; found: ${eqOffenders.join(', ')}`); + + const isCodebuddyHits = stripped.match(/\bisCodebuddy\b/g) || []; + assert.deepEqual(isCodebuddyHits, [], + `AC2: no live isCodebuddy read may remain in ${path.relative(repoRoot, file)}; found ${isCodebuddyHits.length} occurrence(s)`); + + const canonicalOffenders = stripped.match(/canonical\s*===\s*'codebuddy'/g) || []; + assert.deepEqual(canonicalOffenders, [], + `AC2: no canonical==='codebuddy' branch may remain in ${path.relative(repoRoot, file)}; found: ${canonicalOffenders.join(', ')}`); + } +});