Skip to content
Back to search

gsd-core

Marketplace for GSD Core — meta-prompting, context engineering, and spec-driven development system for AI coding agents.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 16 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/open-gsd/gsd-core with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/open-gsd/gsd-core'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/open-gsd--gsd-core/badge.svg)](/listings/open-gsd--gsd-core)

HTML

<a href="/listings/open-gsd--gsd-core"><img src="/api/listings/open-gsd--gsd-core/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npx @opengsd/gsd-core@latest

The installer prompts for your runtime (Claude Code, OpenCode, Antigravity CLI, Kimi CLI, Kilo, Codex, Copilot, Cursor, Windsurf, and more) and whether to install globally or locally. The installer is required for cross-runtime compatibility — do not copy files from `agents/` or `commands/` directly.

On another runtime or without Node.js? See [Install on your runtime](docs/how-to/install-on-your-runtime.md).

Once installed, start a new project or onboard an existing repo:

/gsd-new-project   # greenfield project
/gsd-onboard       # existing codebase

New here? Follow [Your first project](docs/tutorials/your-first-project.md) for a guided walkthrough from install to first shipped phase, or [Onboarding an existing codebase](docs/tutorials/onboarding-an-existing-codebase.md) for brownfield setup.

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 24 lines
  1. {
  2. "name": "gsd-core",
  3. "description": "Marketplace for GSD Core — meta-prompting, context engineering, and spec-driven development system for AI coding agents.",
  4. "owner": {
  5. "name": "open-gsd",
  6. "url": "https://github.com/open-gsd"
  7. },
  8. "plugins": [
  9. {
  10. "name": "gsd-core",
  11. "description": "GSD Core is a meta-prompting, context engineering, and spec-driven development system for AI coding agents.",
  12. "version": "1.21.0",
  13. "source": {
  14. "source": "github",
  15. "repo": "open-gsd/gsd-core",
  16. "ref": "plugin"
  17. },
  18. "author": {
  19. "name": "open-gsd",
  20. "url": "https://github.com/open-gsd"
  21. }
  22. }
  23. ]
  24. }
README.md · README · 128 lines
  1. <div align="center">
  2. # GSD Core
  3. **Git. Ship. Done.**
  4. **English** · [Português](README.pt-BR.md) · [简体中文](README.zh-CN.md) · [日本語](README.ja-JP.md) · [한국어](README.ko-KR.md)
  5. **A light-weight meta-prompting, context engineering, and spec-driven development system for Claude Code, OpenCode, Antigravity CLI, Kimi CLI, Kilo, Codex, Copilot, Cursor, Windsurf, and more.**
  6. [![npm version](https://img.shields.io/npm/v/%40opengsd%2Fgsd-core?style=for-the-badge&logo=npm&logoColor=white&color=CB3837)](https://www.npmjs.com/package/@opengsd/gsd-core)
  7. [![npm downloads](https://img.shields.io/npm/dm/%40opengsd%2Fgsd-core?style=for-the-badge&logo=npm&logoColor=white&color=CB3837)](https://www.npmjs.com/package/@opengsd/gsd-core)
  8. [![Tests](https://img.shields.io/github/actions/workflow/status/open-gsd/gsd-core/test.yml?branch=main&style=for-the-badge&logo=github&label=Tests)](https://github.com/open-gsd/gsd-core/actions/workflows/test.yml)
  9. [![Discord](https://img.shields.io/badge/Discord-Join-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/mYgfVNfA2r)
  10. [![GitHub stars](https://img.shields.io/github/stars/open-gsd/gsd-core?style=for-the-badge&logo=github&color=181717)](https://github.com/open-gsd/gsd-core)
  11. [![License](https://img.shields.io/badge/license-MIT-blue?style=for-the-badge)](LICENSE)
  12. </div>
  13. ---
  14. ## What is GSD Core
  15. GSD Core is a context-engineering and spec-driven development framework that drives AI coding agents (Claude Code, Codex, Antigravity CLI, Kimi CLI, Copilot, Cursor, and more) through a disciplined phase loop. It solves [context rot](docs/explanation/context-engineering.md) — the quality degradation that accumulates as an AI fills its context window — by running all heavy research, planning, and execution work in fresh-context subagents while keeping your main session lean.
  16. ---
  17. ## How it works
  18. Each milestone repeats the same five-step loop, one phase at a time:
  19. 1. **Discuss** — capture implementation decisions before anything is planned
  20. 2. **Plan** — research, decompose, and verify the plan fits a fresh context window
  21. 3. **Execute** — run plans in parallel waves; each executor starts with a clean 200k-token context
  22. 4. **Verify** — walk through what was built; diagnose and fix before declaring done
  23. 5. **Ship** — create the PR, archive the phase, repeat for the next one
  24. ---
  25. ## Quickstart
  26. ```bash
  27. npx @opengsd/gsd-core@latest
  28. ```
  29. The installer prompts for your runtime (Claude Code, OpenCode, Antigravity CLI, Kimi CLI, Kilo, Codex, Copilot, Cursor, Windsurf, and more) and whether to install globally or locally. The installer is required for cross-runtime compatibility — do not copy files from `agents/` or `commands/` directly.
  30. On another runtime or without Node.js? See [Install on your runtime](docs/how-to/install-on-your-runtime.md).
  31. Once installed, start a new project or onboard an existing repo:
  32. ```bash
  33. /gsd-new-project # greenfield project
  34. /gsd-onboard # existing codebase
  35. ```
  36. New here? Follow [Your first project](docs/tutorials/your-first-project.md) for a guided walkthrough from install to first shipped phase, or [Onboarding an existing codebase](docs/tutorials/onboarding-an-existing-codebase.md) for brownfield setup.
  37. ---
  38. ## Documentation
  39. **What's new in 1.7.0** → [docs/whats-new-1.7.0.md](docs/whats-new-1.7.0.md)
  40. **Tutorials** — learning by doing:
  41. - [Your first project](docs/tutorials/your-first-project.md)
  42. - [Onboarding an existing codebase](docs/tutorials/onboarding-an-existing-codebase.md)
  43. **How-to guides** — task-focused recipes:
  44. - [Install on your runtime](docs/how-to/install-on-your-runtime.md)
  45. - [Plan a phase](docs/how-to/plan-a-phase.md)
  46. - [Verify and ship](docs/how-to/verify-and-ship.md)
  47. - … [see all how-to guides](docs/README.md#how-to-guides)
  48. **Reference** — authoritative facts:
  49. - [Commands](docs/COMMANDS.md)
  50. - [Configuration](docs/CONFIGURATION.md)
  51. - [CLI tools](docs/CLI-TOOLS.md)
  52. **Explanation** — concepts and design decisions:
  53. - [Context engineering](docs/explanation/context-engineering.md)
  54. - [The phase loop](docs/explanation/the-phase-loop.md)
  55. - [Architecture](docs/ARCHITECTURE.md)
  56. Full index: [docs/README.md](docs/README.md). Other languages: [日本語](README.ja-JP.md) · [한국어](README.ko-KR.md) · [Português](README.pt-BR.md) · [简体中文](README.zh-CN.md).
  57. ---
  58. ## Why it works
  59. Most AI-coding setups fail at scale because context bloat silently degrades output quality, there is no shared memory between sessions, and nothing verifies that code actually works. GSD Core solves all three: heavy work runs in fresh subagents, structured artifacts like `STATE.md` and `CONTEXT.md` survive session boundaries, and the verify step walks through what was built and generates fix plans before a phase is declared done. See [docs/explanation/context-engineering.md](docs/explanation/context-engineering.md) for the full reasoning.
  60. Troubleshooting? See [docs/how-to/recover-and-troubleshoot.md](docs/how-to/recover-and-troubleshoot.md).
  61. ---
  62. ## Community
  63. | Project | Platform |
  64. |---------|----------|
  65. | [gsd-opencode](https://github.com/rokicool/gsd-opencode) | Original OpenCode port |
  66. | [Discord](https://discord.gg/mYgfVNfA2r) | Community support |
  67. ---
  68. ## Star History
  69. <a href="https://star-history.com/#open-gsd/gsd-core&Date">
  70. <picture>
  71. <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-gsd/gsd-core&type=Date&theme=dark" />
  72. <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-gsd/gsd-core&type=Date" />
  73. <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=open-gsd/gsd-core&type=Date" />
  74. </picture>
  75. </a>
  76. ---
  77. ## License
  78. MIT License. See [LICENSE](LICENSE) for details.
  79. ---
  80. <div align="center">
  81. **Claude Code is powerful. GSD Core makes it reliable.**
  82. </div>
bin/install.js · Bundled script · 11,135 lines · 1 finding marked
  1. #!/usr/bin/env node
  2. const fs = require('fs');
  3. const path = require('path');
  4. const os = require('os');
  5. const readline = require('readline');
  6. const crypto = require('crypto');
  7. const {
  8. isManagedHookBasename,
  9. isManagedHookCommand,
  10. projectLocalHookPrefix,
  11. projectLegacySettingsHookCommand,
  12. projectManagedHookCommand,
  13. projectPathActionProjection,
  14. projectPortableHookBaseDir,
  15. projectPersistentPathExportActions,
  16. PATH_ACTION_REASON,
  17. projectShellCommandText,
  18. projectCodexHookTomlCommand,
  19. shellHookOmitsBashRunner,
  20. buildLocalShellHookCommand,
  21. } = require('../gsd-core/bin/lib/shell-command-projection.cjs');
  22. // Bidirectional GSD slash-command namespace transformer (#3583).
  23. // Required at module scope so the command list can be computed once per install
  24. // and passed down to convertClaudeCommandToClaudeSkill, avoiding repeated
  25. // fs.readdirSync + RegExp work for every skill.
  26. const {
  27. transformContentToHyphen,
  28. readGsdCommandNames,
  29. } = require('../gsd-core/bin/lib/command-roster.cjs');
  30. const {
  31. resolveAntigravityGlobalDir,
  32. getGlobalConfigDir,
  33. getGlobalSkillsBase,
  34. resolveKimiHooksTomlDir,
  35. isRegisteredRuntimeId,
  36. resolveGsdHome,
  37. } = require('../gsd-core/bin/lib/runtime-homes.cjs');
  38. // #2870: the Install Scope Module — turns a bare 'global' | 'local' scope id
  39. // plus a runtime into one resolved value (configHome, settingsFile,
  40. // consentRequired, hostPrecedenceRank) instead of the id being re-derived
  41. // and re-interpreted at each call site. See src/install-scope.cts.
  42. const { resolveScope } = require('../gsd-core/bin/lib/install-scope.cjs');
  43. const { isTestHomeGuardRefusal } = require('../gsd-core/bin/lib/real-home-guard.cjs');
  44. // getDirName (runtime -> local config dir name) is relocated out of this
  45. // installer to the runtime-name-policy leaf (ADR-1508 / #1510 Phase 1) so the
  46. // conversion module's rewrite engine can consume it without importing
  47. // bin/install.js. Imported here for install.js's own internal call sites
  48. // (getConfigDirFromHome and the runtime-content-rewrite loops below) — #2876
  49. // retired the re-export; tests now import getDirName directly from
  50. // gsd-core/bin/lib/runtime-name-policy.cjs.
  51. const { getDirName, getRuntimeLabel, getGlobalConfigHomeFragment, runtimeFlags, hostBehaviorsFor } = require('../gsd-core/bin/lib/runtime-name-policy.cjs');
  52. const {
  53. applyWorktreeBaseRef,
  54. readBaseRefFromSettings,
  55. } = require('../gsd-core/bin/lib/worktree-base-ref.cjs');
  56. const { resolveInstallPlan } = require('../gsd-core/bin/lib/runtime-config-adapter-registry.cjs');
  57. const { createImperativeAdapter } = require('../gsd-core/bin/lib/adapter-imperative.cjs');
  58. // #2930 (epic #1671 Phase 3): strips `<!-- gsd:section -->` markers from
  59. // workflow .md content at emit time, before any per-runtime rewrite runs.
  60. const { composeWorkflow } = require('../gsd-core/bin/lib/workflow-fragments.cjs');
  61. // #3072: THE shared composition-scope predicate (also consumed by the served
  62. // MCP catalog, src/mcp-catalog.cts) — see the comment at its call site below.
  63. const { shouldCompose } = require('../gsd-core/bin/lib/mcp-catalog.cjs');
  64. // #5637: per-install terminator for the typed-text capture heredoc.
  65. const { armArgsNonce, disarmArgsNonce, stampInstalledContent } =require('../gsd-core/bin/lib/args-terminator.cjs');
  66. const runtimeArtifactConversion = require('../gsd-core/bin/lib/runtime-artifact-conversion.cjs');
  67. const { escapeRegex: escapeRegExp } = require('../gsd-core/bin/lib/pattern.cjs');
  68. // #2873: cross-scope shadow detection — reports (never fails) when a
  69. // GSD-owned scope shadows another on this machine (design doc:
  70. // .gsd/phase/feat-2873-cross-scope-shadowing/40-design.md).
  71. const { buildShadowReport, renderShadowReport } = require('../gsd-core/bin/lib/install-shadow-report.cjs');
  72. // #2544: the CommonJS marker's single source of truth. classifyMarker() backs
  73. // BOTH ensureCommonJsMarker() (install) and removeCommonJsMarker() (uninstall),
  74. // so the write side can no longer clobber a package.json the remove side would
  75. // correctly refuse to delete.
  76. const { ensureCommonJsMarker, removeCommonJsMarker } = require('../gsd-core/bin/lib/commonjs-marker.cjs');
  77. // Canonical set of hook files shipped to users. Imported here so writeManifest()
  78. // records exactly the same set that build-hooks.js copies to hooks/dist/, making
  79. // the manifest and the installed hooks/ dir structurally identical. Avoids the
  80. // prefix/extension-regex approach that missed managed-hooks-registry.cjs (#941).
  81. const { HOOKS_TO_COPY: _HOOKS_TO_COPY } = require('../scripts/build-hooks.js');
  82. const INSTALLED_HOOK_FILES = new Set(_HOOKS_TO_COPY);
  83. // ADR-857 phase 5f-1: hook-surface writer functions extracted to a dedicated
  84. // module. install.js used to re-export the whole hooksSurface surface so
  85. // existing callers (require('../bin/install.js').writeCursorHooksJson etc.)
  86. // kept working — #2876 found zero production/test consumers of any of those
  87. // re-exports (tests import runtime-hooks-surface.cjs directly) and retired
  88. // them from module.exports. install.js still requires hooksSurface below for
  89. // its own internal call sites (writeCursorHooksJson, writeClineArtifacts,
  90. // resolveNodeRunner, applySettingsJsonHooks, etc.).
  91. const hooksSurface = require('../gsd-core/bin/lib/runtime-hooks-surface.cjs');
  92. /**
  93. * #3677 predicate — true when an agent body needs `/gsd:<cmd>` → `/gsd-<cmd>`
  94. * normalization at install time. Descriptor-driven
  95. * (capabilities/<runtime>/capability.json -> runtime.hostBehaviors.hyphenNameAgentBody)
  96. * instead of a hardcoded runtime allow-list (ADR-1239 / #2086). Sibling fixes
  97. * #3583 / #3629 covered SKILL.md bodies, #3584 / #3606 covered runtime
  98. * emissions — this is the agent-body surface (#3677).
  99. *
  100. * Unknown / future runtimes that don't declare the flag default to "no
  101. * rewrite" (better to leak than to mangle a runtime whose namespace
  102. * behavior we haven't verified).
  103. */
  104. function shouldNormalizeHyphenNamespaceInAgentBody(runtime) {
  105. if (typeof runtime !== 'string' || runtime === '') return false;
  106. return hostBehaviorsFor(runtime).hyphenNameAgentBody === true;
  107. }
  108. /**
  109. * #3677 helper — applies the hyphen-namespace transform iff the predicate
  110. * says so. Pure function; safe to call unconditionally from the install
  111. * loop. Returns the input unchanged for runtimes that self-convert or
  112. * intentionally keep colon refs.
  113. */
  114. function normalizeAgentBodyForRuntime(content, runtime, cmdNames) {
  115. if (!shouldNormalizeHyphenNamespaceInAgentBody(runtime)) return content;
  116. return transformContentToHyphen(content, cmdNames);
  117. }
  118. // Colors
  119. const cyan = '\x1b[36m';
  120. const green = '\x1b[32m';
  121. const yellow = '\x1b[33m';
  122. const red = '\x1b[31m';
  123. const bold = '\x1b[1m';
  124. const dim = '\x1b[2m';
  125. const reset = '\x1b[0m';
  126. // Codex config.toml constants
  127. const GSD_CODEX_MARKER = '# GSD Agent Configuration \u2014 managed by gsd-core installer';
  128. const GSD_CODEX_HOOKS_OWNERSHIP_PREFIX = '# GSD codex_hooks ownership: ';
  129. // Known scalar fields of Codex's `AgentsToml` struct (codex-rs/config/src/
  130. // config_toml.rs \u2014 `[agents]` table). Codex marks the struct
  131. // `#[schemars(deny_unknown_fields)]`, so a bare `[agents]` table is valid ONLY
  132. // when every direct key is one of these (named agent roles live in the flattened
  133. // `[agents.<name>]` sub-tables, a separate `AgentRoleToml`). GSD writes only
  134. // `max_depth` (ADR-1239 upgrade 2 / #2088); the full set is enumerated so the
  135. // schema check accepts a user's other legitimate AgentsToml scalars too.
  136. const CODEX_AGENTS_TOML_SCALAR_KEYS = new Set([
  137. 'max_threads',
  138. 'max_depth',
  139. 'job_max_runtime_seconds',
  140. 'interrupt_message',
  141. ]);
  142. // GSD's managed dispatch-depth value. Codex's implicit default is also 1 (root
  143. // sessions start at depth 0); writing it EXPLICITLY pins the negotiated
  144. // `dispatch.maxDepth: 1` axis instead of relying on codex-cli's implicit default
  145. // (ADR-1239 upgrade 2 / #2088). Per the negotiated capability, GSD-hosted Codex
  146. // dispatch is single-level (maxDepth === 1 \u2192 `degradationFor` flattens waves).
  147. const GSD_CODEX_AGENTS_MAX_DEPTH = 1;
  148. // Codex hooks.json lifecycle events GSD registers beyond SessionStart (which has
  149. // its own dedicated path). This is Codex's OWN hook-event vocabulary (per
  150. // developers.openai.com/codex/config-reference), distinct from the cross-runtime
  151. // settings.json `extendedHookEvents` descriptor field (a claude/gemini-family
  152. // allowlist consumed only by hooksSurface==='settings-json' runtimes — Codex is
  153. // codex-hooks-json). All route through gsd-context-monitor.js. #772 wired the
  154. // first three; #2088 adds the remaining six documented events so GSD's monitor
  155. // fires at the same lifecycle points as in Claude Code. Install and uninstall
  156. // share this list so the registered set and the removed set never diverge.
  157. const CODEX_EXTENDED_HOOK_EVENTS = [
  158. 'SubagentStart',
  159. 'Stop',
  160. 'PostToolUse',
  161. 'PreToolUse',
  162. 'PermissionRequest',
  163. 'PreCompact',
  164. 'PostCompact',
  165. 'SubagentStop',
  166. 'UserPromptSubmit',
  167. ];
  168. // Codex's hook-enabling feature flag (issue #3566). Codex itself marks
  169. // `codex_hooks` as a `legacy_key` in codex-rs/features/src/legacy.rs; the
  170. // canonical current key under [features] is `hooks`. The installer always
  171. // emits the canonical key going forward, recognizes legacy aliases as
  172. // equivalent during reinstall, and migrates them forward on rewrite. The
  173. // audit-marker string above is intentionally unchanged so existing
  174. // installs' ownership lines continue to round-trip.
  175. const CODEX_HOOKS_FEATURE_KEY = 'hooks';
  176. const CODEX_HOOKS_FEATURE_LEGACY_KEYS = ['codex_hooks'];
  177. const CODEX_HOOKS_FEATURE_ALL_KEYS = [CODEX_HOOKS_FEATURE_KEY, ...CODEX_HOOKS_FEATURE_LEGACY_KEYS];
  178. function isCodexHooksFeatureKey(key) {
  179. return CODEX_HOOKS_FEATURE_ALL_KEYS.includes(key);
  180. }
  181. // #768 \u2014 Claude Code permissions.allow entries.
  182. // Pre-populated during Claude installs to eliminate first-run approval friction
  183. // for gsd-core's own known-safe tool calls. (The defense-in-depth deny entries
  184. // for credential files that #768 also wrote are retired \u2014 see
  185. // GSD_CLAUDE_LEGACY_DENY_PERMISSIONS below.)
  186. //
  187. // Format: each string uses Claude Code's documented permission rule syntax \u2014
  188. // "Tool(pattern)" e.g. "Read(.planning/*)", "Edit(STATE.md)"
  189. // "Tool" (bare tool name, no pattern)
  190. //
  191. // Merge policy: additive, non-destructive \u2014 existing user entries are preserved;
  192. // GSD entries are appended only when not already present (idempotent).
  193. // The reference/default runtime (ADR-1239 reference host). Single-sourced here
  194. // instead of scattered literal 'claude' defaults/rosters (#2086).
  195. const DEFAULT_RUNTIME = 'claude';
  196. const GSD_CLAUDE_ALLOW_PERMISSIONS = Object.freeze([
  197. 'Read(.planning/*)',
  198. 'Edit(.planning/*)',
  199. 'Read(STATE.md)',
  200. 'Edit(STATE.md)',
  201. ]);
  202. // #4221 \u2014 Retired deny rules. #768 wrote these three `Read()` deny rules
  203. // into settings.json; Claude Code 2.1.259 hardened the Bash-side enforcement
  204. // of Read() deny rules so that ANY such rule makes every
  205. // `cd DIR && grep/cat relative-path` compound prompt for approval, even in
  206. // `auto` permission mode \u2014 and GSD subagents emit hundreds of those per
  207. // session. The same protection now ships as the managed PreToolUse hook
  208. // hooks/gsd-secret-read-guard.js (a hook denial is not a permission rule and
  209. // never arms that check). Unlike the #2278 allow-side migration, there is no
  210. // surviving "current" deny list: the constant is RENAMED to its legacy role
  211. // and only ever filtered, never added. Byte-equal strings only \u2014 a user's
  212. // own hand-written identical rule is indistinguishable and is removed too
  213. // (the install manifest never recorded permission strings, so a
  214. // manifest-gated cleanup is not possible).
  215. const GSD_CLAUDE_LEGACY_DENY_PERMISSIONS = Object.freeze([
  216. 'Read(.env)',
  217. 'Read(.env.*)',
  218. 'Read(.secrets)',
  219. ]);
  220. // #2278 — Stale allow-rule forms from before the fix. Claude Code has no
  221. // standalone `Write` permission gate: file-editing tools (Write/Edit/
  222. // NotebookEdit) are gated collectively via `Edit(pattern)`. The original
  223. // `Write(.planning/*)` / `Write(STATE.md)` entries were therefore silently
  224. // unmatched (never granted anything) and Claude Code additionally surfaces a
  225. // session-start warning about unmatched permission rules. This list lets
  226. // mergeClaudePermissions and uninstall cleanup retire those stale entries on
  227. // existing installs while the current GSD_CLAUDE_ALLOW_PERMISSIONS above
  228. // carries the working `Edit(...)` forms.
  229. // #5054 — `Bash(npx gsd-core *)` is retired the same way. The project ships
  230. // as `@opengsd/gsd-core`; the unscoped `gsd-core` npm name belongs to someone
  231. // else, so the rule pre-authorized whatever that name's owner publishes next.
  232. // GSD never runs the bare form (update.md uses `--package=@opengsd/gsd-core`).
  233. const GSD_CLAUDE_LEGACY_ALLOW_PERMISSIONS = Object.freeze([
  234. 'Write(.planning/*)',
  235. 'Write(STATE.md)',
  236. 'Bash(npx gsd-core *)',
  237. ]);
  238. /**
  239. * Merge GSD-owned permission entries into a Claude Code settings object.
  240. *
  241. * Additive and idempotent: existing allow/deny entries are preserved; GSD
  242. * entries are appended only if not already present. No other permission sub-keys
  243. * (ask, disableBypassPermissionsMode, etc.) are touched.
  244. *
  245. * Migration (#2278): before adding the current GSD_CLAUDE_ALLOW_PERMISSIONS,
  246. * any stale GSD_CLAUDE_LEGACY_ALLOW_PERMISSIONS entry (e.g. the unmatched
  247. * `Write(...)` forms from before the fix) is removed from permissions.allow,
  248. * so existing installs end up with the working `Edit(...)` forms instead of
  249. * both the dead legacy entry and its replacement sitting side by side.
  250. * The same filter retires the unscoped `Bash(npx gsd-core *)` rule (#5054).
  251. *
  252. * Migration (#4221): the retired GSD_CLAUDE_LEGACY_DENY_PERMISSIONS entries
  253. * are removed from permissions.deny (byte-equal only). Nothing is added to
  254. * deny any more: an absent `deny` key is left absent (never created as an
  255. * empty array), and a `deny` array emptied BY THIS FILTER is deleted so the
  256. * retirement leaves no `"deny": []` residue; a user's pre-existing empty
  257. * `deny: []` is untouched.
  258. *
  259. * Defensive: if settings is not a plain object, returns immediately without
  260. * throwing. If permissions.allow / permissions.deny exist but are not arrays
  261. * (malformed settings), they are replaced with valid arrays.
  262. *
  263. * @param {object} settings - The parsed settings.json object to mutate in-place.
  264. */
  265. function mergeClaudePermissions(settings) {
  266. if (settings === null || typeof settings !== 'object' || Array.isArray(settings)) return;
  267. if (!settings.permissions || typeof settings.permissions !== 'object' || Array.isArray(settings.permissions)) {
  268. settings.permissions = {};
  269. }
  270. if (!Array.isArray(settings.permissions.allow)) {
  271. settings.permissions.allow = [];
  272. }
  273. if (settings.permissions.deny !== undefined && !Array.isArray(settings.permissions.deny)) {
  274. settings.permissions.deny = [];
  275. }
  276. settings.permissions.allow = settings.permissions.allow.filter(
  277. (e) => !GSD_CLAUDE_LEGACY_ALLOW_PERMISSIONS.includes(e)
  278. );
  279. for (const entry of GSD_CLAUDE_ALLOW_PERMISSIONS) {
  280. if (!settings.permissions.allow.includes(entry)) {
  281. settings.permissions.allow.push(entry);
  282. }
  283. }
  284. if (Array.isArray(settings.permissions.deny)) {
  285. const before = settings.permissions.deny.length;
  286. settings.permissions.deny = settings.permissions.deny.filter(
  287. (e) => !GSD_CLAUDE_LEGACY_DENY_PERMISSIONS.includes(e)
  288. );
  289. if (settings.permissions.deny.length === 0 && before > 0) {
  290. delete settings.permissions.deny;
  291. }
  292. }
  293. }
  294. // Copilot instructions marker constants
  295. const GSD_COPILOT_INSTRUCTIONS_MARKER = '<!-- GSD Configuration \u2014 managed by gsd-core installer -->';
  296. const GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER = '<!-- /GSD Configuration -->';
  297. // #786 \u2014 GitHub Copilot CLI lifecycle hook constants.
  298. // Copilot reads hook configs from <config>/hooks/*.json (repo scope: .github/hooks/,
  299. // user scope: ~/.copilot/hooks/) with the shape { version, hooks: { <event>: [...] } }.
  300. // Events use camelCase (sessionStart, preToolUse, postToolUse, ...). A `command`
  301. // hook runs an INLINE shell command (bash / powershell), so the GSD hook is fully
  302. // self-contained \u2014 there is no separate hook script to install, and therefore
  303. // nothing that can dangle if a script copy is skipped. See
  304. // https://docs.github.com/en/copilot/reference/hooks-configuration
  305. const GSD_COPILOT_HOOK_FILE = 'gsd-session.json';
  306. // Copilot parses a command hook's stdout as the hook-output JSON. For sessionStart
  307. // the schema is `{ additionalContext?: string }` (the text is prepended to the
  308. // session as context). So the hook must emit that JSON envelope — not bare text.
  309. // The two messages contain no JSON-special characters, so they embed verbatim.
  310. const GSD_COPILOT_SESSION_MSG_PRESENT =
  311. 'GSD: .planning/STATE.md present - review the current phase and any blockers before acting.';
  312. const GSD_COPILOT_SESSION_MSG_ABSENT =
  313. 'GSD: no .planning/ workflow found - run /gsd-new-project to start a tracked workflow.';
  314. const GSD_COPILOT_SESSION_HOOK_BASH =
  315. 'if [ -f .planning/STATE.md ]; then ' +
  316. `printf '%s' '{"additionalContext":"${GSD_COPILOT_SESSION_MSG_PRESENT}"}'; else ` +
  317. `printf '%s' '{"additionalContext":"${GSD_COPILOT_SESSION_MSG_ABSENT}"}'; fi`;
  318. const GSD_COPILOT_SESSION_HOOK_PWSH =
  319. 'if (Test-Path .planning/STATE.md) ' +
  320. `{ '{"additionalContext":"${GSD_COPILOT_SESSION_MSG_PRESENT}"}' } ` +
  321. `else { '{"additionalContext":"${GSD_COPILOT_SESSION_MSG_ABSENT}"}' }`;
  322. // #777 — Cursor CLI lifecycle hook constants.
  323. // Cursor reads hook configs from <project-root>/.cursor/hooks.json (local) or
  324. // ~/.cursor/hooks.json (global) with the shape { version: 1, hooks: { <event>: [...] } }.
  325. // Events use camelCase: sessionStart, postToolUse, preToolUse, etc.
  326. // A `command` hook entry runs an external script. GSD registers six managed hooks
  327. // (AC4a upgrade, #2089 — ADR-1239):
  328. // sessionStart → gsd-cursor-session-start.js (context injection)
  329. // postToolUse → gsd-cursor-post-tool.js (STATE.md update monitor)
  330. // preToolUse → gsd-cursor-pre-tool.js (write-path guard)
  331. // stop → gsd-cursor-stop.js (verify-work reminder)
  332. // subagentStart → gsd-cursor-subagent-start.js (subagent context injection)
  333. // subagentStop → gsd-cursor-subagent-stop.js (subagent completion reminder)
  334. // Cursor docs: https://cursor.com/docs/hooks
  335. //
  336. // These script-name/marker constants used to be independently re-declared
  337. // here with their own string literals — a second, unlinked copy of exactly
  338. // the values runtime-hooks-surface.cts also defines for its own internal use
  339. // (buildCursorHookEntry, writeCursorHooksJson, etc.). #2876's code review
  340. // found tests reading the constant from install.js's copy while calling
  341. // functions built from hooksSurface's copy, with nothing guarding the two
  342. // staying equal — the same unlinked-duplicate-value hazard the ADR-1508
  343. // dedup elsewhere in this file exists to prevent. Fixed at the root: these
  344. // are now bare references to hooksSurface's own exports, so there is exactly
  345. // one literal definition of each value, full stop.
  346. const GSD_CURSOR_SESSION_HOOK_SCRIPT = hooksSurface.GSD_CURSOR_SESSION_HOOK_SCRIPT;
  347. const GSD_CURSOR_POST_TOOL_HOOK_SCRIPT = hooksSurface.GSD_CURSOR_POST_TOOL_HOOK_SCRIPT;
  348. const GSD_CURSOR_PRE_TOOL_HOOK_SCRIPT = hooksSurface.GSD_CURSOR_PRE_TOOL_HOOK_SCRIPT;
  349. const GSD_CURSOR_STOP_HOOK_SCRIPT = hooksSurface.GSD_CURSOR_STOP_HOOK_SCRIPT;
  350. const GSD_CURSOR_SUBAGENT_START_HOOK_SCRIPT = hooksSurface.GSD_CURSOR_SUBAGENT_START_HOOK_SCRIPT;
  351. const GSD_CURSOR_SUBAGENT_STOP_HOOK_SCRIPT = hooksSurface.GSD_CURSOR_SUBAGENT_STOP_HOOK_SCRIPT;
  352. // All GSD-managed Cursor hook scripts (used by uninstall cleanup). Not
  353. // independently defined in hooksSurface — built here from the bare
  354. // references above, so it can never drift from them either.
  355. const GSD_CURSOR_HOOK_SCRIPTS = [
  356. GSD_CURSOR_SESSION_HOOK_SCRIPT,
  357. GSD_CURSOR_POST_TOOL_HOOK_SCRIPT,
  358. GSD_CURSOR_PRE_TOOL_HOOK_SCRIPT,
  359. GSD_CURSOR_STOP_HOOK_SCRIPT,
  360. GSD_CURSOR_SUBAGENT_START_HOOK_SCRIPT,
  361. GSD_CURSOR_SUBAGENT_STOP_HOOK_SCRIPT,
  362. ];
  363. // Marker comment embedded in managed hook entries so GSD can find+remove them.
  364. const GSD_CURSOR_HOOK_MARKER = hooksSurface.GSD_CURSOR_HOOK_MARKER;
  365. // #2100 Stage 2 — Windsurf/Cascade lifecycle hook constants.
  366. // Windsurf/Cascade reads hook configs from <project-root>/.windsurf/hooks.json
  367. // (local) or ~/.codeium/windsurf/hooks.json (global) with the shape
  368. // { hooks: { <event>: [ { command, ... } ] } } — note: no top-level `version`
  369. // field, and each entry carries a bare `command` shell string (no `type`
  370. // field), unlike Cursor's hooks.json. GSD registers two managed BLOCKING
  371. // hooks (exit code 2 to block, vs. Cursor's stdout-JSON form):
  372. // pre_write_code → gsd-windsurf-pre-write.js (write-path guard)
  373. // pre_run_command → gsd-windsurf-pre-command.js (destructive-command guard)
  374. // Cascade has no context-injection channel, so the 4 advisory hooks GSD
  375. // registers on Cursor (sessionStart, postToolUse, stop, subagentStart/Stop)
  376. // have no Windsurf counterpart and are deliberately NOT ported.
  377. // Cascade hooks docs (reference): https://docs.windsurf.com/llms-full.txt ,
  378. // https://docs.devin.ai/desktop/cascade/hooks
  379. //
  380. // Same #2876 fix as the Cursor block above: bare references to hooksSurface's
  381. // own exports instead of a second, unlinked literal copy.
  382. const GSD_WINDSURF_PRE_WRITE_HOOK_SCRIPT = hooksSurface.GSD_WINDSURF_PRE_WRITE_HOOK_SCRIPT;
  383. const GSD_WINDSURF_PRE_COMMAND_HOOK_SCRIPT = hooksSurface.GSD_WINDSURF_PRE_COMMAND_HOOK_SCRIPT;
  384. // All GSD-managed Windsurf hook scripts (used by uninstall cleanup).
  385. // hooksSurface independently defines the same array — bare reference here so
  386. // the two can never drift.
  387. const GSD_WINDSURF_HOOK_SCRIPTS = hooksSurface.GSD_WINDSURF_HOOK_SCRIPTS;
  388. // GSD-managed files under hooks/lib/ (helpers required by gsd-*.js hooks).
  389. // git-cmd.js does not start with "gsd-" (shared classifier for #3129), gsd-graphify-rebuild.sh does.
  390. // cursor-workspace.js (#2587) is required by the Cursor lifecycle hooks. Those
  391. // are staged individually by writeCursorHooksJson (Cursor sets
  392. // hostBehaviors.skipSharedHooksInstall, so it never reaches the bulk hooks/lib
  393. // copy below) — that function stages this helper alongside them. Listing it
  394. // here keeps uninstall and the manifest managing it for every OTHER runtime
  395. // that does receive hooks/lib.
  396. // injection-patterns.js (#3504) is required by gsd-prompt-guard.js and
  397. // gsd-read-injection-scanner.js — the shared prompt-injection pattern list the
  398. // two guards require so their copies cannot drift.
  399. const GSD_HOOK_LIB_FILES = ['git-cmd.js', 'gsd-graphify-rebuild.sh', 'cursor-workspace.js', 'injection-patterns.js'];
  400. /**
  401. * Every file GSD stages under `hooks/lib/` (#5335). The install copies `hooks/dist/lib/` wholesale (and the
  402. * allow-listed names from `hooks/lib/`), so a fixed list drifts the moment a helper is added: the new file is
  403. * staged but never removed, which also keeps `hooks/lib/` non-empty and blocks its rmdir. The set is the
  404. * allow-list plus the top-level files of the directories the installer copies from, so uninstall and the
  405. * manifest cannot disagree with install. Only these names are ever removed; a user's own helper beside them
  406. * is left alone.
  407. */
  408. function gsdHookLibFiles() {
  409. const names = new Set(GSD_HOOK_LIB_FILES);
  410. for (const parts of [['hooks', 'dist', 'lib'], ['hooks', 'lib']]) {
  411. try {
  412. for (const entry of fs.readdirSync(path.join(__dirname, '..', ...parts), { withFileTypes: true })) {
  413. if (entry.isFile()) names.add(entry.name);
  414. }
  415. } catch { /* the directory is absent from this package layout */ }
  416. }
  417. return [...names];
  418. }
  419. /**
  420. * Directory name GSD stages its shared hook bundle under, inside a runtime's
  421. * install root. Defaults to 'hooks' — the name every runtime used before #3023.
  422. *
  423. * pi (pi.dev) reserves `hooks/` as its own now-deprecated extension location and
  424. * prints a migration warning on every startup when one exists, so pi overrides
  425. * this via hostBehaviors.sharedHooksDirName. Following pi's advised remediation
  426. * (move it into extensions/) would break the adapter's path resolution AND expose
  427. * GSD's .js helpers to pi's extension auto-discovery, so the bundle is renamed in
  428. * place instead — same depth, so every `__dirname/..`-relative resolution inside
  429. * the bundle (e.g. hooks/gsd-context-monitor.js reaching ../gsd-core/bin/) keeps
  430. * working.
  431. */
  432. const SHARED_HOOKS_DIR_DEFAULT = 'hooks';
  433. // #3184 — GSD-managed file enumerations for scripts/changeset/ and scripts/lib/
  434. // uninstall. The install-side copy of both directories is wholesale ("copy every
  435. // file present"), so these enumerations MUST be kept in parity with the real
  436. // directory contents or an added file ships on install and then orphans on
  437. // uninstall (survives removal, keeps the dir non-empty, blocks its rmdir).
  438. // Hoisted to module scope (and exported below) so tests/install.test.cjs can
  439. // assert parity against fs.readdirSync(scripts/lib) / fs.readdirSync(scripts/changeset)
  440. // without source-grepping this file.
  441. const GSD_CHANGESET_FILES = [
  442. 'cli.cjs', 'parse.cjs', 'render.cjs', 'serialize.cjs',
  443. 'github-release-notes.cjs', 'lint.cjs', 'new.cjs',
  444. 'README.md', // documentation only — not user-authored
  445. ];
  446. const GSD_SCRIPTS_LIB_FILES = ['cli-exit.cjs', 'allowlist-ratchet.cjs', 'drift-scan.cjs', 'alias-drift-families.cjs', 'exit-code-registry.cjs', 'ndjson-reporter.cjs', 'ci-job-timing.cjs', 'shellcheck-fetch.cjs', 'npm-version-check-diagnosis.cjs', 'platform-conformance-tier.generated.cjs', 'suite-detection.cjs', 'macos-conformance-tier.generated.cjs', 'vendor-bundle.cjs', 'registration-ledger-preload.cjs'];
  447. // #4544 — the Codex hook payload the install stages into <targetDir>/hooks/.
  448. // Hoisted to module scope (the #3184 precedent above) so the rollback's
  449. // incomplete-capture path can name exactly the files GSD owns without a
  450. // second copy of the list drifting away from the staging site, which lives
  451. // inside the Codex config block where the constant used to be declared.
  452. const CODEX_HOOKS_TO_COPY = [
  453. 'gsd-check-update.js',
  454. 'gsd-check-update-worker.js',
  455. 'managed-hooks-registry.cjs',
  456. ];
  457. /**
  458. * Resolve a runtime's shared-hooks directory name from its descriptor.
  459. *
  460. * The value is a single path SEGMENT. This string is joined onto a user's config
  461. * root and then written to and recursively read, so anything that is not a plain,
  462. * non-empty, separator-free, non-dot segment is rejected back to the default —
  463. * a descriptor typo must never let the installer write outside the install root.
  464. *
  465. * The "non-dot" part of that contract is enforced beyond the literal '.' / '..'
  466. * segments: an all-dot (or dot-and-whitespace-only) segment is rejected as a
  467. * meaningless name, a segment with a trailing dot or space is rejected because
  468. * Windows silently strips it at directory-creation time (which would split the
  469. * name the installer creates from the name callers probe for), and a Windows
  470. * reserved device name (CON, PRN, AUX, NUL, COM1-9, LPT1-9, with or without an
  471. * extension) is rejected because it cannot exist as a directory on Windows at
  472. * all. These checks are unconditional on every platform: the descriptor is
  473. * authored once and shipped everywhere, so a value invalid on Windows must be
  474. * rejected identically on Linux/macOS, or the install and its fixtures disagree
  475. * cross-platform.
  476. *
  477. * @param {string} runtime
  478. * @returns {string}
  479. */
  480. function resolveSharedHooksDirName(runtime) {
  481. const raw = hostBehaviorsFor(runtime).sharedHooksDirName;
  482. if (typeof raw !== 'string') return SHARED_HOOKS_DIR_DEFAULT;
  483. const name = raw.trim();
  484. if (name === '') return SHARED_HOOKS_DIR_DEFAULT;
  485. if (name === '.' || name === '..') return SHARED_HOOKS_DIR_DEFAULT;
  486. // All-dot or dot+whitespace segments ('...', '. .') are not meaningful
  487. // directory names and are almost certainly a descriptor typo.
  488. if (name.replace(/[.\s]/g, '') === '') return SHARED_HOOKS_DIR_DEFAULT;
  489. // Windows silently strips a trailing dot or space at creation time, so the
  490. // directory the installer creates would not match the name the adapter
  491. // probes for — a split-brain that only reproduces off-Linux.
  492. if (/[. ]$/.test(name)) return SHARED_HOOKS_DIR_DEFAULT;
  493. // Windows reserved device names cannot exist as directories.
  494. if (/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$/i.test(name)) return SHARED_HOOKS_DIR_DEFAULT;
  495. if (name.includes('/') || name.includes('\\')) return SHARED_HOOKS_DIR_DEFAULT;
  496. // Belt-and-braces: reject anything path.basename() would reduce, and any
  497. // Windows drive/UNC-flavoured value.
  498. if (path.basename(name) !== name) return SHARED_HOOKS_DIR_DEFAULT;
  499. if (path.isAbsolute(name)) return SHARED_HOOKS_DIR_DEFAULT;
  500. if (name.includes('\0')) return SHARED_HOOKS_DIR_DEFAULT;
  501. return name;
  502. }
  503. // #3897 rung 3 — sandbox_mode derivation, the hold list, and the hold-roster
  504. // validator now live in `src/codex-agent-toml.cts` (compiled to
  505. // `gsd-core/bin/lib/codex-agent-toml.cjs`), NOT here. This module used to be
  506. // the sole owner, and `agent-install-check.cts`'s `checkCodexSandboxPosture`
  507. // lazily `require()`d THIS FILE to reach `deriveCodexSandboxMode` — but
  508. // requiring `bin/install.js` runs its whole top-level script, including the
  509. // CLI's ASCII banner print to stdout, which corrupted every stdout-JSON
  510. // caller downstream of that posture check (`gsd-tools validate agents`).
  511. // `codex-agent-toml.cjs` is a genuine leaf (no top-level side effects), so
  512. // both this file and `agent-install-check.cts` import the derivation from
  513. // there — ONE owner, no second predicate. See that module's header for the
  514. // full rationale, and CAUSE B (below, `installCodexConfig`) for the removal
  515. // of `validateCodexSandboxHolds`'s call from the install runtime path.
  516. const {
  517. CODEX_SANDBOX_HOLDS,
  518. deriveCodexSandboxMode,
  519. validateCodexSandboxHolds,
  520. // #3897 list-form parse fix, Fix 3 (generative-fix-divergence): this
  521. // file's own `generateCodexAgentToml` used to pull `tools:` via its
  522. // private `extractFrontmatterField` (single-line only) instead of this
  523. // shared reader — the two sandbox-feeding paths (this emitter and
  524. // `agent-install-check.cts`'s `checkCodexSandboxPosture`) silently
  525. // disagreed on YAML block-list `tools:` form. Both now route through this
  526. // ONE extractor.
  527. extractToolsValue,
  528. } = require(path.join(__dirname, '..', 'gsd-core', 'bin', 'lib', 'codex-agent-toml.cjs'));
  529. // Copilot tool name mapping — Claude Code tools to GitHub Copilot tools
  530. // Tool mapping applies ONLY to agents, NOT to skills (per CONTEXT.md decision)
  531. const claudeToCopilotTools = {
  532. Read: 'read',
  533. Write: 'edit',
  534. Edit: 'edit',
  535. Bash: 'execute',
  536. Grep: 'search',
  537. Glob: 'search',
  538. Task: 'agent',
  539. WebSearch: 'web',
  540. WebFetch: 'web',
  541. TodoWrite: 'todo',
  542. AskUserQuestion: 'ask_user',
  543. SlashCommand: 'skill',
  544. };
  545. // Get version from package.json
  546. const pkg = require('../package.json');
  547. // #2517 — runtime-aware tier resolution shared with core.cjs.
  548. // Hoisted to top with absolute __dirname-based paths so `gsd install codex` works
  549. // when invoked via npm global install (cwd is the user's project, not the gsd repo
  550. // root). Inline `require('../gsd-core/...')` from inside install functions
  551. // works only because Node resolves it relative to the install.js file regardless
  552. // of cwd, but keeping the require at the top makes the dependency explicit and
  553. // surfaces resolution failures at process start instead of at first install call.
  554. const _gsdLibDir = path.join(__dirname, '..', 'gsd-core', 'bin', 'lib');
  555. const {
  556. RUNTIME_PROFILE_MAP: GSD_RUNTIME_PROFILE_MAP,
  557. isAnthropicFlavoredModel: gsdIsAnthropicFlavoredModel,
  558. } = require(path.join(_gsdLibDir, 'model-catalog.cjs'));
  559. // #4145: shared hash-first recovery for gsd-pristine/ baselines stored at an
  560. // unexpected path (e.g. without the gsd-core/ prefix an earlier release's
  561. // writer dropped). Same module the reapply verifier uses, so the two readers
  562. // cannot drift apart again.
  563. const {
  564. findPristineByHash: gsdFindPristineByHash,
  565. } = require(path.join(_gsdLibDir, 'pristine-baseline.cjs'));
  566. // #2875 Part 2: MODEL_PROFILES + resolveTierEntry are now consumed only by
  567. // install-model-override-resolver.cjs's readGsdRuntimeProfileResolver
  568. // (required below) — this installer no longer needs its own bindings.
  569. // #2071 — install-time effort resolution (readGsdEffectiveEffortConfig /
  570. // resolveInstallTimeEffort, plus their _getGsdEffortCatalog + _readGsdConfigFile
  571. // helpers) was extracted into the shipped gsd-core/bin/lib/install-effort-resolver.cjs
  572. // so `gsd-tools effort sync` can require it from the installed runtime instead of this
  573. // package-root bin/install.js, which the installer never copies (#2071 crash). The
  574. // installer imports it back here — single source of truth for both surfaces.
  575. const {
  576. readGsdEffectiveEffortConfig,
  577. resolveInstallTimeEffort,
  578. _getGsdEffortCatalog,
  579. _readGsdConfigFile,
  580. } = require(path.join(_gsdLibDir, 'install-effort-resolver.cjs'));
  581. const {
  582. MINIMAL_SKILL_ALLOWLIST,
  583. PROFILES,
  584. isMinimalMode,
  585. stageSkillsForMode,
  586. readActiveProfile,
  587. writeActiveProfile,
  588. resolveEffectiveProfile,
  589. mostRestrictiveProfile,
  590. resolveProfile,
  591. loadSkillsManifest,
  592. stageSkillsForProfile,
  593. stageAgentsForProfile,
  594. stageSkillsForRuntimeAsSkills,
  595. } = require(path.join(_gsdLibDir, 'install-profiles.cjs'));
  596. // ADR-857 phase 4c: load capability registry (optional; missing → falls back to undefined)
  597. // #5759: bounded config.json reader shared with the runtime (non-blocking open, regular file, 1 MiB cap).
  598. const { readConfigFileBounded } = require(path.join(_gsdLibDir, 'config-file-read.cjs'));
  599. let _capabilityRegistry;
  600. try {
  601. _capabilityRegistry = require(path.join(_gsdLibDir, 'capability-registry.cjs'));
  602. } catch (_) {
  603. _capabilityRegistry = undefined;
  604. }
  605. // #2322 BLOCKER 2: `_capabilityRegistry` above is the FROZEN first-party registry
  606. // (capability-registry.cjs, built at publish time) — it never reflects an
  607. // INSTALLED third-party overlay capability, so a fresh `gsd install` could never
  608. // stage an installed third-party capability's skill regardless of registration,
  609. // even on the DEFAULT `--profile full`. `_installedCapabilityRegistry` composes
  610. // the overlay via capability-loader's `loadRegistry({includeInstalled:true})` —
  611. // the SAME call capability-writer.cts's `capability set --runtime` path already
  612. // uses — so a fresh install and a post-install `capability set` agree on
  613. // third-party skill availability. Used ONLY for skill-profile resolution and
  614. // runtime-artifact-layout staging below; `_capabilityRegistry` (frozen) remains
  615. // the source for gsd-core's OWN runtime/host-behavior descriptors (unaffected —
  616. // those are always first-party). A load failure degrades to the frozen
  617. // `_capabilityRegistry` (no overlay data -> no third-party skills staged; never
  618. // a crash and never a scan-and-guess fallback).
  619. let _installedCapabilityRegistry;
  620. try {
  621. const _capabilityLoader = require(path.join(_gsdLibDir, 'capability-loader.cjs'));
  622. _installedCapabilityRegistry = _capabilityLoader.loadRegistry({
  623. includeInstalled: true,
  624. cwd: process.cwd(),
  625. gsdHome: process.env['GSD_HOME'],
  626. });
  627. } catch (_) {
  628. _installedCapabilityRegistry = _capabilityRegistry;
  629. }
  630. /**
  631. * Read a runtime's documentation-sourced `hostIntegration.dispatch` axes
  632. * (ADR-1239 Phase A — `capabilities/<runtime>/capability.json`
  633. * `runtime.hostIntegration.dispatch`): `{namedDispatch, nested, maxDepth,
  634. * background, backgroundDispatch, subagentToolkit}`. These are validated,
  635. * closed-vocabulary FACTS about what the runtime's real dispatch primitive
  636. * supports (never inferred) — see `docs/reference/host-integration-capability-
  637. * matrix.md` for citations. Unlike `hostBehaviorsFor` (install *policy*), this is
  638. * the negotiated *capability* surface; #2284 is its first content-projection
  639. * consumer (previously read only by `shouldFlattenDispatch`). Returns `{}` if
  640. * the registry or the runtime's descriptor is unavailable, so callers must
  641. * treat every axis as absent/unknown (fail-closed) rather than assume a value.
  642. */
  643. function _hostIntegrationDispatch(runtime) {
  644. const cap = _capabilityRegistry && _capabilityRegistry.runtimes && _capabilityRegistry.runtimes[runtime];
  645. const dispatch = cap && cap.runtime && cap.runtime.hostIntegration && cap.runtime.hostIntegration.dispatch;
  646. return dispatch || {};
  647. }
  648. /**
  649. * #2870: shared install()/uninstall() scope resolution. Routes `id` through
  650. * the Install Scope Module (src/install-scope.cts) and degrades to `null` on
  651. * failure (unknown/non-installable runtime, broken registry bundle) instead
  652. * of throwing, so each call site's own plain-id fallback keeps working
  653. * exactly as it did before this migration. Both call sites previously carried
  654. * their own copy of this try/catch; this is the one shared copy.
  655. */
  656. function _resolveScopeSafe(id, runtime) {
  657. try {
  658. return resolveScope({ id, runtime });
  659. } catch (_) {
  660. return null;
  661. }
  662. }
  663. /**
  664. * Resolve a layout kind's on-disk destination directory. Shared by the
  665. * skills-root resolution above and the #3664 warning below so the
  666. * home-override + destSubpath join exists once (#3659-class re-encoding guard).
  667. */
  668. function _kindDestDir(layout, kindName, targetDir) {
  669. const kind = layout.kinds.find((k) => k.kind === kindName);
  670. if (!kind) return null;
  671. return path.join(kind.home || targetDir, kind.destSubpath);
  672. }
  673. /**
  674. * #3738: scope-aware, layout-resolving wrapper over _kindDestDir for callers
  675. * that have (runtime, configDir, scope) rather than a resolved Layout — the
  676. * writeManifest agents surface being the first. Never throws: a runtime whose
  677. * layout cannot be resolved (unknown id, descriptor error) keeps the caller's
  678. * own fallback rather than losing the manifest.
  679. */
  680. function _kindDestDirSafe(runtime, configDir, scope, kindName) {
  681. try {
  682. return _kindDestDir(resolveRuntimeArtifactLayout(runtime, configDir, scope), kindName, configDir);
  683. } catch {
  684. return null;
  685. }
  686. }
  687. /**
  688. * #3664 — warn (never refuse) when `--config-dir` points the install at a
  689. * directory whose agent destination already holds FOREIGN (non-GSD) agent
  690. * files — the fingerprint of another harness's config home (e.g. ~/.junie,
  691. * ~/.factory) or a hand-curated agents dir. GSD emits the selected runtime's
  692. * artifacts verbatim: tool IDs (`Skill`) and MCP grants (`mcp__server__tool`)
  693. * that are inert or invalid in a foreign harness surface only at dispatch
  694. * time, months later. Warn-and-proceed is the issue-sanctioned option (b):
  695. * a fresh custom dir (the documented brand-specific-dir use), a gsd-only dir
  696. * (updates, the --all shared dir — including kimi's root `gsd.md`, which is
  697. * GSD-owned despite the bare `gsd` stem), and the no-flag default-home path
  698. * (users keep personal agents in ~/.claude/agents) all stay silent. Degrades
  699. * silently on any resolution failure — the warn path never blocks install.
  700. */
  701. function warnIfForeignAgentDest(runtime, targetDir, scope, explicitConfigDir) {
  702. if (explicitConfigDir !== true) return;
  703. try {
  704. const layout = resolveRuntimeArtifactLayout(runtime, targetDir, scope);
  705. // kimi's global agents kind is `kimi-agents` (#2095 EoS), every other
  706. // runtime's is `agents`.
  707. const agentsDir = _kindDestDir(layout, 'agents', targetDir)
  708. || _kindDestDir(layout, 'kimi-agents', targetDir);
  709. if (!agentsDir) return;
  710. if (!fs.existsSync(agentsDir) || !fs.statSync(agentsDir).isDirectory()) return;
  711. const foreign = fs
  712. .readdirSync(agentsDir)
  713. .filter((f) => f.endsWith('.md') && !f.startsWith('gsd-') && f !== 'gsd.md');
  714. if (foreign.length === 0) return;
  715. console.log(
  716. ` ${yellow}⚠${reset} ${bold}${targetDir}${reset} already contains ${foreign.length} non-GSD agent file(s) — this may be another harness's config home. GSD emits artifacts shaped for ${runtime}: tool IDs and MCP grants may be inert or invalid for whatever harness reads this directory (#3664).`
  717. );
  718. } catch (_) {
  719. /* never block install on the warning path */
  720. }
  721. }
  722. /**
  723. * Resolve the ACTUAL on-disk skills-install directory for a runtime, honoring a
  724. * skills-kind `home` override (ADR-1239 upgrade 3 / #2088: e.g. Codex skills ->
  725. * $HOME/.agents/skills instead of the runtime's configDir). Descriptor-driven
  726. * (no runtime === '<id>' check) so the snapshot/rollback machinery and post-install
  727. * verification look where the skills actually landed. Falls back to <targetDir>/skills.
  728. */
  729. function _resolveSkillsRootDir(runtime, targetDir, scope) {
  730. try {
  731. const layout = resolveRuntimeArtifactLayout(runtime, targetDir, scope);
  732. const skillsDir = _kindDestDir(layout, 'skills', targetDir);
  733. if (skillsDir) return skillsDir;
  734. } catch (_e) { /* fall through to the configDir default */ }
  735. return path.join(targetDir, 'skills');
  736. }
  737. /**
  738. * Construct the imperative Host-Integration adapter (ADR-1239 / #2086), FAIL-OPEN.
  739. * `createImperativeAdapter` composes the capability registry via
  740. * `loadRegistry({includeInstalled:true})`, which require()s several capability
  741. * modules. If any is unavailable (e.g. a packaging regression), return null so
  742. * the caller degrades to the engine directly rather than hard-crashing install/
  743. * uninstall — matching the optional `capability-registry.cjs` load posture above.
  744. */
  745. function _runtimeAdapter(runtime) {
  746. try {
  747. return createImperativeAdapter({ runtime });
  748. } catch {
  749. return null;
  750. }
  751. }
  752. const {
  753. acquireInstallMigrationLock,
  754. applyInstallerMigrationPlan,
  755. discoverInstallerMigrations,
  756. MANIFEST_SCHEMA_VERSION,
  757. planInstallerMigrations,
  758. readInstallManifest,
  759. readInstallState,
  760. recordHostGeneration,
  761. runInstallerMigrations,
  762. } = require(path.join(_gsdLibDir, 'installer-migrations.cjs'));
  763. const { setJsoncValue, removeJsoncValue, hasJsoncFeatures, parseJsonc } = require(path.join(_gsdLibDir, 'jsonc-edit.cjs'));
  764. const { isGsdMcpEntry, GSD_MCP_NO_PROMPTS_FLAG } = require(path.join(_gsdLibDir, 'opencode-mcp-entry.cjs'));
  765. const {
  766. assertInstallerMigrationsUnblocked,
  767. resolveInstallerMigrationPromptsForNonTty,
  768. summarizeInstallerMigrationResult,
  769. } = require(path.join(_gsdLibDir, 'installer-migration-report.cjs'));
  770. const {
  771. resolveRuntimeArtifactLayout,
  772. resolveAdvertisedNewProject,
  773. } = require(path.join(_gsdLibDir, 'runtime-artifact-layout.cjs'));
  774. const {
  775. readSurface,
  776. resolveSurface,
  777. } = require(path.join(_gsdLibDir, 'surface.cjs'));
  778. const {
  779. assertDestWithinConfigHome,
  780. resolveRuntimeArtifactDestination,
  781. resolveRuntimeArtifactInstallRoot,
  782. plannedActionsMutateCodexHooksInputs,
  783. shouldInstallCombinedFamily,
  784. isLegacyFlatLocalInstall,
  785. shouldInstallStandaloneAgents,
  786. codexAgentRolesEnabled,
  787. copyWithPathReplacementSymlinkRefusalMessage,
  788. installRuntimeArtifactsSymlinkRefusalMessage,
  789. installOpencodeFamilySkillsSymlinkRefusalMessage,
  790. installAgentsKindStandaloneSymlinkRefusalMessage,
  791. installCodexConfigSymlinkRefusalMessage,
  792. installCodexAgentTomlSymlinkRefusalMessage,
  793. createRuntimeArtifactInstallPlan,
  794. createRuntimeArtifactUninstallPlan,
  795. } = require(path.join(_gsdLibDir, 'runtime-artifact-install-plan.cjs'));
  796. const {
  797. planLegacyCleanup,
  798. applyLegacyCleanup,
  799. } = require(path.join(__dirname, '..', 'gsd-core', 'bin', 'lib', 'legacy-cleanup.cjs'));
  800. const {
  801. updateCacheFileName,
  802. PACKAGE_NAME,
  803. } = require(path.join(__dirname, '..', 'gsd-core', 'bin', 'lib', 'package-identity.cjs'));
  804. // ADR-1239 Phase B: runtime-artifact install cluster extracted to install-engine.cjs.
  805. // getCommitAttribution STAYS here (impure install-time config I/O); it is injected
  806. // into the engine functions via the resolveAttribution parameter at each call site.
  807. const installEngine = require(path.join(_gsdLibDir, 'install-engine.cjs'));
  808. // #2876: _copyStaged, convertClaudeCommandToOpencodeSkill, and
  809. // convertClaudeCommandToKiloSkill used to be destructured here too — all
  810. // three had no install.js internal caller and no export consumer (tests
  811. // import all three directly from gsd-core/bin/lib/install-engine.cjs), so
  812. // the retired bindings were dead code. applyOpencodeFamilyPathPrefix,
  813. // _runLegacyInstallMigrations, _runLegacyUninstallCleanup,
  814. // _removeGsdEntries, _restoreDir, and _removeHermesBareStemDirs were the
  815. // same — unused local bindings that were never part of this module's export
  816. // surface either — found and retired in the same sweep.
  817. const {
  818. installRuntimeArtifacts,
  819. uninstallRuntimeArtifacts,
  820. installOpencodeFamilySkills,
  821. installAgentsKindStandalone,
  822. _installNativePluginIfDeclared,
  823. hasExistingSymlinkBetween,
  824. isSymlinkedDestOptIn,
  825. migrateLegacyDevPreferencesToSkill,
  826. USER_OWNED_ARTIFACTS,
  827. _snapshotDir,
  828. createSkillDirOwnership,
  829. _warnPreservedSkillDirs,
  830. USER_OWNED_SKILL_DIRS,
  831. } = installEngine;
  832. // #2875 (epic #2866 Phase 6): durable on-disk staging for USER_OWNED_ARTIFACTS
  833. // across the preserve -> wipe -> restore window (#1874-F19). See
  834. // src/user-artifact-staging.cts's module doc.
  835. const {
  836. stageUserArtifacts,
  837. restoreStagedUserArtifacts,
  838. discardStagedUserArtifacts,
  839. recoverOrphanedUserArtifacts,
  840. } = require(path.join(_gsdLibDir, 'user-artifact-staging.cjs'));
  841. /**
  842. * Resolve the durable staging root for `configDir`, confined via
  843. * `assertDestWithinConfigHome` and refused via `hasExistingSymlinkBetween`
  844. * (test-matrix E1/E4) — mirrors install-engine.cts's
  845. * `_resolveUserArtifactStagingRoot`, kept local here because bin/install.js's
  846. * two call sites (uninstall's legacy-migration block, install's mainline
  847. * gsd-core copy) are not inside that module.
  848. */
  849. function _resolveUserArtifactStagingRoot(configDir) {
  850. const stagingRoot = assertDestWithinConfigHome(configDir, path.posix.join('.gsd-staging', 'user-artifacts'));
  851. if (hasExistingSymlinkBetween(path.resolve(configDir), stagingRoot, { allowOptInFollow: isSymlinkedDestOptIn() })) {
  852. throw new Error(
  853. `_resolveUserArtifactStagingRoot: staging root "${stagingRoot}" contains a symlink the install root "${configDir}" does not trust — refusing to stage. If this is an intentional user-owned symlink layout, re-run with GSD_ALLOW_SYMLINKED_DEST=1.`,
  854. );
  855. }
  856. return stagingRoot;
  857. }
  858. function isSkillsRuntimeInstall(runtime, scope) {
  859. const isGlobal = scope === 'global';
  860. const behaviors = hostBehaviorsFor(runtime);
  861. if (isLegacyFlatLocalInstall(behaviors, scope) && !isGlobal) return false; // legacy flat local path (descriptor-driven; #2086)
  862. // #2875 Part 2 defect fix: a runtime whose LOCAL commands are embedded in a
  863. // rules file rather than materialized as files (hostBehaviors.localCommandsViaRules
  864. // — cline is the only declarant, capabilities/cline/capability.json) must not
  865. // flip into this skills/commands-reporting branch merely because its local
  866. // artifactLayout now also declares an `agents` kind (#2875 Part 2 cline-local
  867. // agents regression fix). That branch's own verification reporting expects a
  868. // skills/ or commands/ directory this runtime never writes locally and would
  869. // spuriously fail; the `localCommandsViaRules` branch below (unchanged
  870. // messaging) and the unconditional agents-materialization block further down
  871. // (installAgentsKindStandalone) already cover this runtime/scope correctly.
  872. if (!isGlobal && behaviors.localCommandsViaRules) return false;
  873. const cap = _capabilityRegistry && _capabilityRegistry.runtimes && _capabilityRegistry.runtimes[runtime];
  874. const layout = cap && cap.runtime && cap.runtime.artifactLayout;
  875. if (!layout) return false;
  876. const scopeLayout = isGlobal ? layout.global : layout.local;
  877. return Array.isArray(scopeLayout) && scopeLayout.length > 0;
  878. }
  879. function preflightInstallSymlinkDestinations(runtime, configDir, scope, installMode, agentProfile, installerMigrations) {
  880. const check = (installRoot, destination, message) => {
  881. if (hasExistingSymlinkBetween(path.resolve(installRoot), destination, { allowOptInFollow: isSymlinkedDestOptIn() })) {
  882. throw new Error(message);
  883. }
  884. };
  885. const coreDir = assertDestWithinConfigHome(configDir, path.join(configDir, 'gsd-core'));
  886. check(configDir, coreDir, copyWithPathReplacementSymlinkRefusalMessage(coreDir, configDir));
  887. const layout = resolveRuntimeArtifactLayout(runtime, configDir, scope, _installedCapabilityRegistry);
  888. const behaviors = hostBehaviorsFor(runtime);
  889. const combinedFamily = shouldInstallCombinedFamily(behaviors);
  890. const legacyFlatLocal = isLegacyFlatLocalInstall(behaviors, scope);
  891. const skillsRuntime = isSkillsRuntimeInstall(runtime, scope);
  892. const standaloneAgents = shouldInstallStandaloneAgents(Boolean(behaviors.pluginOnlyInstall), skillsRuntime);
  893. for (const kind of layout.kinds) {
  894. // These flat writers have no write-time trust check to front-run.
  895. // Keep their existing behavior here; a new refusal needs separate approval.
  896. if (combinedFamily && kind.kind === 'commands') continue;
  897. if (legacyFlatLocal && (kind.kind === 'commands' || kind.kind === 'skills')) continue;
  898. const installRoot = resolveRuntimeArtifactInstallRoot(configDir, kind);
  899. const dest = resolveRuntimeArtifactDestination(configDir, kind);
  900. if (hasExistingSymlinkBetween(path.resolve(installRoot), dest, { allowOptInFollow: isSymlinkedDestOptIn() })) {
  901. if (combinedFamily && kind.kind === 'skills') {
  902. throw new Error(installOpencodeFamilySkillsSymlinkRefusalMessage(dest, installRoot));
  903. }
  904. if ((standaloneAgents || combinedFamily) && kind.kind === 'agents') {
  905. throw new Error(installAgentsKindStandaloneSymlinkRefusalMessage(dest, installRoot));
  906. }
  907. throw new Error(installRuntimeArtifactsSymlinkRefusalMessage(dest, installRoot));
  908. }
  909. }
  910. if (behaviors.tomlConfigInstall && codexAgentRolesEnabled(installMode, agentProfile)) {
  911. const configPath = assertDestWithinConfigHome(configDir, 'config.toml');
  912. const agentsTomlDir = assertDestWithinConfigHome(configDir, 'agents');
  913. check(configDir, configPath, installCodexConfigSymlinkRefusalMessage(configDir));
  914. check(configDir, path.resolve(agentsTomlDir), installCodexConfigSymlinkRefusalMessage(configDir));
  915. // The layout agents pass prunes gsd-* entries (including TOML symlinks)
  916. // before installCodexConfig. Its leaf guard sees the replacement state,
  917. // so front-running that guard here would introduce a new refusal.
  918. }
  919. if (resolveInstallPlan(runtime).installSurface === 'codex-toml') {
  920. const migrations = installerMigrations || discoverInstallerMigrations({
  921. migrationsDir: path.join(_gsdLibDir, 'installer-migrations'),
  922. });
  923. // Planning is read-only. A pending id alone says nothing about whether
  924. // this install's hooks/config inputs change (002 can itself be a no-op).
  925. // Defer only actual mutations of those inputs; the migration executor
  926. // and reconciler retain authority over publication and write failures.
  927. // baselineScan intentionally stays off: migration 000 only records,
  928. // preserves, or prompts; it cannot mutate hooks/config inputs. The real
  929. // baseline scan and prompt resolution remain with the migration executor.
  930. const migrationPlan = planInstallerMigrations({ configDir, runtime, scope, migrations });
  931. if (plannedActionsMutateCodexHooksInputs(migrationPlan.actions)) return;
  932. const configPath = path.join(configDir, 'config.toml');
  933. let configContent = fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : '';
  934. if (codexAgentRolesEnabled(installMode, agentProfile)) {
  935. // The managed config block contains no roster-dependent fields (#2406).
  936. // If that changes, pass the writer's selected roster to both projections.
  937. configContent = mergeCodexConfigContent(configContent, generateCodexConfigBlock([], configDir));
  938. }
  939. const prepared = prepareCodexHooksConfig(configContent);
  940. // Extended-event cleanup reconciles hooks.json even when SessionStart has
  941. // no script/runner. Inline/scalar features may leave reconciliation off.
  942. if (hasEnabledCodexHooksFeature(prepared.content)) {
  943. hooksSurface.resolveCodexHooksJsonDestination(configDir);
  944. }
  945. }
  946. }
  947. function prepareCodexAgentConfigContent(source, sourcePath, targetDir) {
  948. let content = composeWorkflow(source, { sourcePath });
  949. const codexGsdPath = `${path.resolve(targetDir, 'gsd-core').replace(/\\/g, '/')}/`;
  950. // Replace full .claude/gsd-core prefix so path resolves to the Codex
  951. // GSD install before generic .claude → .codex conversion rewrites it.
  952. // #5715: one pass, function replacement: a string replacement would expand `$&` in a
  953. // config dir, and a second pass would rescan the path the first emitted.
  954. content = content.replace(/(?:~|\$HOME)\/\.claude\/gsd-core\//g, () => codexGsdPath);
  955. // Route TOML emit through the same full Claude→Codex conversion pipeline
  956. // used on the `.md` emit path (#2639). Covers: slash-command rewrites,
  957. // $ARGUMENTS → {{GSD_ARGS}}, /clear removal, anchored and bare .claude/
  958. // paths, .claudeignore → .codexignore, and standalone "Claude" /
  959. // CLAUDE.md neutralization via neutralizeAgentReferences(..., 'AGENTS.md').
  960. // #5715: the converter runs after the path above was emitted; shield it from the converter.
  961. return runtimeArtifactConversion._shieldEmittedPrefix(content, codexGsdPath, convertClaudeToCodexMarkdown);
  962. }
  963. function codexAgentTomlName(file, source) {
  964. const { frontmatter } = extractFrontmatterAndBody(source);
  965. // Resolve identity from converted frontmatter, matching the header
  966. // conversion in prepareCodexAgentConfigContent.
  967. return extractFrontmatterField(convertClaudeToCodexMarkdown(frontmatter), 'name') || file.replace(/\.md$/, '');
  968. }
  969. /**
  970. * Degrade-not-abort wrapper over `_resolveUserArtifactStagingRoot` — mirrors
  971. * install-engine.cts's own `_tryResolveUserArtifactStagingRoot` (kept local
  972. * here for the same reason the throwing version above is: bin/install.js's
  973. * own call sites are not inside that module). A hostile/broken
  974. * `.gsd-staging` path (or a symlinked configDir itself) must never brick
  975. * `install()` or `uninstall()` — before this fix, `_resolveUserArtifactStagingRoot`
  976. * was called UNGUARDED as the first statement of both, so
  977. * `ln -s /nonexistent ~/.claude/.gsd-staging` killed both commands, including
  978. * uninstall, the remedy for the first problem. Returns `null` (never throws),
  979. * logging one warning; every call site MUST treat `null` as "skip the
  980. * staging-dependent step for this run".
  981. */
  982. function _tryResolveUserArtifactStagingRoot(configDir) {
  983. try {
  984. return _resolveUserArtifactStagingRoot(configDir);
  985. } catch (err) {
  986. console.warn(` ${yellow}!${reset} user-artifact staging unavailable for "${configDir}" (${err.message}) — proceeding without durable staging for this step.`);
  987. return null;
  988. }
  989. }
  990. // Parse args
  991. const args = process.argv.slice(2);
  992. const hasGlobal = args.includes('--global') || args.includes('-g');
  993. const hasLocal = args.includes('--local') || args.includes('-l');
  994. const hasUninstall = args.includes('--uninstall') || args.includes('-u');
  995. const hasSkillsRoot = args.includes('--skills-root');
  996. const hasPortableHooks = args.includes('--portable-hooks') || process.env.GSD_PORTABLE_HOOKS === '1';
  997. const hasMinimal = args.includes('--minimal') || args.includes('--core-only');
  998. const hasDryRun = args.includes('--dry-run');
  999. // #4377: emit project-relative `@` includes (`.claude/gsd-core/...`) for a
  1000. // LOCAL install instead of this checkout's absolute path.
  1001. //
  1002. // Opt-in, and it stays opt-in: absolute includes work for a single checkout,
  1003. // which is nearly everyone, and flipping the default would change every
  1004. // existing local install to solve a problem those users do not have. The
  1005. // people who need it know they do — they run the same repo from several git
  1006. // worktrees, where a baked absolute path means every worktree reads its
  1007. // workflow prose out of whichever checkout happened to run the installer, and
  1008. // updating that one checkout breaks all the others at once with no way to
  1009. // stage it.
  1010. //
  1011. // Exported through the environment rather than threaded as a parameter,
  1012. // exactly like --portable-hooks/GSD_PORTABLE_HOOKS above: five separate seams
  1013. // compute a path prefix (the install engine, both rewrite entry points, the
  1014. // install plan, and applySurface), and one variable they all read cannot fall
  1015. // out of sync the way five signatures can.
  1016. const hasRelativeIncludes = args.includes('--relative-includes') || process.env.GSD_RELATIVE_INCLUDES === '1';
  1017. if (hasRelativeIncludes) process.env.GSD_RELATIVE_INCLUDES = '1';
  1018. // #3031: opt-in reclaim of the GSD artifacts a PRE-#2755 `--kimi-code` install
  1019. // orphaned in Kimi CLI's `~/.kimi`. Opt-in and not automatic because the stale
  1020. // block is BYTE-IDENTICAL to a legitimate Kimi CLI one — both runtimes render
  1021. // the same bytes for the same root, since the command paths derive from the
  1022. // hooks root and not from the runtime — so no inspection can tell "litter GSD
  1023. // wrote for kimi-code" from "Kimi CLI's working hooks". Cleaning unasked would
  1024. // break #2755's own acceptance criterion ("Uninstalling GSD hooks for one
  1025. // runtime does not touch or remove the other runtime's hooks") for anyone with
  1026. // both products installed. The user, who knows which products they run, is the
  1027. // only party that can decide — so they ask for it explicitly.
  1028. const hasReclaimKimiLegacy = args.includes('--reclaim-kimi-legacy');
  1029. // --profile=<name> or --profile=<n1>,<n2> (composable); mutually exclusive with --minimal
  1030. const _profileArgRaw = (() => {
  1031. for (const arg of args) {
  1032. if (arg.startsWith('--profile=')) return arg.slice('--profile='.length);
  1033. }
  1034. return null;
  1035. })();
  1036. // Resolve active profile name:
  1037. // 1. --minimal / --core-only → 'core' (back-compat alias)
  1038. // 2. --profile=<name> → named profile
  1039. // 3. neither → 'full' (default, back-compat)
  1040. // Note: when re-running as `gsd update` the marker is read later (after
  1041. // configDir is resolved) and may override 'full' — see writeActiveProfile call below.
  1042. const _profileIsCore = _profileArgRaw === 'core';
  1043. const _requestedProfileName = (hasMinimal || _profileIsCore) ? 'core' : (_profileArgRaw || null);
  1044. if (hasMinimal && _profileArgRaw) {
  1045. console.error(` ${yellow}Cannot specify both --minimal/--core-only and --profile${reset}`);
  1046. process.exit(1);
  1047. }
  1048. function selectRuntimesFromArgs(runtimeArgs) {
  1049. if (runtimeArgs.includes('--all')) {
  1050. return ['claude', 'kimi', 'kimi-code', 'kilo', 'opencode', 'pi', 'codex', 'copilot', 'antigravity', 'cursor', 'windsurf', 'augment', 'trae', 'qwen', 'hermes', 'codebuddy', 'cline', 'zcode'];
  1051. }
  1052. if (runtimeArgs.includes('--both')) {
  1053. return ['claude', 'opencode'];
  1054. }
  1055. const selected = [];
  1056. if (runtimeArgs.includes('--claude')) selected.push('claude');
  1057. if (runtimeArgs.includes('--opencode')) selected.push('opencode');
  1058. if (runtimeArgs.includes('--pi')) selected.push('pi');
  1059. if (runtimeArgs.includes('--kilo')) selected.push('kilo');
  1060. if (runtimeArgs.includes('--codex')) selected.push('codex');
  1061. if (runtimeArgs.includes('--copilot')) selected.push('copilot');
  1062. if (runtimeArgs.includes('--antigravity')) selected.push('antigravity');
  1063. if (runtimeArgs.includes('--cursor')) selected.push('cursor');
  1064. if (runtimeArgs.includes('--windsurf') || runtimeArgs.includes('--devin-desktop')) selected.push('windsurf');
  1065. if (runtimeArgs.includes('--augment')) selected.push('augment');
  1066. if (runtimeArgs.includes('--trae')) selected.push('trae');
  1067. if (runtimeArgs.includes('--qwen')) selected.push('qwen');
  1068. if (runtimeArgs.includes('--hermes')) selected.push('hermes');
  1069. if (runtimeArgs.includes('--kimi')) selected.push('kimi');
  1070. if (runtimeArgs.includes('--kimi-code')) selected.push('kimi-code');
  1071. if (runtimeArgs.includes('--codebuddy')) selected.push('codebuddy');
  1072. if (runtimeArgs.includes('--cline')) selected.push('cline');
  1073. if (runtimeArgs.includes('--zcode')) selected.push('zcode');
  1074. return selected;
  1075. }
  1076. // Runtime selection - can be set by flags or interactive prompt
  1077. let selectedRuntimes = selectRuntimesFromArgs(args);
  1078. // #2505 Phase 5: Kimi variant disambiguation (#2513). Kimi CLI (Python, ~/.kimi/)
  1079. // and Kimi Code (Node, ~/.kimi-code/) are two distinct Moonshot products that
  1080. // share the "kimi" brand. Probe for each product's config.toml and warn when
  1081. // the selected runtime doesn't match the detected install — catches the common
  1082. // "ran --kimi --global but actually on Kimi Code" mistake that produced inert
  1083. // YAMLs and empty agent-skills before the Phase 1 descriptor split.
  1084. function disambiguateKimiVariant(runtimes) {
  1085. const home = os.homedir();
  1086. const hasKimiCli = fs.existsSync(path.join(home, '.kimi', 'config.toml'));
  1087. const hasKimiCode = fs.existsSync(path.join(home, '.kimi-code', 'config.toml'));
  1088. const notices = [];
  1089. if (runtimes.includes('kimi') && hasKimiCode && !hasKimiCli) {
  1090. notices.push({
  1091. kind: 'wrong-variant',
  1092. selected: 'kimi',
  1093. detected: 'kimi-code',
  1094. message: `Detected ~/.kimi-code/config.toml (Kimi Code, Node CLI) but not ~/.kimi/config.toml (Kimi CLI, Python). You selected --kimi but appear to be on Kimi Code. Re-run with --kimi-code for a working install. (Kimi CLI = Python kimi-cli with named subagents; Kimi Code = Node CLI with coder/explore/plan built-ins only.)`,
  1095. });
  1096. }
  1097. if (runtimes.includes('kimi-code') && hasKimiCli && !hasKimiCode) {
  1098. notices.push({
  1099. kind: 'wrong-variant',
  1100. selected: 'kimi-code',
  1101. detected: 'kimi',
  1102. message: `Detected ~/.kimi/config.toml (Kimi CLI, Python) but not ~/.kimi-code/config.toml (Kimi Code, Node CLI). You selected --kimi-code but appear to be on Kimi CLI. Re-run with --kimi for a working install.`,
  1103. });
  1104. }
  1105. // Distinct-entry descriptions when either Kimi variant is selected.
  1106. if (runtimes.includes('kimi')) {
  1107. notices.push({
  1108. kind: 'description',
  1109. runtime: 'kimi',
  1110. message: 'Kimi CLI (Python kimi-cli): named subagents via YAML, config at ~/.kimi/, hooks via ~/.kimi/config.toml [[hooks]].',
  1111. });
  1112. }
  1113. if (runtimes.includes('kimi-code')) {
  1114. notices.push({
  1115. kind: 'description',
  1116. runtime: 'kimi-code',
  1117. message: 'Kimi Code (Node CLI): three built-in subagents (coder/explore/plan), Agent Skills at ~/.kimi-code/skills/, config at ~/.kimi-code/.',
  1118. });
  1119. }
  1120. return notices;
  1121. }
  1122. // #3031: `--reclaim-kimi-legacy` only ever acts inside the kimi-code GLOBAL
  1123. // install branch. Say so when it cannot act, rather than exiting 0 having
  1124. // silently done nothing: the user asked for a cleanup, and silence is
  1125. // indistinguishable from "it ran and found nothing". Not a hard error — it
  1126. // stays composable with `--all`, where it is legitimately inert for the other
  1127. // seventeen runtimes.
  1128. if (hasReclaimKimiLegacy && !selectedRuntimes.includes('kimi-code')) {
  1129. console.error(`${yellow}⚠ --reclaim-kimi-legacy ignored${reset} — it applies only to a --kimi-code install; nothing in ~/.kimi was touched.`);
  1130. } else if (hasReclaimKimiLegacy && hasLocal) {
  1131. // Scope, checked HERE rather than inside install(): kimi-code declares
  1132. // hostBehaviors.localInstallDeferred, so install() returns early long before
  1133. // the kimi-hooks-toml branch — a warning placed there would be unreachable.
  1134. console.error(`${yellow}⚠ --reclaim-kimi-legacy ignored${reset} — the legacy root is a global location; re-run with --global to reclaim it.`);
  1135. }
  1136. if (selectedRuntimes.includes('kimi') || selectedRuntimes.includes('kimi-code')) {
  1137. const kimiNotices = disambiguateKimiVariant(selectedRuntimes);
  1138. for (const notice of kimiNotices) {
  1139. if (notice.kind === 'wrong-variant') {
  1140. console.error(`${yellow}⚠ Kimi variant mismatch (${notice.selected} → ${notice.detected}).${reset} ${notice.message}`);
  1141. } else if (notice.kind === 'description') {
  1142. console.log(`${dim} ${notice.runtime}: ${notice.message}${reset}`);
  1143. }
  1144. }
  1145. }
  1146. // #1928: Google sunset Gemini CLI on 2026-06-18; Antigravity CLI is its
  1147. // official successor. `--gemini` is no longer a valid runtime selector —
  1148. // selectRuntimesFromArgs above no longer recognizes it, so it never lands in
  1149. // selectedRuntimes. Print a one-time redirect notice, and — when `--gemini`
  1150. // was the ONLY runtime flag supplied (selectedRuntimes is empty) — exit
  1151. // deterministically rather than silently falling through to the "no runtime
  1152. // specified" defaults below (which would install Claude Code, surprising a
  1153. // user who explicitly asked for Gemini). Other flags (e.g. `--codex`) still
  1154. // parse and install normally alongside the notice.
  1155. if (args.includes('--gemini')) {
  1156. const wantsHelp = args.includes('--help') || args.includes('-h');
  1157. console.error('Gemini CLI was sunset by Google on 2026-06-18 and is no longer served for free/Pro/Ultra tiers.');
  1158. console.error('GSD now supports Antigravity CLI (the official successor). Re-run with: --antigravity');
  1159. if (hasUninstall) {
  1160. // The gemini runtime was removed (#1928), so there is no automated
  1161. // `--gemini --uninstall`. Guide manual cleanup and exit — do NOT fall
  1162. // through to the uninstall dispatch below, which defaults an empty runtime
  1163. // selection to 'claude' and would wrongly uninstall the user's Claude install.
  1164. console.error('The gemini runtime was removed, so `--gemini --uninstall` is no longer available.');
  1165. console.error('To remove a prior Gemini install, delete GSD files under your Gemini config dir');
  1166. console.error('(e.g. ~/.gemini/commands/gsd) and GSD hook entries in ~/.gemini/settings.json.');
  1167. process.exit(1);
  1168. }
  1169. // For `--gemini --help`, fall through so the usage block still prints. For a
  1170. // bare install attempt (no other runtime selected), exit rather than silently
  1171. // installing Claude.
  1172. if (!wantsHelp && selectedRuntimes.length === 0) {
  1173. process.exit(1);
  1174. }
  1175. }
  1176. // WSL + Windows Node.js detection
  1177. // When Windows-native Node runs on WSL, os.homedir() and path.join() produce
  1178. // backslash paths that don't resolve correctly on the Linux filesystem.
  1179. if (process.platform === 'win32') {
  1180. let isWSL = false;
  1181. try {
  1182. if (process.env.WSL_DISTRO_NAME) {
  1183. isWSL = true;
  1184. } else if (fs.existsSync('/proc/version')) {
  1185. const procVersion = fs.readFileSync('/proc/version', 'utf8').toLowerCase();
  1186. if (procVersion.includes('microsoft') || procVersion.includes('wsl')) {
  1187. isWSL = true;
  1188. }
  1189. }
  1190. } catch {
  1191. // Ignore read errors — not WSL
  1192. }
  1193. if (isWSL) {
  1194. console.error(`
  1195. ${yellow}⚠ Detected WSL with Windows-native Node.js.${reset}
  1196. This causes path resolution issues that prevent correct installation.
  1197. Please install a Linux-native Node.js inside WSL:
  1198. curl -fsSL https://fnm.vercel.app/install | bash
  1199. fnm install --lts
  1200. Then re-run: npx ${pkg.name}@latest
  1201. `);
  1202. process.exit(1);
  1203. }
  1204. }
  1205. // getDirName (runtime -> local config dir name) now lives in
  1206. // runtime-name-policy.cjs (ADR-1508 / #1510 Phase 1); imported above for
  1207. // install.js's own internal use only — #2876 retired the re-export.
  1208. /**
  1209. * Get the config directory path relative to home directory for a runtime
  1210. * Used for templating hooks that use path.join(homeDir, '<configDir>', ...)
  1211. * @param {string} runtime - 'claude', 'opencode', 'codex', or 'copilot'
  1212. * @param {boolean} isGlobal - Whether this is a global install
  1213. */
  1214. function getConfigDirFromHome(runtime, isGlobal) {
  1215. if (!isGlobal) {
  1216. // Local installs use the same dir name pattern
  1217. return `'${getDirName(runtime)}'`;
  1218. }
  1219. // Global installs. antigravity's home is resolved dynamically (env-overridable,
  1220. // multi-segment via resolveAntigravityGlobalDir + path.relative) — not a table
  1221. // entry. (The prior inner `if (!isGlobal) return "'.agents'"` was unreachable:
  1222. // !isGlobal returns at the top of this function.)
  1223. // Descriptor-driven (ADR-1239 / #2096): folded from a hardcoded
  1224. // `runtime === 'antigravity'` literal into a read of the runtime's
  1225. // `hostBehaviors.globalDirResolver` descriptor field (via hostBehaviorsFor, which
  1226. // also degrades to its #338 floor on registry-load failure). This is
  1227. // antigravity-unique: unlike `configHome.kind === 'dot-home-nested'` (which
  1228. // windsurf also declares — see capabilities/windsurf/capability.json — and
  1229. // would wrongly route windsurf's global dir through
  1230. // resolveAntigravityGlobalDir), `globalDirResolver` is only set by antigravity.
  1231. if (hostBehaviorsFor(runtime).globalDirResolver === 'antigravity') {
  1232. const antigravityDir = resolveAntigravityGlobalDir();
  1233. const rel = path.relative(os.homedir(), antigravityDir);
  1234. const segments = rel.split(path.sep).filter(Boolean);
  1235. if (segments.length > 0 && !rel.startsWith('..') && !path.isAbsolute(rel)) {
  1236. return segments.map((seg) => `'${seg}'`).join(', ');
  1237. }
  1238. // If resolution points outside HOME (e.g. via env override), keep the
  1239. // stable legacy template so generated path.join() calls remain valid.
  1240. return "'.gemini', 'antigravity'";
  1241. }
  1242. // All other runtimes: single source-of-truth fragment table (ADR-1239 Phase B,
  1243. // #1679). claude/unknown fall through to the table's default '.claude'.
  1244. return getGlobalConfigHomeFragment(runtime);
  1245. }
  1246. /**
  1247. * Compatibility seam for tests and older installer consumers.
  1248. * Runtime home resolution now lives in runtime-homes.cjs.
  1249. */
  1250. function getGlobalDir(runtime, explicitDir = null) {
  1251. return getGlobalConfigDir(runtime, explicitDir);
  1252. }
  1253. const banner = '\n' +
  1254. cyan + ' ██████╗ ███████╗██████╗\n' +
  1255. ' ██╔════╝ ██╔════╝██╔══██╗\n' +
  1256. ' ██║ ███╗███████╗██║ ██║\n' +
  1257. ' ██║ ██║╚════██║██║ ██║\n' +
  1258. ' ╚██████╔╝███████║██████╔╝\n' +
  1259. ' ╚═════╝ ╚══════╝╚═════╝' + reset + '\n' +
  1260. '\n' +
  1261. ' GSD Core ' + dim + 'v' + pkg.version + reset + '\n' +
  1262. ' Git. Ship. Done.\n' +
  1263. ' A meta-prompting, context engineering and spec-driven\n' +
  1264. ' development workflows for Claude Code, OpenCode, Kimi CLI, Kilo, Codex, Copilot, Antigravity, Cursor, Windsurf, Augment, Trae, Qwen Code, Hermes Agent, Cline, CodeBuddy, ZCode and pi.\n';
  1265. // Pure seam: parse --config-dir / -c from an arbitrary args array.
  1266. // Returns the path string, '' for an empty equals-form value, or null when the
  1267. // flag is absent. Space-separated form returns null (not an error string) when
  1268. // the next token is missing or flag-looking — callers that want process.exit
  1269. // behaviour must check after calling this function.
  1270. // Exported via module.exports so unit tests can exercise it directly.
  1271. function parseConfigDirFromArgs(argsArray) {
  1272. const configDirIndex = argsArray.findIndex(arg => arg === '--config-dir' || arg === '-c');
  1273. if (configDirIndex !== -1) {
  1274. const nextArg = argsArray[configDirIndex + 1];
  1275. // No value / next token is a flag → signal "missing" by returning null
  1276. if (!nextArg || nextArg.startsWith('-')) {
  1277. return null;
  1278. }
  1279. return nextArg;
  1280. }
  1281. // Handle --config-dir=value and -c=value format.
  1282. // Use indexOf('=') + 1 so that = signs inside the path value are preserved.
  1283. const configDirArg = argsArray.find(arg => arg.startsWith('--config-dir=') || arg.startsWith('-c='));
  1284. if (configDirArg) {
  1285. return configDirArg.slice(configDirArg.indexOf('=') + 1);
  1286. }
  1287. return null;
  1288. }
  1289. // Parse --no-legacy-cleanup (#3799) — skip the legacy get-shit-done-cc scan
  1290. // entirely. Some users run gsd-core alongside a live legacy install on
  1291. // purpose; the scan is best-effbelt cleanup, never load-bearing for the
  1292. // install itself.
  1293. function parseNoLegacyCleanupArg(args = process.argv) {
  1294. return args.includes('--no-legacy-cleanup');
  1295. }
  1296. // Parse --config-dir argument
  1297. function parseConfigDirArg() {
  1298. const result = parseConfigDirFromArgs(args);
  1299. if (result === null) {
  1300. // Check if the space-separated form was present but missing a value
  1301. const configDirIndex = args.findIndex(arg => arg === '--config-dir' || arg === '-c');
  1302. if (configDirIndex !== -1) {
  1303. console.error(` ${yellow}--config-dir requires a path argument${reset}`);
  1304. process.exit(1);
  1305. }
  1306. return null;
  1307. }
  1308. if (result === '') {
  1309. console.error(` ${yellow}--config-dir requires a non-empty path${reset}`);
  1310. process.exit(1);
  1311. }
  1312. return result;
  1313. }
  1314. const explicitConfigDir = parseConfigDirArg();
  1315. const hasHelp = args.includes('--help') || args.includes('-h');
  1316. const forceStatusline = args.includes('--force-statusline');
  1317. if (!hasSkillsRoot) console.log(banner);
  1318. if (hasUninstall) {
  1319. console.log(' Mode: Uninstall\n');
  1320. }
  1321. // Show help if requested
  1322. if (hasHelp) {
  1323. console.log(` ${yellow}Usage:${reset} npx ${pkg.name} [options]\n\n ${yellow}Options:${reset}\n ${cyan}-g, --global${reset} Install globally (to config directory)\n ${cyan}-l, --local${reset} Install locally (to current directory)\n ${cyan}--claude${reset} Install for Claude Code only\n ${cyan}--opencode${reset} Install for OpenCode only\n ${cyan}--kilo${reset} Install for Kilo only\n ${cyan}--codex${reset} Install for Codex only\n ${cyan}--kimi${reset} Install for Kimi CLI only\n ${cyan}--kimi-code${reset} Install for Kimi Code only\n ${cyan}--copilot${reset} Install for Copilot only\n ${cyan}--antigravity${reset} Install for Antigravity only\n ${cyan}--cursor${reset} Install for Cursor only\n ${cyan}--windsurf${reset} Install for Windsurf only\n ${cyan}--augment${reset} Install for Augment only\n ${cyan}--trae${reset} Install for Trae only\n ${cyan}--qwen${reset} Install for Qwen Code only\n ${cyan}--hermes${reset} Install for Hermes Agent only\n ${cyan}--cline${reset} Install for Cline only\n ${cyan}--codebuddy${reset} Install for CodeBuddy only\n ${cyan}--zcode${reset} Install for ZCode only\n ${cyan}--pi${reset} Install for Pi only\n ${cyan}--gemini${reset} Install for Gemini CLI only\n ${cyan}--all${reset} Install for all runtimes\n ${cyan}-u, --uninstall${reset} Uninstall GSD (remove all GSD files)\n ${cyan}-c, --config-dir <path>${reset} Specify custom config directory\n ${cyan}--no-legacy-cleanup${reset} Skip the legacy get-shit-done-cc artifact scan\n (an explicit --config-dir already scopes the scan to it)\n ${cyan}-h, --help${reset} Show this help message\n ${cyan}--force-statusline${reset} Replace existing statusline config\n ${cyan}--portable-hooks${reset} Emit \$HOME-relative hook paths in settings.json\n and resolve the node runner at hook-fire time via\n hooks/gsd-node-runner.sh (WSL/Docker bind-mount\n setups; also GSD_PORTABLE_HOOKS=1)\n ${cyan}--relative-includes${reset} With --local: write project-relative @ includes\n (.claude/gsd-core/...) instead of this checkout's\n absolute path, so several git worktrees of one repo\n each read their own copy (also GSD_RELATIVE_INCLUDES=1)\n ${cyan}--reclaim-kimi-legacy${reset} With --kimi-code: also remove the GSD hooks a\n pre-1.10.0 --kimi-code install orphaned in ~/.kimi.\n Opt-in — those artifacts are indistinguishable from\n Kimi CLI's own, so skip it if you use Kimi CLI too.\n ${cyan}--profile=<name>${reset} Install a named skill profile. Profiles:\n core — ${PROFILES.core.length} main-loop skills incl. phase (~130 desc tokens)\n standard — ${PROFILES.standard.length} skills incl. phase, review, config (~700)\n full — all skills (default)\n Composable: --profile=core,audit installs union of closures.\n Profile is persisted and respected by \`gsd update\`.\n ${cyan}--minimal${reset} Alias for --profile=core (back-compat).\n Cuts cold-start overhead from ~12k tokens to ~700.\n Alias: --core-only.\n\n ${yellow}Examples:${reset}\n ${dim}# Interactive install (prompts for runtime and location)${reset}\n npx ${pkg.name}\n\n ${dim}# Install for Claude Code globally${reset}\n npx ${pkg.name} --claude --global\n\n ${dim}# Install for Kilo globally${reset}\n npx ${pkg.name} --kilo --global\n\n ${dim}# Install for Codex globally${reset}\n npx ${pkg.name} --codex --global\n\n ${dim}# Install for Kimi CLI globally${reset}\n npx ${pkg.name} --kimi --global\n\n ${dim}# Install for Kimi Code globally (its own ~/.kimi-code root)${reset}\n npx ${pkg.name} --kimi-code --global\n\n ${dim}# Kimi Code, also reclaiming hooks a pre-1.10.0 install left in ~/.kimi${reset}\n npx ${pkg.name} --kimi-code --global --reclaim-kimi-legacy\n\n ${dim}# Install for Copilot globally${reset}\n npx ${pkg.name} --copilot --global\n\n ${dim}# Install for Copilot locally${reset}\n npx ${pkg.name} --copilot --local\n\n ${dim}# Install for Antigravity globally${reset}\n npx ${pkg.name} --antigravity --global\n\n ${dim}# Install for Antigravity locally${reset}\n npx ${pkg.name} --antigravity --local\n\n ${dim}# Install for Cursor globally${reset}\n npx ${pkg.name} --cursor --global\n\n ${dim}# Install for Cursor locally${reset}\n npx ${pkg.name} --cursor --local\n\n ${dim}# Install for Windsurf globally${reset}\n npx ${pkg.name} --windsurf --global\n\n ${dim}# Install for Windsurf locally${reset}\n npx ${pkg.name} --windsurf --local\n\n ${dim}# Install for Augment globally${reset}\n npx ${pkg.name} --augment --global\n\n ${dim}# Install for Augment locally${reset}\n npx ${pkg.name} --augment --local\n\n ${dim}# Install for Trae globally${reset}\n npx ${pkg.name} --trae --global\n\n ${dim}# Install for Trae locally${reset}\n npx ${pkg.name} --trae --local\n\n ${dim}# Install for Hermes Agent globally${reset}\n npx ${pkg.name} --hermes --global\n\n ${dim}# Install for Hermes Agent locally${reset}\n npx ${pkg.name} --hermes --local\n\n ${dim}# Install for Cline globally${reset}\n npx ${pkg.name} --cline --global\n\n ${dim}# Install for Cline locally${reset}\n npx ${pkg.name} --cline --local\n\n ${dim}# Install for CodeBuddy globally${reset}\n npx ${pkg.name} --codebuddy --global\n\n ${dim}# Install for CodeBuddy locally${reset}\n npx ${pkg.name} --codebuddy --local\n\n ${dim}# Install for all runtimes globally${reset}\n npx ${pkg.name} --all --global\n\n ${dim}# Install to custom config directory${reset}\n npx ${pkg.name} --kilo --global --config-dir ~/.kilo-work\n\n ${dim}# Install to current project only${reset}\n npx ${pkg.name} --claude --local\n\n ${dim}# Local install for a repo worked from several git worktrees${reset}\n npx ${pkg.name} --claude --local --relative-includes\n\n ${dim}# Uninstall GSD from Cursor globally${reset}\n npx ${pkg.name} --cursor --global --uninstall\n\n ${yellow}Notes:${reset}\n The --config-dir option is useful when you have multiple configurations.\n It takes priority over CLAUDE_CONFIG_DIR / OPENCODE_CONFIG_DIR / KILO_CONFIG_DIR / CODEX_HOME / KIMI_CONFIG_DIR / COPILOT_CONFIG_DIR / COPILOT_HOME / ANTIGRAVITY_CONFIG_DIR / CURSOR_CONFIG_DIR / WINDSURF_CONFIG_DIR / AUGMENT_CONFIG_DIR / TRAE_CONFIG_DIR / QWEN_CONFIG_DIR / HERMES_HOME / CLINE_CONFIG_DIR / CODEBUDDY_CONFIG_DIR environment variables.\n Kimi CLI defaults to the first existing generic skills root: ${cyan}~/.config/agents/skills${reset}, then ${cyan}~/.agents/skills${reset}; if neither exists, GSD creates ${cyan}~/.config/agents${reset}.\n Kimi CLI and Kimi Code are separate products with separate hook roots: use ${cyan}--kimi${reset} (${cyan}~/.kimi${reset}, ${cyan}KIMI_SHARE_DIR${reset}) or ${cyan}--kimi-code${reset} (${cyan}~/.kimi-code${reset}, ${cyan}KIMI_CODE_HOME${reset}).\n`);
  1324. process.exit(0);
  1325. }
  1326. // computePathPrefix: implementation moved to runtimeArtifactConversion._computePathPrefix
  1327. // (ADR-1508 / #1511 Phase 2 — single owner). The const binding above re-binds
  1328. // it here for install.js's own internal call sites only — #2876 retired the
  1329. // module.exports entry (zero consumers found; tests import
  1330. // runtimeArtifactConversion._computePathPrefix directly).
  1331. // Original doc: Compute the path prefix used for `@file` references in installed
  1332. // command/skill markdown. For global installs under $HOME uses $HOME/... form;
  1333. // OpenCode always uses the absolute path (#2376 Windows, #2831 macOS/Linux).
  1334. // resolveNodeRunner, resolveBashRunner, referencesHook are now owned by the
  1335. // runtime-hooks-surface module. Import them here so install.js callers
  1336. // continue to work and so there is a single implementation of these helpers.
  1337. // (normalizeNodePath was re-bound here too until #2876 found bin/install.js
  1338. // had no internal caller and no export consumer for it — hooksSurface owns
  1339. // the single implementation now, used internally by resolveNodeRunner there.)
  1340. const resolveNodeRunner = hooksSurface.resolveNodeRunner;
  1341. // #3662: the runtime-resolving runner token for managed JS hooks — the baked
  1342. // absolute node path tried FIRST, then `command -v node`, then well-known
  1343. // layouts, resolved by the shell at hook-fire time instead of bake time.
  1344. const buildNodeRunnerChainToken = hooksSurface.buildNodeRunnerChainToken;
  1345. const resolveBashRunner = hooksSurface.resolveBashRunner;
  1346. // referencesHook: pure predicate over hook entry objects, shared between
  1347. // install() and finishInstall() (ADR-857 phase 5f-1b).
  1348. const referencesHook = hooksSurface.referencesHook;
  1349. // applySettingsJsonHooks: mutates settings.hooks.* in place with all GSD-managed
  1350. // hook registrations for settings.json-surface runtimes (ADR-857 phase 5f-1b).
  1351. const applySettingsJsonHooks = hooksSurface.applySettingsJsonHooks;
  1352. // writeKimiHooksToml / removeKimiHooksToml: kimi's native config.toml [[hooks]]
  1353. // surface (#2095 EoS/kimi Upgrade 1) — separate from settings.json entirely.
  1354. const writeKimiHooksToml = hooksSurface.writeKimiHooksToml;
  1355. // #4840: false when the runtime declares `context-warnings` unsupported in its
  1356. // descriptor (`hostBehaviors.unsupportedFeatures`). gsd-context-monitor.js reads
  1357. // the metrics bridge file only the statusline hook writes, and the statusline
  1358. // is wired for Claude Code alone, so on any other host the hook fires on every
  1359. // tool event, finds no file and exits silently — forever. Such a host gets no
  1360. // monitor registration (stale ones are stripped), as Codex does since #2586.
  1361. function runtimeSupportsContextWarnings(runtime) {
  1362. const unsupported = hostBehaviorsFor(runtime).unsupportedFeatures;
  1363. return !(Array.isArray(unsupported) && unsupported.includes('context-warnings'));
  1364. }
  1365. const removeKimiHooksToml = hooksSurface.removeKimiHooksToml;
  1366. // processAttribution: pure Co-Authored-By content transform, relocated to the
  1367. // conversion module (ADR-1508 / #1510 Phase 1). Bound here so install.js
  1368. // callers continue to work and there is a single implementation. (All call
  1369. // sites are below this line, so the const binding has no TDZ hazard.)
  1370. const processAttribution = runtimeArtifactConversion.processAttribution;
  1371. const filterRuntimeNotesForTarget = runtimeArtifactConversion.filterRuntimeNotesForTarget;
  1372. // computePathPrefix: implementation lives in runtimeArtifactConversion
  1373. // (ADR-1508 / #1511 Phase 2 — single owner). Re-bound here so install.js call
  1374. // sites continue to work. #2876 retired the sibling
  1375. // applyRuntimeContentRewritesInPlace / applyRuntimeContentRewritesForCommandsInPlace
  1376. // re-bindings that used to sit alongside it, and the entire #1675 Augment
  1377. // converter family re-binding (convertClaudeToAugmentMarkdown /
  1378. // convertClaudeCommandToAugmentSkill / convertClaudeAgentToAugmentAgent) that
  1379. // used to follow — bin/install.js had no internal caller for any of them (the
  1380. // descriptor pipeline in runtimeArtifactConversion calls them directly).
  1381. // (All call sites are below this line → no TDZ hazard.)
  1382. const computePathPrefix = runtimeArtifactConversion._computePathPrefix;
  1383. // #2931 (ADR-1508): the windsurf converter family is single-sourced in the
  1384. // conversion module. install.js re-binds (does not re-define) the one member
  1385. // it still calls internally so there is exactly one body — the
  1386. // generative-drift hazard the dedup removes. #2876 retired the sibling
  1387. // convertClaudeCommandToWindsurfSkill / convertClaudeCommandToWindsurfWorkflow /
  1388. // convertClaudeAgentToWindsurfAgent re-bindings — bin/install.js had no
  1389. // internal caller for any of them (the descriptor pipeline in
  1390. // runtimeArtifactConversion calls them directly).
  1391. // (All call sites are below this line → no TDZ hazard.)
  1392. const convertClaudeToWindsurfMarkdown = runtimeArtifactConversion.convertClaudeToWindsurfMarkdown;
  1393. // #2931 (ADR-1508): single-sourced in the conversion module — was a second,
  1394. // unlinked verbatim copy here (used by the local Cursor/Trae/CodeBuddy/Cline
  1395. // converters below), the exact drift class this PR exists to reduce. Verified
  1396. // behaviorally identical (no block / one block / adjacent blocks / whole-
  1397. // content block / unclosed opening tag / nested-looking tags / repeated
  1398. // sequential calls for global-regex lastIndex leakage) before merging.
  1399. // install.js re-binds (does not re-define) — RUNTIME_COMPATIBILITY_BLOCK_RE
  1400. // is no longer duplicated here either. (All call sites are below this line
  1401. // → no TDZ hazard.)
  1402. const applyClaudeCodeBrandSwap = runtimeArtifactConversion.applyClaudeCodeBrandSwap;
  1403. function rewriteLegacyManagedNodeHookCommands(settings, absoluteRunner, opts) {
  1404. return hooksSurface.rewriteLegacyManagedNodeHookCommands(settings, absoluteRunner, opts);
  1405. }
  1406. // #2876: reconcileManagedShellHookCommands, buildCodexHookBlock,
  1407. // rewriteLegacyCodexHookBlock, reconcileCodexHooksJsonEvent, and
  1408. // reconcileCodexHooksJsonSessionStart used to be re-bound here as one-line
  1409. // delegates to the equivalent hooksSurface.* implementations. None had an
  1410. // install.js internal caller or an export consumer (tests import all five
  1411. // directly from gsd-core/bin/lib/runtime-hooks-surface.cjs), so the retired
  1412. // bindings were dead code with no reachable body — removed rather than kept
  1413. // as unreachable wrappers.
  1414. /**
  1415. * Ensure Codex hooks.json contains exactly one managed SessionStart
  1416. * gsd-check-update hook entry, while preserving user-owned entries.
  1417. *
  1418. * Codex accepts hook config from hooks.json and config.toml. To avoid the
  1419. * startup warning for mixed representations in the same layer, GSD now stores
  1420. * the managed SessionStart hook in hooks.json and keeps config.toml for
  1421. * feature flags / agent metadata only.
  1422. *
  1423. * Supports both known hooks.json shapes:
  1424. * 1) { "SessionStart": [...] }
  1425. * 2) { "hooks": { "SessionStart": [...] } }
  1426. *
  1427. * On Windows, writes a .cmd shim alongside the .js hook file and uses the
  1428. * .cmd shim path as the hook command to avoid the `bash.exe: cannot execute
  1429. * binary file` failure (#3426).
  1430. *
  1431. * #772: also emits `commandWindows` in the hook entry so that a
  1432. * cross-platform hooks.json works on both POSIX and Windows without
  1433. * requiring per-OS regeneration. Codex dispatches `commandWindows` on
  1434. * Windows and `command` on other platforms (HookHandlerConfig in
  1435. * codex-rs/config/src/hook_config.rs).
  1436. *
  1437. * @param {string} targetDir
  1438. * @param {{ absoluteRunner: string|null, platform?: NodeJS.Platform }} opts
  1439. * @returns {{ changed: boolean, wrote: boolean, path: string }}
  1440. */
  1441. function ensureCodexHooksJsonSessionStart(targetDir, opts = {}) {
  1442. return hooksSurface.ensureCodexHooksJsonSessionStart(targetDir, opts);
  1443. }
  1444. /**
  1445. * Remove a GSD-managed event entry from hooks.json. Called during uninstall,
  1446. * and (#2586) unconditionally during install/reinstall to clean up a
  1447. * pre-#2586 install's stale gsd-context-monitor.js registrations — GSD no
  1448. * longer ADDS entries for these events (see CODEX_HOOKS_TO_COPY /
  1449. * cleanupOrphanedCodexContextMonitorScript in bin/install.js's Codex branch),
  1450. * only removes recognized ones, so the `ensureCodexHooksJsonEvent` wrapper
  1451. * that used to add them was removed as dead code.
  1452. *
  1453. * @param {string} targetDir
  1454. * @param {string} eventName
  1455. */
  1456. function removeCodexHooksJsonEvent(targetDir, eventName) {
  1457. return hooksSurface.removeCodexHooksJsonEvent(targetDir, eventName);
  1458. }
  1459. function removeCodexHooksJsonSessionStart(targetDir) {
  1460. return hooksSurface.removeCodexHooksJsonSessionStart(targetDir);
  1461. }
  1462. /**
  1463. * Build a hook command path using forward slashes for cross-platform compatibility.
  1464. * On Windows, $HOME is not expanded by cmd.exe/PowerShell, so we use the actual path.
  1465. *
  1466. * @param {string} configDir - Resolved absolute config directory path
  1467. * @param {string} hookName - Hook filename (e.g. 'gsd-statusline.js')
  1468. * @param {{ portableHooks?: boolean, platform?: NodeJS.Platform, runtime?: string }} [opts] - Options
  1469. * portableHooks: when true, emit $HOME-relative paths instead of absolute paths.
  1470. * Safe for Linux/macOS global installs and WSL/Docker bind-mount scenarios.
  1471. * Not suitable for pure Windows (cmd.exe/PowerShell do not expand $HOME).
  1472. * platform: test injection for shell command formatting. Defaults to process.platform.
  1473. * runtime: target runtime name for shell projection policy.
  1474. */
  1475. function buildHookCommand(configDir, hookName, opts) {
  1476. return hooksSurface.buildHookCommand(configDir, hookName, opts);
  1477. }
  1478. /**
  1479. * Resolve the opencode config file path, preferring .jsonc if it exists.
  1480. */
  1481. function resolveOpencodeConfigPath(configDir) {
  1482. const jsoncPath = path.join(configDir, 'opencode.jsonc');
  1483. if (fs.existsSync(jsoncPath)) {
  1484. return jsoncPath;
  1485. }
  1486. return path.join(configDir, 'opencode.json');
  1487. }
  1488. /**
  1489. * Resolve the Kilo config file path, preferring .jsonc if it exists.
  1490. */
  1491. function resolveKiloConfigPath(configDir) {
  1492. const jsoncPath = path.join(configDir, 'kilo.jsonc');
  1493. if (fs.existsSync(jsoncPath)) {
  1494. return jsoncPath;
  1495. }
  1496. return path.join(configDir, 'kilo.json');
  1497. }
  1498. // #2087 — attribution config-path resolvers, keyed by descriptor (hostBehaviors.attributionConfigResolver)
  1499. const ATTRIBUTION_CONFIG_RESOLVERS = { opencode: resolveOpencodeConfigPath, kilo: resolveKiloConfigPath };
  1500. /**
  1501. * Strip JSONC comments (// and /* *​/) from a string to produce valid JSON.
  1502. * Handles comments inside strings correctly (does not strip them).
  1503. */
  1504. function stripJsonComments(text) {
  1505. let result = '';
  1506. let i = 0;
  1507. let inString = false;
  1508. let stringChar = '';
  1509. while (i < text.length) {
  1510. // Handle string literals — don't strip comments inside strings
  1511. if (inString) {
  1512. if (text[i] === '\\') {
  1513. result += text[i] + (text[i + 1] || '');
  1514. i += 2;
  1515. continue;
  1516. }
  1517. if (text[i] === stringChar) {
  1518. inString = false;
  1519. }
  1520. result += text[i];
  1521. i++;
  1522. continue;
  1523. }
  1524. // Start of string
  1525. if (text[i] === '"' || text[i] === "'") {
  1526. inString = true;
  1527. stringChar = text[i];
  1528. result += text[i];
  1529. i++;
  1530. continue;
  1531. }
  1532. // Line comment
  1533. if (text[i] === '/' && text[i + 1] === '/') {
  1534. // Skip to end of line
  1535. while (i < text.length && text[i] !== '\n') i++;
  1536. continue;
  1537. }
  1538. // Block comment
  1539. if (text[i] === '/' && text[i + 1] === '*') {
  1540. i += 2;
  1541. while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i++;
  1542. i += 2; // skip closing */
  1543. continue;
  1544. }
  1545. result += text[i];
  1546. i++;
  1547. }
  1548. // Remove trailing commas before } or ] (common in JSONC)
  1549. return result.replace(/,\s*([}\]])/g, '$1');
  1550. }
  1551. /**
  1552. * Read and parse settings.json, returning empty object if it doesn't exist.
  1553. * Supports JSONC (JSON with comments) — many CLI tools allow comments in
  1554. * their settings files, so we strip them before parsing to avoid silent
  1555. * data loss from JSON.parse failures.
  1556. */
  1557. function readSettings(settingsPath) {
  1558. if (fs.existsSync(settingsPath)) {
  1559. try {
  1560. const raw = fs.readFileSync(settingsPath, 'utf8');
  1561. let parsed;
  1562. // Try standard JSON first (fast path)
  1563. try { parsed = JSON.parse(raw); }
  1564. catch { parsed = JSON.parse(stripJsonComments(raw)); }
  1565. return parsed === null ? {} : parsed; // valid JSON null = empty settings, not malformed
  1566. } catch (e) {
  1567. // If even JSONC stripping fails, warn instead of silently returning {}
  1568. console.warn(' ' + yellow + '⚠' + reset + ' Warning: Could not parse ' + settingsPath + ' — file may be malformed. Existing settings preserved.');
  1569. return null;
  1570. }
  1571. }
  1572. return {};
  1573. }
  1574. /**
  1575. * Write settings.json with proper formatting.
  1576. *
  1577. * Atomic (temp+rename) because hosts discard the ENTIRE settings file on any
  1578. * parse failure, so a truncated write costs the user every hook, permission,
  1579. * and statusline they have — not just GSD's entries. This is the sole writer
  1580. * of that surface for six runtimes.
  1581. *
  1582. * `atomicWriteFileSync` is declared further down this file; it is dereferenced
  1583. * at call time, after module evaluation, so the ordering is safe.
  1584. */
  1585. function writeSettings(settingsPath, settings) {
  1586. atomicWriteFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf8');
  1587. }
  1588. // #2875 Part 2 (J8): model-override resolution (readGsdGlobalModelOverrides /
  1589. // readGsdEffectiveModelOverrides / readGsdRuntimeProfileResolver, plus the
  1590. // shared resolveAgentModelOverride precedence chain) was extracted into the
  1591. // shipped gsd-core/bin/lib/install-model-override-resolver.cjs, mirroring
  1592. // install-effort-resolver.cjs's existing #2071 precedent, so the descriptor-
  1593. // driven agents pipeline (runtime-artifact-layout.cts's convertedAgentsKind)
  1594. // and this installer resolve model_overrides / model_profile_overrides
  1595. // through the SAME code — a single source of truth for the precedence chain
  1596. // the inline agent loop below used to duplicate across ~24 lines per runtime
  1597. // (kilo, opencode). See install-model-override-resolver.cts's module doc.
  1598. const {
  1599. readGsdEffectiveModelOverrides,
  1600. readGsdRuntimeProfileResolver,
  1601. resolveAgentModelOverride,
  1602. } = require(path.join(_gsdLibDir, 'install-model-override-resolver.cjs'));
  1603. // #2875 Part 2: effort frontmatter injection moved to runtimeArtifactConversion
  1604. // (single source of truth with the descriptor pipeline's
  1605. // applyAgentFrontmatterExtensions step, which now also owns disallowedTools
  1606. // injection + the read-only agent deny-list internally — see its module doc
  1607. // in src/runtime-artifact-conversion.cts). injectEffortFrontmatter used to be
  1608. // re-bound here purely to stay on this module's export surface; #2876 found
  1609. // no install.js internal caller either (tests import it directly from
  1610. // gsd-core/bin/lib/runtime-artifact-conversion.cjs) and retired the binding.
  1611. // Cache for attribution settings (populated once per runtime during install)
  1612. const attributionCache = new Map();
  1613. /**
  1614. * Get commit attribution setting for a runtime
  1615. * @param {string} runtime - 'claude', 'opencode', 'codex', or 'copilot'
  1616. * @returns {null|undefined|string} null = remove, undefined = keep default, string = custom
  1617. */
  1618. function getCommitAttribution(runtime) {
  1619. // Return cached value if available
  1620. if (attributionCache.has(runtime)) {
  1621. return attributionCache.get(runtime);
  1622. }
  1623. let result;
  1624. const _attrResolverKey = hostBehaviorsFor(runtime).attributionConfigResolver;
  1625. if (_attrResolverKey && ATTRIBUTION_CONFIG_RESOLVERS[_attrResolverKey]) {
  1626. const resolveConfigPath = ATTRIBUTION_CONFIG_RESOLVERS[_attrResolverKey];
  1627. const config = readSettings(resolveConfigPath(getGlobalConfigDir(runtime, null)));
  1628. result = (config && config.disable_ai_attribution === true) ? null : undefined;
  1629. } else if (hostBehaviorsFor(runtime).attributionSource === 'settings-json-commit') {
  1630. // Claude Code
  1631. const settings = readSettings(path.join(getGlobalConfigDir(runtime, explicitConfigDir), 'settings.json'));
  1632. if (!settings || !settings.attribution || settings.attribution.commit === undefined) {
  1633. result = undefined;
  1634. } else if (settings.attribution.commit === '') {
  1635. result = null;
  1636. } else {
  1637. result = settings.attribution.commit;
  1638. }
  1639. } else {
  1640. // Codex and Copilot currently have no attribution setting equivalent
  1641. result = undefined;
  1642. }
  1643. // Cache and return
  1644. attributionCache.set(runtime, result);
  1645. return result;
  1646. }
  1647. // processAttribution (pure Co-Authored-By content transform) relocated to
  1648. // runtime-artifact-conversion.cjs (ADR-1508 / #1510 Phase 1); bound above.
  1649. // getCommitAttribution stays here — it is impure install-time config I/O.
  1650. /**
  1651. * Convert Claude Code frontmatter to opencode format
  1652. * - Converts 'allowed-tools:' array to 'permission:' object
  1653. * @param {string} content - Markdown file content with YAML frontmatter
  1654. * @returns {string} - Content with converted frontmatter
  1655. */
  1656. // Color name to hex mapping for opencode compatibility
  1657. const colorNameToHex = {
  1658. cyan: '#00FFFF',
  1659. red: '#FF0000',
  1660. green: '#00FF00',
  1661. blue: '#0000FF',
  1662. yellow: '#FFFF00',
  1663. magenta: '#FF00FF',
  1664. orange: '#FFA500',
  1665. purple: '#800080',
  1666. pink: '#FFC0CB',
  1667. white: '#FFFFFF',
  1668. black: '#000000',
  1669. gray: '#808080',
  1670. grey: '#808080',
  1671. };
  1672. // Tool name mapping from Claude Code to OpenCode
  1673. // OpenCode uses lowercase tool names; special mappings for renamed tools
  1674. const claudeToOpencodeTools = {
  1675. AskUserQuestion: 'question',
  1676. SlashCommand: 'skill',
  1677. TodoWrite: 'todowrite',
  1678. WebFetch: 'webfetch',
  1679. WebSearch: 'websearch', // Plugin/MCP - keep for compatibility
  1680. };
  1681. // Tool name mapping from Claude Code to Antigravity
  1682. // Antigravity uses Gemini's snake_case built-in tool names
  1683. const claudeToAntigravityTools = {
  1684. // #4705: Antigravity-NATIVE tool names (see src/runtime-artifact-conversion.cts)
  1685. Read: 'view_file',
  1686. Write: 'write_to_file',
  1687. Edit: 'replace_file_content',
  1688. Bash: 'run_command',
  1689. Glob: 'find_by_name',
  1690. Grep: 'grep_search',
  1691. WebSearch: 'search_web',
  1692. WebFetch: 'read_url_content',
  1693. }
  1694. // Tool name mapping from Claude/GSD agents to Kimi CLI module paths.
  1695. // Kimi custom agent YAML requires fully-qualified module paths.
  1696. const claudeToKimiTools = {
  1697. Read: 'kimi_cli.tools.file:ReadFile',
  1698. ReadFile: 'kimi_cli.tools.file:ReadFile',
  1699. Write: 'kimi_cli.tools.file:WriteFile',
  1700. WriteFile: 'kimi_cli.tools.file:WriteFile',
  1701. Edit: 'kimi_cli.tools.file:StrReplaceFile',
  1702. MultiEdit: 'kimi_cli.tools.file:StrReplaceFile',
  1703. StrReplaceFile: 'kimi_cli.tools.file:StrReplaceFile',
  1704. Bash: 'kimi_cli.tools.shell:Shell',
  1705. Shell: 'kimi_cli.tools.shell:Shell',
  1706. Grep: 'kimi_cli.tools.file:Grep',
  1707. Glob: 'kimi_cli.tools.file:Glob',
  1708. Agent: 'kimi_cli.tools.agent:Agent',
  1709. Task: 'kimi_cli.tools.agent:Agent',
  1710. AskUserQuestion: 'kimi_cli.tools.ask_user:AskUserQuestion',
  1711. TodoWrite: 'kimi_cli.tools.todo:SetTodoList',
  1712. SetTodoList: 'kimi_cli.tools.todo:SetTodoList',
  1713. WebSearch: 'kimi_cli.tools.web:SearchWeb',
  1714. SearchWeb: 'kimi_cli.tools.web:SearchWeb',
  1715. WebFetch: 'kimi_cli.tools.web:FetchURL',
  1716. FetchURL: 'kimi_cli.tools.web:FetchURL',
  1717. ReadMediaFile: 'kimi_cli.tools.file:ReadMediaFile',
  1718. TaskList: 'kimi_cli.tools.background:TaskList',
  1719. TaskOutput: 'kimi_cli.tools.background:TaskOutput',
  1720. TaskStop: 'kimi_cli.tools.background:TaskStop',
  1721. };
  1722. /**
  1723. * Convert a Claude Code tool name to OpenCode format
  1724. * - Applies special mappings (AskUserQuestion -> question, etc.)
  1725. * - Converts to lowercase (except MCP tools which keep their format)
  1726. */
  1727. function convertToolName(claudeTool) {
  1728. // Check for special mapping first
  1729. if (claudeToOpencodeTools[claudeTool]) {
  1730. return claudeToOpencodeTools[claudeTool];
  1731. }
  1732. // MCP tools (mcp__*) keep their format
  1733. if (claudeTool.startsWith('mcp__')) {
  1734. return claudeTool;
  1735. }
  1736. // Default: convert to lowercase
  1737. return claudeTool.toLowerCase();
  1738. }
  1739. /**
  1740. * Convert a Claude Code tool name to Antigravity format
  1741. * - Applies Claude→Antigravity mapping (Read→read_file, Bash→run_shell_command, etc.)
  1742. * - Filters out MCP tools (mcp__*) — they are auto-discovered at runtime in Antigravity
  1743. * - Filters out Task/Agent — agents are auto-registered as tools in Antigravity
  1744. * @returns {string|null} Antigravity tool name, or null if tool should be excluded
  1745. */
  1746. function convertAntigravityToolName(claudeTool) {
  1747. // MCP tools: exclude — auto-discovered from mcpServers config at runtime
  1748. if (claudeTool.startsWith('mcp__')) {
  1749. return null;
  1750. }
  1751. // Task/Agent: exclude — agents are auto-registered as callable tools.
  1752. // AskUserQuestion: exclude — Antigravity (Gemini tool dialect) does not expose
  1753. // an ask_user tool; emitting it causes frontmatter validation errors (#3362).
  1754. // Skill/SlashCommand: exclude — Antigravity (Gemini tool dialect) has no 'skill'
  1755. // built-in tool; the lowercase fallback would emit an invalid
  1756. // 'skill'/'slashcommand' name that fails frontmatter validation
  1757. // (tools.N: Invalid tool name) and aborts the entire agent load (#1394).
  1758. // TodoWrite: exclude — agy 1.3.5 registers no todo tool, and an unknown name
  1759. // stops the agent from starting (#5447).
  1760. if (
  1761. claudeTool === 'Task' ||
  1762. claudeTool === 'Agent' ||
  1763. claudeTool === 'AskUserQuestion' ||
  1764. claudeTool === 'ask_user' ||
  1765. claudeTool === 'Skill' ||
  1766. claudeTool === 'SlashCommand' ||
  1767. claudeTool === 'TodoWrite'
  1768. ) {
  1769. return null;
  1770. }
  1771. // Check for explicit mapping
  1772. if (claudeToAntigravityTools[claudeTool]) {
  1773. return claudeToAntigravityTools[claudeTool];
  1774. }
  1775. // Default: lowercase
  1776. return claudeTool.toLowerCase();
  1777. }
  1778. function createKimiToolDiagnostic(reason, tool, source = null) {
  1779. const isMcp = reason === 'mcp_managed';
  1780. return {
  1781. level: 'warning',
  1782. code: isMcp ? 'kimi_mcp_tool_excluded' : 'kimi_unsupported_tool',
  1783. reason,
  1784. message: isMcp
  1785. ? `MCP-managed tool '${tool}' is configured outside Kimi agent YAML.`
  1786. : `Tool '${tool}' is not supported by the Kimi tool mapper.`,
  1787. value: tool,
  1788. source,
  1789. };
  1790. }
  1791. /**
  1792. * Convert a Claude/GSD tool name to a Kimi CLI module path.
  1793. * @returns {string|null} Kimi module path, or null when excluded/unsupported.
  1794. */
  1795. function convertKimiToolName(claudeTool) {
  1796. const tool = String(claudeTool || '').trim();
  1797. if (!tool) return null;
  1798. if (tool.startsWith('mcp__')) return null;
  1799. return claudeToKimiTools[tool] || null;
  1800. }
  1801. function mapClaudeToolsToKimiTools(claudeTools, options = {}) {
  1802. const diagnostics = [];
  1803. const tools = [];
  1804. const seen = new Set();
  1805. const source = options && Object.prototype.hasOwnProperty.call(options, 'source')
  1806. ? options.source
  1807. : null;
  1808. for (const rawTool of Array.isArray(claudeTools) ? claudeTools : []) {
  1809. const tool = String(rawTool || '').trim();
  1810. if (!tool) continue;
  1811. if (tool.startsWith('mcp__')) {
  1812. diagnostics.push(createKimiToolDiagnostic('mcp_managed', tool, source));
  1813. continue;
  1814. }
  1815. const kimiTool = convertKimiToolName(tool);
  1816. if (!kimiTool) {
  1817. diagnostics.push(createKimiToolDiagnostic('unsupported_tool', tool, source));
  1818. continue;
  1819. }
  1820. if (!seen.has(kimiTool)) {
  1821. seen.add(kimiTool);
  1822. tools.push(kimiTool);
  1823. }
  1824. }
  1825. return { tools, diagnostics };
  1826. }
  1827. const claudeToKiloAgentPermissions = {
  1828. Read: 'read',
  1829. Write: 'edit',
  1830. Edit: 'edit',
  1831. Bash: 'bash',
  1832. Grep: 'grep',
  1833. Glob: 'glob',
  1834. Task: 'task',
  1835. WebFetch: 'webfetch',
  1836. WebSearch: 'websearch',
  1837. TodoWrite: 'todowrite',
  1838. AskUserQuestion: 'question',
  1839. SlashCommand: 'skill',
  1840. };
  1841. const kiloAgentPermissionOrder = [
  1842. 'read',
  1843. 'edit',
  1844. 'bash',
  1845. 'grep',
  1846. 'glob',
  1847. 'task',
  1848. 'webfetch',
  1849. 'websearch',
  1850. 'skill',
  1851. 'question',
  1852. 'todowrite',
  1853. 'list',
  1854. 'codesearch',
  1855. 'lsp',
  1856. ];
  1857. const kiloMcpPermissionPattern = /^mcp__([A-Za-z0-9_-]+)__((?:[A-Za-z0-9_-]+)|\*)$/;
  1858. // Derives Kilo's native `{server}_{tool}` MCP permission key (kilo.ai/docs —
  1859. // external, fixed format). Not injective: both capture groups allow `_`, so
  1860. // e.g. `mcp__a_b__c` and `mcp__a__b_c` derive the same key. The `Set` below
  1861. // resolves any such collision deterministically to first-seen-wins — see
  1862. // src/runtime-artifact-conversion.cts's regression test. Mirrors that file's
  1863. // convertClaudeToKiloPermissionTool exactly (#4032).
  1864. function convertClaudeToKiloPermissionTool(claudeTool) {
  1865. const builtinPermission = claudeToKiloAgentPermissions[claudeTool];
  1866. if (builtinPermission) return builtinPermission;
  1867. const mcpPermission = kiloMcpPermissionPattern.exec(claudeTool);
  1868. return mcpPermission ? `${mcpPermission[1]}_${mcpPermission[2]}` : null;
  1869. }
  1870. function buildKiloAgentPermissionBlock(claudeTools) {
  1871. const allowedPermissions = new Set();
  1872. for (const tool of claudeTools) {
  1873. const mapped = convertClaudeToKiloPermissionTool(tool);
  1874. if (mapped) {
  1875. allowedPermissions.add(mapped);
  1876. }
  1877. }
  1878. const lines = ['permission:'];
  1879. for (const permission of kiloAgentPermissionOrder) {
  1880. lines.push(` ${permission}: ${allowedPermissions.has(permission) ? 'allow' : 'deny'}`);
  1881. }
  1882. for (const permission of allowedPermissions) {
  1883. if (kiloAgentPermissionOrder.includes(permission)) continue;
  1884. lines.push(` ${permission}: allow`);
  1885. }
  1886. return lines;
  1887. }
  1888. function replaceRelativePathReference(content, fromPath, toPath) {
  1889. const escapedPath = escapeRegExp(fromPath);
  1890. return content.replace(
  1891. new RegExp(`(^|[^A-Za-z0-9_./-])${escapedPath}`, 'g'),
  1892. (_, prefix) => `${prefix}${toPath}`,
  1893. );
  1894. }
  1895. /**
  1896. * Convert a Claude Code tool name to GitHub Copilot format.
  1897. * - Applies explicit mapping from claudeToCopilotTools
  1898. * - Handles mcp__context7__* prefix → io.github.upstash/context7/*
  1899. * - Falls back to lowercase for unknown tools
  1900. */
  1901. function convertCopilotToolName(claudeTool) {
  1902. // mcp__context7__* wildcard → io.github.upstash/context7/*
  1903. if (claudeTool.startsWith('mcp__context7__')) {
  1904. return 'io.github.upstash/context7/' + claudeTool.slice('mcp__context7__'.length);
  1905. }
  1906. // Check explicit mapping
  1907. if (claudeToCopilotTools[claudeTool]) {
  1908. return claudeToCopilotTools[claudeTool];
  1909. }
  1910. // mcp__{tavily,ref,jina,exa,firecrawl}__* use the generic MCP passthrough like exa/firecrawl;
  1911. // add explicit Copilot registry mappings when the io.github ids are confirmed (#657 follow-up)
  1912. // Default: lowercase
  1913. return claudeTool.toLowerCase();
  1914. }
  1915. /**
  1916. * Apply Copilot-specific content conversion — CONV-06 (paths) + CONV-07 (command names).
  1917. * Path mappings depend on install mode:
  1918. * Global: ~/.claude/ → ~/.copilot/, ./.claude/ → ./.github/
  1919. * Local: ~/.claude/ → ./.github/, ./.claude/ → ./.github/
  1920. * Applied to ALL Copilot content (skills, agents, engine files).
  1921. * @param {string} content - Source content to convert
  1922. * @param {boolean} [isGlobal=false] - Whether this is a global install
  1923. */
  1924. function convertClaudeToCopilotContent(content, isGlobal = false) {
  1925. let c = content;
  1926. // CONV-06: Path replacement — most specific first to avoid substring matches.
  1927. // Handle both `~/.claude/foo` (trailing slash) and bare `~/.claude` forms in
  1928. // one pass via a capture group, matching the approach used by Antigravity,
  1929. // OpenCode, Kilo, and Codex converters (issue #2545).
  1930. if (isGlobal) {
  1931. c = c.replace(/\$HOME\/\.claude(\/|\b)/g, '$HOME/.copilot$1');
  1932. c = c.replace(/~\/\.claude(\/|\b)/g, '~/.copilot$1');
  1933. } else {
  1934. c = c.replace(/\$HOME\/\.claude\//g, '.github/');
  1935. c = c.replace(/~\/\.claude\//g, '.github/');
  1936. c = c.replace(/\$HOME\/\.claude\b/g, '.github');
  1937. c = c.replace(/~\/\.claude\b/g, '.github');
  1938. }
  1939. c = c.replace(/\.\/\.claude\//g, './.github/');
  1940. c = c.replace(/\.claude\//g, '.github/');
  1941. // CONV-07: Command name conversion (all gsd: references → gsd-)
  1942. c = c.replace(/gsd:/g, 'gsd-');
  1943. // Runtime-neutral agent name replacement (#766)
  1944. c = neutralizeAgentReferences(c, 'copilot-instructions.md');
  1945. return c;
  1946. }
  1947. // isGlobal is the 5th positional arg (3rd/4th are runtime/cmdNames passed by the skills wrapper). See runtime-artifact-layout skillsKind.
  1948. /**
  1949. * Convert a Claude command (.md) to a Copilot skill (SKILL.md).
  1950. * Transforms frontmatter only — body passes through with CONV-06/07 applied.
  1951. * Skills keep original tool names (no mapping) per CONTEXT.md decision.
  1952. */
  1953. function convertClaudeCommandToCopilotSkill(content, skillName, _runtime = null, _cmdNames = null, isGlobal = false) {
  1954. const converted = convertClaudeToCopilotContent(content, isGlobal);
  1955. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  1956. if (!frontmatter) return converted;
  1957. const description = extractFrontmatterField(frontmatter, 'description') || '';
  1958. const argumentHint = extractFrontmatterField(frontmatter, 'argument-hint');
  1959. const agent = extractFrontmatterField(frontmatter, 'agent');
  1960. // CONV-02: Extract allowed-tools YAML multiline list → comma-separated string
  1961. const toolsMatch = frontmatter.match(/^allowed-tools:\s*\n((?:\s+-\s+.+\n?)*)/m);
  1962. let toolsLine = '';
  1963. if (toolsMatch) {
  1964. const tools = toolsMatch[1].match(/^\s+-\s+(.+)/gm);
  1965. if (tools) {
  1966. toolsLine = tools.map(t => t.replace(/^\s+-\s+/, '').trim()).join(', ');
  1967. }
  1968. }
  1969. // Reconstruct frontmatter in Copilot format
  1970. // #2876: descriptions starting with a YAML flow indicator (`[BETA] …`,
  1971. // `{ … }`, `*ref`, `&anchor`, etc.) parse as flow sequences/mappings and
  1972. // crash gh-copilot's frontmatter loader. Always quote so any leading
  1973. // character is parser-safe.
  1974. let fm = `---\nname: ${skillName}\ndescription: ${yamlQuote(description)}\n`;
  1975. if (argumentHint) fm += `argument-hint: ${yamlQuote(argumentHint)}\n`;
  1976. if (agent) fm += `agent: ${agent}\n`;
  1977. if (toolsLine) fm += `allowed-tools: ${toolsLine}\n`;
  1978. fm += '---';
  1979. return `${fm}\n${body}`;
  1980. }
  1981. /**
  1982. * Map a skill directory name (gsd-<cmd>) to the frontmatter `name:` used
  1983. * by Claude Code as the skill identity. Emits the hyphen form (gsd-<cmd>)
  1984. * so Claude Code autocomplete shows the canonical invocation form, not the
  1985. * deprecated colon form. See #2808.
  1986. *
  1987. * Historical note: this previously returned `gsd:<cmd>` (colon) because
  1988. * workflows called Skill(skill="gsd:<cmd>"). Those calls have been updated
  1989. * to use hyphen form (#2808) so the colon rewrite is no longer needed.
  1990. *
  1991. * Codex must NOT use this helper: its adapter invokes skills as `$gsd-<cmd>`
  1992. * (shell-var syntax) — hyphen form is already correct there.
  1993. */
  1994. function skillFrontmatterName(skillDirName) {
  1995. if (typeof skillDirName !== 'string') return skillDirName;
  1996. // Return the hyphen form as-is (gsd-<cmd>) — canonical since #2808.
  1997. return skillDirName;
  1998. }
  1999. /**
  2000. * Qwen Code skills accept an optional numeric `priority` frontmatter field.
  2001. * Per the Qwen skills spec (qwen-code/docs/users/features/skills.md, verified
  2002. * #778): HIGHER values sort EARLIER in the `/skills` TUI listing (omitted ≈ 0;
  2003. * negatives sort below unset). It affects ONLY the `/skills` list order —
  2004. * slash-command completion and the `/help` view stay alphabetical.
  2005. *
  2006. * We assign descending priorities to GSD's main-loop commands so the most-used
  2007. * workflow skills surface first; utility skills are deliberately left unset
  2008. * (default 0) and sort below.
  2009. *
  2010. * NOTE: the #778 issue body proposed the INVERSE numbering (plan-phase: 10,
  2011. * utilities: 90+). The verified spec shows that would BURY the core loop below
  2012. * utilities, so we implement the spec-correct direction (core = high) instead.
  2013. * Keyed by command stem (skill dir is `gsd-<stem>`).
  2014. */
  2015. const QWEN_SKILL_PRIORITY = Object.freeze({
  2016. 'new-project': 100,
  2017. 'discuss-phase': 95,
  2018. 'plan-phase': 90,
  2019. 'execute-phase': 85,
  2020. progress: 80,
  2021. 'verify-work': 75,
  2022. phase: 70,
  2023. review: 65,
  2024. ship: 60,
  2025. config: 55,
  2026. surface: 50,
  2027. 'resume-work': 45,
  2028. 'pause-work': 40,
  2029. help: 35,
  2030. update: 30,
  2031. });
  2032. /**
  2033. * Convert a Claude command (.md) to a Claude skill (SKILL.md).
  2034. * Claude Code is the native format, so minimal conversion needed —
  2035. * preserve allowed-tools as YAML multiline list, preserve argument-hint.
  2036. * Emits `name: gsd-<cmd>` (hyphen) so Skill(skill="gsd-<cmd>") calls and
  2037. * tab autocomplete use the canonical command namespace.
  2038. */
  2039. function convertClaudeCommandToClaudeSkill(content, skillName, runtime = null, cmdNames = null) {
  2040. const { frontmatter, body } = extractFrontmatterAndBody(content);
  2041. if (!frontmatter) return content;
  2042. // #3583: rewrite any /gsd:<cmd> or gsd:<cmd> in the body to the canonical
  2043. // hyphen form (gsd-<cmd>) so installed SKILL.md bodies match the hyphen
  2044. // `name:` Claude Code (and Qwen/Hermes) register under (#2808). `cmdNames`
  2045. // is optional and pre-computed by the caller for performance; direct test
  2046. // calls fall back to reading the list.
  2047. const names = cmdNames || readGsdCommandNames();
  2048. const normalizedBody = transformContentToHyphen(body, names);
  2049. // #4324: the description is the text the host's skill picker renders, so it
  2050. // needs the same hyphen normalisation the body gets — otherwise a `/gsd:<cmd>`
  2051. // mention in a command description ships the retired colon form to the user.
  2052. const description = transformContentToHyphen(
  2053. extractFrontmatterField(frontmatter, 'description') || '', names,
  2054. );
  2055. const argumentHint = extractFrontmatterField(frontmatter, 'argument-hint');
  2056. const agent = extractFrontmatterField(frontmatter, 'agent');
  2057. // #769: preserve context: from source command files so it is emitted into
  2058. // the installed SKILL.md frontmatter unchanged. (#3151: effort: is no longer
  2059. // emitted into skill frontmatter — a static effort value invalidates the
  2060. // caller's prompt cache at both scope boundaries.)
  2061. const context = extractFrontmatterField(frontmatter, 'context');
  2062. // Preserve allowed-tools as YAML multiline list (Claude native format)
  2063. const toolsMatch = frontmatter.match(/^allowed-tools:\s*\n((?:\s+-\s+.+\n?)*)/m);
  2064. let toolsBlock = '';
  2065. if (toolsMatch) {
  2066. toolsBlock = 'allowed-tools:\n' + toolsMatch[1];
  2067. // Ensure trailing newline
  2068. if (!toolsBlock.endsWith('\n')) toolsBlock += '\n';
  2069. }
  2070. // Reconstruct frontmatter in Claude skill format
  2071. const frontmatterName = skillFrontmatterName(skillName);
  2072. let fm = `---\nname: ${frontmatterName}\ndescription: ${yamlQuote(description)}\n`;
  2073. // Hermes' SKILL.md spec lists `version` as a required frontmatter field.
  2074. // Track GSD's package version so Hermes' skill_view() reports a stable
  2075. // identifier per install.
  2076. if (hostBehaviorsFor(runtime).skillFrontmatterVersion) fm += `version: ${yamlQuote(pkg.version)}\n`;
  2077. // #778 (b) — numeric priority for /skills ordering, declared on the runtime
  2078. // descriptor (runtime.hostBehaviors.skillPriorityFrontmatter). Scoped to
  2079. // runtimes that declare the flag so Claude/Hermes skill frontmatter is
  2080. // unchanged (they ignore the field, but we keep their output byte-stable).
  2081. // skillName is the `gsd-<stem>` dir name. (ADR-1239 / #2086)
  2082. if (hostBehaviorsFor(runtime).skillPriorityFrontmatter) {
  2083. const stem = typeof skillName === 'string' && skillName.startsWith('gsd-')
  2084. ? skillName.slice(4)
  2085. : skillName;
  2086. const priority = Object.prototype.hasOwnProperty.call(QWEN_SKILL_PRIORITY, stem)
  2087. ? QWEN_SKILL_PRIORITY[stem]
  2088. : undefined;
  2089. if (typeof priority === 'number') fm += `priority: ${priority}\n`;
  2090. }
  2091. if (argumentHint) fm += `argument-hint: ${yamlQuote(argumentHint)}\n`;
  2092. if (agent) fm += `agent: ${agent}\n`;
  2093. // #769: emit context: when present so the runtime can honour it natively
  2094. // (context: fork = isolated subagent window). Claude-specific; unknown
  2095. // frontmatter fields are silently ignored by other runtimes (backward-compatible).
  2096. // (#3151: effort: is intentionally NOT emitted into skill frontmatter — a
  2097. // static effort value changes output_config.effort on invocation and
  2098. // invalidates the caller's prompt cache at both scope boundaries.)
  2099. if (context) fm += `context: ${context}\n`;
  2100. if (toolsBlock) fm += toolsBlock;
  2101. fm += '---';
  2102. return `${fm}\n${normalizedBody}`;
  2103. }
  2104. function normalizeKimiSkillName(skillName) {
  2105. let text = String(skillName || '').trim().toLowerCase();
  2106. if (text.startsWith('/')) text = text.slice(1);
  2107. if (text.startsWith('$')) text = text.slice(1);
  2108. text = text.replace(/^gsd:/, 'gsd-');
  2109. if (!text.startsWith('gsd-')) text = `gsd-${text}`;
  2110. text = text.replace(/[^a-z0-9-]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
  2111. return text || 'gsd-command';
  2112. }
  2113. function convertGsdCommandReferencesToKimiSkillInvocations(content, cmdNames) {
  2114. if (!Array.isArray(cmdNames) || cmdNames.length === 0) return content;
  2115. const commands = [...cmdNames].sort((a, b) => b.length - a.length).map(escapeRegExp);
  2116. const commandGroup = commands.join('|');
  2117. const colonPattern = new RegExp(`(?<![A-Za-z0-9_/:.-])/?gsd:(${commandGroup})(?=[^A-Za-z0-9_-]|$)`, 'g');
  2118. const hyphenPattern = new RegExp(`(?:/|\\$)gsd-(${commandGroup})(?=[^A-Za-z0-9_-]|$)`, 'g');
  2119. return content
  2120. .replace(colonPattern, (_, cmd) => `/skill:gsd-${cmd}`)
  2121. .replace(hyphenPattern, (_, cmd) => `/skill:gsd-${cmd}`);
  2122. }
  2123. // DEFECT.GENERATIVE-FIX: this body is mirrored in
  2124. // src/runtime-artifact-conversion.cts's convertClaudeCommandToKimiSkill (dead
  2125. // for the live skills-install path, which routes here via
  2126. // install-engine.cts's SKILLS_CONVERTER_REGISTRY through the kimi capability
  2127. // descriptor's artifactLayout `converter: "convertClaudeCommandToKimiSkill"`;
  2128. // kept for bin/install.js's own module-level export/test surface). Neither
  2129. // copy re-exports the other — mirror any behavior change into both. Guarded
  2130. // by the output-parity test in tests/runtime-converters.test.cjs (#2095).
  2131. function convertClaudeCommandToKimiSkill(content, skillName, _runtime = null, cmdNames = null) {
  2132. const { frontmatter, body } = extractFrontmatterAndBody(content);
  2133. const kimiSkillName = normalizeKimiSkillName(skillName);
  2134. const names = cmdNames || readGsdCommandNames();
  2135. const description = frontmatter
  2136. ? extractFrontmatterField(frontmatter, 'description') || `Run GSD workflow ${kimiSkillName}.`
  2137. : `Run GSD workflow ${kimiSkillName}.`;
  2138. const normalizedBody = convertGsdCommandReferencesToKimiSkillInvocations(
  2139. frontmatter ? body : content,
  2140. names
  2141. );
  2142. return `---\nname: ${kimiSkillName}\ndescription: ${yamlQuote(toSingleLine(description))}\n---\nInvoke this Kimi skill with \`/skill:${kimiSkillName}\`.\n\n${normalizedBody}`;
  2143. }
  2144. const KIMI_CANONICAL_GSD_AGENT_RE = /^gsd-[a-z0-9-]+$/;
  2145. function parseKimiAgentSource(source) {
  2146. if (typeof source === 'string') {
  2147. return {
  2148. path: null,
  2149. content: source,
  2150. };
  2151. }
  2152. if (!source || typeof source !== 'object' || typeof source.content !== 'string') {
  2153. return null;
  2154. }
  2155. return {
  2156. path: typeof source.path === 'string' ? source.path : null,
  2157. content: source.content,
  2158. };
  2159. }
  2160. // #5447: the tools list is read by the compiled module's parser (quoted entries,
  2161. // `#` comments, inline and block lists), the one the runtime pipeline uses, so this
  2162. // copy of the Antigravity and Kimi converters cannot diverge from it.
  2163. function parseFrontmatterTools(frontmatter) {
  2164. return runtimeArtifactConversion.parseFrontmatterTools(frontmatter);
  2165. }
  2166. function addKimiAgentDiagnostic(diagnostics, code, message, value, source = null) {
  2167. diagnostics.push({
  2168. level: 'warning',
  2169. code,
  2170. message,
  2171. value,
  2172. source,
  2173. });
  2174. }
  2175. function mapKimiAgentContractTools(toolNames, diagnostics, sourceName) {
  2176. const result = mapClaudeToolsToKimiTools(toolNames, { source: sourceName });
  2177. diagnostics.push(...result.diagnostics);
  2178. return result.tools;
  2179. }
  2180. function neutralizeKimiAgentPrompt(content) {
  2181. const { frontmatter, body } = extractFrontmatterAndBody(content);
  2182. let prompt = frontmatter ? body : content;
  2183. prompt = neutralizeAgentReferences(prompt, 'AGENTS.md');
  2184. prompt = prompt.replace(/~\/\.claude\/gsd-core\b/g, 'GSD core');
  2185. prompt = prompt.replace(/\$HOME\/\.claude\/gsd-core\b/g, 'GSD core');
  2186. return prompt.replace(/^\s*\r?\n/, '');
  2187. }
  2188. function pushKimiToolsYaml(lines, indent, tools) {
  2189. const prefix = ' '.repeat(indent);
  2190. if (!Array.isArray(tools) || tools.length === 0) {
  2191. lines.push(`${prefix}tools: []`);
  2192. return;
  2193. }
  2194. lines.push(`${prefix}tools:`);
  2195. for (const tool of tools) {
  2196. lines.push(`${prefix} - ${yamlQuote(tool)}`);
  2197. }
  2198. }
  2199. function buildKimiRootAgentYaml({ description, tools, subagents }) {
  2200. const lines = [
  2201. 'version: 1',
  2202. 'agent:',
  2203. ' name: gsd',
  2204. ` description: ${yamlQuote(toSingleLine(description || 'Run GSD workflows in Kimi CLI.'))}`,
  2205. ' extend: default',
  2206. ' system_prompt_path: ./gsd.md',
  2207. ];
  2208. pushKimiToolsYaml(lines, 2, tools);
  2209. if (subagents.length > 0) {
  2210. lines.push(' subagents:');
  2211. for (const subagent of subagents) {
  2212. lines.push(` ${subagent.name}:`);
  2213. lines.push(` path: ./subagents/${subagent.name}.yaml`);
  2214. lines.push(` description: ${yamlQuote(toSingleLine(subagent.description))}`);
  2215. }
  2216. }
  2217. return `${lines.join('\n')}\n`;
  2218. }
  2219. function buildKimiSubagentYaml({ name, description, tools }) {
  2220. const lines = [
  2221. 'version: 1',
  2222. 'agent:',
  2223. ` name: ${name}`,
  2224. ` description: ${yamlQuote(toSingleLine(description || `Run ${name}.`))}`,
  2225. ` system_prompt_path: ./${name}.md`,
  2226. ];
  2227. pushKimiToolsYaml(lines, 2, tools);
  2228. return `${lines.join('\n')}\n`;
  2229. }
  2230. // DEFECT.GENERATIVE-FIX: this body is mirrored in
  2231. // src/runtime-artifact-conversion.cts's buildKimiAgentArtifacts (dead for the
  2232. // live install path, which routes here via runtime-artifact-layout.cts's
  2233. // kimiAgentsKind — see its `conversionExports['buildKimiAgentArtifacts']`
  2234. // dynamic lookup against the compiled runtime-artifact-conversion.cjs; kept
  2235. // for bin/install.js's own module-level export/test surface). Neither copy
  2236. // re-exports the other — mirror any behavior change into both, including the
  2237. // kimi_cli.tools.agent:Agent grant that enables background dispatch
  2238. // (#2095 Upgrade 2). Guarded by the output-parity test in
  2239. // tests/runtime-converters.test.cjs (#2095).
  2240. function buildKimiAgentArtifacts({
  2241. rootAgent = '',
  2242. subagents = [],
  2243. requestedSubagents = null,
  2244. } = {}) {
  2245. const diagnostics = [];
  2246. const rootSource = parseKimiAgentSource(rootAgent) || { path: null, content: '' };
  2247. const { frontmatter: rootFrontmatter } = extractFrontmatterAndBody(rootSource.content);
  2248. const rootDescription = rootFrontmatter
  2249. ? extractFrontmatterField(rootFrontmatter, 'description') || 'Run GSD workflows in Kimi CLI.'
  2250. : 'Run GSD workflows in Kimi CLI.';
  2251. const subagentSources = Array.isArray(subagents) ? subagents : [];
  2252. if (!Array.isArray(subagents)) {
  2253. addKimiAgentDiagnostic(
  2254. diagnostics,
  2255. 'kimi_unsupported_subagents_input',
  2256. 'Subagents input must be an array of Markdown strings or source objects.',
  2257. typeof subagents,
  2258. null
  2259. );
  2260. }
  2261. const subagentMap = new Map();
  2262. for (const source of subagentSources) {
  2263. const parsed = parseKimiAgentSource(source);
  2264. if (!parsed) {
  2265. addKimiAgentDiagnostic(
  2266. diagnostics,
  2267. 'kimi_unsupported_subagent_input',
  2268. 'Subagent source must be a Markdown string or an object with content.',
  2269. typeof source,
  2270. null
  2271. );
  2272. continue;
  2273. }
  2274. const { frontmatter } = extractFrontmatterAndBody(parsed.content);
  2275. const fallbackName = parsed.path ? path.basename(parsed.path, path.extname(parsed.path)) : null;
  2276. const name = frontmatter
  2277. ? extractFrontmatterField(frontmatter, 'name') || fallbackName
  2278. : fallbackName;
  2279. if (!name || !KIMI_CANONICAL_GSD_AGENT_RE.test(name)) {
  2280. addKimiAgentDiagnostic(
  2281. diagnostics,
  2282. 'kimi_invalid_subagent_name',
  2283. 'Subagent source does not use a canonical gsd-* Kimi agent name.',
  2284. name || '(missing)',
  2285. parsed.path
  2286. );
  2287. continue;
  2288. }
  2289. const description = frontmatter
  2290. ? extractFrontmatterField(frontmatter, 'description') || `Run ${name}.`
  2291. : `Run ${name}.`;
  2292. const tools = mapKimiAgentContractTools(parseFrontmatterTools(frontmatter), diagnostics, name);
  2293. subagentMap.set(name, {
  2294. name,
  2295. description,
  2296. tools,
  2297. prompt: neutralizeKimiAgentPrompt(parsed.content),
  2298. });
  2299. }
  2300. const requested = Array.isArray(requestedSubagents) && requestedSubagents.length > 0
  2301. ? requestedSubagents
  2302. : [...subagentMap.keys()];
  2303. const selectedSubagents = [];
  2304. for (const requestedName of requested) {
  2305. if (subagentMap.has(requestedName)) {
  2306. selectedSubagents.push(subagentMap.get(requestedName));
  2307. continue;
  2308. }
  2309. addKimiAgentDiagnostic(
  2310. diagnostics,
  2311. 'kimi_unknown_subagent',
  2312. 'Requested subagent was not generated and will not be emitted in Kimi YAML.',
  2313. requestedName,
  2314. null
  2315. );
  2316. }
  2317. const rootTools = mapKimiAgentContractTools(parseFrontmatterTools(rootFrontmatter), diagnostics, 'gsd');
  2318. if (selectedSubagents.length > 0 && !rootTools.includes('kimi_cli.tools.agent:Agent')) {
  2319. rootTools.push('kimi_cli.tools.agent:Agent');
  2320. }
  2321. return {
  2322. root: {
  2323. name: 'gsd',
  2324. yamlPath: 'agents/gsd.yaml',
  2325. promptPath: 'agents/gsd.md',
  2326. yaml: buildKimiRootAgentYaml({
  2327. description: rootDescription,
  2328. tools: rootTools,
  2329. subagents: selectedSubagents,
  2330. }),
  2331. prompt: neutralizeKimiAgentPrompt(rootSource.content),
  2332. },
  2333. subagents: selectedSubagents.map((subagent) => ({
  2334. name: subagent.name,
  2335. yamlPath: `agents/subagents/${subagent.name}.yaml`,
  2336. promptPath: `agents/subagents/${subagent.name}.md`,
  2337. yaml: buildKimiSubagentYaml(subagent),
  2338. prompt: subagent.prompt,
  2339. })),
  2340. diagnostics,
  2341. };
  2342. }
  2343. /**
  2344. * Convert a Claude agent (.md) to a Copilot agent (.agent.md).
  2345. * Applies tool mapping + deduplication, formats tools as JSON array.
  2346. * CONV-04: JSON array format. CONV-05: Tool name mapping.
  2347. */
  2348. function convertClaudeAgentToCopilotAgent(content, isGlobal = false) {
  2349. const converted = convertClaudeToCopilotContent(content, isGlobal);
  2350. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  2351. if (!frontmatter) return converted;
  2352. const name = extractFrontmatterField(frontmatter, 'name') || 'unknown';
  2353. const description = extractFrontmatterField(frontmatter, 'description') || '';
  2354. const color = extractFrontmatterField(frontmatter, 'color');
  2355. // CONV-04 + CONV-05: Map tools, deduplicate, format as JSON array.
  2356. // parseFrontmatterTools reads both the inline comma list and the YAML block
  2357. // list (#5790).
  2358. const claudeTools = parseFrontmatterTools(frontmatter);
  2359. const mappedTools = claudeTools.map(t => convertCopilotToolName(t));
  2360. const uniqueTools = [...new Set(mappedTools)];
  2361. const toolsArray = uniqueTools.length > 0
  2362. ? "['" + uniqueTools.join("', '") + "']"
  2363. : '[]';
  2364. // Reconstruct frontmatter in Copilot format. Quote description (#2876)
  2365. // so a leading YAML flow indicator (`[BETA] …`, `{ … }`, etc.) doesn't
  2366. // crash the Copilot frontmatter loader.
  2367. let fm = `---\nname: ${name}\ndescription: ${yamlQuote(description)}\ntools: ${toolsArray}\n`;
  2368. if (color) fm += `color: ${color}\n`;
  2369. fm += '---';
  2370. return `${fm}\n${body}`;
  2371. }
  2372. /**
  2373. * Apply Antigravity-specific content conversion — path replacement + command name conversion.
  2374. * Path mappings depend on install mode:
  2375. * Global: ~/.claude/skills/ → ~/.gemini/config/skills/ (#3738),
  2376. * ~/.claude/ → ~/.gemini/antigravity/, ./.claude/ → ./.agents/
  2377. * Local: ~/.claude/ → .agents/, ./.claude/ → ./.agents/
  2378. * Applied to ALL Antigravity content (skills, agents, engine files).
  2379. * @param {string} content - Source content to convert
  2380. * @param {boolean} [isGlobal=false] - Whether this is a global install
  2381. */
  2382. function convertClaudeToAntigravityContent(content, isGlobal = false) {
  2383. let c = filterRuntimeNotesForTarget(content, 'antigravity');
  2384. if (isGlobal) {
  2385. // #3738: global skills install under ~/.gemini/config/skills (the dir AGY
  2386. // scans for global discovery), so skills-path references must divert there
  2387. // — BEFORE the configHome rewrite below, which is correct for gsd-core
  2388. // runtime-file references (settings, workflows, VERSION) but wrong for the
  2389. // skills dir itself. Mirrors src/runtime-artifact-conversion.cts (ADR-1508
  2390. // keeps bin/install.js hand-authored; the two copies must stay in sync).
  2391. c = c.replace(/\$HOME\/\.claude\/skills\//g, '$HOME/.gemini/config/skills/');
  2392. c = c.replace(/~\/\.claude\/skills\//g, '~/.gemini/config/skills/');
  2393. // Bare skills form (no trailing slash) — must also precede the generic
  2394. // slash rule, which would otherwise divert it to the retired configHome
  2395. // path ($HOME/.gemini/antigravity/skills).
  2396. c = c.replace(/\$HOME\/\.claude\/skills\b/g, '$HOME/.gemini/config/skills');
  2397. c = c.replace(/~\/\.claude\/skills\b/g, '~/.gemini/config/skills');
  2398. c = c.replace(/\$HOME\/\.claude\//g, '$HOME/.gemini/antigravity/');
  2399. c = c.replace(/~\/\.claude\//g, '~/.gemini/antigravity/');
  2400. // Bare form (no trailing slash) — must come after slash form to avoid double-replace
  2401. c = c.replace(/\$HOME\/\.claude\b/g, '$HOME/.gemini/antigravity');
  2402. c = c.replace(/~\/\.claude\b/g, '~/.gemini/antigravity');
  2403. } else {
  2404. c = c.replace(/\$HOME\/\.claude\//g, '.agents/');
  2405. c = c.replace(/~\/\.claude\//g, '.agents/');
  2406. // Bare form (no trailing slash) — must come after slash form to avoid double-replace
  2407. c = c.replace(/\$HOME\/\.claude\b/g, '.agents');
  2408. c = c.replace(/~\/\.claude\b/g, '.agents');
  2409. }
  2410. c = c.replace(/\.\/\.claude\//g, './.agents/');
  2411. c = c.replace(/\.claude\//g, '.agents/');
  2412. // Command name conversion (all gsd: references → gsd-)
  2413. c = c.replace(/gsd:/g, 'gsd-');
  2414. // Runtime-neutral agent name replacement (#766)
  2415. c = neutralizeAgentReferences(c, 'GEMINI.md');
  2416. return c;
  2417. }
  2418. // isGlobal is the 5th positional arg (3rd/4th are runtime/cmdNames passed by the skills wrapper). See runtime-artifact-layout skillsKind.
  2419. /**
  2420. * Convert a Claude command (.md) to an Antigravity skill (SKILL.md).
  2421. * Transforms frontmatter to minimal name + description only.
  2422. * Body passes through with path/command conversions applied.
  2423. */
  2424. function convertClaudeCommandToAntigravitySkill(content, skillName, _runtime = null, _cmdNames = null, isGlobal = false) {
  2425. const converted = convertClaudeToAntigravityContent(content, isGlobal);
  2426. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  2427. if (!frontmatter) return converted;
  2428. const name = skillName || extractFrontmatterField(frontmatter, 'name') || 'unknown';
  2429. const description = extractFrontmatterField(frontmatter, 'description') || '';
  2430. // #2876: quote description so YAML flow indicators in the source
  2431. // (e.g. `[BETA] …`) don't break downstream frontmatter parsers.
  2432. const fm = `---\nname: ${name}\ndescription: ${yamlQuote(description)}\n---`;
  2433. return `${fm}\n${body}`;
  2434. }
  2435. /**
  2436. * Convert a Claude agent (.md) to an Antigravity agent.
  2437. * Uses Gemini tool names since Antigravity runs on Gemini 3 backend.
  2438. */
  2439. function convertClaudeAgentToAntigravityAgent(content, isGlobal = false) {
  2440. const converted = convertClaudeToAntigravityContent(content, isGlobal);
  2441. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  2442. if (!frontmatter) return converted;
  2443. const name = extractFrontmatterField(frontmatter, 'name') || 'unknown';
  2444. const description = extractFrontmatterField(frontmatter, 'description') || '';
  2445. const color = extractFrontmatterField(frontmatter, 'color');
  2446. // Map tools to Antigravity equivalents (reuse existing convertAntigravityToolName).
  2447. // parseFrontmatterTools reads both the inline comma list and the YAML block
  2448. // list (e.g. agents/gsd-security-auditor.md) (#5447).
  2449. const claudeTools = parseFrontmatterTools(frontmatter);
  2450. const mappedTools = claudeTools.map(t => convertAntigravityToolName(t)).filter(Boolean);
  2451. // #2876: quote description for the same reason as the skill variant.
  2452. // #4705: tools is a YAML SEQUENCE of native names (see the src twin).
  2453. const toolsBlock = mappedTools.length > 0
  2454. ? `tools:\n${mappedTools.map((t) => `- ${t}`).join('\n')}\n`
  2455. : 'tools: []\n';
  2456. let fm = `---\nname: ${name}\ndescription: ${yamlQuote(description)}\n${toolsBlock}`;
  2457. if (color) fm += `color: ${color}\n`;
  2458. fm += '---';
  2459. return `${fm}\n${body}`;
  2460. }
  2461. function toSingleLine(value) {
  2462. return value.replace(/\s+/g, ' ').trim();
  2463. }
  2464. function yamlQuote(value) {
  2465. return JSON.stringify(value);
  2466. }
  2467. function yamlIdentifier(value) {
  2468. const text = String(value).trim();
  2469. if (/^[A-Za-z0-9][A-Za-z0-9-]*$/.test(text)) {
  2470. return text;
  2471. }
  2472. return yamlQuote(text);
  2473. }
  2474. // The frontmatter block is the one the one fence owner (`locateFrontmatterFence`) finds, read
  2475. // through the conversion module's reader — never a local `indexOf('---', 3)` scan, which ended
  2476. // the block at the first `---` anywhere, even inside a value (found while implementing #5105).
  2477. function extractFrontmatterAndBody(content) {
  2478. return runtimeArtifactConversion.extractFrontmatterAndBody(content);
  2479. }
  2480. function extractFrontmatterField(frontmatter, fieldName) {
  2481. const regex = new RegExp(`^${fieldName}:\\s*(.+)$`, 'm');
  2482. const match = frontmatter.match(regex);
  2483. if (!match) return null;
  2484. return match[1].trim().replace(/^['"]|['"]$/g, '');
  2485. }
  2486. // Tool name mapping from Claude Code to Cursor CLI
  2487. const claudeToCursorTools = {
  2488. Bash: 'Shell',
  2489. Edit: 'StrReplace',
  2490. AskUserQuestion: null, // No direct equivalent — use conversational prompting
  2491. SlashCommand: null, // No equivalent — skills are auto-discovered
  2492. };
  2493. function convertSlashCommandsToCursorSkillMentions(content) {
  2494. // Keep leading "/" for slash commands; only normalize gsd: -> gsd-.
  2495. // This preserves rendered "next step" commands like "/gsd-execute-phase 17".
  2496. return content.replace(/gsd:/gi, 'gsd-');
  2497. }
  2498. function convertClaudeToCursorMarkdown(content) {
  2499. let converted = convertSlashCommandsToCursorSkillMentions(filterRuntimeNotesForTarget(content, 'cursor'));
  2500. // Replace tool name references in body text
  2501. converted = converted.replace(/\bBash\(/g, 'Shell(');
  2502. converted = converted.replace(/\bEdit\(/g, 'StrReplace(');
  2503. converted = converted.replace(/\bAskUserQuestion\b/g, 'conversational prompting');
  2504. // Replace subagent_type from Claude to Cursor format
  2505. converted = converted.replace(/subagent_type="general-purpose"/g, 'subagent_type="generalPurpose"');
  2506. converted = converted.replace(/\$ARGUMENTS\b/g, '{{GSD_ARGS}}');
  2507. // Replace project-level Claude conventions with Cursor equivalents
  2508. converted = converted.replace(/`\.\/CLAUDE\.md`/g, '`.cursor/rules/`');
  2509. converted = converted.replace(/\.\/CLAUDE\.md/g, '.cursor/rules/');
  2510. converted = converted.replace(/`CLAUDE\.md`/g, '`.cursor/rules/`');
  2511. converted = converted.replace(/\bCLAUDE\.md\b/g, '.cursor/rules/');
  2512. converted = converted.replace(/\.claude\/skills\//g, '.cursor/skills/');
  2513. // Remove Claude Code-specific bug workarounds before brand replacement
  2514. converted = converted.replace(/\*\*Known Claude Code bug \(classifyHandoffIfNeeded\):\*\*[^\n]*\n/g, '');
  2515. converted = converted.replace(/- \*\*classifyHandoffIfNeeded false failure:\*\*[^\n]*\n/g, '');
  2516. // Replace "Claude Code" brand references with "Cursor" — #2284(b): skips
  2517. // <runtime_compatibility> comparison-table content (protected region).
  2518. converted = applyClaudeCodeBrandSwap(converted, 'Cursor');
  2519. return converted;
  2520. }
  2521. function getCursorSkillAdapterHeader(skillName) {
  2522. return `<cursor_skill_adapter>
  2523. ## A. Skill Invocation
  2524. - This skill is invoked when the user mentions \`${skillName}\` or describes a task matching this skill.
  2525. - Treat all user text after the skill mention as \`{{GSD_ARGS}}\`.
  2526. - If no arguments are present, treat \`{{GSD_ARGS}}\` as empty.
  2527. ## B. User Prompting
  2528. When the workflow needs user input, prompt the user conversationally:
  2529. - Present options as a numbered list in your response text
  2530. - Ask the user to reply with their choice
  2531. - For multi-select, ask for comma-separated numbers
  2532. ## C. Tool Usage
  2533. Use these Cursor tools when executing GSD workflows:
  2534. - \`Shell\` for running commands (terminal operations)
  2535. - \`StrReplace\` for editing existing files
  2536. - \`Read\`, \`Write\`, \`Glob\`, \`Grep\`, \`Task\`, \`WebSearch\`, \`WebFetch\`, \`TodoWrite\` as needed
  2537. ## D. Subagent Spawning
  2538. When the workflow needs to spawn a subagent:
  2539. - Use \`Task(subagent_type="generalPurpose", ...)\`
  2540. - The \`model\` parameter maps to Cursor's model options (e.g., "fast")
  2541. </cursor_skill_adapter>`;
  2542. }
  2543. function convertClaudeCommandToCursorSkill(content, skillName) {
  2544. const converted = convertClaudeToCursorMarkdown(content);
  2545. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  2546. let description = `Run GSD workflow ${skillName}.`;
  2547. if (frontmatter) {
  2548. const maybeDescription = extractFrontmatterField(frontmatter, 'description');
  2549. if (maybeDescription) {
  2550. description = maybeDescription;
  2551. }
  2552. }
  2553. description = toSingleLine(description);
  2554. const shortDescription = description.length > 180 ? `${description.slice(0, 177)}...` : description;
  2555. const adapter = getCursorSkillAdapterHeader(skillName);
  2556. // Cursor skills are both slash-invocable and model-invocable. Do not emit the
  2557. // unsupported `user-invocable` field: it is ignored by Cursor and previously
  2558. // hid the real cause of duplicate entries, the parallel commands/ surface
  2559. // retired in #2644.
  2560. return `---\nname: ${yamlIdentifier(skillName)}\ndescription: ${yamlQuote(shortDescription)}\n---\n\n${adapter}\n\n${body.trimStart()}`;
  2561. }
  2562. /**
  2563. * Convert Claude Code agent markdown to Cursor agent format.
  2564. * Strips frontmatter fields Cursor doesn't support (color, skills),
  2565. * converts tool references, and adds a role context header.
  2566. */
  2567. function convertClaudeAgentToCursorAgent(content) {
  2568. let converted = convertClaudeToCursorMarkdown(content);
  2569. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  2570. if (!frontmatter) return converted;
  2571. const name = extractFrontmatterField(frontmatter, 'name') || 'unknown';
  2572. const description = extractFrontmatterField(frontmatter, 'description') || '';
  2573. const cleanFrontmatter = `---\nname: ${yamlIdentifier(name)}\ndescription: ${yamlQuote(toSingleLine(description))}\n---`;
  2574. return `${cleanFrontmatter}\n${body}`;
  2575. }
  2576. // --- Windsurf converters ---
  2577. // #2931 (ADR-1508): single-sourced in runtimeArtifactConversion, bound near
  2578. // the top of this file alongside the #1675 Augment family. This block
  2579. // previously carried byte-identical local duplicates of
  2580. // convertSlashCommandsToWindsurfSkillMentions, convertClaudeToWindsurfMarkdown,
  2581. // getWindsurfSkillAdapterHeader, convertClaudeCommandToWindsurfSkill,
  2582. // convertClaudeCommandToWindsurfWorkflow, and convertClaudeAgentToWindsurfAgent,
  2583. // plus an unused claudeToWindsurfTools table. Deleted here; the two
  2584. // unexported helpers (getWindsurfSkillAdapterHeader,
  2585. // convertSlashCommandsToWindsurfSkillMentions) now live only in the
  2586. // conversion module, with no other caller in this file.
  2587. // --- Augment converters ---
  2588. // Augment uses a tool set similar to Cursor/Windsurf.
  2589. // Config lives in .augment/ (local) and ~/.augment/ (global).
  2590. // #1675 (ADR-1508): the augment converter family below was a byte-identical
  2591. // duplicate of runtime-artifact-conversion.cjs:
  2592. // convertSlashCommandsToAugmentSkillMentions, convertClaudeToAugmentMarkdown,
  2593. // getAugmentSkillAdapterHeader, convertClaudeCommandToAugmentSkill,
  2594. // convertClaudeAgentToAugmentAgent
  2595. // Deleted here and bound from runtimeArtifactConversion above (single source).
  2596. // The DEFECT.GENERATIVE-FIX parity guard in
  2597. // tests/enh-1511-rewrite-engine-relocation.test.cjs asserts reference identity.
  2598. function convertSlashCommandsToTraeSkillMentions(content) {
  2599. return content.replace(/\/gsd:([a-z0-9-]+)/g, (_, commandName) => {
  2600. return `/gsd-${commandName}`;
  2601. });
  2602. }
  2603. function convertClaudeToTraeMarkdown(content, pathPrefix) {
  2604. return runtimeArtifactConversion._shieldEmittedPrefix(
  2605. runtimeArtifactConversion._resolveTraeInstructionFileAtPrefix(content, pathPrefix),
  2606. pathPrefix,
  2607. convertClaudeToTraeMarkdownBody,
  2608. );
  2609. }
  2610. function convertClaudeToTraeMarkdownBody(content) {
  2611. let converted = convertSlashCommandsToTraeSkillMentions(filterRuntimeNotesForTarget(content, 'trae'));
  2612. converted = converted.replace(/\bBash\(/g, 'Shell(');
  2613. converted = converted.replace(/\bEdit\(/g, 'StrReplace(');
  2614. // Replace general-purpose subagent type with Trae's equivalent "general_purpose_task"
  2615. converted = converted.replace(/subagent_type="general-purpose"/g, 'subagent_type="general_purpose_task"');
  2616. converted = converted.replace(/\$ARGUMENTS\b/g, '{{GSD_ARGS}}');
  2617. // #2658: full-path forms (with a leading dot-claude-slash prefix) MUST be
  2618. // replaced before the bare Claude-instruction-file pattern and before the
  2619. // generic dot-claude-slash rewrite below — otherwise the bare pattern
  2620. // consumes only the instruction-filename tail, leaving that prefix stale
  2621. // in place, and the generic rewrite then mutates the stale leftover too,
  2622. // producing a doubled trae-prefix segment ahead of the rules path instead
  2623. // of a single clean one. (Deliberately never spelling the instruction
  2624. // filename as one contiguous "CLAUDE" + dot + "md" token, and never
  2625. // spelling either malformed shape out as a literal contiguous string, in
  2626. // ANY comment in this function: this file ships verbatim into local
  2627. // `--trae` installs, where it is itself run through this same class of
  2628. // find/replace — a literal instruction-filename token sitting in a
  2629. // comment gets "fixed" right along with real code, and the emitted-content
  2630. // regression test added alongside this fix asserts neither malformed
  2631. // shape appears anywhere in the installed tree, comments included; this
  2632. // bit the fix itself twice during development.) All forms converge on the
  2633. // same concrete file (never a bare directory) so this stays in parity
  2634. // with the `trae.js` RUNTIME_CONTENT_DISPATCH entry.
  2635. converted = converted.replace(/`\.\/\.claude\/CLAUDE\.md`/g, '`.trae/rules/rules.md`');
  2636. converted = converted.replace(/\.\/\.claude\/CLAUDE\.md/g, '.trae/rules/rules.md');
  2637. converted = converted.replace(/`\.claude\/CLAUDE\.md`/g, '`.trae/rules/rules.md`');
  2638. converted = converted.replace(/\.claude\/CLAUDE\.md/g, '.trae/rules/rules.md');
  2639. // #2658 (found via the end-to-end install regression test, not the static
  2640. // trace above): `copyWithPathReplacement` runs a GENERIC dot-claude-slash
  2641. // -> runtime-config-dir rewrite on every .md file before calling this
  2642. // converter — for `~/.claude/`, `$HOME/.claude/`, AND `./.claude/` alike —
  2643. // substituting a runtime-appropriate `pathPrefix` this function is never
  2644. // given and cannot itself compute (it differs per install invocation: a
  2645. // relative `./.trae/` for a project-local install, an arbitrary absolute
  2646. // path for a local install rooted elsewhere, `~/.trae/` for a global one).
  2647. // So for source using any of those prefixed forms, the patterns above
  2648. // never fire here — this converter only ever sees the ALREADY-rewritten
  2649. // "<runtime-config-dir>/" + instruction-filename shape, with whatever
  2650. // prefix the install actually used. The generic pattern below preserves
  2651. // that prefix verbatim (via the capture group) and only fixes the
  2652. // filename suffix, rather than assuming a fixed `./.trae/` shape — a
  2653. // narrower fixed-prefix version of this pattern shipped first and still
  2654. // left the doubled-prefix defect live for the `$HOME/.claude/` and
  2655. // `~/.claude/` forms specifically (found the same way, one regression-test
  2656. // run later). Scoped to a `.trae/` tail so it cannot also swallow the
  2657. // unprefixed `./CLAUDE.md` form the very next pattern handles differently
  2658. // (discarding the prefix entirely, not preserving it). Must run before
  2659. // the bare pattern for the same consume-the-full-match-first reason.
  2660. converted = converted.replace(/`([^\s`]*\.trae\/)CLAUDE\.md`/g, '`$1rules/rules.md`');
  2661. converted = converted.replace(/([^\s`]*\.trae\/)CLAUDE\.md/g, '$1rules/rules.md');
  2662. converted = converted.replace(/`\.\/CLAUDE\.md`/g, '`.trae/rules/rules.md`');
  2663. converted = converted.replace(/\.\/CLAUDE\.md/g, '.trae/rules/rules.md');
  2664. converted = converted.replace(/`CLAUDE\.md`/g, '`.trae/rules/rules.md`');
  2665. converted = converted.replace(/\bCLAUDE\.md\b/g, '.trae/rules/rules.md');
  2666. converted = converted.replace(/\.claude\/skills\//g, '.trae/skills/');
  2667. converted = converted.replace(/\.\/\.claude\//g, './.trae/');
  2668. converted = converted.replace(/\.claude\//g, '.trae/');
  2669. // Bare forms (no trailing slash) — after slash forms to avoid double-rewrite.
  2670. // Use negative lookahead (?![\w-]|\.\w) to preserve .claude-plugin, .claudeignore and .claude.json.
  2671. // #5715: an emitted prefix is shielded by convertClaudeToTraeMarkdown; the skills path runs this before the prefix pass, and the profile maps the own-dir forms.
  2672. converted = converted.replace(/~\/\.claude(?![\w-]|\.\w)/g, '~/.trae');
  2673. converted = converted.replace(/\$HOME\/\.claude(?![\w-]|\.\w)/g, () => '$HOME/.trae');
  2674. // Environment variable name rewrite
  2675. converted = converted.replace(/\bCLAUDE_CONFIG_DIR\b/g, 'TRAE_CONFIG_DIR');
  2676. converted = converted.replace(/\*\*Known Claude Code bug \(classifyHandoffIfNeeded\):\*\*[^\n]*\n/g, '');
  2677. converted = converted.replace(/- \*\*classifyHandoffIfNeeded false failure:\*\*[^\n]*\n/g, '');
  2678. // #2284(b): skips <runtime_compatibility> comparison-table content (protected region).
  2679. converted = applyClaudeCodeBrandSwap(converted, 'Trae');
  2680. return converted;
  2681. }
  2682. // DEFECT.GENERATIVE-FIX: this body is mirrored in
  2683. // src/runtime-artifact-conversion.cts's convertClaudeCommandToTraeSkill (used
  2684. // by src/install-engine.cts's skills-install path via
  2685. // SKILLS_CONVERTER_REGISTRY). This bin/install.js copy is dead for the live
  2686. // skills-install path — kept for this file's own module-level export/test
  2687. // surface. Neither copy re-exports the other — mirror any behavior change
  2688. // into both. Guarded by the output-parity test in
  2689. // tests/runtime-converters.test.cjs (#2094).
  2690. function convertClaudeCommandToTraeSkill(content, skillName) {
  2691. const converted = convertClaudeToTraeMarkdown(content);
  2692. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  2693. let description = `Run GSD workflow ${skillName}.`;
  2694. if (frontmatter) {
  2695. const maybeDescription = extractFrontmatterField(frontmatter, 'description');
  2696. if (maybeDescription) {
  2697. description = maybeDescription;
  2698. }
  2699. }
  2700. description = toSingleLine(description);
  2701. const shortDescription = description.length > 180 ? `${description.slice(0, 177)}...` : description;
  2702. // #2876: quote so YAML flow indicators (`[BETA] …`) don't break Trae's
  2703. // frontmatter parser.
  2704. let fm = `---\nname: ${yamlIdentifier(skillName)}\ndescription: ${yamlQuote(shortDescription)}\n`;
  2705. // #2094: emit `stage:` so Trae's SOLO agent can auto-invoke GSD skills at
  2706. // the corresponding stage (docs.trae.ai/ide/agent). The field name/schema
  2707. // is not formally documented (thin SPA docs) — descriptor-driven, single
  2708. // fixed GSD-side value (runtime.hostBehaviors.soloStageMetadata), inferred/
  2709. // best-effort.
  2710. const soloStage = hostBehaviorsFor('trae').soloStageMetadata;
  2711. if (soloStage) fm += `stage: ${soloStage}\n`;
  2712. fm += '---';
  2713. return `${fm}\n${body}`;
  2714. }
  2715. function convertClaudeAgentToTraeAgent(content, _isGlobal, meta) {
  2716. let converted = convertClaudeToTraeMarkdown(content, meta && meta.pathPrefix);
  2717. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  2718. if (!frontmatter) return converted;
  2719. const name = extractFrontmatterField(frontmatter, 'name') || 'unknown';
  2720. const description = extractFrontmatterField(frontmatter, 'description') || '';
  2721. const cleanFrontmatter = `---\nname: ${yamlIdentifier(name)}\ndescription: ${yamlQuote(toSingleLine(description))}\n---`;
  2722. return `${cleanFrontmatter}\n${body}`;
  2723. }
  2724. function convertSlashCommandsToCodebuddySkillMentions(content) {
  2725. return content.replace(/\/gsd:([a-z0-9-]+)/g, (_, commandName) => {
  2726. return `/gsd-${commandName}`;
  2727. });
  2728. }
  2729. function convertClaudeToCodebuddyMarkdown(content) {
  2730. let converted = convertSlashCommandsToCodebuddySkillMentions(filterRuntimeNotesForTarget(content, 'codebuddy'));
  2731. // CodeBuddy uses the same tool names as Claude Code (Bash, Edit, Read, Write, etc.)
  2732. // No tool name conversion needed
  2733. converted = converted.replace(/\$ARGUMENTS\b/g, '{{GSD_ARGS}}');
  2734. converted = converted.replace(/`\.\/CLAUDE\.md`/g, '`CODEBUDDY.md`');
  2735. converted = converted.replace(/\.\/CLAUDE\.md/g, 'CODEBUDDY.md');
  2736. converted = converted.replace(/`CLAUDE\.md`/g, '`CODEBUDDY.md`');
  2737. converted = converted.replace(/\bCLAUDE\.md\b/g, 'CODEBUDDY.md');
  2738. converted = converted.replace(/\.claude\/skills\//g, '.codebuddy/skills/');
  2739. converted = converted.replace(/\.\/\.claude\//g, './.codebuddy/');
  2740. converted = converted.replace(/\.claude\//g, '.codebuddy/');
  2741. converted = converted.replace(/\*\*Known Claude Code bug \(classifyHandoffIfNeeded\):\*\*[^\n]*\n/g, '');
  2742. converted = converted.replace(/- \*\*classifyHandoffIfNeeded false failure:\*\*[^\n]*\n/g, '');
  2743. // #2284(b): skips <runtime_compatibility> comparison-table content (protected region).
  2744. converted = applyClaudeCodeBrandSwap(converted, 'CodeBuddy');
  2745. return converted;
  2746. }
  2747. function convertClaudeCommandToCodebuddySkill(content, skillName) {
  2748. const converted = convertClaudeToCodebuddyMarkdown(content);
  2749. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  2750. let description = `Run GSD workflow ${skillName}.`;
  2751. if (frontmatter) {
  2752. const maybeDescription = extractFrontmatterField(frontmatter, 'description');
  2753. if (maybeDescription) {
  2754. description = maybeDescription;
  2755. }
  2756. }
  2757. description = toSingleLine(description);
  2758. const shortDescription = description.length > 180 ? `${description.slice(0, 177)}...` : description;
  2759. // #2876: quote so YAML flow indicators (`[BETA] …`) don't break
  2760. // CodeBuddy's frontmatter parser.
  2761. //
  2762. // #789: mark user-invocable:false so the skill is NOT shown in CodeBuddy's
  2763. // '/' menu (it defaults to true). The commands/ surface (#789) is the sole
  2764. // '/' entry point; skills remain model-invocable background knowledge,
  2765. // avoiding a duplicated /gsd-* entry per workflow.
  2766. return `---\nname: ${yamlIdentifier(skillName)}\ndescription: ${yamlQuote(shortDescription)}\nuser-invocable: false\n---\n${body}`;
  2767. }
  2768. /**
  2769. * Convert a Claude Code slash-command (.md) to a CodeBuddy slash-command (.md).
  2770. *
  2771. * CodeBuddy reads user-level slash commands from ~/.codebuddy/commands/<name>.md
  2772. * (https://www.codebuddy.ai/docs/cli/slash-commands). The filename determines the
  2773. * command name (gsd-help.md → /gsd-help), so the Claude-specific `name: gsd:<x>`
  2774. * frontmatter field is dropped. CodeBuddy command frontmatter supports
  2775. * `description` and `argument-hint`; both are preserved when present. The body is
  2776. * brand/path-converted via convertClaudeToCodebuddyMarkdown.
  2777. *
  2778. * @param {string} content raw Claude command markdown
  2779. * @param {string} commandName installed command name (e.g. 'gsd-help')
  2780. * @returns {string}
  2781. */
  2782. function convertClaudeCommandToCodebuddyCommand(content, commandName) {
  2783. const converted = convertClaudeToCodebuddyMarkdown(content);
  2784. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  2785. let description = `Run GSD workflow ${commandName}.`;
  2786. let argumentHint = '';
  2787. if (frontmatter) {
  2788. const maybeDescription = extractFrontmatterField(frontmatter, 'description');
  2789. if (maybeDescription) description = maybeDescription;
  2790. const maybeArgHint = extractFrontmatterField(frontmatter, 'argument-hint');
  2791. if (maybeArgHint) argumentHint = maybeArgHint;
  2792. }
  2793. description = toSingleLine(description);
  2794. const shortDescription = description.length > 180 ? `${description.slice(0, 177)}...` : description;
  2795. // #2876: quote values so YAML flow indicators (`[BETA] …`, `[name]`) don't
  2796. // break CodeBuddy's frontmatter parser.
  2797. const lines = ['---', `description: ${yamlQuote(shortDescription)}`];
  2798. if (argumentHint) lines.push(`argument-hint: ${yamlQuote(toSingleLine(argumentHint))}`);
  2799. lines.push('---', body.trimStart());
  2800. return lines.join('\n');
  2801. }
  2802. function convertClaudeAgentToCodebuddyAgent(content) {
  2803. let converted = convertClaudeToCodebuddyMarkdown(content);
  2804. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  2805. if (!frontmatter) return converted;
  2806. const name = extractFrontmatterField(frontmatter, 'name') || 'unknown';
  2807. const description = extractFrontmatterField(frontmatter, 'description') || '';
  2808. const cleanFrontmatter = `---\nname: ${yamlIdentifier(name)}\ndescription: ${yamlQuote(toSingleLine(description))}\n---`;
  2809. return `${cleanFrontmatter}\n${body}`;
  2810. }
  2811. // ── Cline converters ────────────────────────────────────────────────────────
  2812. function convertClaudeToCliineMarkdown(content) {
  2813. let converted = filterRuntimeNotesForTarget(content, 'cline');
  2814. // Cline uses the same tool names as Claude Code — no tool name conversion needed
  2815. converted = converted.replace(/`\.\/CLAUDE\.md`/g, '`.clinerules`');
  2816. converted = converted.replace(/\.\/CLAUDE\.md/g, '.clinerules');
  2817. converted = converted.replace(/`CLAUDE\.md`/g, '`.clinerules`');
  2818. converted = converted.replace(/\bCLAUDE\.md\b/g, '.clinerules');
  2819. // Slash forms first (most specific — superset of bare forms)
  2820. converted = converted.replace(/\.claude\/skills\//g, '.cline/skills/');
  2821. converted = converted.replace(/\.\/\.claude\//g, './.cline/');
  2822. converted = converted.replace(/\.claude\//g, '.cline/');
  2823. // Bare forms (no trailing slash) — after slash forms to avoid double-rewrite
  2824. converted = converted.replace(/~\/\.claude\b/g, '~/.cline');
  2825. converted = converted.replace(/\$HOME\/\.claude\b/g, '$HOME/.cline');
  2826. // Environment variable name rewrite
  2827. converted = converted.replace(/\bCLAUDE_CONFIG_DIR\b/g, 'CLINE_CONFIG_DIR');
  2828. converted = converted.replace(/\*\*Known Claude Code bug \(classifyHandoffIfNeeded\):\*\*[^\n]*\n/g, '');
  2829. converted = converted.replace(/- \*\*classifyHandoffIfNeeded false failure:\*\*[^\n]*\n/g, '');
  2830. // #2284(b): skips <runtime_compatibility> comparison-table content (protected region).
  2831. converted = applyClaudeCodeBrandSwap(converted, 'Cline');
  2832. return converted;
  2833. }
  2834. function convertClaudeAgentToClineAgent(content) {
  2835. let converted = convertClaudeToCliineMarkdown(content);
  2836. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  2837. if (!frontmatter) return converted;
  2838. const name = extractFrontmatterField(frontmatter, 'name') || 'unknown';
  2839. const description = extractFrontmatterField(frontmatter, 'description') || '';
  2840. const cleanFrontmatter = `---\nname: ${yamlIdentifier(name)}\ndescription: ${yamlQuote(toSingleLine(description))}\n---`;
  2841. return `${cleanFrontmatter}\n${body}`;
  2842. }
  2843. /**
  2844. * Convert a Claude command (.md) to a Cline skill (SKILL.md).
  2845. * Emits ONLY name + description frontmatter per the Cline skills spec
  2846. * (https://docs.cline.bot/customization/skills) — no allowed-tools,
  2847. * argument-hint, agent, or other Claude-specific fields.
  2848. * Body is hyphen-normalised then converted via convertClaudeToCliineMarkdown
  2849. * (.claude/→.cline/, "Claude Code"→"Cline", etc.).
  2850. * Cline uses Claude-Code-compatible tool names, so no adapter header is needed.
  2851. * Targets ~/.cline/skills/<name>/SKILL.md for Cline >= v3.48.0.
  2852. */
  2853. function convertClaudeCommandToClineSkill(content, skillName, runtime = null, cmdNames = null) {
  2854. const { frontmatter, body } = extractFrontmatterAndBody(content);
  2855. if (!frontmatter) return content;
  2856. // Hyphen-normalise /gsd:<cmd> → gsd-<cmd> references in the body, then
  2857. // apply Cline-specific markdown rewrites (.claude/→.cline/, etc.).
  2858. const names = cmdNames || readGsdCommandNames();
  2859. const normalizedBody = transformContentToHyphen(body, names);
  2860. const clineBody = convertClaudeToCliineMarkdown(normalizedBody);
  2861. // Extract description; fall back to a generic string if absent.
  2862. let description = extractFrontmatterField(frontmatter, 'description');
  2863. if (!description) description = `Run GSD workflow ${skillName}.`;
  2864. description = toSingleLine(description);
  2865. // #4324: same reason as the Claude skill converter above.
  2866. description = transformContentToHyphen(description, names);
  2867. // Cline documented max is 1024 code points (not UTF-16 code units).
  2868. // Use Array.from to iterate by code point so that multibyte characters
  2869. // (e.g. emoji, astral-plane chars) are never split, which would produce
  2870. // lone surrogates and corrupt the YAML output.
  2871. const cp = Array.from(description);
  2872. const shortDescription = cp.length > 1024
  2873. ? cp.slice(0, 1021).join('') + '...'
  2874. : description;
  2875. const fm = `---\nname: ${yamlIdentifier(skillName)}\ndescription: ${yamlQuote(shortDescription)}\n---`;
  2876. return `${fm}\n${clineBody}`;
  2877. }
  2878. // ── End Cline converters ─────────────────────────────────────────────────────
  2879. // ── Hermes converters (#2284) ────────────────────────────────────────────────
  2880. //
  2881. // Hermes exposes `delegate_task` for subagent dispatch, not the Claude-shaped
  2882. // `Agent(...)` tool the host-neutral `gsd-core/workflows/*.md` corpus assumes.
  2883. // Prior to this fix, the hermes `.md` hook (RUNTIME_CONTENT_DISPATCH.hermes)
  2884. // only brand-swapped "Claude Code" → "Hermes Agent" via
  2885. // hostBehaviors.brandingRewrites, leaving the false "Agent tool IS available"
  2886. // assertion and literal `Agent(...)` call syntax installed verbatim.
  2887. //
  2888. // `projectNamedDispatchToStructuralDelegate` is GENERIC projection machinery:
  2889. // it branches ENTIRELY on the runtime's documentation-sourced
  2890. // `hostIntegration.dispatch` facts (read via `_hostIntegrationDispatch`,
  2891. // capabilities/<runtime>/capability.json — never hardcoded here) and a
  2892. // `toolConfig` that supplies only the target primitive's own vocabulary (its
  2893. // call name + native parameter names — not a capability claim; there is no
  2894. // `dispatch` axis for "the call's own parameter names", so that vocabulary is
  2895. // necessarily supplied by the caller, exactly as every other runtime's
  2896. // converter supplies its own tool-name vocabulary, e.g. Trae's `Shell(`).
  2897. //
  2898. // Hermes-specific facts consumed (capabilities/hermes/capability.json,
  2899. // docs/reference/host-integration-capability-matrix.md:244-249 — UNCHANGED by
  2900. // this fix):
  2901. // - dispatch.namedDispatch: false — Hermes's delegate_task has no named-
  2902. // agent lookup ("Subagents are identified only by role ('leaf' or
  2903. // 'orchestrator')"). GSD resolves the referenced gsd-* role itself
  2904. // (fail-closed against the staged agents/ dir) and embeds the loaded
  2905. // PROMPT CONTENT into the delegate_task payload.
  2906. // - dispatch.background: true — `delegate_task(background=true)` "returns a
  2907. // handle immediately"; Claude's `run_in_background=` maps onto Hermes's
  2908. // own `background=` parameter, preserving the async-handle / no-busy-poll
  2909. // / resume-on-completion wording already used throughout these workflows.
  2910. // - dispatch.subagentToolkit: "read-only" / dispatch.maxDepth: 1 — dispatched
  2911. // roles never themselves further delegate, so no nested-delegation
  2912. // instruction is ever emitted toward them.
  2913. /**
  2914. * Resolve the set of gsd-* role-prompt stems actually shipped in this
  2915. * package's `agents/` directory (the FULL source set, not profile-staged —
  2916. * `--minimal`/`--profile=core` intentionally excludes many agents from a
  2917. * given install without those workflows being unreachable, so validating
  2918. * against the profile-filtered subset would fail every restricted-profile
  2919. * Hermes install; validating against the shipped source catches genuine
  2920. * authoring bugs — a stale/typo'd role reference — without that regression).
  2921. * Returns `null` if the directory cannot be resolved (fail-closed: callers
  2922. * must refuse to install rather than skip validation).
  2923. */
  2924. function _resolveAvailableGsdRoles() {
  2925. try {
  2926. const agentsDir = path.join(__dirname, '..', 'agents');
  2927. return new Set(
  2928. fs.readdirSync(agentsDir, { withFileTypes: true })
  2929. .filter((e) => e.isFile() && e.name.endsWith('.md'))
  2930. .map((e) => e.name.slice(0, -3)),
  2931. );
  2932. } catch (_e) {
  2933. return null;
  2934. }
  2935. }
  2936. /**
  2937. * Fail-closed validation (#2284 AC: "Missing role prompts fail closed" /
  2938. * "never emit a workflow referencing an unresolvable role"). A single literal
  2939. * `gsd-*` role value must resolve to a real `agents/<role>.md` file — throws
  2940. * an explicit Error otherwise, aborting the install (the standard
  2941. * `copyWithPathReplacement` failure path already used for its own
  2942. * confinement-violation throws). Called per extracted role value from EVERY
  2943. * call-syntax form (`subagent_type=`, `subagent_type:`, post-rename
  2944. * `gsd_role=`) — the check operates on the resolved value, independent of
  2945. * which source syntax produced it. Non-literal / dynamic expressions (e.g.
  2946. * `research_hook.ref.agent`) are not quoted strings and are never passed
  2947. * here; they carry their own runtime resolution + fail-closed instruction via
  2948. * the injected per-call resolution line.
  2949. */
  2950. function _assertRoleResolvable(role, availableRoles, runtime, sourceDescription) {
  2951. if (!availableRoles) {
  2952. throw new Error(
  2953. `${runtime} workflow install: could not resolve the shipped agents/ directory to validate named-role ` +
  2954. 'dispatch references — refusing to install (fail-closed, #2284)',
  2955. );
  2956. }
  2957. if (role.startsWith('gsd-') && !availableRoles.has(role)) {
  2958. throw new Error(
  2959. `${runtime} workflow install: dispatch references role "${role}" via ${sourceDescription}, but no ` +
  2960. `matching agents/${role}.md prompt file is shipped — refusing to install a workflow that dispatches ` +
  2961. 'an unresolvable role (fail-closed, #2284)',
  2962. );
  2963. }
  2964. }
  2965. /**
  2966. * Segment `text` into 'code' and 'string' runs (recognizes `"..."`, `'...'`,
  2967. * and Python-style `"""..."""`, with backslash-escaping). Required because
  2968. * the real corpus embeds unescaped parens inside quoted prompt bodies (e.g.
  2969. * discuss-phase-assumptions.md's `(e.g., "Technical Approach")` inside a
  2970. * `"""`-quoted prompt) — naive paren/keyword scanning across raw text would
  2971. * desync on these. Downstream call-span detection and header-token
  2972. * extraction operate on a same-length MASK derived from this segmentation
  2973. * (see `maskStringLiterals`) so string content can never be mistaken for
  2974. * call structure.
  2975. */
  2976. function _segmentCodeAndStrings(text) {
  2977. const segments = [];
  2978. let i = 0;
  2979. let segStart = 0;
  2980. const flushCode = (end) => { if (end > segStart) segments.push({ type: 'code', start: segStart, end }); };
  2981. while (i < text.length) {
  2982. const ch = text[i];
  2983. if (ch === '"' && text[i + 1] === '"' && text[i + 2] === '"') {
  2984. flushCode(i);
  2985. const strStart = i;
  2986. i += 3;
  2987. while (i < text.length && !(text[i] === '"' && text[i + 1] === '"' && text[i + 2] === '"')) {
  2988. i += text[i] === '\\' ? 2 : 1;
  2989. }
  2990. i = Math.min(i + 3, text.length);
  2991. segments.push({ type: 'string', start: strStart, end: i, quoteLen: 3 });
  2992. segStart = i;
  2993. continue;
  2994. }
  2995. // Only `"` is recognized as a single-char string delimiter — NOT `'`.
  2996. // The corpus is markdown prose, not code: apostrophes are routine English
  2997. // contractions/possessives ("install's", "don't") and treating them as
  2998. // string delimiters would swallow everything up to the next unrelated
  2999. // apostrophe as "inside a string" (verified against the real corpus —
  3000. // this was a real, disqualifying bug during development of this fix).
  3001. // Every real call-argument value in the corpus uses `"`/`"""` only.
  3002. if (ch === '"') {
  3003. flushCode(i);
  3004. const strStart = i;
  3005. i += 1;
  3006. while (i < text.length && text[i] !== '"') {
  3007. i += text[i] === '\\' ? 2 : 1;
  3008. }
  3009. i = Math.min(i + 1, text.length);
  3010. segments.push({ type: 'string', start: strStart, end: i, quoteLen: 1 });
  3011. segStart = i;
  3012. continue;
  3013. }
  3014. i += 1;
  3015. }
  3016. flushCode(text.length);
  3017. return segments;
  3018. }
  3019. /**
  3020. * Same-length mask of `text` with the INTERIOR of every string literal
  3021. * replaced by a space (newlines preserved, so line-based regexes still work).
  3022. * The delimiting quote character(s) themselves (`"`, `'`, `"""`) are kept
  3023. * verbatim so a value-extraction regex like `key\s*[=:]\s*"[^"]*"` still
  3024. * matches correctly against the mask — only the STRING CONTENT is blanked,
  3025. * never the quote structure. Positions in the mask line up 1:1 with `text`,
  3026. * so match indices/offsets found against the mask are valid offsets into the
  3027. * original.
  3028. */
  3029. function maskStringLiterals(text) {
  3030. let mask = '';
  3031. for (const seg of _segmentCodeAndStrings(text)) {
  3032. const slice = text.slice(seg.start, seg.end);
  3033. if (seg.type === 'code') { mask += slice; continue; }
  3034. const q = seg.quoteLen;
  3035. if (slice.length <= q) { mask += slice; continue; } // truncated/unterminated — keep verbatim
  3036. const closeLen = Math.min(q, slice.length - q);
  3037. const open = slice.slice(0, q);
  3038. const close = slice.slice(slice.length - closeLen);
  3039. const interiorLen = slice.length - q - closeLen;
  3040. const interior = interiorLen > 0 ? slice.slice(q, q + interiorLen) : '';
  3041. mask += open + interior.replace(/[^\n]/g, ' ') + close;
  3042. }
  3043. return mask;
  3044. }
  3045. /**
  3046. * Locate every `<headWord>(` / `<headWord>({` call span in `text`.
  3047. *
  3048. * #2284 round-2 CRITICAL fix: this MUST NOT rely on whole-document quote
  3049. * parity. A markdown workflow file mixes prose, ```bash code fences (full of
  3050. * their own double-quoted strings), and shell quoting — there is no single
  3051. * document-wide quote grammar, so a `"`-heavy bash `echo` upstream of a real
  3052. * call (e.g. code-review.md's fenced `echo "..."` block before its
  3053. * `Agent(subagent_type="gsd-code-reviewer", ...)` call) can desync a
  3054. * CUMULATIVE quote-state scan, making the scanner believe the real call's
  3055. * `Agent(` sits "inside a string" and silently skipping it entirely — the
  3056. * call then survives completely unnormalized. (Reproduced and root-caused
  3057. * against the real corpus.)
  3058. *
  3059. * Fixed shape: find each `<headWord>(` occurrence via a PLAIN literal-text
  3060. * search (`indexOf`, immune to any prior document content), then run a
  3061. * balanced paren-matching scan whose quote-tracking state STARTS FRESH AT
  3062. * THE HEAD — local to this one call, never inherited from (or able to be
  3063. * corrupted by) anything earlier in the document. Handles all three real
  3064. * corpus shapes: multi-line one-key-per-line, single-line object-literal
  3065. * (`Agent({ ... })`), and single-line compact
  3066. * (`Agent(subagent_type="x", model="y", prompt="...")`) — including prompt
  3067. * bodies containing their own unescaped `()`/`{}` (skipped via the SAME
  3068. * span-local quote tracking, e.g. discuss-phase-assumptions.md's
  3069. * `"""`-quoted parenthetical prose).
  3070. *
  3071. * Returns `[{start, end, hasBraceWrapper}]` — `start`/`end` bound the FULL
  3072. * call INCLUDING the head word and the closing `)`/`})`.
  3073. */
  3074. function findDispatchCallSpans(text, headWord) {
  3075. const spans = [];
  3076. const headToken = `${headWord}(`;
  3077. let searchFrom = 0;
  3078. for (;;) {
  3079. const start = text.indexOf(headToken, searchFrom);
  3080. if (start === -1) break;
  3081. const prevChar = start > 0 ? text[start - 1] : '';
  3082. if (/[A-Za-z0-9_]/.test(prevChar)) { searchFrom = start + 1; continue; } // word-boundary guard
  3083. let i = start + headToken.length; // just past the '('
  3084. let j = i;
  3085. while (j < text.length && /\s/.test(text[j])) j++;
  3086. const hasBraceWrapper = text[j] === '{';
  3087. // LOCAL scan — quote/paren state is fresh here, never inherited from
  3088. // anything before `start` in the document.
  3089. let parenDepth = 1;
  3090. let inString = null; // null | '"' | 'triple'
  3091. let end = -1;
  3092. for (; i < text.length; i++) {
  3093. const ch = text[i];
  3094. if (inString) {
  3095. if (ch === '\\') { i++; continue; }
  3096. if (inString === 'triple') {
  3097. if (ch === '"' && text[i + 1] === '"' && text[i + 2] === '"') { inString = null; i += 2; }
  3098. continue;
  3099. }
  3100. if (ch === inString) inString = null;
  3101. continue;
  3102. }
  3103. if (ch === '"' && text[i + 1] === '"' && text[i + 2] === '"') { inString = 'triple'; i += 2; continue; }
  3104. if (ch === '"') { inString = '"'; continue; }
  3105. if (ch === '(') { parenDepth++; continue; }
  3106. if (ch === ')') {
  3107. parenDepth--;
  3108. if (parenDepth === 0) { end = i + 1; break; }
  3109. continue;
  3110. }
  3111. }
  3112. if (end === -1) { searchFrom = start + 1; continue; } // unterminated — skip past, keep scanning
  3113. spans.push({ start, end, hasBraceWrapper });
  3114. searchFrom = end;
  3115. }
  3116. return spans;
  3117. }
  3118. /**
  3119. * Remove a call argument's `[matchStart, matchEnd)` token from `spanText`,
  3120. * consuming its surrounding comma/whitespace so no dangling `, ,` or trailing
  3121. * comment survives. When the argument owns its whole line, the whole line
  3122. * (including a trailing inline `# comment`) is removed; `consumeLeadingComments`
  3123. * additionally removes contiguous comment-only lines immediately ABOVE it —
  3124. * #2284 Finding 5: explanatory prose describing a now-removed conditional
  3125. * (e.g. execute-phase.md's "# Only include model= when ...") must not survive
  3126. * describing a branch that no longer exists. Inline (single-line-compact /
  3127. * object-literal) occurrences instead eat one adjacent comma.
  3128. */
  3129. function _stripCallArgument(spanText, matchStart, matchEnd, { consumeLeadingComments = false } = {}) {
  3130. let end = matchEnd;
  3131. const afterRe = /^[ \t]*,?[ \t]*(#[^\n]*)?\r?\n?/;
  3132. const afterMatch = afterRe.exec(spanText.slice(end));
  3133. const hadTrailingComma = !!(afterMatch && /,/.test(afterMatch[0]));
  3134. if (afterMatch) end += afterMatch[0].length;
  3135. let start = matchStart;
  3136. const lineStart = spanText.lastIndexOf('\n', start - 1) + 1;
  3137. const ownLine = /^[ \t]*$/.test(spanText.slice(lineStart, start));
  3138. if (ownLine) {
  3139. start = lineStart;
  3140. if (consumeLeadingComments) {
  3141. for (;;) {
  3142. const prevLineStart = start > 0 ? spanText.lastIndexOf('\n', start - 2) + 1 : 0;
  3143. const prevLine = spanText.slice(prevLineStart, start);
  3144. if (/^[ \t]*#[^\n]*\r?\n$/.test(prevLine)) {
  3145. start = prevLineStart;
  3146. if (prevLineStart === 0) break;
  3147. } else break;
  3148. }
  3149. }
  3150. } else if (!hadTrailingComma) {
  3151. // Inline form and this was the LAST arg (no trailing comma) — eat a
  3152. // leading comma so the previous arg doesn't dangle one.
  3153. const before = spanText.slice(0, start);
  3154. const cm = /,[ \t]*$/.exec(before);
  3155. if (cm) start -= cm[0].length;
  3156. }
  3157. return spanText.slice(0, start) + spanText.slice(end);
  3158. }
  3159. /**
  3160. * Replace a named-role argument token's `[matchStart, matchEnd)` span
  3161. * (`subagent_type=`/`subagent_type:` + its value) with the projected
  3162. * `gsd_role=` / role-prompt-resolution / structural-role argument group.
  3163. * Preserves the pretty multi-line one-arg-per-line style when the original
  3164. * token owned its own line; falls back to an inline, comma-joined group for
  3165. * the single-line-compact and object-literal forms.
  3166. */
  3167. function _projectRoleArgument(spanText, matchStart, matchEnd, roleValueExpr, toolConfig, canOrchestrate) {
  3168. const { namedRoleParam, promptContentParam, structuralRoleParam, leafRoleValue } = toolConfig;
  3169. // #5569: a primitive that resolves the role prompt itself (Pi `gsd_dispatch`)
  3170. // takes the role name alone — no prompt-content argument, no structural role.
  3171. // The argument's own separator is left in place.
  3172. if (toolConfig.rolePromptResolution === 'tool') {
  3173. return spanText.slice(0, matchStart) + `${namedRoleParam}=${roleValueExpr}` + spanText.slice(matchEnd);
  3174. }
  3175. const lineStart = spanText.lastIndexOf('\n', matchStart - 1) + 1;
  3176. const startsOwnLine = /^[ \t]*$/.test(spanText.slice(lineStart, matchStart));
  3177. // Consume an immediately-following separator comma (+ same-line whitespace/
  3178. // newline) into `end` — never leave it dangling AFTER an injected trailing
  3179. // `# comment` (a bare `,` after `#...` would sit on the comment's own line,
  3180. // outside any real argument list).
  3181. let end = matchEnd;
  3182. const afterRe = /^[ \t]*,[ \t]*\r?\n?/;
  3183. const afterMatch = afterRe.exec(spanText.slice(end));
  3184. const hadTrailingComma = !!afterMatch;
  3185. if (afterMatch) end += afterMatch[0].length;
  3186. const ownLine = startsOwnLine && hadTrailingComma && /\n$/.test(afterMatch[0]);
  3187. const promptContentPhrase =
  3188. `${promptContentParam}=<resolve ${roleValueExpr} against the active install's gsd-* role prompts and load ` +
  3189. 'its contents; FAIL CLOSED with an explicit error if unresolved — never execute the role inline>';
  3190. let replacement;
  3191. if (ownLine) {
  3192. const indent = spanText.slice(lineStart, matchStart);
  3193. const depthNote = canOrchestrate ? '' : ' # nested delegation is unavailable at this dispatch depth/toolkit';
  3194. replacement =
  3195. `${namedRoleParam}=${roleValueExpr},\n` +
  3196. `${indent}${promptContentPhrase},\n` +
  3197. `${indent}${structuralRoleParam}="${leafRoleValue}",${depthNote}\n`;
  3198. } else {
  3199. // Inline forms never carry a trailing `#` comment mid-argument-list (it
  3200. // would silently "comment out" the remainder of the call), so the
  3201. // depth/toolkit caveat is only ever emitted in the pretty own-line form.
  3202. // Re-emit exactly the separator that originally followed this argument
  3203. // (a comma if more args follow; nothing if it was the last one).
  3204. replacement =
  3205. `${namedRoleParam}=${roleValueExpr}, ${promptContentPhrase}, ${structuralRoleParam}="${leafRoleValue}"` +
  3206. (hadTrailingComma ? ', ' : '');
  3207. }
  3208. return spanText.slice(0, matchStart) + replacement + spanText.slice(end);
  3209. }
  3210. // Matches a `subagent_type`/`model` argument's key+delimiter+value across all
  3211. // three corpus forms: quoted-string values ("gsd-planner", "{model}") and
  3212. // bare dynamic-expression values (ref.agent, research_hook.ref.agent,
  3213. // executor_model). The captured group is always the value (a suffix of the
  3214. // whole match), so its start offset is `match.index + match[0].length -
  3215. // match[1].length` — avoids needing the regex `d` (indices) flag.
  3216. function _callArgValueRe(key) {
  3217. return new RegExp(`\\b${key}\\s*[=:]\\s*("(?:[^"\\\\]|\\\\.)*"|[A-Za-z_][\\w.]*)`);
  3218. }
  3219. /**
  3220. * Returns the literal role name from a captured role-argument value EXPR
  3221. * (e.g. `"gsd-planner"`) — or `null` when it is not a genuine static
  3222. * literal: a bare dynamic expression (`ref.agent`), OR a quoted value that
  3223. * still contains `{...}` template interpolation (the corpus's own
  3224. * placeholder convention, e.g. `model="{researcher_model}"` — and,
  3225. * critically, `subagent_type: "gsd-{agent}"` in
  3226. * gsd-core/references/universal-anti-patterns.md, a DOCUMENTATION template
  3227. * illustrating the naming pattern, never a concrete role to resolve).
  3228. * Fail-closed validation only ever runs on a genuine static literal; a
  3229. * template/dynamic value still gets the full role-prompt-resolution
  3230. * projection treatment (the resolve+fail-closed instruction applies equally
  3231. * once a template is substituted at runtime) — only the STATIC CHECK is
  3232. * skipped, never the projection itself.
  3233. */
  3234. function _literalRoleValue(roleValueExpr) {
  3235. const m = /^"([^"]*)"$/.exec(roleValueExpr);
  3236. if (!m) return null;
  3237. if (/[{}]/.test(m[1])) return null;
  3238. return m[1];
  3239. }
  3240. /**
  3241. * `maskStringLiterals` PLUS `#`-to-end-of-line comment blanking (comments are
  3242. * never string literals, so they survive string-masking as literal `#...`
  3243. * text). Header-token searches (subagent_type/model/run_in_background) must
  3244. * use THIS mask, not the string-only one — verified necessary against the
  3245. * real corpus: execute-phase.md's explanatory comment "# Only include
  3246. * model= when executor_model is..." literally contains the substring
  3247. * "model= when", which a comment-blind `model` regex mismatches as a real
  3248. * `model=when` argument, corrupting the comment AND missing the real
  3249. * `model="{executor_model}"` line beneath it. Scoped to call-span text only
  3250. * (never the whole document), so markdown `#`/`##` headings elsewhere are
  3251. * unaffected.
  3252. */
  3253. function _maskStringsAndComments(text) {
  3254. return maskStringLiterals(text).replace(/#[^\n]*/g, (m) => ' '.repeat(m.length));
  3255. }
  3256. /**
  3257. * Normalize ONE `Agent(...)`/`Agent({...})` call span (already isolated by
  3258. * `findDispatchCallSpans`) onto the target's real dispatch primitive. Every
  3259. * behavioral branch reads `dispatch` (the runtime's sourced
  3260. * `hostIntegration.dispatch` facts) — none is hardcoded. Handles all three
  3261. * corpus call-argument shapes uniformly via string-aware token location
  3262. * (`maskStringLiterals` recomputed after each structural edit, since prior
  3263. * edits shift offsets).
  3264. */
  3265. function _normalizeDispatchCallSpan(spanText, hasBraceWrapper, dispatch, toolConfig) {
  3266. const namedDispatch = dispatch.namedDispatch === true;
  3267. const backgroundCapable = dispatch.background === true;
  3268. const canOrchestrate = dispatch.subagentToolkit === 'full'
  3269. && (dispatch.maxDepth === -1 || (typeof dispatch.maxDepth === 'number' && dispatch.maxDepth > 1));
  3270. const { toolName, backgroundParam, supportsPerCallModel, availableRoles, runtime } = toolConfig;
  3271. let text = spanText;
  3272. // 1. Named-role argument (subagent_type= / subagent_type:) — only when the
  3273. // target has no native named-agent lookup (dispatch.namedDispatch).
  3274. // Fail-closed validation runs on the extracted value REGARDLESS of
  3275. // which source syntax produced it (#2284 requirement 2).
  3276. if (!namedDispatch) {
  3277. const roleRe = _callArgValueRe('subagent_type');
  3278. const rm = roleRe.exec(_maskStringsAndComments(text));
  3279. if (rm) {
  3280. // Read the VALUE from the original (unmasked) text at the matched
  3281. // offset — `rm[1]` was captured against the mask, whose string
  3282. // INTERIOR is blanked, so it must never be used as the real value.
  3283. const roleValueExpr = text.slice(rm.index + rm[0].length - rm[1].length, rm.index + rm[0].length);
  3284. const literalRole = _literalRoleValue(roleValueExpr);
  3285. if (literalRole !== null) {
  3286. _assertRoleResolvable(literalRole, availableRoles, runtime, 'subagent_type');
  3287. } else if (!availableRoles) {
  3288. // No literal value to check, but a null availableRoles still means
  3289. // the shipped agents/ dir couldn't be resolved at all — fail closed
  3290. // unconditionally rather than silently install an unverifiable call.
  3291. _assertRoleResolvable('', availableRoles, runtime, 'subagent_type');
  3292. }
  3293. text = _projectRoleArgument(text, rm.index, rm.index + rm[0].length, roleValueExpr, toolConfig, canOrchestrate);
  3294. }
  3295. }
  3296. // 1b. #5569: a tool-resolved primitive (`rolePromptResolution: 'tool'`) takes
  3297. // `role` + `task` only. The task text arrives as `prompt`, so the key is
  3298. // renamed; `description` has no counterpart and is dropped.
  3299. if (toolConfig.rolePromptResolution === 'tool') {
  3300. const pm = /\bprompt(\s*[=:])/.exec(_maskStringsAndComments(text));
  3301. if (pm) {
  3302. text = text.slice(0, pm.index) + toolConfig.taskParam + text.slice(pm.index + 'prompt'.length);
  3303. }
  3304. const dm = _callArgValueRe('description').exec(_maskStringsAndComments(text));
  3305. if (dm) {
  3306. text = _stripCallArgument(text, dm.index, dm.index + dm[0].length);
  3307. }
  3308. }
  3309. // 2. Per-call model argument (model= / model:) — stripped entirely when the
  3310. // target has no per-call model-selection parameter (there is no
  3311. // `dispatch` axis for this — it is inherent tool vocabulary, like the
  3312. // parameter names themselves). Also removes now-dead explanatory
  3313. // comment lines directly above a `model=` line that owns its own line
  3314. // (#2284 Finding 5).
  3315. if (!supportsPerCallModel) {
  3316. const modelRe = _callArgValueRe('model');
  3317. const mm = modelRe.exec(_maskStringsAndComments(text));
  3318. if (mm) {
  3319. text = _stripCallArgument(text, mm.index, mm.index + mm[0].length, { consumeLeadingComments: true });
  3320. }
  3321. }
  3322. // 3. Background-dispatch flag (run_in_background= / run_in_background:) —
  3323. // maps onto the target's own background parameter ONLY when documented
  3324. // to support it; otherwise stripped rather than forwarding a parameter
  3325. // the primitive doesn't accept.
  3326. {
  3327. const bgRe = /\brun_in_background\s*[=:]\s*(?:true|false)/;
  3328. const bm = bgRe.exec(_maskStringsAndComments(text));
  3329. if (bm) {
  3330. if (backgroundCapable) {
  3331. const matched = text.slice(bm.index, bm.index + bm[0].length);
  3332. const replaced = matched.replace(/^run_in_background(\s*[=:]\s*)/, `${backgroundParam}$1`);
  3333. text = text.slice(0, bm.index) + replaced + text.slice(bm.index + bm[0].length);
  3334. } else {
  3335. text = _stripCallArgument(text, bm.index, bm.index + bm[0].length);
  3336. }
  3337. }
  3338. }
  3339. // 4. Call-syntax head rename + object-literal brace stripping. Hermes's
  3340. // delegate_task is a flat kwarg call — `Agent({...})`'s wrapper braces
  3341. // are dropped rather than carried through, so every projected call ends
  3342. // up in the same flat shape regardless of source syntax.
  3343. text = text.replace(/^Agent\(/, `${toolName}(`);
  3344. if (hasBraceWrapper) {
  3345. const openMask = maskStringLiterals(text);
  3346. const braceOpenIdx = openMask.indexOf('{');
  3347. if (braceOpenIdx !== -1) text = text.slice(0, braceOpenIdx) + text.slice(braceOpenIdx + 1);
  3348. const closeMask = maskStringLiterals(text);
  3349. const braceCloseIdx = closeMask.lastIndexOf('}');
  3350. if (braceCloseIdx !== -1) text = text.slice(0, braceCloseIdx) + text.slice(braceCloseIdx + 1);
  3351. }
  3352. return text;
  3353. }
  3354. /**
  3355. * Blank the interior (and delimiters) of every string literal inside
  3356. * `spanText` to spaces — same length, newlines preserved — using a fresh,
  3357. * LOCAL quote-tracking scan that starts at `spanText[0]` with NO inherited
  3358. * state. This is deliberately the SAME state-machine shape as the
  3359. * `inString`/`\\`/triple-quote handling inside `findDispatchCallSpans`
  3360. * (double-quoted and `"""`-triple-quoted, backslash-escape aware) — reused
  3361. * here so a call span's quoted argument VALUES (documentation prose, prompt
  3362. * bodies) never masquerade as real call syntax, without EVER falling back to
  3363. * a whole-document cumulative quote-parity mask (the round-2 defect
  3364. * documented on `findDispatchCallSpans` above).
  3365. */
  3366. function _blankStringLiteralInteriors(spanText) {
  3367. let out = '';
  3368. let inString = null; // null | '"' | 'triple'
  3369. for (let i = 0; i < spanText.length; i++) {
  3370. const ch = spanText[i];
  3371. if (inString) {
  3372. if (ch === '\\') {
  3373. out += ' ';
  3374. i++;
  3375. if (i < spanText.length) out += (spanText[i] === '\n') ? '\n' : ' ';
  3376. continue;
  3377. }
  3378. if (inString === 'triple') {
  3379. if (ch === '"' && spanText[i + 1] === '"' && spanText[i + 2] === '"') {
  3380. inString = null;
  3381. out += ' ';
  3382. i += 2;
  3383. continue;
  3384. }
  3385. out += (ch === '\n') ? '\n' : ' ';
  3386. continue;
  3387. }
  3388. if (ch === inString) { inString = null; out += ' '; continue; }
  3389. out += (ch === '\n') ? '\n' : ' ';
  3390. continue;
  3391. }
  3392. if (ch === '"' && spanText[i + 1] === '"' && spanText[i + 2] === '"') {
  3393. inString = 'triple';
  3394. out += ' ';
  3395. i += 2;
  3396. continue;
  3397. }
  3398. if (ch === '"') { inString = '"'; out += ' '; continue; }
  3399. out += ch;
  3400. }
  3401. return out;
  3402. }
  3403. /**
  3404. * Quote-aware view of `content` for the completeness checks below: for every
  3405. * REAL call span located via `findDispatchCallSpans` (once per head word in
  3406. * `headWords`), the string-literal ARGUMENT VALUES inside that span are
  3407. * blanked via `_blankStringLiteralInteriors`; the call's own head word and
  3408. * bare (unquoted) argument tokens are left untouched. `headWords` is
  3409. * processed in order and each pass re-scans the PROGRESSIVELY-masked string
  3410. * — `toolName` first, then `'Agent'` — so a spurious `Agent(` that
  3411. * `findDispatchCallSpans('Agent')` would otherwise "find" purely because it
  3412. * sits inside an outer call's quoted string (e.g. a `description="...Agent()
  3413. * ...subagent_type=x"` argument value) has ALREADY been blanked away by the
  3414. * outer `toolName` pass by the time the `'Agent'` pass runs, so it is never
  3415. * mistaken for a real, independent call. A genuinely real (unquoted) `Agent(`
  3416. * — including one nested as a raw, un-renamed argument value — survives every
  3417. * pass and remains visible to the caller's regex checks.
  3418. */
  3419. function _maskQuotedRegionsWithinCallSpans(content, headWords) {
  3420. let masked = content;
  3421. for (const headWord of headWords) {
  3422. const spans = findDispatchCallSpans(masked, headWord);
  3423. for (let i = spans.length - 1; i >= 0; i--) {
  3424. const { start, end } = spans[i];
  3425. const maskedSpan = _blankStringLiteralInteriors(masked.slice(start, end));
  3426. masked = masked.slice(0, start) + maskedSpan + masked.slice(end);
  3427. }
  3428. }
  3429. return masked;
  3430. }
  3431. /**
  3432. * Post-projection guard (#2284 requirement 3 — belt-and-suspenders): after
  3433. * projection, assert the corpus form the projection could not anticipate
  3434. * never silently ships. Throws an explicit install error (fail-LOUD) rather
  3435. * than let an unprojected/incompletely-projected dispatch call install.
  3436. *
  3437. * #2284 round-2 CRITICAL fix: this is an INDEPENDENT check — it does NOT use
  3438. * `maskStringLiterals` over the whole document (the round-1 primitive whose
  3439. * cumulative, document-wide quote-parity tracking was the root cause of the
  3440. * round-2 defect: a `"`-heavy bash fence upstream of a real call desynced
  3441. * quote state and made `findDispatchCallSpans` blind to that call, shipping
  3442. * a Frankenstein `Agent(gsd_role="...", model="...")` with no detection).
  3443. *
  3444. * #2284 round-3 fix: a BLUNT, mask-free literal check over the whole
  3445. * document (round-2's fix) over-throws — it cannot tell a real residual
  3446. * `Agent(`/`subagent_type` call from the SAME text appearing INSIDE a quoted
  3447. * string (documentation/prompt prose, e.g. `description="...Agent()..."`).
  3448. * The completeness checks (residual `subagent_type` / literal `Agent(`) now
  3449. * run against `_maskQuotedRegionsWithinCallSpans` — quote-aware, but scoped
  3450. * strictly to already-correctly-bounded, per-occurrence-LOCAL call spans
  3451. * (never a whole-document cumulative mask), so a real Frankenstein call
  3452. * (unquoted, real call syntax) still fires while a same-text mention genuinely
  3453. * inside a quoted string does not.
  3454. *
  3455. * The completeness checks also only apply when `namedDispatch` is false: when
  3456. * `dispatch.namedDispatch === true`, `_normalizeDispatchCallSpan` step 1
  3457. * INTENTIONALLY leaves `subagent_type` unprojected (the target primitive
  3458. * resolves named agents itself) — a residual `subagent_type` in that case is
  3459. * the correct, intended output, not a defect. (The call HEAD is still renamed
  3460. * unconditionally regardless of `namedDispatch` — see step 4 there — so a
  3461. * literal `Agent(` residual is gated the same way purely for symmetry with
  3462. * the dispatch-facts-driven contract; it is never actually left unrenamed by
  3463. * the projection in practice.)
  3464. *
  3465. * The model-leak check is unaffected by either fix above — it is orthogonal
  3466. * to `namedDispatch` (gated only by `supportsPerCallModel`) and already
  3467. * bounds each real call via the independently-fixed, per-occurrence-local,
  3468. * non-cumulative `findDispatchCallSpans`, then does a raw substring check
  3469. * within that bound.
  3470. */
  3471. function _assertProjectionComplete(content, toolConfig, namedDispatch = false) {
  3472. const { toolName, runtime, supportsPerCallModel } = toolConfig;
  3473. if (!namedDispatch) {
  3474. const quoteAware = _maskQuotedRegionsWithinCallSpans(content, [toolName, 'Agent']);
  3475. if (/\bsubagent_type\s*[=:]/.test(quoteAware)) {
  3476. throw new Error(
  3477. `${runtime} workflow install: projection left a residual subagent_type reference — refusing to install ` +
  3478. '(fail-closed post-projection guard, #2284)',
  3479. );
  3480. }
  3481. if (/\bAgent\(/.test(quoteAware)) {
  3482. throw new Error(
  3483. `${runtime} workflow install: projection left literal Agent( call syntax — refusing to install ` +
  3484. '(fail-closed post-projection guard, #2284)',
  3485. );
  3486. }
  3487. }
  3488. if (!supportsPerCallModel) {
  3489. for (const span of findDispatchCallSpans(content, toolName)) {
  3490. const rawSpanText = content.slice(span.start, span.end);
  3491. if (/\bmodel\s*[=:]/.test(rawSpanText)) {
  3492. throw new Error(
  3493. `${runtime} workflow install: projection left a leaked model= argument inside a ${toolName}(...) call ` +
  3494. '— refusing to install (fail-closed post-projection guard, #2284)',
  3495. );
  3496. }
  3497. }
  3498. }
  3499. }
  3500. /**
  3501. * Project host-neutral `Agent(...)` named-subagent dispatch prose onto a
  3502. * target runtime's real dispatch primitive. See the file-header comment above
  3503. * for the governing rule: every behavioral branch reads `dispatch` (the
  3504. * runtime's sourced `hostIntegration.dispatch` facts) — none is a hardcoded
  3505. * assumption about a specific runtime. Handles all three real corpus call
  3506. * forms (multi-line one-key-per-line, single-line object-literal, single-line
  3507. * compact) via string-aware call-span detection rather than three independent
  3508. * line-anchored regexes, and closes with a post-projection guard that fails
  3509. * loud on any form it did not anticipate (#2284).
  3510. *
  3511. * @param {string} content
  3512. * @param {{namedDispatch?: boolean, nested?: boolean, maxDepth?: number, background?: boolean, backgroundDispatch?: boolean, subagentToolkit?: string}} dispatch
  3513. * @param {{toolName: string, namedRoleParam: string, promptContentParam: string, structuralRoleParam: string, leafRoleValue: string, backgroundParam: string, supportsPerCallModel: boolean, availableRoles: Set<string>|null, runtime: string}} toolConfig
  3514. */
  3515. function projectNamedDispatchToStructuralDelegate(content, dispatch, toolConfig) {
  3516. const d = dispatch || {};
  3517. const namedDispatch = d.namedDispatch === true;
  3518. const backgroundCapable = d.background === true;
  3519. const { toolName, promptContentParam } = toolConfig;
  3520. let converted = content;
  3521. // 1. The "Agent tool IS available" contract assertion (currently unique to
  3522. // plan-phase.md, matched generically in case of future reuse elsewhere).
  3523. const assertionRe = /The Agent tool IS available in a top-level ([^\n]+?) session\.\s+Always spawn\s+([\s\S]*?)\s+as separate Agent\(\) calls\./;
  3524. converted = converted.replace(assertionRe, (_m, sessionName, roster) => {
  3525. const rosterFlat = roster.replace(/\s+/g, ' ').trim();
  3526. if (namedDispatch) {
  3527. return `The \`${toolName}\` tool IS available in a top-level ${sessionName} session. Always dispatch ${rosterFlat} as separate \`${toolName}()\` calls.`;
  3528. }
  3529. if (toolConfig.rolePromptResolution === 'tool') {
  3530. return (
  3531. `The \`${toolName}\` tool IS available in a top-level ${sessionName} session. It takes a \`${toolConfig.namedRoleParam}\` ` +
  3532. `(the installed gsd-* role name) and a \`${toolConfig.taskParam}\`, resolves the role prompt from the install itself, and ` +
  3533. 'runs the role in an isolated child session; the child cannot dispatch further. FAIL CLOSED — surface the ' +
  3534. `tool's error and stop — if it reports the role unresolved; never execute the role inline as a substitute. ` +
  3535. `Always dispatch ${rosterFlat} as separate \`${toolName}\` calls.`
  3536. );
  3537. }
  3538. return (
  3539. `${sessionName} has no \`Agent\` tool. It exposes \`${toolName}\`, which dispatches by structural role — ` +
  3540. 'it has no concept of a named subagent identity. GSD projects each named gsd-* role onto this primitive ' +
  3541. `itself: resolve the role's prompt file from the active install, load its contents, and embed them in the ` +
  3542. `\`${toolName}\` payload via \`${promptContentParam}\` as the dispatched task's operating instructions. ` +
  3543. 'FAIL CLOSED — surface an explicit error and stop — if a referenced role prompt cannot be resolved; never ' +
  3544. `execute the role inline as a substitute. In a top-level ${sessionName} session, always dispatch ` +
  3545. `${rosterFlat} as separate \`${toolName}\` calls.`
  3546. );
  3547. });
  3548. // 1b. Dispatch-depth-availability prose immediately adjacent to a renamed
  3549. // `Agent()` mention in the SAME sentence (plan-review-convergence.md
  3550. // ~lines 108, 347, 355) — a bare "Agent" left un-renamed right next to
  3551. // the projection's own `Agent()`→`${toolName}()` rename produced
  3552. // self-contradictory installed text (e.g. "...delegate_task(...)...
  3553. // with Agent available..."). Narrowly scoped to the EXACT known
  3554. // phrases the projection itself creates the inconsistency beside —
  3555. // never a broad bare-word `Agent` rename, which would corrupt
  3556. // legitimate `Agent`-adjacent prose elsewhere in the corpus (role
  3557. // names, "Agent Brief", agent-file references).
  3558. converted = converted.replace(
  3559. /\borchestrator runs at depth 0 with Agent available\b/g,
  3560. `orchestrator runs at depth 0 with ${toolName} available`,
  3561. );
  3562. converted = converted.replace(
  3563. /\(bug #936: depth-1 Agent has no Agent tool\)/g,
  3564. `(bug #936: depth-1 ${toolName} has no nested ${toolName})`,
  3565. );
  3566. // 2. Per-call model-selection prose ("Model resolution:" paragraph,
  3567. // execute-phase.md) + inline backtick-quoted model-mention prose
  3568. // examples (not live call sites) — only rewritten when the target
  3569. // primitive has no per-call model parameter at all.
  3570. if (!toolConfig.supportsPerCallModel) {
  3571. const modelResolutionRe = /\*\*Model resolution:\*\* If `executor_model` is `"inherit"`, omit the `model=` parameter from all `Agent\(\)` calls — do NOT pass `model="inherit"` to Agent\. Omitting the `model=` parameter causes [^.]+\. Only set `model=` when `executor_model` is an explicit model name \(e\.g\., `"claude-sonnet-5"`, `"claude-opus-4-8"`\)\./;
  3572. converted = converted.replace(
  3573. modelResolutionRe,
  3574. `**Model resolution:** \`${toolName}\` has no per-call model-selection parameter — every dispatched role ` +
  3575. `always inherits the host session's active model. Never pass \`model=\` to \`${toolName}\`; drop the ` +
  3576. '`executor_model` value entirely for this runtime.',
  3577. );
  3578. converted = converted.replace(/`model="[^"`\n]*"`,?\s*(?:and\s+)?/g, '');
  3579. }
  3580. // 3. Background-dispatch PROSE mentions outside any real call span (e.g.
  3581. // execute-phase.md:595,600 — `run_in_background: true` inline
  3582. // documentation, not a call argument) — #2284 Finding 3. Only rewritten
  3583. // when the target is documented to support background dispatch (a
  3584. // prose mention of an unsupported capability would be equally
  3585. // misleading as a real leaked argument).
  3586. if (backgroundCapable) {
  3587. converted = converted.replace(
  3588. /\brun_in_background(\s*[=:]\s*(?:true|false))/g,
  3589. `${toolConfig.backgroundParam}$1`,
  3590. );
  3591. }
  3592. // 4. Call-span-based normalization — the core of the fix. Every
  3593. // `Agent(...)`/`Agent({...})` occurrence (all three corpus forms) is
  3594. // located via string-aware balanced paren/brace matching, then
  3595. // normalized as a unit; spans are rebuilt right-to-left so earlier
  3596. // offsets stay valid while later ones are rewritten.
  3597. const spans = findDispatchCallSpans(converted, 'Agent');
  3598. for (let i = spans.length - 1; i >= 0; i--) {
  3599. const { start, end, hasBraceWrapper } = spans[i];
  3600. const rebuilt = _normalizeDispatchCallSpan(converted.slice(start, end), hasBraceWrapper, d, toolConfig);
  3601. converted = converted.slice(0, start) + rebuilt + converted.slice(end);
  3602. }
  3603. // 5. "Agent tool" capability mentions (conditions gating parallel vs.
  3604. // sequential dispatch, e.g. map-codebase.md) → the real target primitive
  3605. // name, which resolves these conditions accurately since it IS a real,
  3606. // always-available dispatch primitive for this target.
  3607. converted = converted.replace(/\bAgent tool\b/g, toolName);
  3608. // 5b. Catch-all: a `subagent_type` mention that is NOT part of any real
  3609. // `Agent(...)` call span (e.g. map-codebase.md's inline documentation
  3610. // prose ``Use Agent tool with `subagent_type="X"`, ...`` — disconnected
  3611. // example syntax, not a live call). Renamed for the same accuracy the
  3612. // real calls get; a literal quoted role value is still fail-closed
  3613. // validated even though there is no call structure to inject
  3614. // role-prompt/fail-closed guidance INTO.
  3615. if (!namedDispatch) {
  3616. converted = converted.replace(
  3617. /\bsubagent_type(\s*[=:]\s*"[^"]*")/g,
  3618. (_m, rest) => {
  3619. const literalRole = _literalRoleValue(rest.replace(/^\s*[=:]\s*/, ''));
  3620. if (literalRole !== null) {
  3621. _assertRoleResolvable(literalRole, toolConfig.availableRoles, toolConfig.runtime, 'subagent_type (prose mention)');
  3622. }
  3623. return `${toolConfig.namedRoleParam}${rest}`;
  3624. },
  3625. );
  3626. converted = converted.replace(/\bsubagent_type(\s*[=:])/g, `${toolConfig.namedRoleParam}$1`);
  3627. }
  3628. // 5c. Safety net (#2284 requirement 2): the PRIMARY mechanism for
  3629. // eliminating literal `Agent(` syntax is complete span detection (step
  3630. // 4) — this unconditional final rename exists only so that even a call
  3631. // span detection somehow misses at least loses its `Agent(` head
  3632. // rather than shipping the literal Claude-shaped tool name verbatim.
  3633. // A call caught only by this safety net is still INCOMPLETELY
  3634. // normalized (no role/model handling) and gets caught by the
  3635. // independent post-projection guard below via its OTHER invariants
  3636. // (residual subagent_type / leaked model=), which this safety net does
  3637. // not touch — the install still fails closed for a missed span.
  3638. converted = converted.replace(/\bAgent\(/g, `${toolName}(`);
  3639. // 6. Post-projection guard (#2284 requirement 3): fail loud, never ship
  3640. // silently, on any residual/leaked form the projection above did not
  3641. // anticipate. `namedDispatch` gates the completeness checks — a
  3642. // residual subagent_type is INTENTIONAL, not a defect, when the target
  3643. // resolves named agents itself (see `_assertProjectionComplete`).
  3644. _assertProjectionComplete(converted, toolConfig, namedDispatch);
  3645. return converted;
  3646. }
  3647. const HERMES_DISPATCH_TOOL_CONFIG = Object.freeze({
  3648. toolName: 'delegate_task',
  3649. namedRoleParam: 'gsd_role',
  3650. promptContentParam: 'gsd_role_prompt',
  3651. structuralRoleParam: 'role',
  3652. leafRoleValue: 'leaf',
  3653. backgroundParam: 'background',
  3654. supportsPerCallModel: false,
  3655. });
  3656. /**
  3657. * Hermes `.md` content converter (#2284): brand-swap (unchanged behavior,
  3658. * descriptor-driven per `hostBehaviors.brandingRewrites`) followed by the
  3659. * generic named-dispatch → `delegate_task` projection above, driven by
  3660. * `capabilities/hermes/capability.json`'s `hostIntegration.dispatch` (read
  3661. * via `_hostIntegrationDispatch`, values UNCHANGED by this fix — they are
  3662. * already documentation-sourced and correct).
  3663. */
  3664. function convertClaudeToHermesMarkdown(content, ctx) {
  3665. const runtime = (ctx && ctx.runtime) || 'hermes';
  3666. const b = hostBehaviorsFor(runtime).brandingRewrites;
  3667. let converted = content;
  3668. if (b) {
  3669. converted = converted.replace(/CLAUDE\.md/g, b['CLAUDE.md']);
  3670. // #2284(b): skips <runtime_compatibility> comparison-table content (protected region).
  3671. converted = applyClaudeCodeBrandSwap(converted, b['Claude Code']);
  3672. converted = converted.replace(/\.claude\//g, b['.claude/']);
  3673. }
  3674. const dispatch = _hostIntegrationDispatch(runtime);
  3675. const toolConfig = Object.assign({}, HERMES_DISPATCH_TOOL_CONFIG, {
  3676. availableRoles: _resolveAvailableGsdRoles(),
  3677. runtime,
  3678. });
  3679. return projectNamedDispatchToStructuralDelegate(converted, dispatch, toolConfig);
  3680. }
  3681. // ── End Hermes converters ────────────────────────────────────────────────────
  3682. // #5569: Pi projects host-neutral `Agent(...)` calls onto its `gsd_dispatch`
  3683. // tool (pi/gsd.cjs). The tool resolves and verifies the role prompt itself, so
  3684. // the projection only renames the arguments (`rolePromptResolution: 'tool'`).
  3685. const PI_DISPATCH_TOOL_CONFIG = Object.freeze({
  3686. toolName: 'gsd_dispatch',
  3687. namedRoleParam: 'role',
  3688. taskParam: 'task',
  3689. promptContentParam: 'task',
  3690. structuralRoleParam: 'role',
  3691. leafRoleValue: 'leaf',
  3692. backgroundParam: 'background',
  3693. supportsPerCallModel: false,
  3694. rolePromptResolution: 'tool',
  3695. });
  3696. function convertClaudeToPiMarkdown(content, ctx) {
  3697. const runtime = (ctx && ctx.runtime) || 'pi';
  3698. const dispatch = _hostIntegrationDispatch(runtime);
  3699. const toolConfig = Object.assign({}, PI_DISPATCH_TOOL_CONFIG, {
  3700. availableRoles: _resolveAvailableGsdRoles(),
  3701. runtime,
  3702. });
  3703. return projectNamedDispatchToStructuralDelegate(content, dispatch, toolConfig);
  3704. }
  3705. function convertSlashCommandsToCodexSkillMentions(content) {
  3706. // Colon-style /gsd: never appears as a filesystem path segment, so no boundary guard is needed (unlike the hyphen-style below).
  3707. let converted = content.replace(/\/gsd:([a-z0-9-]+)/gi, (_, commandName) => {
  3708. return `$gsd-${String(commandName).toLowerCase()}`;
  3709. });
  3710. // Convert hyphen-style command references (workflow output) to Codex $ prefix.
  3711. // A real /gsd-<cmd> MENTION is defined positively by two boundaries, so any
  3712. // in-path occurrence is excluded by construction (no denylist of preceding
  3713. // chars to maintain — see #712, supersedes the #637/#704 lookbehind treadmill):
  3714. // 1. Left boundary: opens at start-of-string, whitespace, or an inline-prose
  3715. // delimiter (backtick/quote/paren/bracket) — e.g. `/gsd-execute-phase`.
  3716. // 2. Right boundary: the command token is NOT followed by a path separator
  3717. // `/` (a path continues: `/gsd-core/bin/...`; a command does not). The
  3718. // `(?![a-z0-9/-])` also blocks regex backtracking to a shorter command.
  3719. // This converts backtick-wrapped MENTIONS (`/gsd-foo`) while leaving backtick-
  3720. // wrapped PATHS (`/gsd-core/workflows/update.md`) untouched (#712).
  3721. converted = converted.replace(/(?<=^|[\s`"'([])\/gsd-([a-z0-9-]+)(?![a-z0-9/-])/gi, (_, commandName) => {
  3722. return `$gsd-${String(commandName).toLowerCase()}`;
  3723. });
  3724. return converted;
  3725. }
  3726. const CODEX_GSD_TOOLS_INVOCATION = 'node "$HOME/.codex/gsd-core/bin/gsd-tools.cjs"';
  3727. function rewriteBareGsdToolsCommandsForCodex(content) {
  3728. return content
  3729. .replace(/(^[ \t]*)gsd-tools(?=\s)/gm, `$1${CODEX_GSD_TOOLS_INVOCATION}`)
  3730. .replace(/(\$\(\s*)gsd-tools(?=\s)/g, `$1${CODEX_GSD_TOOLS_INVOCATION}`)
  3731. .replace(/(`\s*)gsd-tools(?=\s)/g, `$1${CODEX_GSD_TOOLS_INVOCATION}`)
  3732. .replace(/((?:&&|\|\||[;|])\s*)gsd-tools(?=\s)/g, `$1${CODEX_GSD_TOOLS_INVOCATION}`);
  3733. }
  3734. function convertClaudeToCodexMarkdown(content) {
  3735. let converted = convertSlashCommandsToCodexSkillMentions(filterRuntimeNotesForTarget(content, 'codex'));
  3736. converted = converted.replace(/\$ARGUMENTS\b/g, '{{GSD_ARGS}}');
  3737. // Remove /clear references — Codex has no equivalent command
  3738. // Handle backtick-wrapped: `\/clear` then: → (removed)
  3739. converted = converted.replace(/`\/clear`\s*,?\s*then:?\s*\n?/gi, '');
  3740. // Handle bare: /clear then: → (removed)
  3741. converted = converted.replace(/\/clear\s*,?\s*then:?\s*\n?/gi, '');
  3742. // Handle standalone /clear on its own line
  3743. converted = converted.replace(/^\s*`?\/clear`?\s*$/gm, '');
  3744. // Path replacement: .claude → .codex (#1430)
  3745. converted = converted.replace(/\$HOME\/\.claude\//g, '$HOME/.codex/');
  3746. converted = converted.replace(/~\/\.claude\//g, '~/.codex/');
  3747. converted = converted.replace(/\.\/\.claude\//g, './.codex/');
  3748. // Bare ~/.claude without trailing slash (e.g. configDir = ~/.claude)
  3749. converted = converted.replace(/\$HOME\/\.claude\b/g, '$HOME/.codex');
  3750. converted = converted.replace(/~\/\.claude\b/g, '~/.codex');
  3751. // Bare/project-relative .claude/... references (#2639). Covers strings like
  3752. // "check `.claude/skills/`" where there is no ~/, $HOME/, or ./ anchor.
  3753. // Negative lookbehind prevents double-replacing already-anchored forms and
  3754. // avoids matching inside URLs or other slash-prefixed paths.
  3755. converted = converted.replace(/(?<![A-Za-z0-9_\-./~$])\.claude\//g, '.codex/');
  3756. // `.claudeignore` → `.codexignore` (#2639). Codex honors its own ignore
  3757. // file; leaving the Claude-specific name is misleading in agent prompts.
  3758. converted = converted.replace(/\.claudeignore\b/g, '.codexignore');
  3759. // Codex installs the tools shim under ~/.codex but does not guarantee a
  3760. // bare `gsd-tools` binary on PATH. Keep resolver probes such as
  3761. // `command -v gsd-tools` intact; rewrite only command invocations.
  3762. converted = rewriteBareGsdToolsCommandsForCodex(converted);
  3763. // Runtime-neutral agent name replacement (#766)
  3764. converted = neutralizeAgentReferences(converted, 'AGENTS.md');
  3765. return converted;
  3766. }
  3767. function getCodexSkillAdapterHeader(skillName) {
  3768. const invocation = `$${skillName}`;
  3769. return `<codex_skill_adapter>
  3770. ## A. Skill Invocation
  3771. - This skill is invoked by mentioning \`${invocation}\`.
  3772. - Treat all user text after \`${invocation}\` as \`{{GSD_ARGS}}\`.
  3773. - If no arguments are present, treat \`{{GSD_ARGS}}\` as empty.
  3774. ## B. AskUserQuestion → request_user_input Mapping
  3775. GSD workflows use \`AskUserQuestion\` (Claude Code syntax). Translate to Codex \`request_user_input\`:
  3776. Parameter mapping:
  3777. - \`header\` → \`header\`
  3778. - \`question\` → \`question\`
  3779. - Options formatted as \`"Label" — description\` → \`{label: "Label", description: "description"}\`
  3780. - Generate \`id\` from header: lowercase, replace spaces with underscores
  3781. Batched calls:
  3782. - \`AskUserQuestion([q1, q2])\` → single \`request_user_input\` with multiple entries in \`questions[]\`
  3783. Multi-select workaround:
  3784. - Codex has no \`multiSelect\`. Use sequential single-selects, or present a numbered freeform list asking the user to enter comma-separated numbers.
  3785. Execute mode fallback:
  3786. - When \`request_user_input\` is rejected or unavailable, activate TEXT_MODE: append \`--text\` to \`{{GSD_ARGS}}\` so the workflow's built-in text-mode branching takes over. Present every \`AskUserQuestion\` call as a plain-text numbered list, then stop and wait for the user's reply. Do NOT pick a default and continue (#3018 / #3808).
  3787. - You may only proceed without a user answer when one of these is true:
  3788. (a) the invocation included an explicit non-interactive flag (\`--auto\` or \`--all\`),
  3789. (b) the user has explicitly approved a specific default for this question, or
  3790. (c) the workflow's documented contract says defaults are safe (e.g. autonomous lifecycle paths).
  3791. - Do NOT write workflow artifacts (CONTEXT.md, DISCUSSION-LOG.md, PLAN.md, checkpoint files) until the user has answered the plain-text questions or one of (a)-(c) above applies. Surfacing the questions and waiting is the correct response — silently defaulting and writing artifacts is the #3018 failure mode.
  3792. ## C. Task() → spawn_agent Mapping
  3793. GSD workflows use \`Task(...)\` (Claude Code syntax). Translate to Codex collaboration tools:
  3794. **Schema detection (required first step):** Before spawning, inspect the \`spawn_agent\`
  3795. tool's visible parameter schema (via \`tool_search\` or the tool list). Use the presence
  3796. of \`agent_type\` only to choose typed dispatch versus the generic-agent workaround.
  3797. Detect optional fields independently: \`model\`, \`reasoning_effort\`, \`task_name\`,
  3798. \`fork_turns\`, and \`fork_context\` may be added or removed without \`agent_type\` changing.
  3799. Never infer one field from a schema/version label or from the presence of another field.
  3800. - **agent_type-capable schema:** \`spawn_agent\` advertises \`agent_type\` — typed GSD agent dispatch is available.
  3801. - **Generic schema:** \`spawn_agent\` does not advertise \`agent_type\` — typed GSD agent dispatch is unavailable in this session, even if other optional fields are present.
  3802. Typed mapping (agent_type-capable schema only):
  3803. - \`Task(subagent_type="X", prompt="Y")\` → \`spawn_agent(agent_type="X", message="Y")\`
  3804. - \`Agent(subagent_type="X", prompt="Y")\` → \`spawn_agent(agent_type="X", message="Y")\`
  3805. - \`Task(model="{resolved_model}")\` → pass \`model="{resolved_model}"\` when the
  3806. visible \`spawn_agent\` schema advertises \`model\` and the resolved value is explicit.
  3807. This is how \`model_profile\` tier routing, including \`adaptive\`, reaches the child agent.
  3808. Omit \`model\` only when the schema does not advertise \`model\`, or when the value is
  3809. missing, empty, or \`"inherit"\`; omission deliberately inherits the session/static agent
  3810. configuration. Explicit \`model_overrides\` may also be embedded in agent \`.toml\` files,
  3811. but ordinary profile-resolved models are not, so a TOML file is not a reason to discard
  3812. an available inline value.
  3813. - Before each typed spawn, obtain the paired effort for its role with
  3814. \`gsd_run query resolve-model <subagent_type> --pick effort\` when the workflow has not
  3815. already exposed it. The resolver's unified \`effort\` field maps to the Codex spawn argument
  3816. \`reasoning_effort\`; do not look for a resolver field named \`reasoning_effort\`.
  3817. Pass it when the visible \`spawn_agent\` schema advertises \`reasoning_effort\`. Omit the
  3818. field when it is not advertised, or when the value is missing, empty, \`"inherit"\`, or
  3819. unsupported; do not invent one-off effort literals in workflow prose.
  3820. - \`fork_context: false\` by default — GSD agents load their own context via \`<required_reading>\` blocks
  3821. - \`task_name\` — when advertised, provide a descriptive name for each spawned task
  3822. - \`fork_turns\` — when advertised, controls turn-forking depth; coexists with \`fork_context\` (not a replacement)
  3823. - \`Task(isolation="worktree")\` / \`Agent(isolation="worktree")\` → no direct \`spawn_agent\` mapping,
  3824. but Codex declares \`dispatch.isolation: orchestrator-worktree\` (#2584). Codex
  3825. \`spawn_agent\` still does not create or bind a git worktree; instead GSD itself
  3826. creates the worktree and process-spawns the executor into it with
  3827. \`codex exec --cd <dir>\`, performing every git operation on the executor's behalf
  3828. (its \`workspace-write\` sandbox makes \`.git\` read-only). Workflows must therefore
  3829. never fabricate a manual worktree protocol — route through the negotiated
  3830. isolation adapter, which still fails closed for hosts declaring \`none\` (#3360).
  3831. Foreground handoffs:
  3832. - spawn_agent is asynchronous. When the source Agent(...) or Task(...) declares
  3833. run_in_background=false, call collaboration.wait_agent(timeout_ms=...) immediately after
  3834. spawn and keep the parent turn active until that child returns a terminal result.
  3835. - collaboration.wait_agent is a mailbox wakeup, NOT a completion oracle: "Wait completed"
  3836. can mean only that a child sent an interim MESSAGE or status update. After every wakeup,
  3837. inspect the named child's update/status. Only a FINAL_ANSWER or a terminal agent status
  3838. (completed, failed, or cancelled) ends the foreground handoff.
  3839. - On an interim MESSAGE or any non-terminal status, do not report an outcome, send a
  3840. continuation, start parent work, or end the parent turn. Call collaboration.wait_agent
  3841. again for the same child. If a terminal response is absent after an abnormal end, reconcile
  3842. the workflow's durable artifacts before classifying the child.
  3843. - This applies to one foreground child as well as fan-out. The child retains its workflow's
  3844. own checkpoint loop; do not report an outcome or start any further parent work before its
  3845. terminal result is available.
  3846. Generic-agent workaround (multi_agent_v1 schema — NO agent_type field):
  3847. When only the generic \`multi_agent_v1\` schema is available, typed GSD agent dispatch
  3848. (\`gsd-planner\`, \`gsd-executor\`, etc.) is NOT possible. This is a known Codex limitation
  3849. (openai/codex#15250). **This workaround is NOT equivalent to typed gsd-planner/gsd-executor
  3850. execution** — GSD agents carry project-aware prompts, audit logging, and workflow context
  3851. that a generic subagent lacks. Use the following fallback:
  3852. 1. Resolve your active Codex config root — the directory that contains your \`config.toml\`.
  3853. This directory is determined in priority order: \`$CODEX_HOME\` (if set), the path given
  3854. by \`--config-dir\` (if passed on invocation), a local \`.codex\` directory in the current
  3855. project (if \`--local\` was used), or the default global config directory. Read
  3856. \`agents/<agent-name>.toml\` relative to that config root to extract the agent's system
  3857. instructions.
  3858. 2. Inject those instructions as a role-preamble into a generic \`spawn_agent(message=...)\` call.
  3859. 3. Label results and logs clearly as "generic-agent workaround" so the orchestrator and user
  3860. know full typed-agent guarantees are not in effect.
  3861. 4. Where typed dispatch is mandatory for correctness (e.g. worktree isolation), fail closed
  3862. and report the schema limitation rather than silently degrading.
  3863. Spawn restriction:
  3864. - Codex restricts \`spawn_agent\` to cases where the user has explicitly
  3865. requested sub-agents. When automatic spawning is not permitted, do the
  3866. work inline in the current agent rather than attempting to force a spawn.
  3867. - In some Codex sessions, multi-agent tooling can be deferred. If \`spawn_agent\`
  3868. is not currently visible, discover tools first via \`tool_search\` before
  3869. defaulting to inline execution.
  3870. Parallel fan-out:
  3871. - For each child, loop on collaboration.wait_agent(timeout_ms=...) until its own terminal
  3872. result is observed. A mailbox update from one child never completes another child, and an
  3873. interim MESSAGE never completes its sender.
  3874. - Spawn multiple agents → collect agent IDs → \`collaboration.wait_agent(timeout_ms=...)\` for each to complete
  3875. - Do NOT use \`functions.wait(cell_id=...)\` — that is an unrelated exec-cell tool, not the collaboration wait
  3876. Result parsing:
  3877. - Look for structured markers in agent output: \`CHECKPOINT\`, \`PLAN COMPLETE\`, \`SUMMARY\`, etc.
  3878. - \`close_agent(id)\` after collecting results — but only if \`close_agent\` is visible in the current
  3879. tool schema (check via \`tool_search\` first, same schema-detection gate as \`spawn_agent\` above)
  3880. </codex_skill_adapter>`;
  3881. }
  3882. function convertClaudeCommandToCodexSkill(content, skillName) {
  3883. const converted = convertClaudeToCodexMarkdown(content);
  3884. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  3885. let description = `Run GSD workflow ${skillName}.`;
  3886. if (frontmatter) {
  3887. const maybeDescription = extractFrontmatterField(frontmatter, 'description');
  3888. if (maybeDescription) {
  3889. description = maybeDescription;
  3890. }
  3891. }
  3892. description = toSingleLine(description);
  3893. const shortDescription = description.length > 180 ? `${description.slice(0, 177)}...` : description;
  3894. const adapter = getCodexSkillAdapterHeader(skillName);
  3895. return `---\nname: ${yamlQuote(skillName)}\ndescription: ${yamlQuote(description)}\nmetadata:\n short-description: ${yamlQuote(shortDescription)}\n---\n\n${adapter}\n\n${body.trimStart()}`;
  3896. }
  3897. /**
  3898. * Convert Claude Code agent markdown to Codex agent format.
  3899. * Applies base markdown conversions, then adds a <codex_agent_role> header
  3900. * and cleans up frontmatter (removes tools/color fields).
  3901. */
  3902. function convertClaudeAgentToCodexAgent(content) {
  3903. let converted = convertClaudeToCodexMarkdown(content);
  3904. const { frontmatter, body } = extractFrontmatterAndBody(converted);
  3905. if (!frontmatter) return converted;
  3906. const name = extractFrontmatterField(frontmatter, 'name') || 'unknown';
  3907. const description = extractFrontmatterField(frontmatter, 'description') || '';
  3908. // parseFrontmatterTools reads both the inline comma list and the YAML block
  3909. // list (#5790).
  3910. const tools = parseFrontmatterTools(frontmatter).join(', ');
  3911. const roleHeader = `<codex_agent_role>
  3912. role: ${name}
  3913. tools: ${tools}
  3914. purpose: ${toSingleLine(description)}
  3915. </codex_agent_role>`;
  3916. const cleanFrontmatter = `---\nname: ${yamlQuote(name)}\ndescription: ${yamlQuote(toSingleLine(description))}\n---`;
  3917. return `${cleanFrontmatter}\n\n${roleHeader}\n${body}`;
  3918. }
  3919. /**
  3920. * #2310 — True if `model` is an Anthropic-flavored value that must never appear as a
  3921. * Codex agent `.toml` `model`. Two forms: (a) a bare Claude Agent-tool tier alias
  3922. * (opus/sonnet/haiku/fable — the canonical CLAUDE_AGENT_ALIASES); (b) any Claude model
  3923. * id in any provider namespacing — `claude-*`, `anthropic/claude-*`, `us.anthropic.claude-*`
  3924. * (the forms the catalog assigns to opencode/hermes/kilo, reachable on a Codex .toml via
  3925. * the runtime-resolver path). No OpenAI/Codex model id contains "claude", so a
  3926. * case-insensitive substring test is a safe, exhaustive guard for (b). Codex/ChatGPT
  3927. * rejects all of these.
  3928. *
  3929. * #3241 — thin delegation to the shared predicate on src/model-catalog.cts (moved there
  3930. * so it can't diverge across Codex-posture surfaces); kept as a local name because it
  3931. * reads better at the call sites below.
  3932. */
  3933. function _isAnthropicFlavoredModel(model) {
  3934. return gsdIsAnthropicFlavoredModel(model);
  3935. }
  3936. // #2310 — dedupe stderr warnings so repeated agent emits don't spam (mirrors the
  3937. // #2041/#1133 model-resolver warn-dedupe). Value is length-capped so an oversized
  3938. // or secret-shaped override cannot leak in full to logs.
  3939. const _codexModelOverrideDroppedWarned = new Set();
  3940. function _warnCodexModelOverrideDropped(agentName, value) {
  3941. const key = `${agentName}::${value}`;
  3942. if (_codexModelOverrideDroppedWarned.has(key)) return;
  3943. _codexModelOverrideDroppedWarned.add(key);
  3944. const safe = String(value).length > 64 ? `${String(value).slice(0, 64)}…` : String(value);
  3945. process.stderr.write(
  3946. `gsd: warning — Codex agent "${agentName}" model "${safe}" is not a valid Codex model ` +
  3947. `(Anthropic alias/id); dropping it so Codex uses a valid default. ` +
  3948. `Set runtime:"codex" or pin a gpt-* model to route it.\n`,
  3949. );
  3950. }
  3951. // #3241 — one-time per-install deprecation notice: the automatic runtime-resolver
  3952. // per-tier Codex model embed was removed (D1/D5, ADR-2313 passive-posture epic). When
  3953. // the resolver *would have* supplied a model and nothing else ends up pinned, this
  3954. // notice points the user at model_overrides as the explicit-pin replacement. Dedupes
  3955. // with a module-level boolean (mirrors _codexModelOverrideDroppedWarned's Set above)
  3956. // so a multi-agent install — every Codex agent hits this condition simultaneously —
  3957. // emits exactly one line, not one per agent. Reset once per install() call (see
  3958. // install()) so the "at most once" window is per-install, not per-process. That
  3959. // reset lives ONLY inside install() (~:10116) — generateCodexAgentToml is also
  3960. // exported standalone (~:13460), and a caller invoking it directly/repeatedly
  3961. // outside install() gets process-lifetime dedupe instead of per-install. No
  3962. // current test depends on the standalone caller's dedupe window.
  3963. let _codexResolverModelOmittedWarned = false;
  3964. function _warnCodexResolverModelOmitted() {
  3965. if (_codexResolverModelOmittedWarned) return;
  3966. _codexResolverModelOmittedWarned = true;
  3967. process.stderr.write(
  3968. 'gsd: notice — Codex agents no longer auto-pin a per-tier model from the runtime ' +
  3969. 'resolver; set model_overrides for an agent if you want a specific Codex model ' +
  3970. 'instead of the session model.\n',
  3971. );
  3972. }
  3973. // Test seam only — bin/install.js deliberately keeps per-install warning/notice
  3974. // dedupe in module scope (both the _codexModelOverrideDroppedWarned Set above and
  3975. // the _codexResolverModelOmittedWarned boolean; install() resets the latter at
  3976. // ~:10116). A unit test that drives generateCodexAgentToml() directly, without
  3977. // going through install(), has no other way to reset either store between
  3978. // assertions without busting the require.cache (which breaks module-instance
  3979. // sharing with the rest of the suite). This is the single sanctioned way for a
  3980. // unit test to clear both dedupe stores — exported so tests can call it instead.
  3981. function _resetCodexWarningDedupeForTests() {
  3982. _codexModelOverrideDroppedWarned.clear();
  3983. _codexResolverModelOmittedWarned = false;
  3984. }
  3985. /**
  3986. * Generate a per-agent .toml config file for Codex.
  3987. * Sets required agent metadata, sandbox_mode, and developer_instructions
  3988. * from the agent markdown content.
  3989. *
  3990. * @param {string} agentName
  3991. * @param {string} agentContent
  3992. * @param {object|null} modelOverrides
  3993. * @param {object|null} runtimeResolver — runtime-aware tier resolver from readGsdRuntimeProfileResolver
  3994. * @param {object|null} effortCfg — #443: merged effort config from readGsdEffectiveEffortConfig
  3995. */
  3996. function generateCodexAgentToml(agentName, agentContent, modelOverrides = null, runtimeResolver = null, effortCfg = null, sandboxTier = 'codex-agent-sandbox') {
  3997. const { frontmatter, body } = extractFrontmatterAndBody(agentContent);
  3998. const frontmatterText = frontmatter || '';
  3999. // #3897 list-form parse fix, Fix 3: `toolsRaw` MUST come from the same
  4000. // shared `extractToolsValue` reader `checkCodexSandboxPosture` uses, not
  4001. // this file's own `extractFrontmatterField` — the two used to disagree on
  4002. // YAML block-list `tools:` form (`extractFrontmatterField`'s single-line
  4003. // regex read only the first list item), which is exactly the generative-
  4004. // fix-divergence shape CLAUDE.md warns about for two paths feeding one
  4005. // derivation. `extractToolsValue` does its own `---`-delimited frontmatter
  4006. // scan of the full `agentContent`, so it is not re-derived from
  4007. // `frontmatterText` here.
  4008. const toolsRaw = extractToolsValue(agentContent) ?? '';
  4009. const resolvedName = extractFrontmatterField(frontmatterText, 'name') || agentName;
  4010. // #3897 rung 3 — derived from the role's own tool contract (HALT.md option
  4011. // 2). The former hand-maintained CODEX_AGENT_SANDBOX map is deleted (ADR-3473
  4012. // §8.3): it was fully redundant with this derivation, zero disagreements
  4013. // across all 11 entries. Never a silent `|| 'read-only'` fallback either.
  4014. // Derivation itself lives in codex-agent-toml.cjs, which does no frontmatter
  4015. // parsing of its own (no third copy of that extraction) — it takes the
  4016. // already-resolved `tools:` value, extracted via the shared reader above.
  4017. //
  4018. // #3897 security review F1 (blocker): pass BOTH candidate identities —
  4019. // `agentName` (the caller's filename-stem identity) AND `resolvedName`
  4020. // (the frontmatter `name:` this function's OWN emitted `name = ...` line
  4021. // uses, and what `installCodexConfig`'s caller keys the output PATH on) —
  4022. // never just one. Deciding the sandbox for `agentName` alone and applying
  4023. // it to an artifact that a DIFFERENT identity (`resolvedName`) names is
  4024. // exactly how a held role's own `.toml` could end up `workspace-write`
  4025. // (rename the source file, or plant a sibling whose `name:` collides with
  4026. // a held role). `deriveCodexSandboxMode` takes the most restrictive result
  4027. // across every candidate — see its doc and `isSandboxHeld` in
  4028. // codex-agent-toml.cjs.
  4029. const sandboxMode = deriveCodexSandboxMode([agentName, resolvedName], toolsRaw);
  4030. const resolvedDescription = toSingleLine(
  4031. extractFrontmatterField(frontmatterText, 'description') || `GSD agent ${resolvedName}`
  4032. );
  4033. const instructions = body.trim();
  4034. const lines = [
  4035. `name = ${JSON.stringify(resolvedName)}`,
  4036. `description = ${JSON.stringify(resolvedDescription)}`,
  4037. ];
  4038. if (sandboxTier != null && sandboxTier !== 'none') {
  4039. lines.push(`sandbox_mode = "${sandboxMode}"`);
  4040. }
  4041. // Embed model override when configured in ~/.gsd/defaults.json so that
  4042. // model_overrides is respected on Codex (which uses static TOML, not inline
  4043. // Task() model parameters). See #2256.
  4044. // #2310 — a Codex .toml `model` MUST be a real Codex/OpenAI model id. Codex is a
  4045. // passive/session-only model host (ADR-1239): GSD cannot reliably route per-agent
  4046. // tiers, and a bare GSD/Claude tier alias (opus/sonnet/haiku/fable) or a claude-*
  4047. // id 400s on a ChatGPT-account Codex ("The 'sonnet' model is not supported when
  4048. // using Codex with a ChatGPT account"). So: embed ONLY an explicit real-Codex
  4049. // model pin from model_overrides; omit anything Anthropic-flavored so the agent
  4050. // inherits the always-available session model.
  4051. // #3241 (D1/D5) — the runtime-aware tier-resolver auto-embed that used to fall
  4052. // through here when model_overrides had nothing was removed: Codex is passive by
  4053. // default now, and only an explicit model_overrides pin survives. See the
  4054. // deprecation-notice block below for the population that used to get a pin from
  4055. // the resolver and no longer does.
  4056. const rawModelOverride = modelOverrides?.[resolvedName] || modelOverrides?.[agentName];
  4057. let pinnedModel = null;
  4058. if (rawModelOverride) {
  4059. // Trim before the truthiness test (#3241 defect fix): a whitespace-only value
  4060. // (e.g. ' ') is a truthy JS string but not a model id — it must not be
  4061. // embedded verbatim (`model = " "`, a live pre-fix defect) or routed to
  4062. // _warnCodexModelOverrideDropped, whose "is not a valid Codex model
  4063. // (Anthropic alias/id)" text would misdescribe a blank config field. It is
  4064. // silently dropped, matching how '' already behaves (no pin, no warning).
  4065. const trimmedOverride = typeof rawModelOverride === 'string' ? rawModelOverride.trim() : rawModelOverride;
  4066. if (typeof trimmedOverride === 'string' && trimmedOverride && !_isAnthropicFlavoredModel(trimmedOverride)) {
  4067. pinnedModel = trimmedOverride; // explicit real-Codex model pin → embed verbatim (#2256)
  4068. } else if (typeof rawModelOverride === 'string' && trimmedOverride === '') {
  4069. // whitespace-only override — no pin, no warning (#3241).
  4070. } else {
  4071. _warnCodexModelOverrideDropped(resolvedName, rawModelOverride); // alias/claude-* → omit
  4072. }
  4073. }
  4074. // #2310 — final safety gate: never emit an Anthropic-flavored model into a Codex
  4075. // .toml, even one that reached here through some other path than the override
  4076. // check above.
  4077. if (pinnedModel && _isAnthropicFlavoredModel(pinnedModel)) {
  4078. _warnCodexModelOverrideDropped(resolvedName, pinnedModel);
  4079. pinnedModel = null;
  4080. }
  4081. // #3241 — one-time deprecation notice: if nothing ends up pinned but the
  4082. // runtime resolver would have supplied a per-tier model that would actually
  4083. // have been EMBEDDED (the population that loses a pin now that the
  4084. // auto-embed above is gone), point the user at model_overrides. The would-be
  4085. // model must also clear the #2310 Anthropic-flavored gate above — if it
  4086. // wouldn't have survived that gate, the user never had that pin pre-Phase-1
  4087. // either, and the notice would be false. Never fires when the resolver is
  4088. // null, resolves to nothing, resolves to an Anthropic-flavored model, or an
  4089. // explicit real-Codex pin survived — in all of those cases nothing was lost.
  4090. if (!pinnedModel && runtimeResolver) {
  4091. const wouldHavePinned = runtimeResolver.resolve(resolvedName) || runtimeResolver.resolve(agentName);
  4092. if (wouldHavePinned?.model && !_isAnthropicFlavoredModel(wouldHavePinned.model)) {
  4093. _warnCodexResolverModelOmitted();
  4094. }
  4095. }
  4096. let hasPinnedModel = false;
  4097. if (pinnedModel) {
  4098. lines.push(`model = ${JSON.stringify(pinnedModel)}`);
  4099. hasPinnedModel = true;
  4100. // model is resolved here; reasoning_effort from catalog tier is REPLACED by the
  4101. // unified effort resolver below (#443). Do NOT emit entry.reasoning_effort here.
  4102. }
  4103. // #443 — Unified effort for Codex .toml. Uses the same config-driven precedence chain
  4104. // as the Claude .md effort injection (resolveInstallTimeEffort), so both runtimes read
  4105. // from the same effort.agent_overrides / effort.routing_tier_defaults / effort.default
  4106. // config source. #3007 — Codex advertises supported_reasoning_levels per model, so the
  4107. // pinned model id is passed through and the value is resolved against that model's own
  4108. // set: 'max' now passes, 'minimal' clamps up to 'low', and 'ultra' is refused (no key
  4109. // emitted) rather than clamped to a fabricated level.
  4110. // #838 — Do not pin effort when Codex is intentionally inheriting the parent
  4111. // chat model. A TOML with no `model` but a static `model_reasoning_effort`
  4112. // creates confusing partial routing: model follows the Codex UI while effort
  4113. // follows GSD. Keep those knobs coupled unless GSD also pins the model.
  4114. if (hasPinnedModel) {
  4115. const _universalEffortCodex = resolveInstallTimeEffort(effortCfg, resolvedName !== agentName ? resolvedName : agentName);
  4116. // #3533 (10d): 'inherit' means OMIT the pin — the agent follows the host's
  4117. // own effort default. Never write the literal.
  4118. if (_universalEffortCodex !== 'inherit') {
  4119. const _renderedEffortCodex = _getGsdEffortCatalog().renderEffortForRuntime('codex', _universalEffortCodex, pinnedModel).value;
  4120. // #3007 — 'ultra' is rejected by the model's supported_reasoning_levels and
  4121. // renders as null. Omit the key entirely rather than write a literal `null`.
  4122. if (_renderedEffortCodex !== null) {
  4123. lines.push(`model_reasoning_effort = ${JSON.stringify(_renderedEffortCodex)}`);
  4124. }
  4125. }
  4126. }
  4127. // #774 — Emit service_tier and model_verbosity for light-tier agents.
  4128. // Light-tier agents (routingTier: "light" in model-catalog.json) are haiku-equivalent
  4129. // and benefit from Codex's "flex" service tier (lower cost, background processing)
  4130. // and "low" verbosity (reduced token output). Both fields are validated against the
  4131. // Codex ConfigProfile schema (codex-rs/config/src/profile_toml.rs):
  4132. // service_tier: Option<String> — "flex" | "fast" (legacy)
  4133. // model_verbosity: Option<Verbosity> — "low" | "medium" | "high"
  4134. const { AGENT_DEFAULT_TIERS: _agentTiers } = _getGsdEffortCatalog();
  4135. const _agentRoutingTier = _agentTiers?.[resolvedName] || _agentTiers?.[agentName];
  4136. if (_agentRoutingTier === 'light') {
  4137. lines.push(`service_tier = "flex"`);
  4138. lines.push(`model_verbosity = "low"`);
  4139. }
  4140. // Agent prompts contain raw backslashes in regexes and shell snippets.
  4141. // TOML literal multiline strings preserve them without escape parsing.
  4142. lines.push(`developer_instructions = '''`);
  4143. lines.push(instructions);
  4144. lines.push(`'''`);
  4145. return lines.join('\n') + '\n';
  4146. }
  4147. /**
  4148. * Remove stale agents/openai.yaml sidecar files from GSD-managed Codex skill dirs.
  4149. *
  4150. * Prior to #1326, GSD's Codex install path wrote an agents/openai.yaml file
  4151. * alongside each gsd-* SKILL.md. Recent Codex builds index BOTH SKILL.md and
  4152. * the sidecar, causing each GSD skill to appear twice in autocomplete. This
  4153. * function removes those stale sidecars and — if the agents/ subdirectory is
  4154. * now empty — prunes it too.
  4155. *
  4156. * Behaviour:
  4157. * - Returns immediately if skillsDir does not exist (fails open).
  4158. * - Only touches directories whose names start with "gsd-".
  4159. * - Skips user-owned dirs (gsd-dev-preferences) — their agents/ content is
  4160. * never modified, by the same USER_OWNED_SKILL_DIRS guard
  4161. * installOpencodeFamilySkills uses.
  4162. * - For each managed gsd-* dir, if agents/openai.yaml exists, deletes it.
  4163. * - If agents/ is now empty, removes the directory; if it still contains
  4164. * other files (e.g. user-added content), leaves it in place.
  4165. * - Non-gsd-* dirs and their agents/ content are never touched.
  4166. * - Individual failures are caught and swallowed so a single bad dir cannot
  4167. * block the install (fail-open, matching the original design).
  4168. *
  4169. * @param {string} skillsDir - Path to the skills/ directory (e.g. ~/.codex/skills)
  4170. */
  4171. function cleanupCodexSkillMetadataSidecars(skillsDir, owns) {
  4172. if (!fs.existsSync(skillsDir)) return;
  4173. // USER_OWNED_SKILL_DIRS (#2973) is the engine's one list. We MUST skip these
  4174. // dirs — their contents are user-generated and must never be modified by
  4175. // GSD's install path.
  4176. for (const entry of fs.readdirSync(skillsDir, { withFileTypes: true })) {
  4177. if (!entry.isDirectory() || !entry.name.startsWith('gsd-')) continue;
  4178. if (USER_OWNED_SKILL_DIRS.includes(entry.name)) continue; // preserve user content
  4179. // #5161: install keeps gsd-* dirs GSD does not own; their files are not
  4180. // GSD's sidecars to clean.
  4181. if (owns && !owns(entry.name)) continue;
  4182. const agentsSubdir = path.join(skillsDir, entry.name, 'agents');
  4183. const sidecarPath = path.join(agentsSubdir, 'openai.yaml');
  4184. try {
  4185. // Symlink guard: if agents/ is a symlink pointing outside the skills tree,
  4186. // deleting through it could escape the tree. Skip this dir entirely.
  4187. let agentsStat;
  4188. try { agentsStat = fs.lstatSync(agentsSubdir); } catch (_e) { continue; }
  4189. if (agentsStat.isSymbolicLink()) continue;
  4190. if (fs.existsSync(sidecarPath)) {
  4191. fs.rmSync(sidecarPath);
  4192. }
  4193. // Prune the agents/ dir only if it is now empty (leave it if other files remain).
  4194. if (fs.existsSync(agentsSubdir) && fs.readdirSync(agentsSubdir).length === 0) {
  4195. fs.rmdirSync(agentsSubdir);
  4196. }
  4197. } catch (_err) {
  4198. // Fail open — a single bad dir must not block the install.
  4199. }
  4200. }
  4201. }
  4202. /**
  4203. * Remove legacy Windsurf skill artifacts from .devin/skills/gsd- directories.
  4204. *
  4205. * Pre-#1615 Windsurf installs wrote skills under .devin/ (Devin Desktop
  4206. * preferred dir, #1085). #1615 moved Windsurf to .windsurf/workflows/.
  4207. * Old .devin/skills/gsd- dirs linger on disk indefinitely and confuse
  4208. * users who see two GSD trees.
  4209. *
  4210. * Preserves user-owned content:
  4211. * - non-gsd-* dirs under .devin/skills/ (user-authored skills)
  4212. * - gsd-dev-preferences/ (user-owned per #2973)
  4213. * - any files (not dirs) under .devin/skills/
  4214. * - with `owns` (#5161), any gsd-* dir GSD does not own, which is named by path
  4215. *
  4216. * @param {string} workspaceDir - workspace root (process.cwd() for local installs)
  4217. * @param {(name: string) => boolean} [owns] ownership predicate (createSkillDirOwnership)
  4218. * @returns {number} count of removed legacy gsd-* skill directories
  4219. */
  4220. function cleanupWindsurfLegacyDevinSkills(workspaceDir, owns) {
  4221. const legacySkillsDir = path.join(workspaceDir, '.devin', 'skills');
  4222. if (!fs.existsSync(legacySkillsDir)) return 0;
  4223. let removed = 0;
  4224. // Decide ownership once, BEFORE deleting: the capability-marker leg reads the
  4225. // dir itself, so asking after a removal would report the removed dir as kept.
  4226. // USER_OWNED_SKILL_DIRS (#2973) dirs are never candidates.
  4227. const candidates = fs.readdirSync(legacySkillsDir, { withFileTypes: true })
  4228. .filter((entry) => entry.isDirectory() && entry.name.startsWith('gsd-') && !USER_OWNED_SKILL_DIRS.includes(entry.name));
  4229. const notOwned = owns ? candidates.filter((entry) => !owns(entry.name)).map((entry) => entry.name) : [];
  4230. for (const entry of candidates) {
  4231. if (notOwned.includes(entry.name)) continue;
  4232. const dirToRemove = path.join(legacySkillsDir, entry.name);
  4233. try {
  4234. // Symlink guard: if the gsd-* dir is itself a symlink pointing outside
  4235. // the .devin tree, deleting through it could escape the tree. Skip.
  4236. const stat = fs.lstatSync(dirToRemove);
  4237. if (stat.isSymbolicLink()) continue;
  4238. fs.rmSync(dirToRemove, { recursive: true, force: true });
  4239. removed++;
  4240. } catch (_err) {
  4241. // Fail open — a single bad dir must not block the install.
  4242. }
  4243. }
  4244. _warnPreservedSkillDirs(legacySkillsDir, notOwned);
  4245. // If .devin/skills/ is now empty, prune it. If .devin/ itself is then empty,
  4246. // prune that too — leaves the workspace clean for the new .windsurf/ layout.
  4247. // Never remove non-empty containers (user may have other Devin content).
  4248. try {
  4249. if (fs.existsSync(legacySkillsDir) && fs.readdirSync(legacySkillsDir).length === 0) {
  4250. fs.rmdirSync(legacySkillsDir);
  4251. const devinDir = path.join(workspaceDir, '.devin');
  4252. if (fs.existsSync(devinDir) && fs.readdirSync(devinDir).length === 0) {
  4253. fs.rmdirSync(devinDir);
  4254. }
  4255. }
  4256. } catch (_err) {
  4257. // best-effort container cleanup
  4258. }
  4259. return removed;
  4260. }
  4261. /**
  4262. * Migrate a skills kind that moved to an alternate `home` (ADR-1239 split-home):
  4263. * remove now-stale `<prefix>*` skill dirs left at the OLD configDir-rooted
  4264. * location by installs from before the move. Without this, upgrading (e.g. Codex
  4265. * relocating skills to ~/.agents/skills) orphans the pre-move dirs at
  4266. * ~/.codex/skills. Only managed `<prefix>*` dirs are touched; user-owned content
  4267. * (non-prefixed dirs, gsd-dev-preferences, symlinks) is preserved. Fail-open.
  4268. *
  4269. * #5161: with `owns`, a `<prefix>*` dir is removed only when GSD owns it; any
  4270. * other is kept and named by path. Install passes it. Uninstall does not: it
  4271. * removes every `gsd-*` skill dir, at either location.
  4272. * @param {string} oldSkillsDir absolute path to the pre-move skills location
  4273. * @param {string} prefix managed skill-dir prefix (e.g. 'gsd-')
  4274. * @param {(name: string) => boolean} [owns] ownership predicate (createSkillDirOwnership)
  4275. * @returns {number} count of stale dirs removed
  4276. */
  4277. function cleanupMovedSkillsOldLocation(oldSkillsDir, prefix, owns) {
  4278. if (!fs.existsSync(oldSkillsDir)) return 0;
  4279. let removed = 0;
  4280. // Decide ownership once, BEFORE deleting: the capability-marker leg reads the
  4281. // dir itself, so asking after a removal would report the removed dir as kept.
  4282. // USER_OWNED_SKILL_DIRS (#2973) dirs are never candidates.
  4283. const candidates = fs.readdirSync(oldSkillsDir, { withFileTypes: true })
  4284. .filter((entry) => entry.isDirectory() && entry.name.startsWith(prefix) && !USER_OWNED_SKILL_DIRS.includes(entry.name));
  4285. const notOwned = owns ? candidates.filter((entry) => !owns(entry.name)).map((entry) => entry.name) : [];
  4286. for (const entry of candidates) {
  4287. if (notOwned.includes(entry.name)) continue;
  4288. const dirToRemove = path.join(oldSkillsDir, entry.name);
  4289. try {
  4290. // Symlink guard (mirrors cleanupWindsurfLegacyDevinSkills): never delete
  4291. // through a symlinked gsd-* dir — it could escape the tree.
  4292. const stat = fs.lstatSync(dirToRemove);
  4293. if (stat.isSymbolicLink()) continue;
  4294. fs.rmSync(dirToRemove, { recursive: true, force: true });
  4295. removed++;
  4296. } catch (_err) {
  4297. // Fail open — a single bad dir must not block install/uninstall.
  4298. }
  4299. }
  4300. _warnPreservedSkillDirs(oldSkillsDir, notOwned);
  4301. // Prune the old skills dir if now empty — leaves the configHome clean.
  4302. // Never remove a non-empty container (user may keep other content there).
  4303. try {
  4304. if (fs.existsSync(oldSkillsDir) && fs.readdirSync(oldSkillsDir).length === 0) {
  4305. fs.rmdirSync(oldSkillsDir);
  4306. }
  4307. } catch (_err) {
  4308. // best-effort container cleanup
  4309. }
  4310. return removed;
  4311. }
  4312. /**
  4313. * When a runtime's skills kind declares an alternate `home` (split-home move),
  4314. * return the now-stale configDir-rooted skills location that installs before the
  4315. * move used; null when no move is in effect (no home override, or home resolves
  4316. * to the same path). Descriptor-driven — no per-runtime hardcoding.
  4317. * @returns {string|null}
  4318. */
  4319. function _resolveMovedSkillsOldDir(runtime, targetDir, scope) {
  4320. try {
  4321. const layout = resolveRuntimeArtifactLayout(runtime, targetDir, scope);
  4322. const skillsKind = layout.kinds.find((k) => k.kind === 'skills');
  4323. if (skillsKind && skillsKind.home) {
  4324. const oldDir = path.join(targetDir, skillsKind.destSubpath);
  4325. const newDir = path.join(skillsKind.home, skillsKind.destSubpath);
  4326. if (path.resolve(oldDir) !== path.resolve(newDir)) return oldDir;
  4327. }
  4328. } catch (_e) {
  4329. // No migration when the layout can't resolve — never block on this.
  4330. }
  4331. return null;
  4332. }
  4333. /**
  4334. * Generate the GSD config block for Codex config.toml.
  4335. *
  4336. * #2406 — standalone per-agent TOMLs (written by installCodexConfig to
  4337. * `$CODEX_HOME/agents/<name>.toml`) are auto-discovered by Codex and are the
  4338. * SOLE canonical registration source for each role. This block therefore no
  4339. * longer emits `[agents.<name>]` role tables that point `config_file` back at
  4340. * those same standalone TOMLs — that was a second, redundant declaration of
  4341. * the same role in one config layer, and Codex logged "Ignoring malformed
  4342. * agent role definition: duplicate agent role name" once per agent as a
  4343. * result. Only the bare `[agents]` dispatch-tuning scalar table is emitted
  4344. * here; role name/description/model/reasoning-effort/sandbox settings remain
  4345. * fully discoverable through the standalone TOML alone.
  4346. * @param {Array<{name: string, description: string}>} _agents unused — kept
  4347. * in the signature for call-site compatibility (installCodexConfig and
  4348. * existing tests still pass it positionally); per-agent role tables are no
  4349. * longer generated from it.
  4350. * @param {string} [_targetDir] unused — the standalone-TOML `config_file`
  4351. * path it used to resolve is no longer emitted here; kept for the same
  4352. * call-site-compatibility reason as `_agents`.
  4353. */
  4354. function generateCodexConfigBlock(_agents, _targetDir) {
  4355. const lines = [
  4356. GSD_CODEX_MARKER,
  4357. '',
  4358. ];
  4359. // ADR-1239 upgrade 2 / #2088 — explicit dispatch tuning. Pin `max_depth` on the
  4360. // `[agents]` (AgentsToml) table rather than relying on codex-cli's implicit
  4361. // default, realizing the negotiated `dispatch.maxDepth: 1` axis. This bare
  4362. // `[agents]` scalar table is validated by validateCodexConfigSchema, which
  4363. // permits a known-scalar-only `[agents]`.
  4364. lines.push('[agents]');
  4365. lines.push(`max_depth = ${GSD_CODEX_AGENTS_MAX_DEPTH}`);
  4366. lines.push('');
  4367. return lines.join('\n');
  4368. }
  4369. /**
  4370. * Extract a user's pre-existing AgentsToml scalar assignments from a bare
  4371. * `[agents]` table — every known scalar EXCEPT `max_depth` (which GSD manages
  4372. * and always re-emits as 1). Returned as raw `key = value` line strings so
  4373. * mergeCodexConfig can PRESERVE them in the managed block instead of silently
  4374. * dropping the user's tuning when the bare `[agents]` table is purged (#2088
  4375. * review finding: the loosened validator declares such a table legitimate, so
  4376. * install must not destroy it). Only the first bare `[agents]` section is read;
  4377. * `[agents.<name>]` role tables are ignored. Fail-open → [].
  4378. * @returns {string[]}
  4379. */
  4380. function extractCodexUserAgentsScalars(content) {
  4381. const preserved = [];
  4382. let section;
  4383. try {
  4384. section = getTomlTableSections(content).find((s) => !s.array && s.path === 'agents');
  4385. } catch (_e) {
  4386. return preserved;
  4387. }
  4388. if (!section) return preserved;
  4389. const body = content.slice(section.headerEnd, section.end);
  4390. for (const record of getTomlLineRecords(body)) {
  4391. if (record.startsInMultilineString || record.tableHeader) continue;
  4392. const trimmed = record.text.trim();
  4393. if (!trimmed || trimmed.startsWith('#')) continue;
  4394. if (!record.keySegments || record.keySegments.length !== 1) continue;
  4395. const key = record.keySegments[0];
  4396. if (key === 'max_depth') continue; // GSD-managed — GSD's value wins.
  4397. if (!CODEX_AGENTS_TOML_SCALAR_KEYS.has(key)) continue;
  4398. preserved.push(trimmed);
  4399. }
  4400. return preserved;
  4401. }
  4402. /**
  4403. * Splice preserved user AgentsToml scalar lines into the managed GSD config
  4404. * block, immediately after the `[agents]` header and before GSD's `max_depth`
  4405. * line. Operates on the pre-EOL-normalization block (LF joins), matching only
  4406. * the bare `[agents]` header (never `[agents.<name>]`). Returns the block
  4407. * unchanged when there is nothing to preserve or the anchor is absent.
  4408. */
  4409. function spliceCodexAgentsScalars(block, scalarLines) {
  4410. if (!scalarLines || scalarLines.length === 0) return block;
  4411. return block.replace(/(\n\[agents\]\n)(max_depth = )/, `$1${scalarLines.join('\n')}\n$2`);
  4412. }
  4413. /**
  4414. * Strip any managed GSD agent sections from a TOML string.
  4415. *
  4416. * Used by the uninstall path (`stripGsdFromCodexConfig`). Removes only what GSD
  4417. * owns; user-authored `[agents.<name>]` and `[[agents]]` entries are preserved
  4418. * so uninstall returns the file to its pre-GSD shape.
  4419. *
  4420. * Handles BOTH shapes so reinstall self-heals configs from all GSD versions:
  4421. * - Current (#2727): `[agents.gsd-*]` struct tables (Codex 0.120.0+).
  4422. * - Legacy (#2645): `[[agents]]` array-of-tables whose `name = "gsd-*"`.
  4423. *
  4424. * A section runs from its header to the next `[` header or EOF.
  4425. */
  4426. function stripCodexGsdAgentSections(content) {
  4427. // Use the TOML-aware section parser so we never absorb adjacent user-authored
  4428. // tables — even if their headers are indented or otherwise oddly placed.
  4429. const sections = getTomlTableSections(content).filter((section) => {
  4430. // Current `[agents.gsd-<name>]` struct tables (#2727, Codex 0.120.0+).
  4431. if (!section.array && /^agents\.gsd-/.test(section.path)) {
  4432. return true;
  4433. }
  4434. // GSD's managed `[agents]` scalar block (ADR-1239 upgrade 2 / #2088 — the
  4435. // `max_depth` dispatch-tuning table). Install purges any pre-existing bare
  4436. // `[agents]` and writes its own, so a known-scalar-only bare `[agents]` is
  4437. // GSD-owned; strip it on uninstall. (The marker path already removes it via
  4438. // the marker-to-EOF cut; this covers the no-marker fallback.)
  4439. if (!section.array && section.path === 'agents') {
  4440. const body = content.slice(section.headerEnd, section.end);
  4441. return codexBareAgentsHasOnlyKnownScalars(body);
  4442. }
  4443. // Legacy `[[agents]]` array-of-tables (#2645) — only strip blocks whose
  4444. // `name = "gsd-..."`, preserving user-authored [[agents]] entries.
  4445. if (section.array && section.path === 'agents') {
  4446. const body = content.slice(section.headerEnd, section.end);
  4447. const nameMatch = body.match(/^[ \t]*name[ \t]*=[ \t]*["']([^"']+)["']/m);
  4448. return Boolean(nameMatch && /^gsd-/.test(nameMatch[1]));
  4449. }
  4450. return false;
  4451. });
  4452. return removeContentRanges(
  4453. content,
  4454. sections.map(({ start, end }) => ({ start, end })),
  4455. );
  4456. }
  4457. /**
  4458. * Strip GSD sections from Codex config.toml content.
  4459. * Returns cleaned content, or null if file would be empty.
  4460. */
  4461. function stripGsdFromCodexConfig(content) {
  4462. const eol = detectLineEnding(content);
  4463. const markerIndex = content.indexOf(GSD_CODEX_MARKER);
  4464. const codexHooksOwnership = getManagedCodexHooksOwnership(content);
  4465. if (markerIndex !== -1) {
  4466. // Has GSD marker — remove everything from marker to EOF. First recover the
  4467. // user's own AgentsToml scalars (max_threads etc.) that install folded into
  4468. // the managed [agents] block (#2088), so a full install→uninstall cycle
  4469. // round-trips the user's tuning. GSD-managed max_depth is dropped.
  4470. const preservedScalars = extractCodexUserAgentsScalars(content.slice(markerIndex));
  4471. let before = content.substring(0, markerIndex);
  4472. before = stripCodexHooksFeatureAssignments(before, codexHooksOwnership);
  4473. // Also strip GSD-injected feature keys above the marker (Case 3 inject)
  4474. before = before.replace(/^multi_agent\s*=\s*true\s*(?:\r?\n)?/m, '');
  4475. before = before.replace(/^default_mode_request_user_input\s*=\s*true\s*(?:\r?\n)?/m, '');
  4476. before = before.replace(/^\[features\]\s*\n(?=\[|$)/m, '');
  4477. before = before.replace(/^\[agents\]\s*\n(?=\[|$)/m, '');
  4478. before = before.replace(/^(?:\r?\n)+/, '').trimEnd();
  4479. if (preservedScalars.length > 0) {
  4480. before = (before ? before + eol + eol : '') + '[agents]' + eol + preservedScalars.join(eol);
  4481. }
  4482. if (!before) return null;
  4483. return before + eol;
  4484. }
  4485. // No marker but may have GSD-injected feature keys
  4486. let cleaned = content;
  4487. cleaned = stripCodexHooksFeatureAssignments(cleaned, codexHooksOwnership);
  4488. cleaned = cleaned.replace(/^multi_agent\s*=\s*true\s*(?:\r?\n)?/m, '');
  4489. cleaned = cleaned.replace(/^default_mode_request_user_input\s*=\s*true\s*(?:\r?\n)?/m, '');
  4490. // #2088: recover the user's own AgentsToml scalars before the [agents] table is
  4491. // stripped, so they survive uninstall even in the no-marker fallback path.
  4492. const preservedScalars = extractCodexUserAgentsScalars(cleaned);
  4493. // Remove [agents.gsd-*] sections + the managed known-scalar [agents] table.
  4494. cleaned = stripCodexGsdAgentSections(cleaned);
  4495. // Remove [features] section if now empty (only header, no keys before next section)
  4496. cleaned = cleaned.replace(/^\[features\]\s*\n(?=\[|$)/m, '');
  4497. // Remove [agents] section if now empty
  4498. cleaned = cleaned.replace(/^\[agents\]\s*\n(?=\[|$)/m, '');
  4499. cleaned = cleaned.replace(/^(?:\r?\n)+/, '').trimEnd();
  4500. if (preservedScalars.length > 0) {
  4501. cleaned = (cleaned ? cleaned + eol + eol : '') + '[agents]' + eol + preservedScalars.join(eol);
  4502. }
  4503. if (!cleaned) return null;
  4504. return cleaned + eol;
  4505. }
  4506. function detectLineEnding(content) {
  4507. const firstNewlineIndex = content.indexOf('\n');
  4508. if (firstNewlineIndex === -1) {
  4509. return '\n';
  4510. }
  4511. return firstNewlineIndex > 0 && content[firstNewlineIndex - 1] === '\r' ? '\r\n' : '\n';
  4512. }
  4513. function splitTomlLines(content) {
  4514. const lines = [];
  4515. let start = 0;
  4516. while (start < content.length) {
  4517. const newlineIndex = content.indexOf('\n', start);
  4518. if (newlineIndex === -1) {
  4519. lines.push({
  4520. start,
  4521. end: content.length,
  4522. text: content.slice(start),
  4523. eol: '',
  4524. });
  4525. break;
  4526. }
  4527. const hasCr = newlineIndex > start && content[newlineIndex - 1] === '\r';
  4528. const end = hasCr ? newlineIndex - 1 : newlineIndex;
  4529. lines.push({
  4530. start,
  4531. end,
  4532. text: content.slice(start, end),
  4533. eol: hasCr ? '\r\n' : '\n',
  4534. });
  4535. start = newlineIndex + 1;
  4536. }
  4537. return lines;
  4538. }
  4539. function findTomlCommentStart(line) {
  4540. let i = 0;
  4541. let multilineState = null;
  4542. while (i < line.length) {
  4543. if (multilineState === 'literal') {
  4544. const closeIndex = line.indexOf('\'\'\'', i);
  4545. if (closeIndex === -1) {
  4546. return -1;
  4547. }
  4548. i = closeIndex + 3;
  4549. multilineState = null;
  4550. continue;
  4551. }
  4552. if (multilineState === 'basic') {
  4553. const closeIndex = findMultilineBasicStringClose(line, i);
  4554. if (closeIndex === -1) {
  4555. return -1;
  4556. }
  4557. i = closeIndex + 3;
  4558. multilineState = null;
  4559. continue;
  4560. }
  4561. const ch = line[i];
  4562. if (ch === '#') {
  4563. return i;
  4564. }
  4565. if (ch === '\'') {
  4566. if (line.startsWith('\'\'\'', i)) {
  4567. multilineState = 'literal';
  4568. i += 3;
  4569. continue;
  4570. }
  4571. const close = line.indexOf('\'', i + 1);
  4572. if (close === -1) return -1;
  4573. i = close + 1;
  4574. continue;
  4575. }
  4576. if (ch === '"') {
  4577. if (line.startsWith('"""', i)) {
  4578. multilineState = 'basic';
  4579. i += 3;
  4580. continue;
  4581. }
  4582. i += 1;
  4583. while (i < line.length) {
  4584. if (line[i] === '\\') {
  4585. i += 2;
  4586. continue;
  4587. }
  4588. if (line[i] === '"') {
  4589. i += 1;
  4590. break;
  4591. }
  4592. i += 1;
  4593. }
  4594. continue;
  4595. }
  4596. i += 1;
  4597. }
  4598. return -1;
  4599. }
  4600. function isEscapedInBasicString(line, index) {
  4601. let slashCount = 0;
  4602. let cursor = index - 1;
  4603. while (cursor >= 0 && line[cursor] === '\\') {
  4604. slashCount += 1;
  4605. cursor -= 1;
  4606. }
  4607. return slashCount % 2 === 1;
  4608. }
  4609. function findMultilineBasicStringClose(line, startIndex) {
  4610. let searchIndex = startIndex;
  4611. while (searchIndex < line.length) {
  4612. const closeIndex = line.indexOf('"""', searchIndex);
  4613. if (closeIndex === -1) {
  4614. return -1;
  4615. }
  4616. if (!isEscapedInBasicString(line, closeIndex)) {
  4617. return closeIndex;
  4618. }
  4619. searchIndex = closeIndex + 1;
  4620. }
  4621. return -1;
  4622. }
  4623. function advanceTomlMultilineStringState(line, multilineState) {
  4624. let i = 0;
  4625. let state = multilineState;
  4626. while (i < line.length) {
  4627. if (state === 'literal') {
  4628. const closeIndex = line.indexOf('\'\'\'', i);
  4629. if (closeIndex === -1) {
  4630. return state;
  4631. }
  4632. i = closeIndex + 3;
  4633. state = null;
  4634. continue;
  4635. }
  4636. if (state === 'basic') {
  4637. const closeIndex = findMultilineBasicStringClose(line, i);
  4638. if (closeIndex === -1) {
  4639. return state;
  4640. }
  4641. i = closeIndex + 3;
  4642. state = null;
  4643. continue;
  4644. }
  4645. const ch = line[i];
  4646. if (ch === '#') {
  4647. return state;
  4648. }
  4649. if (ch === '\'') {
  4650. if (line.startsWith('\'\'\'', i)) {
  4651. state = 'literal';
  4652. i += 3;
  4653. continue;
  4654. }
  4655. const close = line.indexOf('\'', i + 1);
  4656. if (close === -1) {
  4657. return state;
  4658. }
  4659. i = close + 1;
  4660. continue;
  4661. }
  4662. if (ch === '"') {
  4663. if (line.startsWith('"""', i)) {
  4664. state = 'basic';
  4665. i += 3;
  4666. continue;
  4667. }
  4668. i += 1;
  4669. while (i < line.length) {
  4670. if (line[i] === '\\') {
  4671. i += 2;
  4672. continue;
  4673. }
  4674. if (line[i] === '"') {
  4675. i += 1;
  4676. break;
  4677. }
  4678. i += 1;
  4679. }
  4680. continue;
  4681. }
  4682. i += 1;
  4683. }
  4684. return state;
  4685. }
  4686. function parseTomlBracketHeader(line, array) {
  4687. let i = 0;
  4688. while (i < line.length && /\s/.test(line[i])) {
  4689. i += 1;
  4690. }
  4691. const open = array ? '[[' : '[';
  4692. const close = array ? ']]' : ']';
  4693. if (!line.startsWith(open, i)) {
  4694. return null;
  4695. }
  4696. i += open.length;
  4697. const start = i;
  4698. while (i < line.length) {
  4699. if (line[i] === '\'' || line[i] === '"') {
  4700. const quote = line[i];
  4701. i += 1;
  4702. while (i < line.length) {
  4703. if (quote === '"' && line[i] === '\\') {
  4704. i += 2;
  4705. continue;
  4706. }
  4707. if (line[i] === quote) {
  4708. i += 1;
  4709. break;
  4710. }
  4711. i += 1;
  4712. }
  4713. continue;
  4714. }
  4715. if (line.startsWith(close, i)) {
  4716. const rawPath = line.slice(start, i).trim();
  4717. const segments = parseTomlKeyPath(rawPath);
  4718. if (!segments) {
  4719. return null;
  4720. }
  4721. i += close.length;
  4722. while (i < line.length && /\s/.test(line[i])) {
  4723. i += 1;
  4724. }
  4725. if (i < line.length && line[i] !== '#') {
  4726. return null;
  4727. }
  4728. return { path: segments.join('.'), segments, array };
  4729. }
  4730. if (line[i] === '#' || line[i] === '\r' || line[i] === '\n') {
  4731. return null;
  4732. }
  4733. i += 1;
  4734. }
  4735. return null;
  4736. }
  4737. function parseTomlTableHeader(line) {
  4738. return parseTomlBracketHeader(line, true) || parseTomlBracketHeader(line, false);
  4739. }
  4740. function findTomlAssignmentEquals(line) {
  4741. let i = 0;
  4742. while (i < line.length) {
  4743. const ch = line[i];
  4744. if (ch === '#') {
  4745. return -1;
  4746. }
  4747. if (ch === '\'') {
  4748. i += 1;
  4749. while (i < line.length) {
  4750. if (line[i] === '\'') {
  4751. i += 1;
  4752. break;
  4753. }
  4754. i += 1;
  4755. }
  4756. continue;
  4757. }
  4758. if (ch === '"') {
  4759. i += 1;
  4760. while (i < line.length) {
  4761. if (line[i] === '\\') {
  4762. i += 2;
  4763. continue;
  4764. }
  4765. if (line[i] === '"') {
  4766. i += 1;
  4767. break;
  4768. }
  4769. i += 1;
  4770. }
  4771. continue;
  4772. }
  4773. if (ch === '=') {
  4774. return i;
  4775. }
  4776. i += 1;
  4777. }
  4778. return -1;
  4779. }
  4780. function parseTomlKeyPath(keyText) {
  4781. const segments = [];
  4782. let i = 0;
  4783. while (i < keyText.length) {
  4784. while (i < keyText.length && /\s/.test(keyText[i])) {
  4785. i += 1;
  4786. }
  4787. if (i >= keyText.length) {
  4788. break;
  4789. }
  4790. if (keyText[i] === '\'' || keyText[i] === '"') {
  4791. const quote = keyText[i];
  4792. let segment = '';
  4793. let closed = false;
  4794. i += 1;
  4795. while (i < keyText.length) {
  4796. if (quote === '"' && keyText[i] === '\\') {
  4797. if (i + 1 >= keyText.length) {
  4798. return null;
  4799. }
  4800. segment += keyText[i + 1];
  4801. i += 2;
  4802. continue;
  4803. }
  4804. if (keyText[i] === quote) {
  4805. i += 1;
  4806. closed = true;
  4807. break;
  4808. }
  4809. segment += keyText[i];
  4810. i += 1;
  4811. }
  4812. if (!closed) {
  4813. return null;
  4814. }
  4815. segments.push(segment);
  4816. } else {
  4817. const match = keyText.slice(i).match(/^[A-Za-z0-9_-]+/);
  4818. if (!match) {
  4819. return null;
  4820. }
  4821. segments.push(match[0]);
  4822. i += match[0].length;
  4823. }
  4824. while (i < keyText.length && /\s/.test(keyText[i])) {
  4825. i += 1;
  4826. }
  4827. if (i >= keyText.length) {
  4828. break;
  4829. }
  4830. if (keyText[i] !== '.') {
  4831. return null;
  4832. }
  4833. i += 1;
  4834. }
  4835. return segments.length > 0 ? segments : null;
  4836. }
  4837. function parseTomlKey(line) {
  4838. const header = parseTomlTableHeader(line);
  4839. if (header) {
  4840. return null;
  4841. }
  4842. const equalsIndex = findTomlAssignmentEquals(line);
  4843. if (equalsIndex === -1) {
  4844. return null;
  4845. }
  4846. const raw = line.slice(0, equalsIndex).trim();
  4847. const segments = parseTomlKeyPath(raw);
  4848. if (!segments) {
  4849. return null;
  4850. }
  4851. return { raw, segments };
  4852. }
  4853. function getTomlLineRecords(content) {
  4854. const lines = splitTomlLines(content);
  4855. const records = [];
  4856. let currentTablePath = null;
  4857. let multilineState = null;
  4858. for (const line of lines) {
  4859. const startsInMultilineString = multilineState !== null;
  4860. const record = {
  4861. ...line,
  4862. startsInMultilineString,
  4863. tablePath: currentTablePath,
  4864. tableHeader: null,
  4865. keySegments: null,
  4866. };
  4867. if (!startsInMultilineString) {
  4868. const header = parseTomlTableHeader(line.text);
  4869. if (header) {
  4870. record.tableHeader = header;
  4871. currentTablePath = header.path;
  4872. } else {
  4873. const key = parseTomlKey(line.text);
  4874. record.keySegments = key ? key.segments : null;
  4875. record.keyRaw = key ? key.raw : null;
  4876. }
  4877. }
  4878. multilineState = advanceTomlMultilineStringState(line.text, multilineState);
  4879. records.push(record);
  4880. }
  4881. return records;
  4882. }
  4883. function getTomlTableSections(content) {
  4884. const headerLines = getTomlLineRecords(content).filter((record) => record.tableHeader);
  4885. return headerLines.map((record, index) => ({
  4886. path: record.tableHeader.path,
  4887. // segments preserves the true parsed key count so callers that need to
  4888. // distinguish a 2-segment path like hooks."before.tool" from a 3-segment
  4889. // path like hooks.SessionStart.hooks can do so without splitting on dots
  4890. // (which misclassifies quoted key names that contain dot characters).
  4891. segments: record.tableHeader.segments,
  4892. array: record.tableHeader.array,
  4893. start: record.start,
  4894. headerEnd: record.end + record.eol.length,
  4895. end: index + 1 < headerLines.length ? headerLines[index + 1].start : content.length,
  4896. }));
  4897. }
  4898. function collapseTomlBlankLines(content) {
  4899. const eol = detectLineEnding(content);
  4900. return content.replace(/(?:\r?\n){3,}/g, eol + eol);
  4901. }
  4902. function removeContentRanges(content, ranges) {
  4903. const normalizedRanges = ranges
  4904. .filter((range) => range && range.start < range.end)
  4905. .sort((a, b) => a.start - b.start);
  4906. if (normalizedRanges.length === 0) {
  4907. return content;
  4908. }
  4909. const mergedRanges = [{ ...normalizedRanges[0] }];
  4910. for (let i = 1; i < normalizedRanges.length; i += 1) {
  4911. const current = normalizedRanges[i];
  4912. const previous = mergedRanges[mergedRanges.length - 1];
  4913. if (current.start <= previous.end) {
  4914. previous.end = Math.max(previous.end, current.end);
  4915. continue;
  4916. }
  4917. mergedRanges.push({ ...current });
  4918. }
  4919. let cleaned = '';
  4920. let cursor = 0;
  4921. for (const range of mergedRanges) {
  4922. cleaned += content.slice(cursor, range.start);
  4923. cursor = range.end;
  4924. }
  4925. cleaned += content.slice(cursor);
  4926. return cleaned;
  4927. }
  4928. function stripCodexHooksFeatureAssignments(content, ownership = null) {
  4929. const lineRecords = getTomlLineRecords(content);
  4930. const tableSections = getTomlTableSections(content);
  4931. const removalRanges = [];
  4932. const featuresSection = tableSections.find((section) => !section.array && section.path === 'features');
  4933. const shouldStripSectionKey = ownership === 'section' || ownership === 'all';
  4934. const shouldStripRootDottedKey = ownership === 'root_dotted' || ownership === 'all';
  4935. if (featuresSection && shouldStripSectionKey) {
  4936. const sectionRecords = lineRecords.filter((record) =>
  4937. !record.tableHeader &&
  4938. record.start >= featuresSection.headerEnd &&
  4939. record.end + record.eol.length <= featuresSection.end
  4940. );
  4941. const codexHookRecords = sectionRecords.filter((record) =>
  4942. !record.startsInMultilineString &&
  4943. record.keySegments &&
  4944. record.keySegments.length === 1 &&
  4945. isCodexHooksFeatureKey(record.keySegments[0])
  4946. );
  4947. for (const record of codexHookRecords) {
  4948. removalRanges.push({
  4949. start: record.start,
  4950. end: findTomlAssignmentBlockEnd(content, record),
  4951. });
  4952. }
  4953. if (codexHookRecords.length > 0) {
  4954. const removedStarts = new Set(codexHookRecords.map((record) => record.start));
  4955. const hasRemainingContent = sectionRecords.some((record) => {
  4956. if (removedStarts.has(record.start)) {
  4957. return false;
  4958. }
  4959. const trimmed = record.text.trim();
  4960. return trimmed !== '' && !trimmed.startsWith('#');
  4961. });
  4962. const hasRemainingComments = sectionRecords.some((record) => {
  4963. if (removedStarts.has(record.start)) {
  4964. return false;
  4965. }
  4966. return record.text.trim().startsWith('#');
  4967. });
  4968. if (!hasRemainingContent && !hasRemainingComments) {
  4969. removalRanges.push({
  4970. start: featuresSection.start,
  4971. end: featuresSection.end,
  4972. });
  4973. }
  4974. }
  4975. }
  4976. if (shouldStripRootDottedKey) {
  4977. const rootCodexHookRecords = lineRecords.filter((record) =>
  4978. !record.tableHeader &&
  4979. !record.startsInMultilineString &&
  4980. record.tablePath === null &&
  4981. record.keySegments &&
  4982. record.keySegments.length === 2 &&
  4983. record.keySegments[0] === 'features' &&
  4984. isCodexHooksFeatureKey(record.keySegments[1])
  4985. );
  4986. for (const record of rootCodexHookRecords) {
  4987. removalRanges.push({
  4988. start: record.start,
  4989. end: findTomlAssignmentBlockEnd(content, record),
  4990. });
  4991. }
  4992. }
  4993. return removeContentRanges(content, removalRanges);
  4994. }
  4995. function getManagedCodexHooksOwnership(content) {
  4996. const markerIndex = content.indexOf(GSD_CODEX_MARKER);
  4997. if (markerIndex === -1) {
  4998. return null;
  4999. }
  5000. const afterMarker = content.slice(markerIndex + GSD_CODEX_MARKER.length);
  5001. const match = afterMarker.match(/^\r?\n# GSD codex_hooks ownership: (section|root_dotted)\r?\n/);
  5002. return match ? match[1] : null;
  5003. }
  5004. function setManagedCodexHooksOwnership(content, ownership) {
  5005. const markerIndex = content.indexOf(GSD_CODEX_MARKER);
  5006. if (markerIndex === -1) {
  5007. return content;
  5008. }
  5009. const eol = detectLineEnding(content);
  5010. const markerEnd = markerIndex + GSD_CODEX_MARKER.length;
  5011. const afterMarker = content.slice(markerEnd);
  5012. const normalizedAfterMarker = afterMarker.replace(
  5013. /^\r?\n# GSD codex_hooks ownership: (?:section|root_dotted)\r?\n/,
  5014. eol
  5015. );
  5016. if (!ownership) {
  5017. return content.slice(0, markerEnd) + normalizedAfterMarker;
  5018. }
  5019. const remainder = normalizedAfterMarker.replace(/^\r?\n/, '');
  5020. return content.slice(0, markerEnd) +
  5021. eol +
  5022. `${GSD_CODEX_HOOKS_OWNERSHIP_PREFIX}${ownership}${eol}` +
  5023. remainder;
  5024. }
  5025. function isLegacyGsdAgentsSection(body) {
  5026. const lineRecords = getTomlLineRecords(body);
  5027. const legacyKeys = new Set(['max_threads', 'max_depth']);
  5028. let sawLegacyKey = false;
  5029. for (const record of lineRecords) {
  5030. if (record.startsInMultilineString) {
  5031. return false;
  5032. }
  5033. if (record.tableHeader) {
  5034. return false;
  5035. }
  5036. const trimmed = record.text.trim();
  5037. if (!trimmed || trimmed.startsWith('#')) {
  5038. continue;
  5039. }
  5040. if (!record.keySegments || record.keySegments.length !== 1 || !legacyKeys.has(record.keySegments[0])) {
  5041. return false;
  5042. }
  5043. sawLegacyKey = true;
  5044. }
  5045. return sawLegacyKey;
  5046. }
  5047. function stripLeakedGsdCodexSections(content) {
  5048. // Defensive precedence (#2760): we own the `agents` namespace under our
  5049. // managed `gsd-*` names, and the legacy bare-table and sequence forms
  5050. // (`[agents]`, `[[agents]]`) are invalid in the current Codex schema —
  5051. // they trigger "invalid type: ..., expected struct AgentsToml" and break
  5052. // every Codex CLI invocation. They MUST never coexist with the new
  5053. // `[agents.<name>]` struct format we now emit, so install-time always
  5054. // purges them regardless of GSD marker presence. Users who had legitimate
  5055. // user-authored `[[agents]]` entries before are already broken on Codex
  5056. // ≥0.124 — purging is the only path to a loadable config.
  5057. const leakedSections = getTomlTableSections(content)
  5058. .filter((section) => {
  5059. // Legacy [agents.gsd-<name>] map tables (pre-#2645).
  5060. if (!section.array && section.path.startsWith('agents.gsd-')) return true;
  5061. // ANY bare [agents] single-bracket table — invalid in current Codex
  5062. // schema, always purged at install time (#2760). Previously gated
  5063. // on `isLegacyGsdAgentsSection`, which missed bare tables holding
  5064. // arbitrary user keys (`default = "..."`, etc.) that still produce
  5065. // the AgentsToml type error.
  5066. if (!section.array && section.path === 'agents') return true;
  5067. // ANY [[agents]] array-of-tables — invalid in current Codex schema,
  5068. // always purged at install time (#2760). Previously gated on
  5069. // `name = "gsd-..."` which preserved user-authored entries that are
  5070. // themselves rejected by Codex 0.124+.
  5071. if (section.array && section.path === 'agents') return true;
  5072. return false;
  5073. });
  5074. if (leakedSections.length === 0) {
  5075. return content;
  5076. }
  5077. let cleaned = '';
  5078. let cursor = 0;
  5079. for (const section of leakedSections) {
  5080. cleaned += content.slice(cursor, section.start);
  5081. cursor = section.end;
  5082. }
  5083. cleaned += content.slice(cursor);
  5084. return collapseTomlBlankLines(cleaned);
  5085. }
  5086. /**
  5087. * Strip GSD-managed legacy Codex hook blocks from a config.toml string
  5088. * using the TOML AST already used elsewhere in this file
  5089. * (`getTomlTableSections` + `removeContentRanges`). The earlier regex-based
  5090. * implementation required a precise key order, exact single-space padding
  5091. * around `=`, and exactly one blank line between Shape 4's parent/child
  5092. * tables — any deviation (an extra blank line, key reorder, an added
  5093. * `timeout` key, `event="SessionStart"` without spaces) silently leaked the
  5094. * stale block, sometimes corrupting the file by leaving orphaned key=value
  5095. * lines outside any table.
  5096. *
  5097. * The structural approach: find every `hooks*` table whose body contains a
  5098. * `command = "...gsd-(check-update|update-check).js"` value, remove its
  5099. * exact byte range, and additionally remove any orphaned parent
  5100. * `[[hooks.SessionStart]]` whose body becomes empty as a result (Shape 4).
  5101. * The leading `# GSD Hooks` header line is swallowed by extending the
  5102. * removal range backward through any single preceding comment line.
  5103. *
  5104. * Pure function, exported for test coverage. Returns the input unchanged
  5105. * if no GSD-managed hook section is present.
  5106. */
  5107. function stripStaleGsdHookBlocks(configContent) {
  5108. const sections = getTomlTableSections(configContent);
  5109. const lineRecords = getTomlLineRecords(configContent);
  5110. const hookSections = sections.filter(
  5111. (s) => s.path === 'hooks' || s.path.startsWith('hooks.')
  5112. );
  5113. if (hookSections.length === 0) {
  5114. return configContent;
  5115. }
  5116. // A section is GSD-managed if any structural `command` key inside its
  5117. // body parses to a string whose basename matches `gsd-(check-update|
  5118. // update-check).js`. The TOML line parser already classified each line's
  5119. // `keySegments`, so we never inspect raw text — this handles arbitrary
  5120. // whitespace, key reordering, and additional keys robustly.
  5121. function sectionHasStaleCommand(section) {
  5122. const records = lineRecords.filter(
  5123. (r) => !r.startsInMultilineString
  5124. && !r.tableHeader
  5125. && r.start >= section.headerEnd
  5126. && r.end + r.eol.length <= section.end
  5127. && r.keySegments
  5128. && r.keySegments.length === 1
  5129. && r.keySegments[0] === 'command'
  5130. );
  5131. for (const record of records) {
  5132. const equalsIndex = findTomlAssignmentEquals(record.text);
  5133. if (equalsIndex === -1) continue;
  5134. let parsed;
  5135. try {
  5136. parsed = parseTomlValue(record.text, equalsIndex + 1);
  5137. } catch {
  5138. continue;
  5139. }
  5140. if (typeof parsed.value !== 'string') continue;
  5141. if (isManagedHookCommand(parsed.value, {
  5142. surface: 'codex-toml',
  5143. includeLegacyAliases: true,
  5144. })) {
  5145. return true;
  5146. }
  5147. }
  5148. return false;
  5149. }
  5150. const stale = new Set(hookSections.filter(sectionHasStaleCommand));
  5151. if (stale.size === 0) {
  5152. return configContent;
  5153. }
  5154. // Shape 4: a `[[hooks.SessionStart]]` event-table whose body is empty and
  5155. // whose immediately following section is a stale child handler table
  5156. // (`[[hooks.SessionStart.hooks]]`) becomes orphaned once the child is
  5157. // stripped. Detect emptiness via line records — no key/value lines and no
  5158. // non-blank, non-comment text between this section's header and the next.
  5159. function sectionBodyHasContent(section) {
  5160. return lineRecords.some(
  5161. (r) => !r.startsInMultilineString
  5162. && !r.tableHeader
  5163. && r.start >= section.headerEnd
  5164. && r.end + r.eol.length <= section.end
  5165. && r.text.trim() !== ''
  5166. && !r.text.trim().startsWith('#')
  5167. );
  5168. }
  5169. for (let i = 0; i < sections.length; i += 1) {
  5170. const parent = sections[i];
  5171. if (stale.has(parent)) continue;
  5172. if (!parent.array || parent.path !== 'hooks.SessionStart') continue;
  5173. if (sectionBodyHasContent(parent)) continue;
  5174. const next = sections[i + 1];
  5175. if (next && stale.has(next) && next.path.startsWith('hooks.SessionStart.')) {
  5176. stale.add(parent);
  5177. }
  5178. }
  5179. // Each removal range starts at the table header. If the immediately
  5180. // preceding line is the GSD marker comment `# GSD Hooks` (and is not part
  5181. // of an already-removed section), extend the range backward to swallow it
  5182. // — preserves cleanliness on round-trip strip+rewrite.
  5183. const ranges = [];
  5184. for (const section of stale) {
  5185. let start = section.start;
  5186. const headerLineIdx = lineRecords.findIndex((r) => r.start === section.start);
  5187. const prev = headerLineIdx > 0 ? lineRecords[headerLineIdx - 1] : null;
  5188. if (prev && !prev.startsInMultilineString && prev.text.trim() === '# GSD Hooks') {
  5189. start = prev.start;
  5190. }
  5191. ranges.push({ start, end: section.end });
  5192. }
  5193. return collapseTomlBlankLines(removeContentRanges(configContent, ranges));
  5194. }
  5195. /**
  5196. * Migrate legacy Codex [hooks] map format to [[hooks]] array-of-tables format.
  5197. *
  5198. * Codex 0.124.0 changed from the old map-style hooks config:
  5199. * [hooks]
  5200. * [hooks.shell]
  5201. * command = "..."
  5202. *
  5203. * to the new array-of-tables format. #2760 CR5 finding 3 — emit the
  5204. * namespaced AoT shape directly so a mixed flat + namespaced layout never
  5205. * arises post-install:
  5206. * [[hooks.shell]]
  5207. * command = "..."
  5208. *
  5209. * This function detects any non-array hooks sections in the config and
  5210. * converts them to the namespaced `[[hooks.<TYPE>]]` array-of-tables form,
  5211. * preserving all key-value pairs and user comments. Bare [hooks] container
  5212. * sections (no key-value content) are dropped. User-authored AoT entries are
  5213. * left untouched.
  5214. *
  5215. * Returns the migrated content, or the original content unchanged if no
  5216. * legacy hooks sections were found.
  5217. */
  5218. function migrateCodexHooksMapFormat(content) {
  5219. const sections = getTomlTableSections(content);
  5220. // Find all non-array hooks sections: bare [hooks] container or [hooks.TYPE] event tables.
  5221. // Use section.segments (parsed key count) rather than section.path.startsWith() so that
  5222. // nested handler tables like [hooks.SessionStart.hooks] (3 segments) are not mistakenly
  5223. // included and re-emitted as an event named "SessionStart.hooks".
  5224. // Exclude hooks.state and hooks.state.* — these are Codex's persistent hook-trust
  5225. // namespace (Codex CLI 0.130.0+) and use regular-table shape, never AoT.
  5226. const legacyMapSections = sections.filter(
  5227. (section) => !section.array && (
  5228. section.path === 'hooks' ||
  5229. (section.path.startsWith('hooks.') && section.segments.length === 2 &&
  5230. section.path !== 'hooks.state' && !section.path.startsWith('hooks.state.'))
  5231. )
  5232. );
  5233. // Find flat [[hooks]] array-of-tables entries (path === 'hooks', array === true).
  5234. // These are incompatible with [[hooks.<EVENT>]] namespaced form — both cannot
  5235. // coexist in the same TOML file because `hooks` cannot be simultaneously an
  5236. // array and a table. Migrate each flat entry to [[hooks.<EVENT>]] form using
  5237. // the `event` key as the event name.
  5238. const flatAotSections = sections.filter(
  5239. (section) => section.array && section.path === 'hooks'
  5240. );
  5241. // Find [[hooks.TYPE]] namespaced AoT entries that carry handler fields
  5242. // (command, type, timeout, statusMessage) at event-entry level but have no
  5243. // [[hooks.TYPE.hooks]] sub-table. This is the pre-#2773 single-block shape
  5244. // that Codex 0.124.0+ rejects. Promote them to the two-level nested form.
  5245. // Entries that already have a [[hooks.TYPE.hooks]] sub-table are left untouched.
  5246. // Matcher-only entries (no handler fields) are intentionally valid and skipped.
  5247. const STALE_HANDLER_FIELD_PATTERN = /^\s*(?:command|type|timeout|statusMessage)\s*=/m;
  5248. const staleNamespacedAotSections = sections.filter((section) => {
  5249. if (!section.array) return false;
  5250. if (!section.path.startsWith('hooks.')) return false;
  5251. // [[hooks.TYPE.hooks]] sub-tables have 3 parsed segments — skip them.
  5252. // Use section.segments (true parsed key count) rather than splitting
  5253. // section.path on '.', which misclassifies quoted event names that contain
  5254. // dots (e.g. [[hooks."before.tool"]] has segments ['hooks','before.tool']
  5255. // but path 'hooks.before.tool' would split into 3 parts).
  5256. if (section.segments.length !== 2) return false;
  5257. // Must carry at least one handler field at event-entry level.
  5258. const body = content.slice(section.headerEnd, section.end);
  5259. if (!STALE_HANDLER_FIELD_PATTERN.test(body)) return false;
  5260. // Don't migrate when the nested [[hooks.TYPE.hooks]] sub-table already exists.
  5261. const subPath = section.path + '.hooks';
  5262. return !sections.some((s) => s.array && s.path === subPath);
  5263. });
  5264. if (legacyMapSections.length === 0 && flatAotSections.length === 0 && staleNamespacedAotSections.length === 0) {
  5265. return content;
  5266. }
  5267. const eol = detectLineEnding(content);
  5268. // Helper: parse a hooks body into event-level and handler-level entries,
  5269. // returning { eventEntries, handlerEntries, hasExplicitType }.
  5270. // Event-level keys: matcher. Everything else is handler-level.
  5271. // The `event` key (used in flat [[hooks]] blocks) is consumed as the type
  5272. // name and excluded from both levels.
  5273. const EVENT_LEVEL_KEYS = new Set(['matcher']);
  5274. function parseHooksBody(body, skipKeys = new Set()) {
  5275. const bodyLines = body.split(/\r?\n/);
  5276. const eventEntries = [];
  5277. const handlerEntries = [];
  5278. let hasExplicitType = false;
  5279. for (const line of bodyLines) {
  5280. const trimmed = line.trim();
  5281. if (!trimmed || trimmed.startsWith('#')) continue;
  5282. // Use parseTomlKey so hyphenated keys (e.g. status-message) and quoted
  5283. // keys are recognised — the old /^([\w.]+)\s*=/ regex silently dropped them.
  5284. const parsed = parseTomlKey(trimmed);
  5285. if (!parsed) continue;
  5286. // Hook body keys are always single-segment; use segments[0] for the name.
  5287. const key = parsed.segments[0];
  5288. if (skipKeys.has(key)) continue;
  5289. if (key === 'type') {
  5290. hasExplicitType = true;
  5291. handlerEntries.push(trimmed);
  5292. } else if (EVENT_LEVEL_KEYS.has(key)) {
  5293. eventEntries.push(trimmed);
  5294. } else {
  5295. handlerEntries.push(trimmed);
  5296. }
  5297. }
  5298. return { eventEntries, handlerEntries, hasExplicitType };
  5299. }
  5300. // TOML key quoting: bare keys may only contain [A-Za-z0-9_-]. Event names
  5301. // containing spaces, dots, or other punctuation must be wrapped in double-
  5302. // quoted TOML strings with backslash and double-quote characters escaped.
  5303. // Using raw event names in [[hooks.${type}]] headers produces invalid TOML
  5304. // for any non-bare-key character (e.g. "Before Tool" → [[hooks.Before Tool]]).
  5305. function tomlBareKey(key) {
  5306. if (/^[A-Za-z0-9_-]+$/.test(key)) return key;
  5307. return '"' + key.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
  5308. }
  5309. function buildNestedBlock(type, body, skipKeys = new Set()) {
  5310. const quotedType = tomlBareKey(type);
  5311. const { eventEntries, handlerEntries, hasExplicitType } = parseHooksBody(body, skipKeys);
  5312. const eventBody = eventEntries.length > 0 ? eventEntries.join(eol) + eol : '';
  5313. // If no handler fields were found (e.g. matcher-only entry), do not synthesise
  5314. // an empty [[hooks.TYPE.hooks]] block — that would produce structurally valid
  5315. // TOML but semantically broken output (a handler entry with no command).
  5316. if (handlerEntries.length === 0) {
  5317. return `[[hooks.${quotedType}]]${eol}${eventBody}`;
  5318. }
  5319. if (!hasExplicitType) handlerEntries.unshift('type = "command"');
  5320. const handlerBody = handlerEntries.join(eol) + eol;
  5321. return `[[hooks.${quotedType}]]${eol}${eventBody}${eol}[[hooks.${quotedType}.hooks]]${eol}${handlerBody}`;
  5322. }
  5323. // Extract the event name from a flat [[hooks]] section body.
  5324. // Returns null if no `event` key is found, if the value is an empty string, or if
  5325. // the quoting is unrecognised. Both TOML double-quoted ("...") and single-quoted
  5326. // ('...') strings are accepted. An empty event string (event = "" or event = '')
  5327. // is explicitly rejected — it cannot be meaningfully namespaced and is left untouched.
  5328. function extractFlatHookEventName(body) {
  5329. const TOML_EVENT_CAPTURE = /^\s*event\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')/m;
  5330. const m = body.match(TOML_EVENT_CAPTURE);
  5331. if (!m) return null;
  5332. const name = (m[1] ?? m[2] ?? '').trim();
  5333. return name || null;
  5334. }
  5335. const migratedFlatAotSections = flatAotSections.filter((section) => {
  5336. const body = content.slice(section.headerEnd, section.end);
  5337. return extractFlatHookEventName(body) !== null;
  5338. });
  5339. const legacyHooksSections = [...legacyMapSections, ...migratedFlatAotSections, ...staleNamespacedAotSections];
  5340. // Remove all legacy hooks sections from the content
  5341. let result = removeContentRanges(
  5342. content,
  5343. legacyHooksSections.map(({ start, end }) => ({ start, end })),
  5344. );
  5345. result = collapseTomlBlankLines(result);
  5346. // Map-format blocks ([hooks.TYPE]) are inserted at the position of the first
  5347. // remaining table section (preserving their relative placement in the file).
  5348. // Flat AoT blocks ([[hooks]] with event = "...") are always APPENDED because
  5349. // flat [[hooks]] entries only appear at the END of a TOML file (AoT cannot
  5350. // precede a regular table), and inserting before the first table would push
  5351. // them above [features] / [model] etc., corrupting relative ordering.
  5352. const mapOnlyBlocks = legacyMapSections
  5353. .filter((s) => s.path !== 'hooks') // skip bare [hooks] container
  5354. .map((s) => {
  5355. const body = content.slice(s.headerEnd, s.end);
  5356. // #3346: when the legacy `[hooks.<X>]` body declares `event = "..."`,
  5357. // prefer that as the event-name leaf key. The path segment <X> may be
  5358. // a `<file>:<event>:<line>:<col>` location identifier (Codex pre-AoT
  5359. // wrote those as table keys), which is not a valid leaf event name —
  5360. // emitting it verbatim produces a TOML key chain Codex 0.124.0+ rejects.
  5361. const bodyEvent = extractFlatHookEventName(body);
  5362. const type = bodyEvent !== null ? bodyEvent : s.path.slice('hooks.'.length);
  5363. const skipKeys = bodyEvent !== null ? new Set(['event']) : new Set();
  5364. return buildNestedBlock(type, body, skipKeys);
  5365. });
  5366. // Stale namespaced AoT blocks: [[hooks.TYPE]] entries with handler fields at
  5367. // event-entry level (no .hooks sub-table). Treated like map-format blocks —
  5368. // inserted before the first remaining table section.
  5369. const staleNamespacedAotBlocks = staleNamespacedAotSections.map((s) => {
  5370. const body = content.slice(s.headerEnd, s.end);
  5371. // #3346: see note in mapOnlyBlocks — body `event = "..."` wins over the
  5372. // raw path segment when both are present.
  5373. const bodyEvent = extractFlatHookEventName(body);
  5374. const type = bodyEvent !== null ? bodyEvent : s.path.slice('hooks.'.length);
  5375. const skipKeys = bodyEvent !== null ? new Set(['event']) : new Set();
  5376. return buildNestedBlock(type, body, skipKeys);
  5377. });
  5378. const flatAotBlocks = migratedFlatAotSections.map((s) => {
  5379. const body = content.slice(s.headerEnd, s.end);
  5380. const eventName = extractFlatHookEventName(body);
  5381. if (!eventName) return '';
  5382. return buildNestedBlock(eventName, body, new Set(['event']));
  5383. }).filter(Boolean);
  5384. // Insert map-format and stale-namespaced-AoT conversions before the first
  5385. // remaining table section (both share the same placement strategy).
  5386. const allMapStyleBlocks = [...mapOnlyBlocks, ...staleNamespacedAotBlocks];
  5387. if (allMapStyleBlocks.length > 0) {
  5388. const insertionText = allMapStyleBlocks.join('');
  5389. const remainingSections = getTomlTableSections(result);
  5390. if (remainingSections.length > 0) {
  5391. const firstTable = remainingSections[0];
  5392. const before = result.slice(0, firstTable.start);
  5393. const after = result.slice(firstTable.start);
  5394. const needsLeadingGap = before.length > 0 && !before.endsWith(eol + eol);
  5395. const needsTrailingGap = after.length > 0 && !insertionText.endsWith(eol + eol);
  5396. result = before +
  5397. (needsLeadingGap ? eol : '') +
  5398. insertionText +
  5399. (needsTrailingGap ? eol : '') +
  5400. after;
  5401. } else {
  5402. const needsGap = result.length > 0 && !result.endsWith(eol + eol);
  5403. result = result + (needsGap ? eol : '') + insertionText;
  5404. }
  5405. }
  5406. // Insert flat-AoT conversions before the GSD managed marker (if present) so
  5407. // the migrated user hooks stay in the "user" portion of the file and are not
  5408. // swept away when stripGsdFromCodexConfig strips from the marker to EOF.
  5409. // If no marker exists, append at the end of the file.
  5410. if (flatAotBlocks.length > 0) {
  5411. const insertionText = flatAotBlocks.join('');
  5412. const markerIdx = result.indexOf(GSD_CODEX_MARKER);
  5413. if (markerIdx !== -1) {
  5414. const before = result.slice(0, markerIdx).trimEnd();
  5415. const after = result.slice(markerIdx);
  5416. result = before + eol + eol + insertionText + eol + after;
  5417. } else {
  5418. const needsGap = result.length > 0 && !result.endsWith(eol + eol);
  5419. result = result + (needsGap ? eol : '') + insertionText;
  5420. }
  5421. }
  5422. return result;
  5423. }
  5424. /**
  5425. * Detect whether the user already uses the namespaced AoT hooks form
  5426. * (`[[hooks.<EVENT>]]`) for the given event in the config. When true,
  5427. * the GSD-managed hook block must be emitted in the same shape so it
  5428. * coexists cleanly — mixing `[[hooks]]` (flat) with `[[hooks.SessionStart]]`
  5429. * (namespaced) in the same file confuses round-trip writers and can
  5430. * produce a config that Codex rejects (#2760, defect 3).
  5431. */
  5432. function hasUserNamespacedAotHooks(content, event) {
  5433. const sections = getTomlTableSections(content);
  5434. return sections.some(
  5435. (section) => section.array && section.path === `hooks.${event}`
  5436. );
  5437. }
  5438. /**
  5439. * Parse a TOML value RHS expression starting at index `i` of `text`.
  5440. * Returns { value, end } on success or throws on parse failure.
  5441. *
  5442. * Supports the value forms GSD emits or that real Codex configs commonly use:
  5443. * - basic strings ("…" with simple escapes)
  5444. * - literal strings ('…')
  5445. * - booleans (true / false)
  5446. * - integers (optional sign, decimal digits)
  5447. * - inline arrays of the above
  5448. * - inline tables { k = v, … }
  5449. *
  5450. * This is intentionally not a complete TOML implementation — it is the
  5451. * minimal value grammar required to validate Codex config structure and to
  5452. * back behavioral assertions in tests (#2760).
  5453. */
  5454. function parseTomlValue(text, i) {
  5455. // Skip leading whitespace.
  5456. while (i < text.length && (text[i] === ' ' || text[i] === '\t')) {
  5457. i += 1;
  5458. }
  5459. if (i >= text.length) {
  5460. throw new Error('expected value, got end of input');
  5461. }
  5462. const ch = text[i];
  5463. // Basic string
  5464. if (ch === '"') {
  5465. if (text.startsWith('"""', i)) {
  5466. const close = findMultilineBasicStringClose(text, i + 3);
  5467. if (close === -1) {
  5468. throw new Error('unterminated multi-line basic string');
  5469. }
  5470. const raw = text.slice(i + 3, close);
  5471. return { value: raw.replace(/^\r?\n/, ''), end: close + 3 };
  5472. }
  5473. let j = i + 1;
  5474. let out = '';
  5475. while (j < text.length) {
  5476. const c = text[j];
  5477. if (c === '\\') {
  5478. const next = text[j + 1];
  5479. if (next === 'n') { out += '\n'; j += 2; continue; }
  5480. if (next === 't') { out += '\t'; j += 2; continue; }
  5481. if (next === 'r') { out += '\r'; j += 2; continue; }
  5482. if (next === '\\') { out += '\\'; j += 2; continue; }
  5483. if (next === '"') { out += '"'; j += 2; continue; }
  5484. if (next === '/') { out += '/'; j += 2; continue; }
  5485. // Pass-through unrecognized escape (Codex/GSD don't use these).
  5486. out += next === undefined ? '' : next;
  5487. j += 2;
  5488. continue;
  5489. }
  5490. if (c === '"') {
  5491. return { value: out, end: j + 1 };
  5492. }
  5493. out += c;
  5494. j += 1;
  5495. }
  5496. throw new Error('unterminated basic string');
  5497. }
  5498. // Literal string
  5499. if (ch === '\'') {
  5500. if (text.startsWith('\'\'\'', i)) {
  5501. const close = text.indexOf('\'\'\'', i + 3);
  5502. if (close === -1) throw new Error('unterminated multi-line literal string');
  5503. return { value: text.slice(i + 3, close).replace(/^\r?\n/, ''), end: close + 3 };
  5504. }
  5505. const close = text.indexOf('\'', i + 1);
  5506. if (close === -1) throw new Error('unterminated literal string');
  5507. return { value: text.slice(i + 1, close), end: close + 1 };
  5508. }
  5509. // Boolean
  5510. if (text.startsWith('true', i) && !/[A-Za-z0-9_-]/.test(text[i + 4] || '')) {
  5511. return { value: true, end: i + 4 };
  5512. }
  5513. if (text.startsWith('false', i) && !/[A-Za-z0-9_-]/.test(text[i + 5] || '')) {
  5514. return { value: false, end: i + 5 };
  5515. }
  5516. // Inline array
  5517. if (ch === '[') {
  5518. const arr = [];
  5519. let j = i + 1;
  5520. while (true) {
  5521. while (j < text.length && /[\s\r\n]/.test(text[j])) j += 1;
  5522. if (j >= text.length) throw new Error('unterminated inline array');
  5523. if (text[j] === ']') return { value: arr, end: j + 1 };
  5524. if (text[j] === '#') {
  5525. const nl = text.indexOf('\n', j);
  5526. j = nl === -1 ? text.length : nl + 1;
  5527. continue;
  5528. }
  5529. const parsed = parseTomlValue(text, j);
  5530. arr.push(parsed.value);
  5531. j = parsed.end;
  5532. while (j < text.length && /[\s\r\n]/.test(text[j])) j += 1;
  5533. if (j < text.length && text[j] === ',') {
  5534. j += 1;
  5535. continue;
  5536. }
  5537. while (j < text.length && /[\s\r\n]/.test(text[j])) j += 1;
  5538. if (text[j] === ']') return { value: arr, end: j + 1 };
  5539. throw new Error(`expected , or ] in inline array at offset ${j}`);
  5540. }
  5541. }
  5542. // Inline table
  5543. if (ch === '{') {
  5544. const obj = {};
  5545. let j = i + 1;
  5546. while (true) {
  5547. while (j < text.length && /[\s\r\n]/.test(text[j])) j += 1;
  5548. if (text[j] === '}') return { value: obj, end: j + 1 };
  5549. const keyMatch = text.slice(j).match(/^([A-Za-z0-9_-]+|"[^"]*"|'[^']*')\s*=\s*/);
  5550. if (!keyMatch) throw new Error(`expected key in inline table at offset ${j}`);
  5551. let rawKey = keyMatch[1];
  5552. if ((rawKey.startsWith('"') && rawKey.endsWith('"')) || (rawKey.startsWith('\'') && rawKey.endsWith('\''))) {
  5553. rawKey = rawKey.slice(1, -1);
  5554. }
  5555. j += keyMatch[0].length;
  5556. const parsed = parseTomlValue(text, j);
  5557. obj[rawKey] = parsed.value;
  5558. j = parsed.end;
  5559. while (j < text.length && /[\s\r\n]/.test(text[j])) j += 1;
  5560. if (text[j] === ',') { j += 1; continue; }
  5561. if (text[j] === '}') return { value: obj, end: j + 1 };
  5562. throw new Error(`expected , or } in inline table at offset ${j}`);
  5563. }
  5564. }
  5565. // Number — integer or TOML 1.0 float. (#2760 CR4 finding 3 required explicit
  5566. // rejection of floats; #3245 inverts that: Codex CLI's serde schema requires
  5567. // f64 for tool_timeout_sec / startup_timeout_sec, so integers are what Codex
  5568. // rejects. Accept TOML floats and store as JS Number.)
  5569. //
  5570. // Still rejected: date/time literals (`-`, `:`, `T`, `Z` after integer prefix)
  5571. // and hex/oct/bin literals (`0x`, `0o`, `0b` — `x`, `o`, `b` fall through to
  5572. // the unsupported-value throw below because the integer-part pattern won't match `x`).
  5573. // TOML 1.0 §2: underscores in numeric literals are only allowed BETWEEN
  5574. // digits (each underscore must have a digit on both sides). The pre-check
  5575. // regex uses (?:_?\d)* rather than [\d_]* so `1__0`, `1_.0`, and `1._0`
  5576. // are rejected before normalization silently hides them.
  5577. //
  5578. // TOML 1.0 §2 (integer part): the integer part of a number must follow
  5579. // decimal-integer rules — no leading zeros except the value 0 itself.
  5580. // `01`, `00`, `01.5`, `00e2`, `+01`, `-01` are therefore all invalid.
  5581. // The pre-check and float regexes use (0|[1-9](?:_?\d)*) for the integer
  5582. // part so that `01` and `00` are rejected (k021 sibling rule).
  5583. const numMatch = text.slice(i).match(/^[+-]?(0|[1-9](?:_?\d)*)/);
  5584. if (numMatch) {
  5585. const afterInt = text[i + numMatch[0].length];
  5586. // Reject date/time separators that cannot be part of a float.
  5587. if (afterInt !== undefined && /[:\-TZ]/.test(afterInt)) {
  5588. throw new Error(
  5589. `unsupported TOML value at offset ${i}: dates and times are not supported (got ${text.slice(i, i + 20)})`
  5590. );
  5591. }
  5592. // Accept float: optional decimal part, optional exponent part.
  5593. // Each segment uses (?:_?\d)* so underscores are only between digits.
  5594. // Integer part uses (0|[1-9](?:_?\d)*) to reject leading zeros per TOML 1.0.
  5595. const floatMatch = text.slice(i).match(
  5596. /^[+-]?(0|[1-9](?:_?\d)*)(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?/
  5597. );
  5598. const raw = floatMatch ? floatMatch[0] : numMatch[0];
  5599. const normalized = raw.replace(/_/g, '');
  5600. const n = Number(normalized);
  5601. if (!Number.isFinite(n)) throw new Error(`invalid number: ${raw}`);
  5602. return { value: n, end: i + raw.length };
  5603. }
  5604. throw new Error(`unsupported value at offset ${i}: ${text.slice(i, i + 20)}`);
  5605. }
  5606. /**
  5607. * Parse TOML content into a JavaScript object. Throws on malformed input.
  5608. *
  5609. * Handles `[table]`, `[[array.of.tables]]`, dotted key paths, and the value
  5610. * forms supported by parseTomlValue. Sufficient for validating Codex config
  5611. * structure and for behavioral test assertions in #2760 — not a general
  5612. * TOML implementation.
  5613. */
  5614. function parseTomlToObject(content) {
  5615. const root = {};
  5616. const records = getTomlLineRecords(content);
  5617. // Tracks the *object* (not path) that subsequent key=value lines target.
  5618. let currentTable = root;
  5619. // #2760 CR5 finding 2 — track shape and definition status of every path so
  5620. // we can reject duplicate header redeclarations, shape mismatches, and
  5621. // duplicate keys per real TOML 1.0 semantics. Without this, walkPath
  5622. // silently reuses existing tables and assignment overwrites existing keys —
  5623. // a real TOML parser would refuse the file.
  5624. //
  5625. // pathShape: dotted path -> 'table' | 'array' | 'inline_parent' | 'key'
  5626. // - 'table' — declared via [a.b]
  5627. // - 'array' — declared via [[a.b]] (path is the array itself; each
  5628. // element is its own implicit table)
  5629. // - 'inline_parent' — created implicitly while walking parents
  5630. // - 'key' — assigned a scalar value
  5631. // declaredHeaders: set of dotted paths explicitly declared via [hdr] (not
  5632. // [[arr]]) — used to reject duplicate [a] / [a] sections.
  5633. // tableKeys: dotted-path -> Set<string> of keys assigned in that exact
  5634. // table instance. For [[arr]] elements we use a per-element marker.
  5635. const pathShape = new Map();
  5636. const declaredHeaders = new Set();
  5637. const tableKeys = new Map();
  5638. // currentTableId — string identifier for the current table instance, used
  5639. // as the key into tableKeys so that key uniqueness is per-table-instance
  5640. // (each [[arr]] element gets its own id).
  5641. let currentTableId = '__root__';
  5642. pathShape.set('__root__', 'table');
  5643. tableKeys.set('__root__', new Set());
  5644. function ensureKeySet(id) {
  5645. if (!tableKeys.has(id)) tableKeys.set(id, new Set());
  5646. return tableKeys.get(id);
  5647. }
  5648. function walkPath(segments, { creatingArrayElement = false } = {}) {
  5649. let node = root;
  5650. const parents = segments.slice(0, -1);
  5651. const last = segments[segments.length - 1];
  5652. for (let p = 0; p < parents.length; p += 1) {
  5653. const seg = parents[p];
  5654. const partialPath = parents.slice(0, p + 1).join('.');
  5655. if (node[seg] === undefined) {
  5656. node[seg] = {};
  5657. if (!pathShape.has(partialPath)) {
  5658. pathShape.set(partialPath, 'inline_parent');
  5659. }
  5660. } else if (Array.isArray(node[seg])) {
  5661. // Walk into the latest element of an array-of-tables.
  5662. node = node[seg][node[seg].length - 1];
  5663. continue;
  5664. } else if (typeof node[seg] !== 'object' || node[seg] === null) {
  5665. throw new Error(`path segment ${seg} is not a table`);
  5666. }
  5667. node = node[seg];
  5668. }
  5669. const fullPath = segments.join('.');
  5670. if (creatingArrayElement) {
  5671. const existingShape = pathShape.get(fullPath);
  5672. if (node[last] === undefined) {
  5673. node[last] = [];
  5674. pathShape.set(fullPath, 'array');
  5675. } else if (!Array.isArray(node[last])) {
  5676. throw new Error(
  5677. `duplicate or shape-mismatched table header at ${fullPath}: ` +
  5678. `cannot redefine as array of tables (previously seen as ${existingShape || 'table'})`
  5679. );
  5680. } else if (existingShape && existingShape !== 'array') {
  5681. throw new Error(
  5682. `duplicate or shape-mismatched table header at ${fullPath}: ` +
  5683. `previously seen as ${existingShape}, cannot extend as array of tables`
  5684. );
  5685. }
  5686. const elem = {};
  5687. node[last].push(elem);
  5688. const elemId = `${fullPath}[${node[last].length - 1}]`;
  5689. pathShape.set(elemId, 'array_element');
  5690. tableKeys.set(elemId, new Set());
  5691. currentTableId = elemId;
  5692. return elem;
  5693. }
  5694. // Plain [table] header.
  5695. if (node[last] === undefined) {
  5696. node[last] = {};
  5697. pathShape.set(fullPath, 'table');
  5698. declaredHeaders.add(fullPath);
  5699. tableKeys.set(fullPath, new Set());
  5700. } else if (Array.isArray(node[last])) {
  5701. throw new Error(
  5702. `duplicate or shape-mismatched table header at ${fullPath}: ` +
  5703. `previously declared as array of tables ([[${fullPath}]]), cannot redeclare as table ([${fullPath}])`
  5704. );
  5705. } else if (typeof node[last] !== 'object') {
  5706. throw new Error(`cannot redefine ${fullPath} as table`);
  5707. } else if (declaredHeaders.has(fullPath)) {
  5708. throw new Error(
  5709. `duplicate or shape-mismatched table header at ${fullPath}: ` +
  5710. `[${fullPath}] declared more than once`
  5711. );
  5712. } else {
  5713. // Implicitly created earlier (e.g., as a parent path); first explicit
  5714. // declaration is allowed.
  5715. pathShape.set(fullPath, 'table');
  5716. declaredHeaders.add(fullPath);
  5717. if (!tableKeys.has(fullPath)) tableKeys.set(fullPath, new Set());
  5718. }
  5719. currentTableId = fullPath;
  5720. return node[last];
  5721. }
  5722. for (let idx = 0; idx < records.length; idx += 1) {
  5723. const rec = records[idx];
  5724. if (rec.startsInMultilineString) continue;
  5725. if (rec.tableHeader) {
  5726. const segs = rec.tableHeader.segments;
  5727. currentTable = walkPath(segs, { creatingArrayElement: rec.tableHeader.array });
  5728. continue;
  5729. }
  5730. const trimmed = rec.text.trim();
  5731. if (trimmed === '' || trimmed.startsWith('#')) continue;
  5732. const equalsIndex = findTomlAssignmentEquals(rec.text);
  5733. if (equalsIndex === -1) continue;
  5734. const keyText = rec.text.slice(0, equalsIndex).trim();
  5735. const segments = parseTomlKeyPath(keyText);
  5736. if (!segments) {
  5737. throw new Error(`invalid TOML key on line ${idx + 1}: ${rec.text}`);
  5738. }
  5739. // Value RHS may span multiple lines (inline arrays, multi-line strings,
  5740. // inline tables). Parse from the absolute content offset right after `=`.
  5741. const valueStartAbs = rec.start + equalsIndex + 1;
  5742. const parsed = parseTomlValue(content, valueStartAbs);
  5743. // #2760 CR4 finding 3 — verify the full RHS was consumed. Anything other
  5744. // than whitespace + optional # comment between parsed.end and the next
  5745. // newline (or EOF) means the parser silently accepted a prefix and
  5746. // dropped trailing bytes. Reject so malformed TOML cannot slip past
  5747. // "parse before commit" guarantees.
  5748. let scan = parsed.end;
  5749. while (scan < content.length && (content[scan] === ' ' || content[scan] === '\t')) {
  5750. scan += 1;
  5751. }
  5752. if (scan < content.length && content[scan] !== '\n' && content[scan] !== '\r' && content[scan] !== '#') {
  5753. const lineEnd = content.indexOf('\n', scan);
  5754. const trailing = content.slice(scan, lineEnd === -1 ? content.length : lineEnd);
  5755. throw new Error(
  5756. `trailing bytes after value on line ${idx + 1}: ${JSON.stringify(trailing)}`
  5757. );
  5758. }
  5759. // Place value into currentTable under dotted key.
  5760. // #2760 CR5 finding 2 — reject duplicate keys per real TOML 1.0. Track
  5761. // the dotted key against the current table instance id; an exact repeat
  5762. // throws.
  5763. let target = currentTable;
  5764. for (let s = 0; s < segments.length - 1; s += 1) {
  5765. const seg = segments[s];
  5766. if (target[seg] === undefined) target[seg] = {};
  5767. else if (typeof target[seg] !== 'object' || Array.isArray(target[seg])) {
  5768. throw new Error(`cannot descend into non-table key ${seg}`);
  5769. }
  5770. target = target[seg];
  5771. }
  5772. const finalKey = segments[segments.length - 1];
  5773. const dottedKey = segments.join('.');
  5774. const keySet = ensureKeySet(currentTableId);
  5775. if (keySet.has(dottedKey) || Object.prototype.hasOwnProperty.call(target, finalKey)) {
  5776. throw new Error(
  5777. `duplicate key ${dottedKey} in ${currentTableId === '__root__' ? 'root table' : currentTableId}`
  5778. );
  5779. }
  5780. keySet.add(dottedKey);
  5781. target[finalKey] = parsed.value;
  5782. }
  5783. return root;
  5784. }
  5785. /**
  5786. * Validate that the post-install config.toml matches Codex's expected schema
  5787. * (#2760, fix 3). Returns { ok: true } on success, or { ok: false, reason }
  5788. * with a human-readable explanation of the offending section.
  5789. *
  5790. * Strategy: parse the bytes into a structured object first — malformed TOML
  5791. * fails validation immediately rather than slipping past a header-only scan.
  5792. * Then enforce the schema-shape rules against the parsed structure.
  5793. *
  5794. * Schema rules enforced:
  5795. * - File MUST parse as TOML (no syntax errors).
  5796. * - `agents` MUST be a struct table (`[agents.<name>]`) — never a bare
  5797. * table value or an array of tables.
  5798. * - `hooks.<Event>` MUST be an array of tables when present (Codex ≥0.124
  5799. * rejects bare `[hooks.<Event>]` single-bracket maps).
  5800. */
  5801. /**
  5802. * True when a bare `[agents]` table body contains ONLY known AgentsToml scalar
  5803. * keys (CODEX_AGENTS_TOML_SCALAR_KEYS) — i.e. it is a valid AgentsToml struct
  5804. * that Codex's `deny_unknown_fields` will accept, not the break-causing form
  5805. * (#2760) that carries an unknown key. Comments and blank lines are ignored; an
  5806. * empty body is trivially valid. Mirrors isLegacyGsdAgentsSection's line scan.
  5807. */
  5808. function codexBareAgentsHasOnlyKnownScalars(body) {
  5809. const lineRecords = getTomlLineRecords(body);
  5810. for (const record of lineRecords) {
  5811. // Conservative reject of anything not positively a single known-scalar
  5812. // assignment. A multiline-string value cannot be a valid AgentsToml scalar
  5813. // (max_threads/max_depth/job_max_runtime_seconds are integers,
  5814. // interrupt_message is a bool — none are strings), so codex would reject it
  5815. // too; rejecting here is correct, not a false negative.
  5816. if (record.startsInMultilineString) return false;
  5817. if (record.tableHeader) return false;
  5818. const trimmed = record.text.trim();
  5819. if (!trimmed || trimmed.startsWith('#')) continue;
  5820. if (!record.keySegments || record.keySegments.length !== 1 ||
  5821. !CODEX_AGENTS_TOML_SCALAR_KEYS.has(record.keySegments[0])) {
  5822. return false;
  5823. }
  5824. }
  5825. return true;
  5826. }
  5827. function validateCodexConfigSchema(content) {
  5828. let parsed;
  5829. try {
  5830. parsed = parseTomlToObject(content);
  5831. } catch (e) {
  5832. return {
  5833. ok: false,
  5834. reason: `TOML parse failed: ${e.message}`,
  5835. };
  5836. }
  5837. // Header-shape check: arrays-of-tables are visible in the parsed structure
  5838. // (as Array values) but bare-vs-struct distinction for `[agents]` requires
  5839. // looking at section headers too — `[agents]` with `default = "x"` parses
  5840. // to `{ agents: { default: 'x' } }`, indistinguishable from
  5841. // `[agents.foo]` writing into the same shape. Use header sections to
  5842. // disambiguate.
  5843. const sections = getTomlTableSections(content);
  5844. for (const section of sections) {
  5845. if (section.array && section.path === 'agents') {
  5846. return {
  5847. ok: false,
  5848. reason: '[[agents]] sequence form is invalid in current Codex schema (expected [agents.<name>] struct form)',
  5849. };
  5850. }
  5851. if (!section.array && section.path === 'agents') {
  5852. // #2760 rejected ALL bare `[agents]` tables because a bare table holding a
  5853. // non-AgentsToml key (`default = "x"`, a role name, etc.) triggers Codex's
  5854. // "invalid type: ..., expected struct AgentsToml" and breaks every CLI
  5855. // invocation. But a bare `[agents]` whose keys are all valid AgentsToml
  5856. // scalars (max_depth/max_threads/...) IS a valid struct — that is exactly
  5857. // GSD's managed `max_depth` dispatch-tuning block (ADR-1239 upgrade 2 /
  5858. // #2088), and a user's own scalar tuning. Permit known-scalar-only; still
  5859. // reject any bare `[agents]` carrying an unknown key.
  5860. const body = content.slice(section.headerEnd, section.end);
  5861. if (!codexBareAgentsHasOnlyKnownScalars(body)) {
  5862. return {
  5863. ok: false,
  5864. reason: 'bare [agents] table with a non-AgentsToml key is invalid in current Codex schema (expected [agents.<name>] struct form, or only AgentsToml scalars like max_depth/max_threads)',
  5865. };
  5866. }
  5867. }
  5868. // hooks.state.* is Codex's persistent hook-trust namespace (added in
  5869. // Codex CLI 0.130.0). It uses regular-table shape, NOT array-of-tables.
  5870. // [[hooks.state]] or [[hooks.state.<key>]] (AoT) is invalid; reject it.
  5871. if (section.array && (section.path === 'hooks.state' || section.path.startsWith('hooks.state.'))) {
  5872. return {
  5873. ok: false,
  5874. reason: `[[${section.path}]] is invalid; hooks.state namespace must use regular tables`,
  5875. };
  5876. }
  5877. // All other hooks.* paths (event handlers like hooks.SessionStart) require
  5878. // AoT shape — bare [hooks.<Event>] (single-bracket) is invalid.
  5879. if (!section.array && section.path.startsWith('hooks.') &&
  5880. section.path !== 'hooks.state' && !section.path.startsWith('hooks.state.')) {
  5881. return {
  5882. ok: false,
  5883. reason: `bare [${section.path}] table is invalid in current Codex schema (expected [[${section.path}]] array-of-tables)`,
  5884. };
  5885. }
  5886. }
  5887. // Structural confirmation against parsed object: any present hooks.<Event>
  5888. // must be an array, and flat top-level [[hooks]] (parsed as Array on root)
  5889. // is rejected — Codex 0.124.0+ requires [[hooks.<Event>]] namespaced form.
  5890. if (parsed.hooks !== undefined) {
  5891. if (Array.isArray(parsed.hooks)) {
  5892. return {
  5893. ok: false,
  5894. reason: 'flat [[hooks]] array-of-tables is invalid in Codex 0.124.0+ (expected [[hooks.<Event>]] namespaced form)',
  5895. };
  5896. }
  5897. if (typeof parsed.hooks === 'object' && parsed.hooks !== null) {
  5898. for (const [event, value] of Object.entries(parsed.hooks)) {
  5899. // hooks.state is Codex's persistent hook-trust namespace — a regular
  5900. // object (table), not an array of event-handler tables.
  5901. // Reject AoT shape (Array) and scalar forms; only plain objects are valid.
  5902. if (event === 'state') {
  5903. if (Array.isArray(value)) {
  5904. return {
  5905. ok: false,
  5906. reason: `hooks.state must be a regular table/object, got array-of-tables`,
  5907. };
  5908. }
  5909. if (typeof value !== 'object' || value === null) {
  5910. return {
  5911. ok: false,
  5912. reason: `hooks.state must be a regular table/object, got ${typeof value}`,
  5913. };
  5914. }
  5915. continue;
  5916. }
  5917. // Skip the nested .hooks sub-array — it lives under hooks.<Event>[n].hooks
  5918. // and is validated separately below.
  5919. if (!Array.isArray(value)) {
  5920. return {
  5921. ok: false,
  5922. reason: `hooks.${event} must be an array of tables, got ${typeof value}`,
  5923. };
  5924. }
  5925. // Each entry in hooks.<Event> must either be a matcher-only filter (no
  5926. // handler fields) or carry a .hooks sub-array of handler tables.
  5927. // Entries with handler fields (command, type, timeout, statusMessage) at
  5928. // event-entry level but without a .hooks sub-table are the pre-#2773
  5929. // single-block shape that Codex 0.124.0+ rejects. migrateCodexHooksMapFormat
  5930. // converts these before validation runs; their presence here means migration
  5931. // failed to cover this entry — fail loudly rather than pass a broken config.
  5932. const HANDLER_FIELD_NAMES = new Set(['command', 'type', 'timeout', 'statusMessage']);
  5933. for (const entry of value) {
  5934. if (!entry || typeof entry !== 'object') continue;
  5935. if (entry.hooks === undefined) {
  5936. const strayKey = Object.keys(entry).find((k) => HANDLER_FIELD_NAMES.has(k));
  5937. if (strayKey) {
  5938. return {
  5939. ok: false,
  5940. reason: `hooks.${event}[] entry has handler field "${strayKey}" at event-entry level; ` +
  5941. `Codex 0.124.0+ requires handler fields nested under [[hooks.${event}.hooks]]`,
  5942. };
  5943. }
  5944. continue;
  5945. }
  5946. if (!Array.isArray(entry.hooks)) {
  5947. return {
  5948. ok: false,
  5949. reason: `hooks.${event}[].hooks must be an array of handler tables, got ${typeof entry.hooks}`,
  5950. };
  5951. }
  5952. for (const handler of entry.hooks) {
  5953. if (handler && typeof handler === 'object' && handler.type !== undefined) {
  5954. if (handler.type !== 'command') {
  5955. return {
  5956. ok: false,
  5957. reason: `hooks.${event}[].hooks[].type must be "command", got "${handler.type}"`,
  5958. };
  5959. }
  5960. }
  5961. }
  5962. }
  5963. }
  5964. }
  5965. }
  5966. return { ok: true };
  5967. }
  5968. function normalizeCodexHooksLine(line, key) {
  5969. const leadingWhitespace = line.match(/^\s*/)[0];
  5970. const commentStart = findTomlCommentStart(line);
  5971. const comment = commentStart === -1 ? '' : line.slice(commentStart);
  5972. return `${leadingWhitespace}${key} = true${comment ? ` ${comment}` : ''}`;
  5973. }
  5974. function findTomlAssignmentBlockEnd(content, record) {
  5975. const equalsIndex = findTomlAssignmentEquals(record.text);
  5976. if (equalsIndex === -1) {
  5977. return record.end + record.eol.length;
  5978. }
  5979. let i = record.start + equalsIndex + 1;
  5980. let arrayDepth = 0;
  5981. let inlineTableDepth = 0;
  5982. while (i < content.length) {
  5983. if (content.startsWith('\'\'\'', i)) {
  5984. const closeIndex = content.indexOf('\'\'\'', i + 3);
  5985. if (closeIndex === -1) {
  5986. return content.length;
  5987. }
  5988. i = closeIndex + 3;
  5989. continue;
  5990. }
  5991. if (content.startsWith('"""', i)) {
  5992. const closeIndex = findMultilineBasicStringClose(content, i + 3);
  5993. if (closeIndex === -1) {
  5994. return content.length;
  5995. }
  5996. i = closeIndex + 3;
  5997. continue;
  5998. }
  5999. const ch = content[i];
  6000. if (ch === '\'') {
  6001. i += 1;
  6002. while (i < content.length) {
  6003. if (content[i] === '\'') {
  6004. i += 1;
  6005. break;
  6006. }
  6007. i += 1;
  6008. }
  6009. continue;
  6010. }
  6011. if (ch === '"') {
  6012. i += 1;
  6013. while (i < content.length) {
  6014. if (content[i] === '\\') {
  6015. i += 2;
  6016. continue;
  6017. }
  6018. if (content[i] === '"') {
  6019. i += 1;
  6020. break;
  6021. }
  6022. i += 1;
  6023. }
  6024. continue;
  6025. }
  6026. if (ch === '[') {
  6027. arrayDepth += 1;
  6028. i += 1;
  6029. continue;
  6030. }
  6031. if (ch === ']') {
  6032. if (arrayDepth > 0) {
  6033. arrayDepth -= 1;
  6034. }
  6035. i += 1;
  6036. continue;
  6037. }
  6038. if (ch === '{') {
  6039. inlineTableDepth += 1;
  6040. i += 1;
  6041. continue;
  6042. }
  6043. if (ch === '}') {
  6044. if (inlineTableDepth > 0) {
  6045. inlineTableDepth -= 1;
  6046. }
  6047. i += 1;
  6048. continue;
  6049. }
  6050. if (ch === '#') {
  6051. while (i < content.length && content[i] !== '\n') {
  6052. i += 1;
  6053. }
  6054. continue;
  6055. }
  6056. if (ch === '\n' && arrayDepth === 0 && inlineTableDepth === 0) {
  6057. return i + 1;
  6058. }
  6059. i += 1;
  6060. }
  6061. return content.length;
  6062. }
  6063. function rewriteTomlKeyLines(content, matches, key) {
  6064. if (matches.length === 0) {
  6065. return content;
  6066. }
  6067. let rewritten = '';
  6068. let cursor = 0;
  6069. matches.forEach((match, index) => {
  6070. rewritten += content.slice(cursor, match.start);
  6071. if (index === 0) {
  6072. const blockEnd = findTomlAssignmentBlockEnd(content, match);
  6073. const blockEol = blockEnd > 0 && content[blockEnd - 1] === '\n'
  6074. ? (blockEnd > 1 && content[blockEnd - 2] === '\r' ? '\r\n' : '\n')
  6075. : '';
  6076. // Preserve the existing key when one is present on the line
  6077. // (`match.keyRaw`). This respects user ownership: a user-authored
  6078. // `codex_hooks = true` line stays as `codex_hooks = true` even
  6079. // though `hooks` is the canonical key in current Codex (#3566).
  6080. // Codex's own `legacy_key` alias mechanism in codex-rs handles the
  6081. // backward compat at the runtime layer. Migration to canonical is
  6082. // a fresh-insert-only operation in ensureCodexHooksFeature.
  6083. rewritten += normalizeCodexHooksLine(match.text, match.keyRaw || key) + blockEol;
  6084. cursor = blockEnd;
  6085. return;
  6086. }
  6087. cursor = findTomlAssignmentBlockEnd(content, match);
  6088. });
  6089. rewritten += content.slice(cursor);
  6090. return rewritten;
  6091. }
  6092. // atomicWriteFileSync and __atomicWrittenTmps are now owned by the
  6093. // runtime-hooks-surface module and imported here so both install.js's
  6094. // direct config.toml writes and the module's Cursor/Codex hooks.json
  6095. // writes share the SAME tracking Set. _cleanTmpFiles() below reads
  6096. // hooksSurface.__atomicWrittenTmps to scope cleanup to installer-owned
  6097. // temps only.
  6098. const atomicWriteFileSync = hooksSurface.atomicWriteFileSync;
  6099. const __atomicWrittenTmps = hooksSurface.__atomicWrittenTmps;
  6100. /**
  6101. * Merge GSD config block into an existing or new config.toml.
  6102. * Three cases: new file, existing with GSD marker, existing without marker.
  6103. *
  6104. * All writes go through atomicWriteFileSync so a mid-write failure leaves
  6105. * the original config.toml untouched (#2760 fix 4).
  6106. */
  6107. /**
  6108. * Split TOML content into its leading TOP-LEVEL key lines and everything from
  6109. * the first table header onward (#3610).
  6110. *
  6111. * Top-level keys were file-scoped before a merge. The regenerated GSD block
  6112. * opens with a table header (`[agents]`, #2088/ADR-1239 upgrade 2), so placing
  6113. * that block ABOVE surviving top-level keys re-scopes them into `[agents]` —
  6114. * `validateCodexConfigSchema` then correctly rejects the merged file and the
  6115. * install aborts. Hoisting the keys above the block preserves their scope.
  6116. *
  6117. * Table headers inside multiline strings do not start the "rest" region (the
  6118. * record parser already excludes them via startsInMultilineString).
  6119. */
  6120. function splitTopLevelKeys(content) {
  6121. for (const record of getTomlLineRecords(content)) {
  6122. if (record.tableHeader && !record.startsInMultilineString) {
  6123. return {
  6124. topLevel: content.slice(0, record.start).trim(),
  6125. rest: content.slice(record.start).trim(),
  6126. };
  6127. }
  6128. }
  6129. return { topLevel: content.trim(), rest: '' };
  6130. }
  6131. /**
  6132. * #5301: the path a config write must target. atomicWriteFileSync ends in a
  6133. * rename(2) onto its destination, which REPLACES a symlink at that path rather than
  6134. * writing through it, so a dotfiles-managed `config.toml -> ~/dotfiles/codex.toml`
  6135. * became a plain file and the user's copy never saw the merge. With
  6136. * GSD_ALLOW_SYMLINKED_DEST the symlink is intentional: resolve it and write the
  6137. * file it points at, leaving the link itself alone. Without the opt-in the path is
  6138. * returned unchanged (the install-root symlink guard refuses such a layout before
  6139. * any write), and so does a dangling link (the guard cannot resolve it), so only a
  6140. * link whose target exists reaches the resolution below.
  6141. */
  6142. function resolveSymlinkWriteTarget(filePath) {
  6143. if (!isSymlinkedDestOptIn()) return filePath;
  6144. let stat;
  6145. try { stat = fs.lstatSync(filePath); } catch (_) { return filePath; }
  6146. if (!stat.isSymbolicLink()) return filePath;
  6147. try { return fs.realpathSync(filePath); } catch (_) { return filePath; }
  6148. }
  6149. function mergeCodexConfig(configPath, gsdBlock) {
  6150. // #5301: the write lands on the symlink's target, never replaces the link.
  6151. configPath = resolveSymlinkWriteTarget(configPath);
  6152. const existing = fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : null;
  6153. atomicWriteFileSync(configPath, mergeCodexConfigContent(existing, gsdBlock));
  6154. }
  6155. function mergeCodexConfigContent(existing, gsdBlock) {
  6156. // Case 1: No config.toml — create fresh
  6157. if (existing === null) return gsdBlock + '\n';
  6158. const eol = detectLineEnding(existing);
  6159. // #2088 review: the bare `[agents]` table is purged below (Case 2/3 via
  6160. // stripLeakedGsdCodexSections) to keep a single managed `[agents]`. Preserve
  6161. // the user's own AgentsToml scalar tuning (max_threads, job_max_runtime_seconds,
  6162. // interrupt_message — everything except GSD-managed max_depth) by re-emitting
  6163. // it inside the managed block, so install never silently drops it.
  6164. const mergedGsdBlock = spliceCodexAgentsScalars(gsdBlock, extractCodexUserAgentsScalars(existing));
  6165. const normalizedGsdBlock = mergedGsdBlock.replace(/\r?\n/g, eol);
  6166. const markerIndex = existing.indexOf(GSD_CODEX_MARKER);
  6167. // Case 2: Has GSD marker — preserve user content on BOTH sides, regenerate the GSD block.
  6168. //
  6169. // #2940: the marker delimits where GSD's OWN block begins, NOT where every post-marker byte
  6170. // is GSD-owned. A fresh install writes the GSD block as the file's entire content, so any
  6171. // settings the user or Codex CLI later adds ([model], [mcp_servers.*], [profiles.*]) land
  6172. // AFTER the block. The previous truncate-to-marker logic discarded that trailing region on
  6173. // every update, destroying user config. The fix routes the trailing region through the
  6174. // existing AST-based `stripLeakedGsdCodexSections`, which removes GSD's own managed/leaked
  6175. // sections (the bare [agents] table GSD regenerates, legacy [agents.gsd-*], [[agents]])
  6176. // while preserving genuine user TOML — so #2406's de-dup still holds AND user content survives.
  6177. if (markerIndex !== -1) {
  6178. let before = existing.substring(0, markerIndex).trimEnd();
  6179. if (before) {
  6180. // Strip any GSD-managed sections that leaked above the marker from previous installs
  6181. before = stripLeakedGsdCodexSections(before).trimEnd();
  6182. }
  6183. // Capture and preserve genuine user content AFTER the GSD-managed region. The whole
  6184. // post-marker region is passed through stripLeakedGsdCodexSections: GSD's own previously-
  6185. // emitted [agents] table (regenerated above as normalizedGsdBlock) and any leaked sections
  6186. // are removed, while user tables ([model], [mcp_servers.*], [profiles.*]) are kept. The
  6187. // marker comment line itself (and the optional codex_hooks ownership line right under it)
  6188. // is GSD-owned and is stripped from the trailing region so it is not duplicated alongside
  6189. // the freshly regenerated block.
  6190. const rawAfter = existing.substring(markerIndex);
  6191. const markerStripped = rawAfter
  6192. .replace(GSD_CODEX_MARKER, '')
  6193. .replace(/^\r?\n# GSD codex_hooks ownership: (?:section|root_dotted)\r?\n/, '');
  6194. const afterUser = stripLeakedGsdCodexSections(markerStripped).trim();
  6195. // #3610: top-level keys that survived BELOW the marker were file-scoped
  6196. // before this merge; the regenerated block opens with the `[agents]` table
  6197. // header, so they must be hoisted to FILE scope or TOML re-scopes them
  6198. // into a table. File scope means BEFORE the first table header of the
  6199. // pre-marker region too — appending them after a pre-marker table (the
  6200. // default real-world layout: user tables precede the marker) would merely
  6201. // capture them into THAT table instead of [agents], and the schema
  6202. // validator is blind to non-agents tables.
  6203. const beforeSplit = before ? splitTopLevelKeys(before) : { topLevel: '', rest: '' };
  6204. const { topLevel: afterTopLevel, rest: afterTables } = splitTopLevelKeys(afterUser);
  6205. const parts = [];
  6206. const topParts = [];
  6207. if (beforeSplit.topLevel) topParts.push(beforeSplit.topLevel);
  6208. if (afterTopLevel) topParts.push(afterTopLevel);
  6209. if (topParts.length > 0) parts.push(topParts.join(eol + eol));
  6210. if (beforeSplit.rest) parts.push(beforeSplit.rest);
  6211. parts.push(normalizedGsdBlock);
  6212. if (afterTables) parts.push(afterTables);
  6213. return parts.join(eol + eol) + eol;
  6214. }
  6215. // Case 3: No marker — append GSD block
  6216. let content = stripLeakedGsdCodexSections(existing).trimEnd();
  6217. if (content) {
  6218. content = content + eol + eol + normalizedGsdBlock + eol;
  6219. } else {
  6220. content = normalizedGsdBlock + eol;
  6221. }
  6222. return content;
  6223. }
  6224. /**
  6225. * Repair config.toml files corrupted by pre-#1346 GSD installs.
  6226. * Non-boolean keys (e.g. model = "gpt-5.4") that ended up under [features]
  6227. * are relocated before the [features] header so Codex can parse them correctly.
  6228. * Returns the content unchanged if no trapped keys are found.
  6229. */
  6230. function repairTrappedFeaturesKeys(content) {
  6231. const eol = detectLineEnding(content);
  6232. const lineRecords = getTomlLineRecords(content);
  6233. const featuresSection = getTomlTableSections(content)
  6234. .find((section) => !section.array && section.path === 'features');
  6235. if (!featuresSection) {
  6236. return content;
  6237. }
  6238. // Find non-boolean key-value lines inside [features] that don't belong there.
  6239. // Boolean keys (codex_hooks, multi_agent, etc.) are legitimate feature flags.
  6240. const trappedLines = lineRecords.filter((record) => {
  6241. if (record.tableHeader || record.startsInMultilineString) return false;
  6242. if (record.tablePath !== 'features') return false;
  6243. if (record.start < featuresSection.headerEnd) return false;
  6244. if (record.end + record.eol.length > featuresSection.end) return false;
  6245. if (!record.keySegments || record.keySegments.length === 0) return false;
  6246. // Check if the value is a boolean — if so, it belongs under [features]
  6247. const equalsIndex = findTomlAssignmentEquals(record.text);
  6248. if (equalsIndex === -1) return false;
  6249. const commentStart = findTomlCommentStart(record.text);
  6250. const valueText = record.text
  6251. .slice(equalsIndex + 1, commentStart === -1 ? record.text.length : commentStart)
  6252. .trim();
  6253. if (valueText === 'true' || valueText === 'false') return false;
  6254. // Skip values that start a multiline string — they may legitimately live
  6255. // under [features] and spanning multiple lines makes relocation unsafe.
  6256. if (valueText.startsWith("'''") || valueText.startsWith('"""')) return false;
  6257. // Non-boolean value — this key is trapped
  6258. return true;
  6259. });
  6260. if (trappedLines.length === 0) {
  6261. return content;
  6262. }
  6263. // Build the relocated text block from trapped lines
  6264. const relocatedText = trappedLines.map((r) => r.text).join(eol) + eol;
  6265. // Remove trapped lines from their current positions (with their EOLs)
  6266. const removalRanges = trappedLines.map((r) => ({
  6267. start: r.start,
  6268. end: r.end + r.eol.length,
  6269. }));
  6270. let cleaned = removeContentRanges(content, removalRanges);
  6271. // Collapse any runs of 3+ blank lines left behind
  6272. cleaned = collapseTomlBlankLines(cleaned);
  6273. // Re-locate the [features] header in the cleaned content
  6274. const cleanedRecords = getTomlLineRecords(cleaned);
  6275. const cleanedFeaturesHeader = cleanedRecords.find(
  6276. (r) => r.tableHeader && r.tableHeader.path === 'features' && !r.tableHeader.array
  6277. );
  6278. if (!cleanedFeaturesHeader) {
  6279. return cleaned;
  6280. }
  6281. // Insert relocated keys before [features]
  6282. const before = cleaned.slice(0, cleanedFeaturesHeader.start);
  6283. const after = cleaned.slice(cleanedFeaturesHeader.start);
  6284. const needsGap = before.length > 0 && !before.endsWith(eol + eol);
  6285. const trailingGap = after.length > 0 && !relocatedText.endsWith(eol + eol) ? eol : '';
  6286. return before + (needsGap ? eol : '') + relocatedText + trailingGap + after;
  6287. }
  6288. function ensureCodexHooksFeature(configContent) {
  6289. const eol = detectLineEnding(configContent);
  6290. const lineRecords = getTomlLineRecords(configContent);
  6291. const featuresSection = getTomlTableSections(configContent)
  6292. .find((section) => !section.array && section.path === 'features');
  6293. if (featuresSection) {
  6294. const sectionLines = lineRecords
  6295. .filter((record) =>
  6296. !record.tableHeader &&
  6297. !record.startsInMultilineString &&
  6298. record.tablePath === 'features' &&
  6299. record.start >= featuresSection.headerEnd &&
  6300. record.end + record.eol.length <= featuresSection.end &&
  6301. record.keySegments &&
  6302. record.keySegments.length === 1 &&
  6303. isCodexHooksFeatureKey(record.keySegments[0])
  6304. );
  6305. if (sectionLines.length > 0) {
  6306. // Rewrite to canonical key — this migrates legacy `codex_hooks` to
  6307. // `hooks` in-place on every reinstall. If the file already has the
  6308. // canonical key the rewrite is a no-op shape-wise (same key, same
  6309. // value). The rewriteTomlKeyLines helper preserves indentation,
  6310. // trailing comments, and ownership-marker positioning, and always
  6311. // emits the caller-supplied canonical key (#3566).
  6312. const rewritten = rewriteTomlKeyLines(configContent, sectionLines, CODEX_HOOKS_FEATURE_KEY);
  6313. return {
  6314. content: repairTrappedFeaturesKeys(rewritten),
  6315. ownership: null,
  6316. };
  6317. }
  6318. const sectionBody = configContent.slice(featuresSection.headerEnd, featuresSection.end);
  6319. const needsSeparator = sectionBody.length > 0 && !sectionBody.endsWith('\n') && !sectionBody.endsWith('\r\n');
  6320. const insertPrefix = sectionBody.length === 0 && featuresSection.headerEnd === configContent.length ? eol : '';
  6321. const insertText = `${insertPrefix}${needsSeparator ? eol : ''}${CODEX_HOOKS_FEATURE_KEY} = true${eol}`;
  6322. const merged = configContent.slice(0, featuresSection.end) + insertText + configContent.slice(featuresSection.end);
  6323. return {
  6324. content: repairTrappedFeaturesKeys(merged),
  6325. ownership: 'section',
  6326. };
  6327. }
  6328. const rootFeatureLines = lineRecords
  6329. .filter((record) =>
  6330. !record.tableHeader &&
  6331. !record.startsInMultilineString &&
  6332. record.tablePath === null &&
  6333. record.keySegments &&
  6334. record.keySegments[0] === 'features'
  6335. );
  6336. const rootCodexHooksLines = rootFeatureLines
  6337. .filter((record) => record.keySegments.length === 2 && isCodexHooksFeatureKey(record.keySegments[1]));
  6338. if (rootCodexHooksLines.length > 0) {
  6339. return {
  6340. content: rewriteTomlKeyLines(configContent, rootCodexHooksLines, `features.${CODEX_HOOKS_FEATURE_KEY}`),
  6341. ownership: null,
  6342. };
  6343. }
  6344. const rootFeaturesValueLines = rootFeatureLines
  6345. .filter((record) => record.keySegments.length === 1);
  6346. if (rootFeaturesValueLines.length > 0) {
  6347. return { content: configContent, ownership: null };
  6348. }
  6349. if (rootFeatureLines.length > 0) {
  6350. const lastFeatureLine = rootFeatureLines[rootFeatureLines.length - 1];
  6351. const insertAt = findTomlAssignmentBlockEnd(configContent, lastFeatureLine);
  6352. const prefix = insertAt > 0 && configContent[insertAt - 1] === '\n' ? '' : eol;
  6353. return {
  6354. content: configContent.slice(0, insertAt) +
  6355. `${prefix}features.${CODEX_HOOKS_FEATURE_KEY} = true${eol}` +
  6356. configContent.slice(insertAt),
  6357. ownership: 'root_dotted',
  6358. };
  6359. }
  6360. const featuresBlock = `[features]${eol}${CODEX_HOOKS_FEATURE_KEY} = true${eol}`;
  6361. if (!configContent) {
  6362. return { content: featuresBlock, ownership: 'section' };
  6363. }
  6364. // Insert [features] before the first table header, preserving bare top-level keys.
  6365. // Prepending would trap them under [features] where Codex expects only booleans (#1202).
  6366. const firstTableHeader = lineRecords.find(r => r.tableHeader);
  6367. if (firstTableHeader) {
  6368. const before = configContent.slice(0, firstTableHeader.start);
  6369. const after = configContent.slice(firstTableHeader.start);
  6370. const needsGap = before.length > 0 && !before.endsWith(eol + eol);
  6371. return {
  6372. content: before + (needsGap ? eol : '') + featuresBlock + eol + after,
  6373. ownership: 'section',
  6374. };
  6375. }
  6376. // No table headers — append [features] after top-level keys
  6377. const needsGap = configContent.length > 0 && !configContent.endsWith(eol + eol);
  6378. return { content: configContent + (needsGap ? eol : '') + featuresBlock, ownership: 'section' };
  6379. }
  6380. function prepareCodexHooksConfig(configContent) {
  6381. // Strip GSD-owned legacy blocks before migrating user hooks (#2698).
  6382. // Share this exact projection with preflight, including inline/scalar
  6383. // features values that ensureCodexHooksFeature deliberately preserves.
  6384. const stripped = stripStaleGsdHookBlocks(configContent);
  6385. const migrated = migrateCodexHooksMapFormat(stripped);
  6386. const feature = ensureCodexHooksFeature(migrated);
  6387. return {
  6388. content: setManagedCodexHooksOwnership(feature.content, feature.ownership),
  6389. migrated: migrated !== stripped,
  6390. };
  6391. }
  6392. function hasEnabledCodexHooksFeature(configContent) {
  6393. const lineRecords = getTomlLineRecords(configContent);
  6394. return lineRecords.some((record) => {
  6395. if (record.tableHeader || record.startsInMultilineString || !record.keySegments) {
  6396. return false;
  6397. }
  6398. const isSectionKey = record.tablePath === 'features' &&
  6399. record.keySegments.length === 1 &&
  6400. isCodexHooksFeatureKey(record.keySegments[0]);
  6401. const isRootDottedKey = record.tablePath === null &&
  6402. record.keySegments.length === 2 &&
  6403. record.keySegments[0] === 'features' &&
  6404. isCodexHooksFeatureKey(record.keySegments[1]);
  6405. if (!isSectionKey && !isRootDottedKey) {
  6406. return false;
  6407. }
  6408. const equalsIndex = findTomlAssignmentEquals(record.text);
  6409. if (equalsIndex === -1) {
  6410. return false;
  6411. }
  6412. const commentStart = findTomlCommentStart(record.text);
  6413. const valueText = record.text.slice(equalsIndex + 1, commentStart === -1 ? record.text.length : commentStart).trim();
  6414. return valueText === 'true';
  6415. });
  6416. }
  6417. /**
  6418. * Merge GSD instructions into copilot-instructions.md.
  6419. * Three cases: new file, existing with markers, existing without markers.
  6420. * @param {string} filePath - Full path to copilot-instructions.md
  6421. * @param {string} gsdContent - Template content (without markers)
  6422. */
  6423. function mergeCopilotInstructions(filePath, gsdContent) {
  6424. const gsdBlock = GSD_COPILOT_INSTRUCTIONS_MARKER + '\n' +
  6425. gsdContent.trim() + '\n' +
  6426. GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER;
  6427. // Case 1: No file — create fresh
  6428. if (!fs.existsSync(filePath)) {
  6429. fs.writeFileSync(filePath, gsdBlock + '\n');
  6430. return;
  6431. }
  6432. const existing = fs.readFileSync(filePath, 'utf8');
  6433. const openIndex = existing.indexOf(GSD_COPILOT_INSTRUCTIONS_MARKER);
  6434. const closeIndex = existing.indexOf(GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER);
  6435. // Case 2: Has GSD markers — replace between markers
  6436. if (openIndex !== -1 && closeIndex !== -1) {
  6437. const before = existing.substring(0, openIndex).trimEnd();
  6438. const after = existing.substring(closeIndex + GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER.length).trimStart();
  6439. let newContent = '';
  6440. if (before) newContent += before + '\n\n';
  6441. newContent += gsdBlock;
  6442. if (after) newContent += '\n\n' + after;
  6443. newContent += '\n';
  6444. fs.writeFileSync(filePath, newContent);
  6445. return;
  6446. }
  6447. // Case 3: No markers — append at end
  6448. const content = existing.trimEnd() + '\n\n' + gsdBlock + '\n';
  6449. fs.writeFileSync(filePath, content);
  6450. }
  6451. /**
  6452. * Strip GSD section from copilot-instructions.md content.
  6453. * Returns cleaned content, or null if file should be deleted (was GSD-only).
  6454. * @param {string} content - File content
  6455. * @returns {string|null} - Cleaned content or null if empty
  6456. */
  6457. function stripGsdFromCopilotInstructions(content) {
  6458. const openIndex = content.indexOf(GSD_COPILOT_INSTRUCTIONS_MARKER);
  6459. const closeIndex = content.indexOf(GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER);
  6460. if (openIndex !== -1 && closeIndex !== -1) {
  6461. const before = content.substring(0, openIndex).trimEnd();
  6462. const after = content.substring(closeIndex + GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER.length).trimStart();
  6463. const cleaned = (before + (before && after ? '\n\n' : '') + after).trim();
  6464. if (!cleaned) return null;
  6465. return cleaned + '\n';
  6466. }
  6467. // No markers found — nothing to strip
  6468. return content;
  6469. }
  6470. // ── Cline directory-form rules + hooks + AGENTS.md (issue #787) ────────────────
  6471. //
  6472. // Cline v3.36 added a hooks system and a `.clinerules/` directory form. Because
  6473. // `.clinerules` cannot be both a file AND a directory, emitting hooks under
  6474. // `.clinerules/hooks/` requires migrating the rules content into the directory
  6475. // form (`.clinerules/gsd.md`). Sources adjudicated:
  6476. // - https://cline.bot/blog/cline-v3-36-hooks
  6477. // - https://docs.cline.bot/customization/cline-rules
  6478. const GSD_AGENTS_MD_MARKER = '<!-- GSD Configuration — managed by gsd-core installer -->';
  6479. const GSD_AGENTS_MD_CLOSE_MARKER = '<!-- End GSD Configuration -->';
  6480. // #2876: buildClineRulesBody, buildClineAgentsMdBody, buildClinePreToolUseHook,
  6481. // and mergeGsdAgentsMd used to be re-bound here as one-line delegates to the
  6482. // equivalent hooksSurface.* implementations. None had an install.js internal
  6483. // caller or an export consumer (tests import all four directly from
  6484. // gsd-core/bin/lib/runtime-hooks-surface.cjs), so the retired bindings were
  6485. // dead code with no reachable body — removed rather than kept as unreachable
  6486. // wrappers.
  6487. /**
  6488. * Strip the GSD block from AGENTS.md content. Returns null if the file became
  6489. * empty (was GSD-only), the unchanged content if no markers were found, or the
  6490. * cleaned content otherwise.
  6491. */
  6492. function stripGsdFromAgentsMd(content) {
  6493. const openIndex = content.indexOf(GSD_AGENTS_MD_MARKER);
  6494. const closeIndex = content.indexOf(GSD_AGENTS_MD_CLOSE_MARKER);
  6495. if (openIndex !== -1 && closeIndex !== -1) {
  6496. const before = content.substring(0, openIndex).trimEnd();
  6497. const after = content.substring(closeIndex + GSD_AGENTS_MD_CLOSE_MARKER.length).trimStart();
  6498. const cleaned = (before + (before && after ? '\n\n' : '') + after).trim();
  6499. if (!cleaned) return null;
  6500. return cleaned + '\n';
  6501. }
  6502. return content;
  6503. }
  6504. /**
  6505. * Write the full Cline runtime artifact set (directory-form rules + PreToolUse
  6506. * hook) into targetDir, migrating a legacy single-file `.clinerules` if present.
  6507. * For global installs, also merge the cross-tool ~/.agents/AGENTS.md target.
  6508. *
  6509. * Returns the list of manifest-relative paths written under targetDir (so the
  6510. * caller can hash-track them).
  6511. */
  6512. function writeClineArtifacts(targetDir, isGlobalInstall) {
  6513. return hooksSurface.writeClineArtifacts(targetDir, isGlobalInstall);
  6514. }
  6515. // ── Cursor hooks.json reconciler (issue #777) ────────────────────────────────
  6516. //
  6517. // Cursor v2.4+ supports a hooks.json lifecycle hook system. GSD registers two
  6518. // managed command hooks:
  6519. // sessionStart → gsd-cursor-session-start.js (context injection)
  6520. // postToolUse → gsd-cursor-post-tool.js (STATE.md update monitor)
  6521. //
  6522. // hooks.json schema:
  6523. // { "version": 1, "hooks": { "<event>": [ { "type": "command", "command": "<path>" } ] } }
  6524. //
  6525. // Location:
  6526. // Global: ~/.cursor/hooks.json
  6527. // Local: <project-root>/.cursor/hooks.json
  6528. //
  6529. // GSD entries are identified by a top-level `"gsd-managed": true` field on
  6530. // each hook entry. Non-GSD entries are preserved. The reconciler is idempotent
  6531. // (safe to re-run) and preserves user-owned entries in the file.
  6532. //
  6533. // References: https://cursor.com/docs/hooks
  6534. // #2876: buildCursorHookEntry, isManagedCursorHookEntry, and
  6535. // reconcileCursorHooksJson used to be re-bound here as one-line delegates to
  6536. // the equivalent hooksSurface.* implementations. None had an install.js
  6537. // internal caller or an export consumer (tests import all three directly from
  6538. // gsd-core/bin/lib/runtime-hooks-surface.cjs), so the retired bindings were
  6539. // dead code with no reachable body — removed rather than kept as unreachable
  6540. // wrappers.
  6541. /**
  6542. * #777 — Write GSD-managed Cursor lifecycle hooks into <targetDir>/hooks.json.
  6543. *
  6544. * Both managed hook scripts (gsd-cursor-session-start.js, gsd-cursor-post-tool.js)
  6545. * are copied from the GSD hooks/ source to <targetDir>/hooks/ first, so the
  6546. * hooks.json entries never reference a script that wasn't installed.
  6547. *
  6548. * @param {string} targetDir - The Cursor config dir (global: ~/.cursor; local: .cursor)
  6549. * @param {string} src - The GSD install source root (for copying hook scripts)
  6550. * @param {{ absoluteRunner?: string|null }} opts
  6551. * @returns {{ hooksJsonPath: string, changed: boolean }}
  6552. */
  6553. function writeCursorHooksJson(targetDir, src, opts) {
  6554. return hooksSurface.writeCursorHooksJson(targetDir, src, opts);
  6555. }
  6556. /**
  6557. * Remove all GSD-managed Cursor lifecycle hook entries from hooks.json.
  6558. * User-owned entries are preserved. If the file becomes empty, it is removed.
  6559. *
  6560. * @param {string} targetDir - The Cursor config dir
  6561. * @returns {{ changed: boolean }}
  6562. */
  6563. function removeCursorHooksJson(targetDir) {
  6564. return hooksSurface.removeCursorHooksJson(targetDir);
  6565. }
  6566. /**
  6567. * #2100 Stage 2 — Write GSD-managed Windsurf/Cascade lifecycle hooks into
  6568. * <targetDir>/hooks.json. Both managed hook scripts
  6569. * (gsd-windsurf-pre-write.js, gsd-windsurf-pre-command.js) are copied from
  6570. * the GSD hooks/ source to <targetDir>/hooks/ first, so the hooks.json
  6571. * entries never reference a script that wasn't installed. Mirrors
  6572. * writeCursorHooksJson's structure; Cascade's blocking protocol (exit code 2)
  6573. * and entry shape (bare `command` string, no `type` field) are distinct from
  6574. * Cursor's.
  6575. *
  6576. * @param {string} targetDir - The Windsurf config dir (global: ~/.codeium/windsurf; local: .windsurf)
  6577. * @param {string} src - The GSD install source root (for copying hook scripts)
  6578. * @param {{ platform?: string }} opts
  6579. * @returns {{ hooksJsonPath: string, changed: boolean }}
  6580. */
  6581. function writeWindsurfHooksJson(targetDir, src, opts) {
  6582. return hooksSurface.writeWindsurfHooksJson(targetDir, src, opts);
  6583. }
  6584. /**
  6585. * Remove all GSD-managed Windsurf/Cascade lifecycle hook entries from
  6586. * hooks.json. User-owned entries are preserved. If the file becomes empty,
  6587. * it is removed.
  6588. *
  6589. * @param {string} targetDir - The Windsurf config dir
  6590. * @returns {{ changed: boolean }}
  6591. */
  6592. function removeWindsurfHooksJson(targetDir) {
  6593. return hooksSurface.removeWindsurfHooksJson(targetDir);
  6594. }
  6595. // #2876: buildCopilotHookConfig used to be re-bound here as a one-line
  6596. // delegate to hooksSurface.buildCopilotHookConfig. It had no install.js
  6597. // internal caller or export consumer (tests import it directly from
  6598. // gsd-core/bin/lib/runtime-hooks-surface.cjs), so the retired binding was
  6599. // dead code with no reachable body — removed rather than kept as an
  6600. // unreachable wrapper. writeCopilotHookConfig below is unaffected — it still
  6601. // has an internal caller (finishInstall).
  6602. /**
  6603. * #786 — Write the GSD-managed Copilot lifecycle hook config under the runtime
  6604. * config dir (`<targetDir>/hooks/gsd-session.json`). For local installs
  6605. * targetDir is `.github` (→ `.github/hooks/`); for global installs it is
  6606. * `~/.copilot` (→ `~/.copilot/hooks/`) — both are valid Copilot hook locations.
  6607. *
  6608. * The managed file is fully owned by GSD, so it is overwritten wholesale on
  6609. * every install (idempotent). User-authored sibling `*.json` hook files in the
  6610. * same directory are untouched.
  6611. *
  6612. * @param {string} targetDir - The Copilot config dir
  6613. * @returns {string} The path the hook config was written to
  6614. */
  6615. function writeCopilotHookConfig(targetDir) {
  6616. return hooksSurface.writeCopilotHookConfig(targetDir);
  6617. }
  6618. /**
  6619. * Generate config.toml and per-agent .toml files for Codex.
  6620. * Reads agent .md files from source, extracts metadata, writes .toml configs.
  6621. */
  6622. // #5335: ~/.gsd/defaults.json is machine-wide, so uninstalling one runtime must not strip a default another
  6623. // still needs, nor one the user chose. A sidecar records which keys an install SET (not ones it found), the
  6624. // value it set, and which non-Claude runtimes have installed since; uninstall reverts a key only when its
  6625. // last such runtime is gone and the value is still the one the installer wrote.
  6626. const DEFAULTS_PROVENANCE_NAME = 'defaults-provenance.json';
  6627. function readDefaultsProvenance(gsdDir) {
  6628. try {
  6629. const p = JSON.parse(fs.readFileSync(path.join(gsdDir, DEFAULTS_PROVENANCE_NAME), 'utf8'));
  6630. if (p && typeof p === 'object' && p.keys && typeof p.keys === 'object') return p;
  6631. } catch { /* absent or unreadable */ }
  6632. return { version: 1, keys: {} };
  6633. }
  6634. function recordDefaultsProvenance(gsdDir, runtime, defaults, setNow) {
  6635. const prov = readDefaultsProvenance(gsdDir);
  6636. let changed = false;
  6637. for (const key of ['resolve_model_ids', 'runtime']) {
  6638. let entry = prov.keys[key];
  6639. if (setNow[key]) {
  6640. entry = { setValue: defaults[key], runtimes: [] };
  6641. prov.keys[key] = entry;
  6642. changed = true;
  6643. }
  6644. if (entry && Array.isArray(entry.runtimes) && !entry.runtimes.includes(runtime)) {
  6645. entry.runtimes.push(runtime);
  6646. changed = true;
  6647. }
  6648. }
  6649. if (changed) atomicWriteFileSync(path.join(gsdDir, DEFAULTS_PROVENANCE_NAME), JSON.stringify(prov, null, 2) + '\n', 'utf8');
  6650. }
  6651. /** @returns {boolean} true when it removed or reverted something */
  6652. function revertNonClaudeDefaults(runtime) {
  6653. if (hostBehaviorsFor(runtime).nativeModelAliases || process.env.GSD_TEST_MODE) return false;
  6654. const gsdDir = path.join(resolveGsdHome(), '.gsd'); // #5017: GSD_HOME-aware, like the loader
  6655. const provPath = path.join(gsdDir, DEFAULTS_PROVENANCE_NAME);
  6656. if (!fs.existsSync(provPath)) return false;
  6657. let releaseLock = null;
  6658. try {
  6659. releaseLock = acquireInstallMigrationLock(gsdDir);
  6660. const prov = readDefaultsProvenance(gsdDir);
  6661. const defaultsPath = path.join(gsdDir, 'defaults.json');
  6662. let defaults = null;
  6663. try { defaults = JSON.parse(fs.readFileSync(defaultsPath, 'utf8')); } catch { /* absent or corrupt */ }
  6664. const reverted = [];
  6665. for (const [key, entry] of Object.entries(prov.keys)) {
  6666. if (!entry || !Array.isArray(entry.runtimes)) { delete prov.keys[key]; continue; }
  6667. entry.runtimes = entry.runtimes.filter((r) => r !== runtime);
  6668. if (entry.runtimes.length > 0) continue;
  6669. if (defaults && typeof defaults === 'object' && defaults[key] === entry.setValue) {
  6670. delete defaults[key];
  6671. reverted.push(key);
  6672. }
  6673. delete prov.keys[key];
  6674. }
  6675. if (reverted.length > 0 && defaults) {
  6676. if (Object.keys(defaults).length === 0) fs.rmSync(defaultsPath, { force: true });
  6677. else atomicWriteFileSync(defaultsPath, JSON.stringify(defaults, null, 2) + '\n', 'utf8');
  6678. console.log(` ${green}✓${reset} Reverted ${reverted.join(', ')} in ~/.gsd/defaults.json (set by the ${runtime} install)`);
  6679. }
  6680. if (Object.keys(prov.keys).length === 0) fs.rmSync(provPath, { force: true });
  6681. else atomicWriteFileSync(provPath, JSON.stringify(prov, null, 2) + '\n', 'utf8');
  6682. return reverted.length > 0;
  6683. } catch (e) {
  6684. console.log(` ${yellow}⚠${reset} Could not update ~/.gsd/defaults.json: ${e.message}`);
  6685. return false;
  6686. } finally {
  6687. if (releaseLock) {
  6688. try { releaseLock(); } catch { /* the stale-lock reaper clears it */ }
  6689. }
  6690. // ~/.gsd is GSD's own directory; drop it once the lock is released and nothing else lives in it.
  6691. try { fs.rmdirSync(gsdDir); } catch { /* other GSD state lives here */ }
  6692. }
  6693. }
  6694. /**
  6695. * #2834: Write ~/.gsd/defaults.json for non-Claude runtimes — sets
  6696. * resolve_model_ids="omit" (so resolveModelInternal() returns '' instead of
  6697. * Claude aliases the runtime can't resolve) and runtime=<runtime> (so
  6698. * resolveRuntime() resolves correctly out of the box). MUST be called BEFORE
  6699. * installCodexConfig (or any other step that reads defaults.json at generation
  6700. * time), so a clean first install produces correctly-model-routed agent TOMLs.
  6701. * No-op for Claude runtimes (Claude is the resolveRuntime fallback + has native
  6702. * model aliases). Preserves an explicit `true` opt-in and existing values.
  6703. */
  6704. function writeNonClaudeDefaults(runtime) {
  6705. if (hostBehaviorsFor(runtime).nativeModelAliases || process.env.GSD_TEST_MODE) return;
  6706. const gsdDir = path.join(resolveGsdHome(), '.gsd'); // #5017: GSD_HOME-aware, like the loader
  6707. const defaultsPath = path.join(gsdDir, 'defaults.json');
  6708. let releaseLock = null;
  6709. try {
  6710. fs.mkdirSync(gsdDir, { recursive: true });
  6711. // defaults.json is machine-global — every runtime and project on the box
  6712. // reads it. Serialize the read-modify-write so two concurrent installs
  6713. // cannot lose each other's key, and apply both mutations in ONE atomic
  6714. // write so a crash cannot leave the file truncated (the read path swallows
  6715. // parse errors and treats a corrupt file as absent, which would silently
  6716. // degrade model resolution everywhere until repaired by hand).
  6717. releaseLock = acquireInstallMigrationLock(gsdDir);
  6718. let defaults = {};
  6719. try { defaults = JSON.parse(fs.readFileSync(defaultsPath, 'utf8')); } catch { /* new file */ }
  6720. if (defaults === null || typeof defaults !== 'object' || Array.isArray(defaults)) {
  6721. defaults = {};
  6722. }
  6723. const applied = [];
  6724. // Three-valued domain: false/absent → aliases; true → full IDs; "omit" → ''.
  6725. const existing = defaults.resolve_model_ids;
  6726. const shouldDefaultToOmit = existing !== true && existing !== 'omit';
  6727. if (shouldDefaultToOmit) {
  6728. defaults.resolve_model_ids = 'omit';
  6729. applied.push(`Set resolve_model_ids: "omit" in ~/.gsd/defaults.json`);
  6730. }
  6731. // #2395: persist runtime for non-Claude runtimes.
  6732. if (defaults.runtime === undefined || defaults.runtime === null || defaults.runtime === '') {
  6733. defaults.runtime = runtime;
  6734. applied.push(`Set runtime: "${runtime}" in ~/.gsd/defaults.json`);
  6735. }
  6736. if (applied.length > 0) {
  6737. atomicWriteFileSync(defaultsPath, JSON.stringify(defaults, null, 2) + '\n', 'utf8');
  6738. for (const message of applied) console.log(` ${green}✓${reset} ${message}`);
  6739. }
  6740. recordDefaultsProvenance(gsdDir, runtime, defaults, {
  6741. resolve_model_ids: shouldDefaultToOmit,
  6742. runtime: applied.some((m) => m.startsWith('Set runtime:')),
  6743. });
  6744. } catch (e) {
  6745. console.log(` ${yellow}⚠${reset} Could not write ~/.gsd/defaults.json: ${e.message}`);
  6746. } finally {
  6747. if (releaseLock) {
  6748. try {
  6749. releaseLock();
  6750. } catch (releaseError) {
  6751. // A leaked lock blocks the next install, so surface it rather than
  6752. // swallowing; the stale-lock reaper clears it once this pid exits.
  6753. console.log(` ${yellow}⚠${reset} Could not release the ~/.gsd install lock: ${releaseError.message}`);
  6754. }
  6755. }
  6756. }
  6757. }
  6758. function installCodexConfig(targetDir, agentsSrc, sandboxTier = 'codex-agent-sandbox') {
  6759. // ADR-1239 Phase B write-confinement: every Codex config write stays under targetDir.
  6760. const configPath = assertDestWithinConfigHome(targetDir, 'config.toml');
  6761. const agentsTomlDir = assertDestWithinConfigHome(targetDir, 'agents');
  6762. const resolvedTargetRoot = path.resolve(targetDir);
  6763. // Symlink-escape guard (parity with _copyStaged / copyWithPathReplacement): the
  6764. // lexical gate above does not resolve symlinks, so a pre-existing config.toml or
  6765. // agents/ symlink could redirect writes outside targetDir. Reject those.
  6766. // #2393: honor GSD_ALLOW_SYMLINKED_DEST for intentional user-owned symlink layouts.
  6767. const symlinkOptIn = isSymlinkedDestOptIn();
  6768. if (
  6769. hasExistingSymlinkBetween(resolvedTargetRoot, configPath, { allowOptInFollow: symlinkOptIn }) ||
  6770. hasExistingSymlinkBetween(resolvedTargetRoot, path.resolve(agentsTomlDir), { allowOptInFollow: symlinkOptIn })
  6771. ) {
  6772. throw new Error(
  6773. installCodexConfigSymlinkRefusalMessage(targetDir),
  6774. );
  6775. }
  6776. fs.mkdirSync(agentsTomlDir, { recursive: true });
  6777. // #3897 rung 3 (CAUSE B fix) — validateCodexSandboxHolds is deliberately
  6778. // NOT called here. The "no stale holds" invariant is a REPO invariant about
  6779. // the canonical roster in `agents/`, not a property of whatever directory
  6780. // an install happens to read from: a partial or synthetic `agentsSrc` (a
  6781. // test fixture, a `--config-dir` subset) legitimately contains only a few
  6782. // agents, and a held role simply absent from THIS source dir must be
  6783. // inert, not fatal. Throwing here also masked unrelated failures further
  6784. // down this same loop (e.g. the name-injection/path-escape guard on
  6785. // `agentTomlPath` below), since this check ran first and unconditionally.
  6786. // The invariant is still enforced — as a test over the real `agents/`
  6787. // roster (tests/codex-config.test.cjs T24/T25) — just never on this
  6788. // runtime path. See src/codex-agent-toml.cts's `validateCodexSandboxHolds`
  6789. // docblock for the full rationale.
  6790. //
  6791. // #3897 security review F2 (assessed post-F1-fix, verified by execution —
  6792. // not asserted): before F1's fix, the "runtime detector removed" gap here
  6793. // was real — a rename (case a) or a sibling `name:` clobber (case b) could
  6794. // reach this loop and land a held role's `.toml` at `workspace-write` with
  6795. // nothing here to catch it. After F1 (`deriveCodexSandboxMode` now decides
  6796. // over BOTH the filename stem and the resolved frontmatter `name:`, most
  6797. // restrictive wins), both cases were re-run end-to-end through this exact
  6798. // function and the EMITTED ARTIFACT for both is `read-only` — the
  6799. // dangerous condition no longer produces a wrong artifact, it produces the
  6800. // SAFE one. A detector guarding a now-fail-safe condition is not
  6801. // load-bearing, and restoring a throw here would re-break the legitimate
  6802. // partial-source-dir case CAUSE B removed it for (see above). Regression
  6803. // coverage for both cases lives in `tests/codex-config.test.cjs` (F1(a)
  6804. // rename / F1(b) sibling-clobber rows), asserted on the emitted `.toml`'s
  6805. // `sandbox_mode`, not on the derivation's return value.
  6806. const agentEntries = fs.readdirSync(agentsSrc).filter(f => f.startsWith('gsd-') && f.endsWith('.md'));
  6807. const agents = [];
  6808. for (const file of agentEntries) {
  6809. const agentTomlSourcePath = path.join(agentsSrc, file);
  6810. const source = fs.readFileSync(agentTomlSourcePath, 'utf8');
  6811. // #2995 (epic #1671 Phase 6.4): Codex embeds each agent's prompt into a
  6812. // per-agent `.toml`, reading the source .md independently of the inline
  6813. // agent loop — a separate emission path that must strip gsd:section
  6814. // markers too, or a marked agent ships its markers inside the TOML.
  6815. // Found by the exhaustive per-runtime emission sweep in
  6816. // tests/agent-fragments-emission.install.test.cjs, not by call-graph
  6817. // analysis, which is why that guard is behavioral rather than structural.
  6818. const content = prepareCodexAgentConfigContent(source, agentTomlSourcePath, targetDir);
  6819. const { frontmatter } = extractFrontmatterAndBody(content);
  6820. // #3897 security review F1 (blocker, post-merge): this loop used to key
  6821. // the sandbox/hold decision off ONLY the filename stem while the emitted
  6822. // `.toml`'s OUTPUT PATH below is keyed off `name` (frontmatter-derived,
  6823. // attacker-editable) — so a renamed source file, or a sibling file whose
  6824. // `name:` collides with a held role, could make the decided identity and
  6825. // the landed artifact disagree, widening a held role's own file to
  6826. // `workspace-write`. `generateCodexAgentToml` (below) now derives
  6827. // `sandbox_mode` over BOTH the filename stem it is given AND the
  6828. // frontmatter `name:` it resolves internally, taking the most
  6829. // restrictive result — this loop no longer needs to choose one identity
  6830. // for that call; see `deriveCodexSandboxMode`'s doc in
  6831. // `codex-agent-toml.cts` for the resolution.
  6832. const fileStem = file.replace(/\.md$/, '');
  6833. const name = codexAgentTomlName(file, source);
  6834. const description = extractFrontmatterField(frontmatter, 'description') || '';
  6835. agents.push({ name, description: toSingleLine(description) });
  6836. // Pass model overrides from both per-project `.planning/config.json` and
  6837. // `~/.gsd/defaults.json` (project wins on conflict) so Codex TOML files
  6838. // embed the configured model — Codex cannot receive model inline (#2256).
  6839. // Previously only the global file was read, which silently dropped the
  6840. // per-project override the reporter had set for gsd-codebase-mapper.
  6841. // #2517 — also pass the runtime-aware tier resolver so profile tiers can
  6842. // resolve to Codex-native model IDs + reasoning_effort when `runtime: "codex"`
  6843. // is set in defaults.json.
  6844. const modelOverrides = readGsdEffectiveModelOverrides(targetDir);
  6845. // Pass `targetDir` so per-project .planning/config.json wins over global
  6846. // ~/.gsd/defaults.json — without this, the PR's headline claim that
  6847. // setting runtime in the project config reaches the Codex emit path is
  6848. // false (review finding #1).
  6849. const runtimeResolver = readGsdRuntimeProfileResolver(targetDir);
  6850. // #443 — pass unified effort config so model_reasoning_effort in the .toml
  6851. // follows the same config-driven precedence as the Claude .md effort key.
  6852. const effortCfg = readGsdEffectiveEffortConfig(targetDir);
  6853. // Pass `fileStem`; `generateCodexAgentToml` itself additionally resolves
  6854. // and folds in the frontmatter `name:` for the sandbox decision (F1
  6855. // above) — this call site does not need to pass `name` explicitly.
  6856. const tomlContent = generateCodexAgentToml(fileStem, content, modelOverrides, runtimeResolver, effortCfg, sandboxTier);
  6857. // Confine the per-agent write to the agents/ dir itself: a crafted agent
  6858. // `name` containing path separators must not escape agents/ (which would let
  6859. // it clobber config.toml or write elsewhere under the configHome).
  6860. const agentTomlPath = assertDestWithinConfigHome(agentsTomlDir, `${name}.toml`);
  6861. if (hasExistingSymlinkBetween(resolvedTargetRoot, agentTomlPath, { allowOptInFollow: symlinkOptIn })) {
  6862. throw new Error(
  6863. installCodexAgentTomlSymlinkRefusalMessage(agentTomlPath),
  6864. );
  6865. }
  6866. fs.writeFileSync(agentTomlPath, tomlContent);
  6867. }
  6868. const gsdBlock = generateCodexConfigBlock(agents, targetDir);
  6869. mergeCodexConfig(configPath, gsdBlock);
  6870. return agents.length;
  6871. }
  6872. /**
  6873. * Runtime-neutral agent name and instruction file replacement.
  6874. * Used by ALL non-Claude runtime converters to avoid Claude-specific
  6875. * references in workflow prompts, agent definitions, and documentation.
  6876. *
  6877. * Replaces:
  6878. * - Standalone "Claude" (agent name) → "the agent"
  6879. * Preserves: "Claude Code" (product), "Claude Opus/Sonnet/Haiku" (models),
  6880. * "claude-" (prefixes), "CLAUDE.md" (handled separately)
  6881. * - "CLAUDE.md" → runtime-appropriate instruction file
  6882. * - "Do NOT load full AGENTS.md" → removed (harmful for AGENTS.md runtimes)
  6883. *
  6884. * @param {string} content - File content to neutralize
  6885. * @param {string} instructionFile - Runtime's instruction file ('AGENTS.md', 'GEMINI.md', etc.)
  6886. * @returns {string} Content with runtime-neutral references
  6887. */
  6888. function neutralizeAgentReferences(content, instructionFile) {
  6889. let c = content;
  6890. // Replace standalone "Claude" (the agent) but preserve product/model names.
  6891. // Negative lookahead avoids: Claude Code, Claude Opus/Sonnet/Haiku, Claude native, Claude-based
  6892. c = c.replace(/\bClaude(?! Code| Opus| Sonnet| Haiku| native| based|-)\b(?!\.md)/g, 'the agent');
  6893. // Replace CLAUDE.md with runtime-appropriate instruction file
  6894. if (instructionFile) {
  6895. c = c.replace(/CLAUDE\.md/g, instructionFile);
  6896. }
  6897. // Remove instructions that conflict with AGENTS.md-based runtimes
  6898. c = c.replace(/Do NOT load full `AGENTS\.md` files[^\n]*/g, '');
  6899. return c;
  6900. }
  6901. function convertClaudeToOpencodeFrontmatter(content, { isAgent = false, modelOverride = null } = {}) {
  6902. // Replace tool name references in content (applies to all files)
  6903. let convertedContent = filterRuntimeNotesForTarget(content, 'opencode');
  6904. convertedContent = convertedContent.replace(/\bAskUserQuestion\b/g, 'question');
  6905. convertedContent = convertedContent.replace(/\bSlashCommand\b/g, 'skill');
  6906. convertedContent = convertedContent.replace(/\bTodoWrite\b/g, 'todowrite');
  6907. // Replace /gsd-command colon variant with /gsd-command for opencode (flat command structure)
  6908. convertedContent = convertedContent.replace(/\/gsd:/g, '/gsd-');
  6909. // Replace ~/.claude and $HOME/.claude with OpenCode's config location
  6910. convertedContent = convertedContent.replace(/~\/\.claude\b/g, '~/.config/opencode');
  6911. convertedContent = convertedContent.replace(/\$HOME\/\.claude\b/g, '$HOME/.config/opencode');
  6912. // Replace general-purpose subagent type with OpenCode's equivalent "general"
  6913. convertedContent = convertedContent.replace(/subagent_type="general-purpose"/g, 'subagent_type="general"');
  6914. // Runtime-neutral agent name replacement (#766)
  6915. convertedContent = neutralizeAgentReferences(convertedContent, 'AGENTS.md');
  6916. // The frontmatter block, as the one fence owner finds it (none → nothing to convert).
  6917. const { frontmatter, body } = extractFrontmatterAndBody(convertedContent);
  6918. if (frontmatter === null) {
  6919. return convertedContent;
  6920. }
  6921. // Parse frontmatter line by line (simple YAML parsing)
  6922. const lines = frontmatter.split('\n');
  6923. const newLines = [];
  6924. let inAllowedTools = false;
  6925. let inSkippedArray = false;
  6926. let inAgentTools = false;
  6927. let inDisallowedTools = false;
  6928. const allowedTools = [];
  6929. const agentTools = [];
  6930. const agentDisallowed = [];
  6931. for (const line of lines) {
  6932. const trimmed = line.trim();
  6933. // For agents: skip commented-out lines (e.g. hooks blocks)
  6934. if (isAgent && trimmed.startsWith('#')) {
  6935. continue;
  6936. }
  6937. // Detect start of allowed-tools array
  6938. if (trimmed.startsWith('allowed-tools:')) {
  6939. inAllowedTools = true;
  6940. continue;
  6941. }
  6942. // Agents: collect the `tools:` allowlist and `disallowedTools:` denylist (block-list continuation
  6943. // lines) so they can be rendered as `permission:` entries below (mirrors
  6944. // src/runtime-artifact-conversion.cts's convertClaudeToOpencodeFrontmatter, #5338).
  6945. if (isAgent && (inAgentTools || inDisallowedTools)) {
  6946. if (trimmed.startsWith('- ')) {
  6947. const tool = runtimeArtifactConversion._decodeToolScalar(trimmed.substring(2));
  6948. if (tool !== null) (inAgentTools ? agentTools : agentDisallowed).push(tool);
  6949. continue;
  6950. }
  6951. if (trimmed && !trimmed.startsWith('-')) {
  6952. inAgentTools = false;
  6953. inDisallowedTools = false;
  6954. }
  6955. }
  6956. // Detect inline tools: field (comma-separated string)
  6957. if (trimmed.startsWith('tools:')) {
  6958. if (isAgent) {
  6959. const toolsValue = trimmed.substring(6).trim();
  6960. // A comment-only value (`tools: # note`) is not inline content: read the block list instead.
  6961. if (toolsValue && !toolsValue.startsWith('#')) {
  6962. agentTools.push(...runtimeArtifactConversion._splitToolScalars(toolsValue).map(runtimeArtifactConversion._decodeToolScalar).filter((tool) => tool !== null));
  6963. } else {
  6964. inAgentTools = true;
  6965. }
  6966. continue;
  6967. }
  6968. const toolsValue = trimmed.substring(6).trim();
  6969. if (toolsValue) {
  6970. // Parse comma-separated tools
  6971. const tools = toolsValue.split(',').map(t => t.trim()).filter(t => t);
  6972. allowedTools.push(...tools);
  6973. }
  6974. continue;
  6975. }
  6976. if (isAgent && trimmed.startsWith('disallowedTools:')) {
  6977. const value = trimmed.substring(16).trim();
  6978. if (value && !value.startsWith('#')) {
  6979. agentDisallowed.push(...runtimeArtifactConversion._splitToolScalars(value).map(runtimeArtifactConversion._decodeToolScalar).filter((tool) => tool !== null));
  6980. } else {
  6981. inDisallowedTools = true;
  6982. }
  6983. continue;
  6984. }
  6985. // For agents: strip skills:, color:, memory:, maxTurns:, permissionMode:
  6986. if (isAgent && /^(skills|color|memory|maxTurns|permissionMode):/.test(trimmed)) {
  6987. inSkippedArray = true;
  6988. continue;
  6989. }
  6990. // Skip continuation lines of a stripped array/object field
  6991. if (inSkippedArray) {
  6992. if (trimmed.startsWith('- ') || trimmed.startsWith('#') || /^\s/.test(line)) {
  6993. continue;
  6994. }
  6995. inSkippedArray = false;
  6996. }
  6997. // For commands: remove name: field (opencode uses filename for command name)
  6998. // For agents: keep name: (required by OpenCode agents)
  6999. if (!isAgent && trimmed.startsWith('name:')) {
  7000. continue;
  7001. }
  7002. // Strip model: field — OpenCode doesn't support Claude Code model aliases
  7003. // like 'haiku', 'sonnet', 'opus', or 'inherit'. Omitting lets OpenCode use
  7004. // its configured default model. See #1156.
  7005. if (trimmed.startsWith('model:')) {
  7006. continue;
  7007. }
  7008. // Convert color names to hex for opencode (commands only; agents strip color above)
  7009. if (trimmed.startsWith('color:')) {
  7010. const colorValue = trimmed.substring(6).trim().toLowerCase();
  7011. const hexColor = colorNameToHex[colorValue];
  7012. if (hexColor) {
  7013. newLines.push(`color: "${hexColor}"`);
  7014. } else if (colorValue.startsWith('#')) {
  7015. // Validate hex color format (#RGB or #RRGGBB)
  7016. if (/^#[0-9a-f]{3}$|^#[0-9a-f]{6}$/i.test(colorValue)) {
  7017. // Already hex and valid, keep as is
  7018. newLines.push(line);
  7019. }
  7020. // Skip invalid hex colors
  7021. }
  7022. // Skip unknown color names
  7023. continue;
  7024. }
  7025. // Collect allowed-tools items
  7026. if (inAllowedTools) {
  7027. if (trimmed.startsWith('- ')) {
  7028. allowedTools.push(trimmed.substring(2).trim());
  7029. continue;
  7030. } else if (trimmed && !trimmed.startsWith('-')) {
  7031. // End of array, new field started
  7032. inAllowedTools = false;
  7033. }
  7034. }
  7035. // Keep other fields
  7036. if (!inAllowedTools) {
  7037. newLines.push(line);
  7038. }
  7039. }
  7040. // For agents: add required OpenCode agent fields
  7041. // Note: Do NOT add 'model: inherit' — OpenCode does not recognize the 'inherit'
  7042. // keyword and throws ProviderModelNotFoundError. Omitting model: lets OpenCode
  7043. // use its default model for subagents. See #1156.
  7044. if (isAgent) {
  7045. newLines.push('mode: subagent');
  7046. // Embed model override from ~/.gsd/defaults.json so model_overrides is
  7047. // respected on OpenCode (which uses static agent frontmatter, not inline
  7048. // Task() model parameters). See #2256.
  7049. if (modelOverride) {
  7050. newLines.push(`model: ${modelOverride}`);
  7051. }
  7052. newLines.push(...runtimeArtifactConversion._buildOpencodeAgentPermissionBlock(agentTools, agentDisallowed));
  7053. }
  7054. // For commands: add tools object if we had allowed-tools or tools
  7055. if (!isAgent && allowedTools.length > 0) {
  7056. newLines.push('tools:');
  7057. for (const tool of allowedTools) {
  7058. newLines.push(` ${convertToolName(tool)}: true`);
  7059. }
  7060. }
  7061. // Rebuild frontmatter (body already has tool names converted)
  7062. const newFrontmatter = newLines.join('\n').trim();
  7063. return `---\n${newFrontmatter}\n---${body}`;
  7064. }
  7065. // Kilo CLI — same conversion logic as OpenCode, different config paths.
  7066. // DEFECT.GENERATIVE-FIX: this body is mirrored in
  7067. // src/runtime-artifact-conversion.cts's convertClaudeToKiloFrontmatter (used by
  7068. // src/install-engine.cts's install path). Neither copy re-exports the other —
  7069. // mirror any behavior change into both. Guarded by the output-parity test in
  7070. // tests/runtime-converters.test.cjs (#2093).
  7071. function convertClaudeToKiloFrontmatter(content, { isAgent = false, modelOverride = null } = {}) {
  7072. // Replace tool name references in content (applies to all files)
  7073. let convertedContent = filterRuntimeNotesForTarget(content, 'kilo');
  7074. convertedContent = convertedContent.replace(/\bAskUserQuestion\b/g, 'question');
  7075. convertedContent = convertedContent.replace(/\bSlashCommand\b/g, 'skill');
  7076. convertedContent = convertedContent.replace(/\bTodoWrite\b/g, 'todowrite');
  7077. // Replace /gsd-command colon variant with /gsd-command for Kilo (flat command structure)
  7078. convertedContent = convertedContent.replace(/\/gsd:/g, '/gsd-');
  7079. // Replace ~/.claude and $HOME/.claude with Kilo's config location
  7080. convertedContent = convertedContent.replace(/~\/\.claude\b/g, '~/.config/kilo');
  7081. convertedContent = convertedContent.replace(/\$HOME\/\.claude\b/g, '$HOME/.config/kilo');
  7082. convertedContent = convertedContent.replace(/\.\/\.claude\//g, './.kilo/');
  7083. // Normalize both Claude skill directory variants to Kilo's canonical skills dir.
  7084. convertedContent = replaceRelativePathReference(convertedContent, '.claude/skills/', '.kilo/skills/');
  7085. convertedContent = replaceRelativePathReference(convertedContent, '.agents/skills/', '.kilo/skills/');
  7086. convertedContent = replaceRelativePathReference(convertedContent, '.claude/agents/', '.kilo/agents/');
  7087. // Replace general-purpose subagent type with Kilo's equivalent "general"
  7088. convertedContent = convertedContent.replace(/subagent_type="general-purpose"/g, 'subagent_type="general"');
  7089. // Runtime-neutral agent name replacement (#766)
  7090. convertedContent = neutralizeAgentReferences(convertedContent, 'AGENTS.md');
  7091. // The frontmatter block, as the one fence owner finds it (none → nothing to convert).
  7092. const { frontmatter, body } = extractFrontmatterAndBody(convertedContent);
  7093. if (frontmatter === null) {
  7094. return convertedContent;
  7095. }
  7096. // Parse frontmatter line by line (simple YAML parsing)
  7097. const lines = frontmatter.split('\n');
  7098. const newLines = [];
  7099. let inAllowedTools = false;
  7100. let inAgentTools = false;
  7101. let inSkippedArray = false;
  7102. const allowedTools = [];
  7103. const agentTools = [];
  7104. for (const line of lines) {
  7105. const trimmed = line.trim();
  7106. // For agents: skip commented-out lines (e.g. hooks blocks)
  7107. if (isAgent && trimmed.startsWith('#')) {
  7108. continue;
  7109. }
  7110. // Detect start of allowed-tools array
  7111. if (trimmed.startsWith('allowed-tools:')) {
  7112. inAllowedTools = true;
  7113. continue;
  7114. }
  7115. if (isAgent && inAgentTools) {
  7116. if (trimmed.startsWith('- ')) {
  7117. const tool = runtimeArtifactConversion._decodeToolScalar(trimmed.substring(2));
  7118. if (tool !== null) agentTools.push(tool);
  7119. continue;
  7120. }
  7121. if (trimmed && !trimmed.startsWith('-')) {
  7122. inAgentTools = false;
  7123. }
  7124. }
  7125. // Detect inline tools: field (comma-separated string)
  7126. if (trimmed.startsWith('tools:')) {
  7127. if (isAgent) {
  7128. const toolsValue = trimmed.substring(6).trim();
  7129. // A comment-only value (`tools: # note`) is not real inline content —
  7130. // fall through to the block-list scan instead of decoding the
  7131. // comment as a bogus tool name and dropping the list (mirrors
  7132. // src/runtime-artifact-conversion.cts's convertClaudeToKiloFrontmatter, #4032).
  7133. if (toolsValue && !toolsValue.startsWith('#')) {
  7134. const tools = runtimeArtifactConversion._splitToolScalars(toolsValue).map(runtimeArtifactConversion._decodeToolScalar).filter(tool => tool !== null);
  7135. agentTools.push(...tools);
  7136. } else {
  7137. inAgentTools = true;
  7138. }
  7139. continue;
  7140. }
  7141. const toolsValue = trimmed.substring(6).trim();
  7142. if (toolsValue) {
  7143. // Parse comma-separated tools
  7144. const tools = toolsValue.split(',').map(t => t.trim()).filter(t => t);
  7145. allowedTools.push(...tools);
  7146. }
  7147. continue;
  7148. }
  7149. // For agents: strip skills:, color:, memory:, maxTurns:, permissionMode:, disallowedTools:
  7150. if (isAgent && /^(skills|color|memory|maxTurns|permissionMode|disallowedTools):/.test(trimmed)) {
  7151. inSkippedArray = true;
  7152. continue;
  7153. }
  7154. // Skip continuation lines of a stripped array/object field
  7155. if (inSkippedArray) {
  7156. if (trimmed.startsWith('- ') || trimmed.startsWith('#') || /^\s/.test(line)) {
  7157. continue;
  7158. }
  7159. inSkippedArray = false;
  7160. }
  7161. // For commands: remove name: field (Kilo uses filename for command name)
  7162. // For agents: keep name: (required by Kilo agents)
  7163. if (!isAgent && trimmed.startsWith('name:')) {
  7164. continue;
  7165. }
  7166. // Strip model: field — Kilo doesn't support Claude Code model aliases
  7167. // like 'haiku', 'sonnet', 'opus', or 'inherit'. Omitting lets Kilo use
  7168. // its configured default model.
  7169. if (trimmed.startsWith('model:')) {
  7170. continue;
  7171. }
  7172. // Convert color names to hex for Kilo (commands only; agents strip color above)
  7173. if (trimmed.startsWith('color:')) {
  7174. const colorValue = trimmed.substring(6).trim().toLowerCase();
  7175. const hexColor = colorNameToHex[colorValue];
  7176. if (hexColor) {
  7177. newLines.push(`color: "${hexColor}"`);
  7178. } else if (colorValue.startsWith('#')) {
  7179. // Validate hex color format (#RGB or #RRGGBB)
  7180. if (/^#[0-9a-f]{3}$|^#[0-9a-f]{6}$/i.test(colorValue)) {
  7181. // Already hex and valid, keep as is
  7182. newLines.push(line);
  7183. }
  7184. // Skip invalid hex colors
  7185. }
  7186. // Skip unknown color names
  7187. continue;
  7188. }
  7189. // Collect allowed-tools items
  7190. if (inAllowedTools) {
  7191. if (trimmed.startsWith('- ')) {
  7192. const tool = trimmed.substring(2).trim();
  7193. if (isAgent) {
  7194. const decoded = runtimeArtifactConversion._decodeToolScalar(tool);
  7195. if (decoded !== null) agentTools.push(decoded);
  7196. } else {
  7197. allowedTools.push(tool);
  7198. }
  7199. continue;
  7200. } else if (trimmed && !trimmed.startsWith('-')) {
  7201. // End of array, new field started
  7202. inAllowedTools = false;
  7203. }
  7204. }
  7205. // Keep other fields
  7206. if (!inAllowedTools) {
  7207. newLines.push(line);
  7208. }
  7209. }
  7210. // For agents: add required Kilo agent fields
  7211. if (isAgent) {
  7212. newLines.push('mode: subagent');
  7213. // Embed model override from ~/.gsd/defaults.json so model_overrides is
  7214. // respected on Kilo (which uses static agent frontmatter, not inline
  7215. // Task() model parameters) — mirrors convertClaudeToOpencodeFrontmatter's
  7216. // model emission exactly (#2093 UPGRADE 2 / ADR-1239). See #2256.
  7217. if (modelOverride) {
  7218. newLines.push(['model:', modelOverride].join(' '));
  7219. }
  7220. newLines.push(...buildKiloAgentPermissionBlock(agentTools));
  7221. }
  7222. // For commands: add tools object if we had allowed-tools or tools
  7223. if (!isAgent && allowedTools.length > 0) {
  7224. newLines.push('tools:');
  7225. for (const tool of allowedTools) {
  7226. newLines.push(` ${convertToolName(tool)}: true`);
  7227. }
  7228. }
  7229. // Rebuild frontmatter (body already has tool names converted)
  7230. const newFrontmatter = newLines.join('\n').trim();
  7231. return `---\n${newFrontmatter}\n---${body}`;
  7232. }
  7233. // convertClaudeCommandToOpencodeFamilySkill, convertClaudeCommandToOpencodeSkill,
  7234. // convertClaudeCommandToKiloSkill: moved to src/install-engine.cts (ADR-1239 Phase B).
  7235. // #2876 found no install.js internal caller for the latter two (tests import
  7236. // them directly from gsd-core/bin/lib/install-engine.cjs) and retired the
  7237. // destructured bindings above.
  7238. // applyOpencodeFamilyPathPrefix: moved to src/install-engine.cts (ADR-1239 Phase B).
  7239. // #2876 found no install.js internal caller (never had one either — it was
  7240. // never part of this module's export surface) and retired the destructured
  7241. // binding above.
  7242. //
  7243. // copyFlattenedCommands (OpenCode/Kilo flattened command/ writer): moved to
  7244. // src/install-engine.cts as installOpencodeFamilyCommands (ADR-1239 / #2087).
  7245. // OpenCode/Kilo installs now route through installRuntimeArtifacts's
  7246. // combinedFamilyInstall path (installOpencodeFamilyArtifacts) instead of the
  7247. // bespoke inline block that used to call this function.
  7248. /**
  7249. * Count the gsd-* skill dirs in `skillsDir` for "Installed N skills" and the
  7250. * non-empty check that detects a failed install (#5161): the dirs GSD owns,
  7251. * plus any USER_OWNED_SKILL_DIRS entry present (gsd-dev-preferences), which
  7252. * both counted before #5161. A gsd-* dir the prune kept because GSD does not
  7253. * own it is not counted, so it can neither inflate the line nor stand in for
  7254. * an install that wrote nothing.
  7255. */
  7256. function _countOwnedSkillDirs(runtime, configDir, skillsDir) {
  7257. // A verification count fails closed: an unreadable install source must not
  7258. // let a user's gsd-* dir stand in for an install that wrote nothing.
  7259. const owns = createSkillDirOwnership(runtime, configDir, skillsDir, 'gsd-', { includeManifest: false, includeWritten: true });
  7260. return fs.readdirSync(skillsDir, { withFileTypes: true })
  7261. .filter((e) => e.isDirectory() && e.name.startsWith('gsd-') && (owns(e.name) || USER_OWNED_SKILL_DIRS.includes(e.name)))
  7262. .length;
  7263. }
  7264. function listCodexSkillNames(skillsDir, prefix = 'gsd-') {
  7265. if (!fs.existsSync(skillsDir)) return [];
  7266. const entries = fs.readdirSync(skillsDir, { withFileTypes: true });
  7267. return entries
  7268. .filter(entry => entry.isDirectory() && entry.name.startsWith(prefix))
  7269. .filter(entry => fs.existsSync(path.join(skillsDir, entry.name, 'SKILL.md')))
  7270. .map(entry => entry.name)
  7271. .sort();
  7272. }
  7273. /**
  7274. * Generic skills install helper used by all copyCommandsAs*Skills shims.
  7275. *
  7276. * Recursively walks srcDir, applies converter to each .md file (mirroring the
  7277. * old per-function recurse() bodies), applies runtime content rewrites
  7278. * (path + branding), and writes each skill as <prefix>-<stem>/SKILL.md under
  7279. * skillsDir. Replaces the ~50-line recursion bodies in the 9 old functions.
  7280. *
  7281. * @param {string} srcDir source commands directory
  7282. * @param {string} skillsDir destination skills directory
  7283. * @param {string} prefix skill name prefix without trailing dash (e.g. 'gsd')
  7284. * @param {string} pathPrefix trailing-slash path prefix for content rewrites
  7285. * @param {string} runtime canonical runtime ID for rewrite table
  7286. * @param {Function} converter wrapped converter (content, skillName) → string
  7287. */
  7288. /**
  7289. * Copy Claude commands as Windsurf skills — one folder per skill with SKILL.md.
  7290. * Mirrors copyCommandsAsCursorSkills but uses Windsurf converters.
  7291. */
  7292. /**
  7293. * Copy Claude commands as CodeBuddy skills — one folder per skill with SKILL.md.
  7294. * CodeBuddy uses the same tool names as Claude Code, but has its own config directory structure.
  7295. */
  7296. /**
  7297. * Copy Claude commands as Copilot skills — one folder per skill with SKILL.md.
  7298. * Applies CONV-01 (structure), CONV-02 (allowed-tools), CONV-06 (paths), CONV-07 (command names).
  7299. */
  7300. /**
  7301. * Copy Claude commands as Claude skills — one folder per skill with SKILL.md.
  7302. * Claude Code 2.1.88+ uses skills/xxx/SKILL.md instead of commands/gsd/xxx.md.
  7303. * Supports runtime='claude'|'qwen'|'hermes'; branding rewrites are applied via
  7304. * applyRuntimeContentRewritesInPlace inside _copyCommandsAsSkillsViaConverter.
  7305. * @param {string} srcDir - Source commands directory
  7306. * @param {string} skillsDir - Target skills directory
  7307. * @param {string} prefix - Skill name prefix (e.g. 'gsd')
  7308. * @param {string} pathPrefix - Path prefix for file references
  7309. * @param {string} runtime - Target runtime
  7310. * @param {boolean} isGlobal - Whether this is a global install (unused; kept for compat)
  7311. */
  7312. /**
  7313. * Write the Hermes "gsd" category DESCRIPTION.md.
  7314. * Hermes' skill loader reads DESCRIPTION.md at the top of each skill category
  7315. * directory and surfaces it in the system prompt so the model knows when to
  7316. * reach for that category. Per spec in #2841 we collapse all 86 GSD commands
  7317. * under a single "gsd" category to keep system-prompt overhead bounded.
  7318. */
  7319. function writeHermesCategoryDescription(categoryDir) {
  7320. fs.mkdirSync(categoryDir, { recursive: true });
  7321. const body = [
  7322. '---',
  7323. 'name: gsd',
  7324. `version: ${pkg.version}`,
  7325. 'description: GSD Core — Git. Ship. Done. Disciplined planning, execution, and shipping workflows. Use any gsd-* skill in this category to drive a project through new-project → discuss-phase → plan-phase → execute-phase → ship.',
  7326. '---',
  7327. '',
  7328. '# GSD Core',
  7329. '',
  7330. 'GSD is a structured development workflow. Skills in this category cover',
  7331. 'project initialization, phase planning, execution, code review, and shipping.',
  7332. '',
  7333. 'Invoke any `gsd-*` skill in this category to drive the corresponding step.',
  7334. '',
  7335. ].join('\n');
  7336. fs.writeFileSync(path.join(categoryDir, 'DESCRIPTION.md'), body);
  7337. }
  7338. /**
  7339. * Recursively install GSD commands as Antigravity skills.
  7340. * Each command becomes a skill-name/ folder containing SKILL.md.
  7341. * Mirrors copyCommandsAsCopilotSkills but uses Antigravity converters.
  7342. * @param {string} srcDir - Source commands directory
  7343. * @param {string} skillsDir - Target skills directory
  7344. * @param {string} prefix - Skill name prefix (e.g. 'gsd')
  7345. * @param {boolean} isGlobal - Whether this is a global install
  7346. */
  7347. // USER_OWNED_ARTIFACTS, migrateLegacyDevPreferencesToSkill, _snapshotDir,
  7348. // installRuntimeArtifacts, installOpencodeFamilySkills, uninstallRuntimeArtifacts:
  7349. // ALL moved to src/install-engine.cts (ADR-1239 Phase B). Imported from
  7350. // installEngine above. _copyStaged, _removeGsdEntries,
  7351. // _runLegacyInstallMigrations, _runLegacyUninstallCleanup, _restoreDir, and
  7352. // _removeHermesBareStemDirs moved there too but #2876 found no install.js
  7353. // internal caller for any of them and retired their destructured bindings.
  7354. // ---------------------------------------------------------------------------
  7355. // Phase 2 — Layout-driven install/uninstall orchestrators (moved to engine)
  7356. // _applyRuntimeRewrites / _stampNonClaudeRuntimeDefaults remain here for
  7357. // call sites in copyWithPathReplacement (not moved).
  7358. // ---------------------------------------------------------------------------
  7359. const _applyRuntimeRewrites = runtimeArtifactConversion._applyRuntimeRewrites;
  7360. const _stampNonClaudeRuntimeDefaults = runtimeArtifactConversion._stampNonClaudeRuntimeDefaults;
  7361. /**
  7362. * Data-driven dispatch table for copyWithPathReplacement (ADR-1239 Phase B).
  7363. * Keyed by runtime id. Each entry declares ONLY what that runtime does differently.
  7364. * The DEFAULT (no entry, or entry with no md/js key) = identity transform after
  7365. * the uniform steps — covers claude, augment, codebuddy, kimi, etc.
  7366. *
  7367. * Entry shape:
  7368. * mdSkipGenericRewrite?: boolean — skip the ~/.claude/ rewrite block (copilot, antigravity)
  7369. * md?: (content, ctx) => string — per-runtime .md transform
  7370. * mdReattributeAfter?: boolean — re-run processAttribution after md() (copilot, antigravity)
  7371. * mdTomlRenameOnCommand?: boolean — when isCommand, rename dest .md → .toml
  7372. * (unused since the gemini runtime was removed, #1928;
  7373. * kept as generic dispatch infra for a future TOML-command runtime)
  7374. * js?: (content, ctx) => string — per-runtime .cjs/.js transform (absent = plain copyFileSync)
  7375. *
  7376. * ctx = { isCommand, isGlobal, dirName, pathPrefix, entryName, runtime }
  7377. */
  7378. const RUNTIME_CONTENT_DISPATCH = {
  7379. opencode: {
  7380. md: (content) => convertClaudeToOpencodeFrontmatter(content),
  7381. },
  7382. kilo: {
  7383. md: (content) => convertClaudeToKiloFrontmatter(content),
  7384. },
  7385. codex: {
  7386. md: (content) => convertClaudeToCodexMarkdown(content),
  7387. },
  7388. copilot: {
  7389. mdSkipGenericRewrite: true,
  7390. md: (content, ctx) => convertClaudeToCopilotContent(content, ctx.isGlobal),
  7391. mdReattributeAfter: true,
  7392. js: (content, ctx) => convertClaudeToCopilotContent(content, ctx.isGlobal),
  7393. },
  7394. antigravity: {
  7395. mdSkipGenericRewrite: true,
  7396. md: (content, ctx) => convertClaudeToAntigravityContent(content, ctx.isGlobal),
  7397. mdReattributeAfter: true,
  7398. js: (content, ctx) => convertClaudeToAntigravityContent(content, ctx.isGlobal),
  7399. },
  7400. cursor: {
  7401. md: (content) => convertClaudeToCursorMarkdown(content),
  7402. js: (content) => {
  7403. content = content.replace(/gsd:/gi, 'gsd-');
  7404. content = content.replace(/\.claude\/skills\//g, '.cursor/skills/');
  7405. content = content.replace(/CLAUDE\.md/g, '.cursor/rules/');
  7406. content = content.replace(/\bClaude Code\b/g, 'Cursor');
  7407. return content;
  7408. },
  7409. },
  7410. windsurf: {
  7411. md: (content) => convertClaudeToWindsurfMarkdown(content),
  7412. js: (content) => {
  7413. // Workspace skills install to .devin/ (Devin Desktop preferred dir, #1085).
  7414. content = content.replace(/gsd:/gi, 'gsd-');
  7415. content = content.replace(/\.claude\/skills\//g, '.devin/skills/');
  7416. content = content.replace(/CLAUDE\.md/g, '.devin/rules');
  7417. content = content.replace(/\bClaude Code\b/g, 'Windsurf');
  7418. return content;
  7419. },
  7420. },
  7421. trae: {
  7422. // #5715: the Trae converter shields (and resolves) the emitted prefix itself.
  7423. mdShieldsPrefix: true,
  7424. md: (content, ctx) => convertClaudeToTraeMarkdown(content, ctx && ctx.pathPrefix),
  7425. js: (content) => {
  7426. content = content.replace(/\/gsd:([a-z0-9-]+)/g, (_, commandName) => {
  7427. return `/gsd-${commandName}`;
  7428. });
  7429. content = content.replace(/\.claude\/skills\//g, '.trae/skills/');
  7430. // #2658: the full dot-claude-slash-prefixed instruction-file path must
  7431. // be replaced before the bare instruction-filename fallback, or the
  7432. // bare regex only rewrites that filename and leaves the prefix stale
  7433. // in place, producing a malformed doubled-prefix path (see the longer
  7434. // note in convertClaudeToTraeMarkdown above — the instruction filename
  7435. // and either malformed shape are deliberately never spelled out
  7436. // contiguously here either, for the same reason: this file ships
  7437. // verbatim). Both forms target the same concrete file (never a bare
  7438. // directory), matching the `.md` converter (convertClaudeToTraeMarkdown)
  7439. // so js/cjs and md content agree on one canonical path.
  7440. content = content.replace(/\.claude\/CLAUDE\.md/g, '.trae/rules/rules.md');
  7441. content = content.replace(/CLAUDE\.md/g, '.trae/rules/rules.md');
  7442. content = content.replace(/\bClaude Code\b/g, 'Trae');
  7443. return content;
  7444. },
  7445. },
  7446. cline: {
  7447. md: (content) => convertClaudeToCliineMarkdown(content),
  7448. js: (content) => {
  7449. content = content.replace(/\.claude\/skills\//g, '.cline/skills/');
  7450. content = content.replace(/CLAUDE\.md/g, '.clinerules');
  7451. content = content.replace(/\bClaude Code\b/g, 'Cline');
  7452. return content;
  7453. },
  7454. },
  7455. // qwen/hermes: brand VALUES are descriptor-driven (ADR-1239 / #2092) via
  7456. // hostBehaviorsFor(ctx.runtime).brandingRewrites — EXACT regexes/ordering
  7457. // preserved from the prior hardcoded-literal versions (including the
  7458. // qwen-specific `.claude/skills/` -> `.qwen/skills/` pre-rewrite, whose
  7459. // target is derived as `${b['.claude/']}skills/`).
  7460. qwen: {
  7461. md: (content, ctx) => {
  7462. // Guarded (post-review #2092): degrade closed to a no-op if the
  7463. // registry fails to load, instead of throwing on `b['CLAUDE.md']`.
  7464. const b = hostBehaviorsFor(ctx.runtime).brandingRewrites;
  7465. if (b) {
  7466. content = content.replace(/CLAUDE\.md/g, b['CLAUDE.md']);
  7467. // #2284(b): skips <runtime_compatibility> comparison-table content (protected region).
  7468. content = applyClaudeCodeBrandSwap(content, b['Claude Code']);
  7469. content = content.replace(/\.claude\//g, b['.claude/']);
  7470. }
  7471. return content;
  7472. },
  7473. js: (content, ctx) => {
  7474. const b = hostBehaviorsFor(ctx.runtime).brandingRewrites;
  7475. if (b) {
  7476. content = content.replace(/\.claude\/skills\//g, `${b['.claude/']}skills/`);
  7477. content = content.replace(/\.claude\//g, b['.claude/']);
  7478. content = content.replace(/CLAUDE\.md/g, b['CLAUDE.md']);
  7479. content = content.replace(/\bClaude Code\b/g, b['Claude Code']);
  7480. }
  7481. return content;
  7482. },
  7483. },
  7484. pi: {
  7485. // #5569: `Agent(...)` -> `gsd_dispatch(role=..., task=...)`.
  7486. md: (content, ctx) => convertClaudeToPiMarkdown(content, ctx),
  7487. },
  7488. hermes: {
  7489. // #2284: brand-swap alone left the false "Agent tool IS available"
  7490. // assertion + literal `Agent(...)` call syntax installed verbatim — see
  7491. // convertClaudeToHermesMarkdown / projectNamedDispatchToStructuralDelegate
  7492. // above (the Hermes converters section) for the full named-dispatch →
  7493. // `delegate_task` projection, driven by capabilities/hermes/capability.json's
  7494. // hostIntegration.dispatch facts.
  7495. md: (content, ctx) => convertClaudeToHermesMarkdown(content, ctx),
  7496. js: (content, ctx) => {
  7497. const b = hostBehaviorsFor(ctx.runtime).brandingRewrites;
  7498. if (b) {
  7499. content = content.replace(/\.claude\/skills\//g, `${b['.claude/']}skills/`);
  7500. content = content.replace(/\.claude\//g, b['.claude/']);
  7501. content = content.replace(/CLAUDE\.md/g, b['CLAUDE.md']);
  7502. content = content.replace(/\bClaude Code\b/g, b['Claude Code']);
  7503. }
  7504. return content;
  7505. },
  7506. },
  7507. };
  7508. /**
  7509. * Recursively copy directory, replacing paths in .md files
  7510. * Deletes existing destDir first to remove orphaned files from previous versions
  7511. * @param {string} srcDir - Source directory
  7512. * @param {string} destDir - Destination directory
  7513. * @param {string} pathPrefix - Path prefix for file references
  7514. * @param {string} runtime - Target runtime ('claude', 'opencode', 'codex')
  7515. * @param {boolean} isCommand - Whether the source is a command directory
  7516. * @param {boolean} isGlobal - Whether the install is global
  7517. */
  7518. function copyWithPathReplacement(srcDir, destDir, pathPrefix, runtime, isCommand = false, isGlobal = false, confinementRoot) {
  7519. const dirName = getDirName(runtime);
  7520. // ADR-1239 Phase B write-confinement: refuse to wipe/write a destDir that
  7521. // escapes the caller-declared install root. Runs BEFORE the rmSync below so a
  7522. // crafted destDir can never delete or write outside confinementRoot.
  7523. if (confinementRoot === undefined) {
  7524. throw new Error(
  7525. 'copyWithPathReplacement: confinementRoot is required to confine writes to the install root — refusing to write',
  7526. );
  7527. }
  7528. const resolvedConfinementRoot = path.resolve(confinementRoot);
  7529. const resolvedDestDir = assertDestWithinConfigHome(confinementRoot, destDir);
  7530. // #2393: honor GSD_ALLOW_SYMLINKED_DEST for intentional user-owned symlink layouts.
  7531. if (hasExistingSymlinkBetween(resolvedConfinementRoot, resolvedDestDir, { allowOptInFollow: isSymlinkedDestOptIn() })) {
  7532. throw new Error(
  7533. copyWithPathReplacementSymlinkRefusalMessage(destDir, confinementRoot),
  7534. );
  7535. }
  7536. // Use the validated absolute path for all writes below so the gate validates
  7537. // exactly what is written (a relative destDir would otherwise resolve to cwd).
  7538. destDir = resolvedDestDir;
  7539. // Clean install: remove existing destination to prevent orphaned files
  7540. if (fs.existsSync(destDir)) {
  7541. fs.rmSync(destDir, { recursive: true });
  7542. }
  7543. fs.mkdirSync(destDir, { recursive: true });
  7544. const entries = fs.readdirSync(srcDir, { withFileTypes: true });
  7545. for (const entry of entries) {
  7546. const srcPath = path.join(srcDir, entry.name);
  7547. const destPath = path.join(destDir, entry.name);
  7548. // #3333: srcPath was enumerated by readdirSync above, but a filesystem is not
  7549. // transactional — the file it named can vanish between listing and this read
  7550. // (a concurrent process, or another test in this suite writing/cleaning up a
  7551. // fixture inside this same real directory). Treat "gone by the time we get
  7552. // here" as benign and skip it, never a fatal crash of the whole install.
  7553. if (!entry.isDirectory() && !fs.existsSync(srcPath)) {
  7554. continue;
  7555. }
  7556. if (entry.isDirectory()) {
  7557. copyWithPathReplacement(srcPath, destPath, pathPrefix, runtime, isCommand, isGlobal, confinementRoot);
  7558. } else if (entry.name.endsWith('.md')) {
  7559. const dispatch = RUNTIME_CONTENT_DISPATCH[runtime] || {};
  7560. const ctx = { isCommand, isGlobal, dirName, pathPrefix, entryName: entry.name, runtime };
  7561. // Replace ~/.claude/ and $HOME/.claude/ and ./.claude/ with runtime-appropriate paths
  7562. // Skip generic replacement for Copilot/Antigravity — their converters handle all paths
  7563. let content = fs.readFileSync(srcPath, 'utf8');
  7564. // #2930 (epic #1671 Phase 3): strip `<!-- gsd:section -->` markers
  7565. // BEFORE any per-runtime rewrite so a `.claude/` -> `.windsurf/` regex
  7566. // (or any other converter below) never reaches inside a marker
  7567. // attribute and corrupts it. composeWorkflow is a no-op (byte-identical
  7568. // return) for the 88+ workflows and every non-workflow .md that carries
  7569. // no markers, and for a malformed marker it throws loudly naming
  7570. // srcPath — never emit a half-composed workflow.
  7571. //
  7572. // Scoped to gsd-core/workflows/ ONLY (two independent reviewers,
  7573. // chore/2930): copyWithPathReplacement is the emit path for every .md
  7574. // under gsd-core/, skills/, and commands/ (see the three call sites),
  7575. // not just workflows. A doc that merely DOCUMENTS the marker syntax
  7576. // with an unfenced example (docs/reference/workflow-fragments.md is
  7577. // the live instance of this class, though not under the install tree
  7578. // today) would otherwise get silently mis-parsed as a real marker and
  7579. // that line lossily dropped — a file class issue #2930 never scoped
  7580. // to. Path is normalized UNCONDITIONALLY (backslash paths arrive on
  7581. // Linux too — CONTEXT.md path-separator rule) and checked as a
  7582. // path-segment match so the recursive descent (srcPath may be several
  7583. // directory levels below gsd-core/workflows/) is still caught.
  7584. //
  7585. // #3072: the scoping predicate itself now lives in ONE place —
  7586. // shouldCompose (src/mcp-catalog.cts, imported above) — rather than
  7587. // being re-declared inline here. The MCP served catalog calls the
  7588. // SAME function to decide what it composes vs serves verbatim, so this
  7589. // install path and the catalog can never independently drift on what
  7590. // gets composed (ADR-1671:309, DEFECT.GENERATIVE-FIX; the parity gate
  7591. // is tests/mcp-catalog-parity.test.cjs). shouldCompose normalizes with
  7592. // the identical unconditional `.replace(/\\/g, '/')` internally, so
  7593. // this call is behavior-preserving byte-for-behavior with the regex it
  7594. // replaces.
  7595. if (shouldCompose(srcPath)) {
  7596. content = composeWorkflow(content, { sourcePath: srcPath });
  7597. }
  7598. // #5637: the typed-text capture heredoc ends at a terminator the typed text cannot know.
  7599. content = stampInstalledContent(content);
  7600. content = filterRuntimeNotesForTarget(content, runtime);
  7601. if (!dispatch.mdSkipGenericRewrite) {
  7602. // #4377: with a project-relative prefix, mask `${VAR:-default}` shell
  7603. // defaults out of the substitutions below and restore them after. The
  7604. // runtime launcher snippet probes gsd-tools through a chain of those
  7605. // (`${CLAUDE_CONFIG_DIR:-$HOME/.claude}/gsd-core/bin/...`, one per
  7606. // runtime); they are shell word expansions, not markdown @ includes,
  7607. // and a relative value there resolves against the shell's cwd instead
  7608. // of the project. Swapping an include that points at the wrong
  7609. // checkout for a path that points at nothing is not a fix, and the
  7610. // launcher already probes `$(git rev-parse --show-toplevel)/.claude`
  7611. // first, so the multi-worktree case is handled before these defaults
  7612. // are ever reached. The shared helper is the single owner of the
  7613. // balanced masking grammar used by this path and the rewrite engine.
  7614. const rewriteGenericPaths = (body) => {
  7615. content = body;
  7616. // #5715: every generic source form in ONE pass (no rescan of the emitted prefix).
  7617. content = runtimeArtifactConversion._rewriteSpecTreeConfigDirForms(content, pathPrefix, dirName);
  7618. // #3544: restore @-file-reference lines to the tilde form Claude Code
  7619. // actually expands — the SAME correction #3133 already applies to
  7620. // skill/command bodies via _applyRuntimeRewrites's 'claude' case (see
  7621. // restoreClaudeGlobalAtRefTilde's doc comment in
  7622. // runtime-artifact-conversion.cts). This is the gsd-core/ spec-tree
  7623. // emit path, which never had it: every @~/.claude/gsd-core/… include
  7624. // in a global install's workflows/references tree silently resolved
  7625. // to nothing (54 includes across 22 files on a live install).
  7626. if (hostBehaviorsFor(runtime).restoreAtRefTildeInSpecTree) {
  7627. content = runtimeArtifactConversion._restoreClaudeGlobalAtRefTilde(content, pathPrefix);
  7628. }
  7629. return content;
  7630. };
  7631. content = runtimeArtifactConversion._isRelativePathPrefix(pathPrefix)
  7632. ? runtimeArtifactConversion._withShellDefaultsPreserved(content, rewriteGenericPaths)
  7633. : rewriteGenericPaths(content);
  7634. }
  7635. content = processAttribution(content, getCommitAttribution(runtime));
  7636. // #1521: stamp the workflow runtime-resolution block so every non-Claude
  7637. // install resolves its own runtime identity and defaults use_worktrees=false.
  7638. // copyWithPathReplacement is the emit path for gsd-core/workflows/*.md;
  7639. // _applyRuntimeRewrites is NOT invoked here, so this is what makes the fix
  7640. // live in real installs (it is a no-op for files without those lines).
  7641. if (!hostBehaviorsFor(runtime).authorsCanonicalWorkflow) {
  7642. content = _stampNonClaudeRuntimeDefaults(content, runtime);
  7643. }
  7644. // #3683 — normalize /gsd:<cmd> → /gsd-<cmd> in any body passing through
  7645. // copyWithPathReplacement for runtimes that register commands under the
  7646. // hyphen form; normalizeAgentBodyForRuntime self-gates on
  7647. // shouldNormalizeHyphenNamespaceInAgentBody(runtime) and is a no-op for
  7648. // colon-canonical / self-converting runtimes.
  7649. content = normalizeAgentBodyForRuntime(content, runtime, readGsdCommandNames());
  7650. // Apply per-runtime .md converter (if any)
  7651. // #5715: the generic pass above emitted `pathPrefix`; shield it from the converter
  7652. // (a converter that skips the generic pass emitted nothing to shield).
  7653. if (dispatch.md) {
  7654. content = runtimeArtifactConversion._shieldEmittedPrefix(
  7655. content,
  7656. dispatch.mdSkipGenericRewrite || dispatch.mdShieldsPrefix ? undefined : pathPrefix,
  7657. (shielded) => dispatch.md(shielded, ctx),
  7658. );
  7659. }
  7660. // Re-run attribution after converter for runtimes that need it (copilot, antigravity)
  7661. if (dispatch.mdReattributeAfter) content = processAttribution(content, getCommitAttribution(runtime));
  7662. // Rename .md → .toml for command files (unused since gemini removal, #1928)
  7663. const finalPath = (dispatch.mdTomlRenameOnCommand && isCommand) ? destPath.replace(/\.md$/, '.toml') : destPath;
  7664. fs.writeFileSync(finalPath, content);
  7665. } else if (entry.name.endsWith('.cjs') || entry.name.endsWith('.js')) {
  7666. const dispatch = RUNTIME_CONTENT_DISPATCH[runtime] || {};
  7667. if (dispatch.js) {
  7668. const ctx = { isCommand, isGlobal, dirName, pathPrefix, entryName: entry.name, runtime };
  7669. let content = fs.readFileSync(srcPath, 'utf8');
  7670. content = dispatch.js(content, ctx);
  7671. fs.writeFileSync(destPath, content);
  7672. } else {
  7673. fs.copyFileSync(srcPath, destPath);
  7674. }
  7675. } else {
  7676. fs.copyFileSync(srcPath, destPath);
  7677. }
  7678. }
  7679. }
  7680. /**
  7681. * Clean up orphaned hook registrations from settings.json
  7682. */
  7683. function cleanupOrphanedHooks(settings) {
  7684. const orphanedHookPatterns = [
  7685. 'gsd-notify.sh', // Removed in v1.6.x
  7686. 'hooks/statusline.js', // Renamed to gsd-statusline.js in v1.9.0
  7687. 'gsd-intel-index.js', // Removed in v1.9.2
  7688. 'gsd-intel-session.js', // Removed in v1.9.2
  7689. 'gsd-intel-prune.js', // Removed in v1.9.2
  7690. ];
  7691. let cleanedHooks = false;
  7692. // Check all hook event types (Stop, SessionStart, etc.)
  7693. if (settings.hooks) {
  7694. for (const eventType of Object.keys(settings.hooks)) {
  7695. const hookEntries = settings.hooks[eventType];
  7696. if (Array.isArray(hookEntries)) {
  7697. // Filter out entries that contain orphaned hooks
  7698. const filtered = hookEntries.filter(entry => {
  7699. if (entry.hooks && Array.isArray(entry.hooks)) {
  7700. // Check if any hook in this entry matches orphaned patterns
  7701. const hasOrphaned = entry.hooks.some(h =>
  7702. h.command && orphanedHookPatterns.some(pattern => h.command.includes(pattern))
  7703. );
  7704. if (hasOrphaned) {
  7705. cleanedHooks = true;
  7706. return false; // Remove this entry
  7707. }
  7708. }
  7709. return true; // Keep this entry
  7710. });
  7711. settings.hooks[eventType] = filtered;
  7712. }
  7713. }
  7714. }
  7715. if (cleanedHooks) {
  7716. console.log(` ${green}✓${reset} Removed orphaned hook registrations`);
  7717. }
  7718. // Fix #330: Update statusLine if it points to old GSD statusline.js path
  7719. // Only match the specific old GSD path pattern (hooks/statusline.js),
  7720. // not third-party statusline scripts that happen to contain 'statusline.js'
  7721. if (settings.statusLine && settings.statusLine.command &&
  7722. /hooks[\/\\]statusline\.js/.test(settings.statusLine.command)) {
  7723. settings.statusLine.command = settings.statusLine.command.replace(
  7724. /hooks([\/\\])statusline\.js/,
  7725. 'hooks$1gsd-statusline.js'
  7726. );
  7727. console.log(` ${green}✓${reset} Updated statusline path (hooks/statusline.js → hooks/gsd-statusline.js)`);
  7728. }
  7729. return settings;
  7730. }
  7731. /**
  7732. * Validate hook field requirements to prevent silent settings.json rejection.
  7733. *
  7734. * Claude Code validates the entire settings file with a strict Zod schema.
  7735. * If ANY hook has an invalid schema (e.g., type: "agent" missing "prompt"),
  7736. * the ENTIRE settings.json is silently discarded — disabling all plugins,
  7737. * env vars, and other configuration.
  7738. *
  7739. * This defensive check removes invalid hook entries and cleans up empty
  7740. * event arrays to prevent this. It validates:
  7741. * - agent hooks require a "prompt" field
  7742. * - command hooks require a "command" field
  7743. * - entries must have a valid "hooks" array (non-array/missing is removed)
  7744. *
  7745. * @param {object} settings - The settings object (mutated in place)
  7746. * @returns {object} The same settings object
  7747. */
  7748. function validateHookFields(settings) {
  7749. if (!settings.hooks || typeof settings.hooks !== 'object') return settings;
  7750. let fixedHooks = false;
  7751. const emptyKeys = [];
  7752. for (const [eventType, hookEntries] of Object.entries(settings.hooks)) {
  7753. if (!Array.isArray(hookEntries)) continue;
  7754. // Pass 1: validate each entry, building a new array without mutation
  7755. const validated = [];
  7756. for (const entry of hookEntries) {
  7757. // Entries without a hooks sub-array are structurally invalid — remove them
  7758. if (!entry.hooks || !Array.isArray(entry.hooks)) {
  7759. fixedHooks = true;
  7760. continue;
  7761. }
  7762. // Filter invalid hooks within the entry
  7763. const validHooks = entry.hooks.filter(h => {
  7764. if (h.type === 'agent' && !h.prompt) {
  7765. fixedHooks = true;
  7766. return false;
  7767. }
  7768. if (h.type === 'command' && !h.command) {
  7769. fixedHooks = true;
  7770. return false;
  7771. }
  7772. return true;
  7773. });
  7774. // Drop entries whose hooks are now empty
  7775. if (validHooks.length === 0) {
  7776. fixedHooks = true;
  7777. continue;
  7778. }
  7779. // Build a clean copy instead of mutating the original entry
  7780. validated.push({ ...entry, hooks: validHooks });
  7781. }
  7782. settings.hooks[eventType] = validated;
  7783. // Collect empty event arrays for removal (avoid delete during iteration)
  7784. if (validated.length === 0) {
  7785. emptyKeys.push(eventType);
  7786. fixedHooks = true;
  7787. }
  7788. }
  7789. // Pass 2: remove empty event arrays
  7790. for (const key of emptyKeys) {
  7791. delete settings.hooks[key];
  7792. }
  7793. if (fixedHooks) {
  7794. console.log(` ${green}✓${reset} Fixed invalid hook entries (prevents settings.json schema rejection)`);
  7795. }
  7796. return settings;
  7797. }
  7798. /**
  7799. * GSD hook filenames removed during uninstall.
  7800. * Module-level so tests can assert structurally instead of regex-parsing source
  7801. * (retires pending-migration-to-typed-ir on hooks-opt-in.test.cjs, per #455).
  7802. *
  7803. * Derived from _HOOKS_TO_COPY (scripts/build-hooks.js — the SAME single source
  7804. * of truth INSTALLED_HOOK_FILES uses for manifest-tracking above) instead of a
  7805. * separately hand-maintained literal array. The hand-maintained array had
  7806. * silently drifted out of sync with the install-time set — missing
  7807. * gsd-check-update-worker.js, gsd-ensure-canonical-path.js,
  7808. * managed-hooks-registry.cjs, gsd-cursor-pre-tool.js, gsd-cursor-stop.js,
  7809. * gsd-cursor-subagent-start.js, gsd-cursor-subagent-stop.js, and
  7810. * gsd-worktree-path-guard.js — so every one of those files (and the hooks/ dir
  7811. * itself, via the non-empty-dir rmdir guard) was left behind on uninstall for
  7812. * every settings-json-hook runtime. `gsd-check-update.cmd` is added on top: a
  7813. * Windows-only SessionStart shim generated at install time (not copied from
  7814. * hooks/dist/, so it is not in _HOOKS_TO_COPY).
  7815. */
  7816. const GSD_UNINSTALL_HOOKS = [..._HOOKS_TO_COPY, 'gsd-check-update.cmd'];
  7817. /**
  7818. * Whether two paths denote the SAME directory — used to stop a reclaim from
  7819. * deleting the very root the current install just wrote (#3031).
  7820. *
  7821. * A plain `path.resolve` comparison is not enough here, because both roots come
  7822. * from user-controlled env vars (`KIMI_SHARE_DIR`, `KIMI_CODE_HOME`) and two
  7823. * different strings routinely name one directory:
  7824. * - case-insensitive filesystems (macOS, Windows): `~/Kimi` vs `~/kimi`
  7825. * - symlinks / bind mounts: `~/link-to-kimi` vs the real target
  7826. * Getting this wrong is not cosmetic — it is the difference between skipping a
  7827. * reclaim and deleting a live install's own hooks.
  7828. *
  7829. * Strategy, cheapest-first: string equality after `resolve`, then identity by
  7830. * `dev`+`ino` (definitive when both exist and the platform reports them), then
  7831. * `realpath` string equality (resolves symlinks AND canonicalizes case). Any
  7832. * rung answering "same" wins; a path that does not exist cannot be the root we
  7833. * just wrote, so a failed stat simply falls through.
  7834. *
  7835. * @returns {boolean} true only when both paths are proven to be one directory.
  7836. */
  7837. function isSameDirectory(a, b) {
  7838. if (path.resolve(a) === path.resolve(b)) return true;
  7839. try {
  7840. const sa = fs.statSync(a);
  7841. const sb = fs.statSync(b);
  7842. // `ino` is 0 on some Windows filesystems; only trust a positive match.
  7843. if (sa.ino && sb.ino && sa.dev === sb.dev && sa.ino === sb.ino) return true;
  7844. } catch (_) { /* one side missing — fall through to realpath */ }
  7845. try {
  7846. return fs.realpathSync.native(a) === fs.realpathSync.native(b);
  7847. } catch (_) {
  7848. return false;
  7849. }
  7850. }
  7851. /**
  7852. * Remove every GSD-owned artifact from a Kimi hooks root (`~/.kimi` for kimi,
  7853. * `~/.kimi-code` for kimi-code — resolveKimiHooksTomlDir, #2755): the managed
  7854. * `[[hooks]]` block in the native config.toml, the hook scripts, hooks/lib/,
  7855. * and the CommonJS marker at both its current (hooks/) and pre-#2544 (root)
  7856. * locations.
  7857. *
  7858. * This root is Kimi's own native config home — SHARED space that may hold the
  7859. * user's real config.toml, providers and their own scripts — so only exact
  7860. * GSD-owned filenames are removed and directories are pruned only when that
  7861. * removal leaves them empty.
  7862. *
  7863. * TWO callers, deliberately one implementation (#3031). `uninstall()` calls it
  7864. * for the runtime being uninstalled; the opt-in `--reclaim-kimi-legacy` path in
  7865. * `install()` calls it for the LEGACY `~/.kimi` root a pre-#2755 `--kimi-code`
  7866. * install orphaned. Duplicating this sequence for the second caller would be
  7867. * exactly the generative-divergence hazard the repo bans — the reclaim must
  7868. * remove precisely what a real uninstall removes, forever, by construction.
  7869. *
  7870. * @param {string} kimiHooksRoot - Absolute path to the Kimi hooks root.
  7871. * @returns {number} count of removal steps performed (0 when nothing matched).
  7872. */
  7873. function reclaimKimiHooksRoot(kimiHooksRoot) {
  7874. let steps = 0;
  7875. const kimiHooksTomlPath = path.join(kimiHooksRoot, 'config.toml');
  7876. const kimiHooksCleanup = removeKimiHooksToml(kimiHooksTomlPath);
  7877. if (kimiHooksCleanup.changed) {
  7878. steps++;
  7879. console.log(` ${green}✓${reset} Removed GSD hooks from ${kimiHooksTomlPath}`);
  7880. }
  7881. // Kimi's shared hook scripts + CommonJS package.json marker are installed
  7882. // into this SAME ~/.kimi root (installSharedHooksBundle, install()'s
  7883. // kimi-hooks-toml branch) rather than under targetDir — mirror steps "4.
  7884. // Remove GSD hooks" / "5. Remove GSD package.json" below, but scoped to
  7885. // kimiHooksRoot. ~/.kimi is Kimi's own native config home (shared space —
  7886. // may hold the user's real config.toml/providers), so only the exact
  7887. // GSD-owned filenames are removed, and directories are pruned only if left
  7888. // empty by that removal.
  7889. const kimiHooksDir = path.join(kimiHooksRoot, 'hooks');
  7890. if (fs.existsSync(kimiHooksDir)) {
  7891. let kimiHookCount = 0;
  7892. for (const hook of GSD_UNINSTALL_HOOKS) {
  7893. const hookPath = path.join(kimiHooksDir, hook);
  7894. if (fs.existsSync(hookPath)) {
  7895. fs.unlinkSync(hookPath);
  7896. kimiHookCount++;
  7897. }
  7898. }
  7899. if (kimiHookCount > 0) {
  7900. steps++;
  7901. console.log(` ${green}✓${reset} Removed ${kimiHookCount} GSD hooks from ${kimiHooksDir}`);
  7902. }
  7903. const kimiHooksLibDir = path.join(kimiHooksDir, 'lib');
  7904. if (fs.existsSync(kimiHooksLibDir)) {
  7905. let removedKimiLibFiles = 0;
  7906. for (const file of gsdHookLibFiles()) {
  7907. try {
  7908. fs.unlinkSync(path.join(kimiHooksLibDir, file));
  7909. removedKimiLibFiles++;
  7910. } catch (_) { /* best-effort */ }
  7911. }
  7912. try { fs.rmdirSync(kimiHooksLibDir); } catch (_) { /* not empty or other error — leave it */ }
  7913. if (removedKimiLibFiles > 0) {
  7914. steps++;
  7915. console.log(` ${green}✓${reset} Removed ${removedKimiLibFiles} hooks/lib/ helper(s) from ${kimiHooksLibDir}`);
  7916. }
  7917. }
  7918. // #2544: the marker now lives inside kimi's hooks/ dir — remove it
  7919. // before the emptiness check below, or the dir would never prune.
  7920. if (removeCommonJsMarker(kimiHooksDir)) {
  7921. steps++;
  7922. console.log(` ${green}✓${reset} Removed GSD package.json from ${kimiHooksDir}`);
  7923. }
  7924. try {
  7925. if (fs.readdirSync(kimiHooksDir).length === 0) fs.rmdirSync(kimiHooksDir);
  7926. } catch (_) { /* not empty — leave it */ }
  7927. }
  7928. // Retire the pre-#2544 marker at kimi's root (~/.kimi), where the bundle
  7929. // used to write it. Exact content match — a user's own package.json in
  7930. // kimi's native config home is never touched.
  7931. if (removeCommonJsMarker(kimiHooksRoot)) {
  7932. steps++;
  7933. console.log(` ${green}✓${reset} Removed GSD package.json from ${kimiHooksRoot} (pre-#2544 marker)`);
  7934. }
  7935. return steps;
  7936. }
  7937. /**
  7938. * Uninstall GSD from the specified directory for a specific runtime
  7939. * Removes only GSD-specific files/directories, preserves user content
  7940. * @param {boolean} isGlobal - Whether to uninstall from global or local
  7941. * @param {string} runtime - Target runtime ('claude', 'opencode', 'codex', 'copilot')
  7942. */
  7943. function uninstall(isGlobal, runtime = DEFAULT_RUNTIME) {
  7944. // #2093: isKilo dropped — the Kilo permission-cleanup branch below is
  7945. // descriptor-driven (resolveInstallPlan(runtime).finishPermissionWriter),
  7946. // not gated on this flag.
  7947. // #2094: isTrae dropped — unused in this function after the
  7948. // skipSharedHooksInstall fold (was never referenced here besides the
  7949. // destructure). #2095: isKimi likewise dropped — kimi is now a hooks/
  7950. // consumer, so its former `&& !isKimi` uninstall guards were removed.
  7951. // #2096: isAntigravity dropped — unused in this function.
  7952. // #2098: isCodebuddy dropped — unused in this function.
  7953. // #2099: isCopilot dropped — both Copilot side-effect branches below are now
  7954. // gated on resolveInstallPlan(runtime).installSurface === 'copilot-instructions'.
  7955. // #2100: isWindsurf dropped — unused in this function.
  7956. const { isOpencode, isCodex, isCursor, isAugment, isQwen, isHermes, isCline } = runtimeFlags(runtime);
  7957. const dirName = getDirName(runtime);
  7958. // Get the target directory based on runtime and install type. Cline local
  7959. // installs write to the project root (.clinerules/ lives at the root, not in
  7960. // a .cline/ subdir), mirroring the install() path resolution (#787).
  7961. // Descriptor-driven (ADR-1239 / #2090): cline local installs write to the
  7962. // project root (.clinerules/ lives at the root, not in a .cline/ subdir),
  7963. // mirroring the install() path resolution (#787). Folded from a hardcoded
  7964. // `runtime === 'cline'` branch into hostBehaviors.localTargetIsProjectRoot.
  7965. const targetDir = isGlobal
  7966. ? getGlobalConfigDir(runtime, explicitConfigDir)
  7967. : hostBehaviorsFor(runtime).localTargetIsProjectRoot
  7968. ? process.cwd()
  7969. : path.join(process.cwd(), dirName);
  7970. const locationLabel = isGlobal
  7971. ? targetDir.replace(os.homedir(), '~')
  7972. : targetDir.replace(process.cwd(), '.');
  7973. // runtimeLabel is now the single-source getRuntimeLabel lookup (ADR-1239
  7974. // Phase B / #1679) — collapses the prior 15-line assignment chain.
  7975. const runtimeLabel = getRuntimeLabel(runtime);
  7976. console.log(` Uninstalling GSD from ${cyan}${runtimeLabel}${reset} at ${cyan}${locationLabel}${reset}\n`);
  7977. // #786: AGENTS.md lives at the repo root (outside targetDir) for local Copilot
  7978. // installs, so its cleanup must run even when .github (targetDir) was already
  7979. // removed — i.e. BEFORE the "target directory missing" early-return below.
  7980. // #2099: descriptor-driven via resolveInstallPlan(runtime).installSurface ===
  7981. // 'copilot-instructions' (was hardcoded `isCopilot`). Mirrors the install-time
  7982. // gate at the 'copilot-instructions' branch below (~line 10471 equivalent),
  7983. // which writes this same repo-root AGENTS.md only for local ('!isGlobal')
  7984. // installs — 'copilot-instructions' is unique to copilot's descriptor, so
  7985. // this is byte-parity.
  7986. if (resolveInstallPlan(runtime).installSurface === 'copilot-instructions' && !isGlobal) {
  7987. const agentsMdPath = path.join(process.cwd(), 'AGENTS.md');
  7988. if (fs.existsSync(agentsMdPath)) {
  7989. const content = fs.readFileSync(agentsMdPath, 'utf8');
  7990. const cleaned = stripGsdFromCopilotInstructions(content);
  7991. if (cleaned === null) {
  7992. fs.unlinkSync(agentsMdPath);
  7993. console.log(` ${green}✓${reset} Removed AGENTS.md (was GSD-only)`);
  7994. } else if (cleaned !== content) {
  7995. fs.writeFileSync(agentsMdPath, cleaned);
  7996. console.log(` ${green}✓${reset} Cleaned GSD section from AGENTS.md`);
  7997. }
  7998. }
  7999. }
  8000. // Check if target directory exists
  8001. if (!fs.existsSync(targetDir)) {
  8002. console.log(` ${yellow}⚠${reset} Directory does not exist: ${locationLabel}`);
  8003. console.log(` Nothing to uninstall.\n`);
  8004. return;
  8005. }
  8006. let removedCount = 0;
  8007. // #2875 (#1874-F19 anti-inertness, test-matrix C7): recover any user
  8008. // artifact orphaned by a PRIOR uninstall run that died between staging and
  8009. // its own restore/discard, BEFORE this run's own preserve steps (sites 2,
  8010. // 3, 5 below) stage anything new. Uninstall's own gsd-core/ removal and
  8011. // legacy-commands cleanup are exactly as crash-exposed as install's —
  8012. // without this, an orphan from a crashed uninstall is recoverable only if
  8013. // the user later re-installs.
  8014. // #2875 defect fix: DEGRADE, never abort uninstall, when the staging root
  8015. // itself cannot be resolved — skip this recovery pass rather than throw
  8016. // out of uninstall() before it does anything.
  8017. {
  8018. const _uninstallEntryStagingRoot = _tryResolveUserArtifactStagingRoot(targetDir);
  8019. if (_uninstallEntryStagingRoot !== null) {
  8020. recoverOrphanedUserArtifacts(_uninstallEntryStagingRoot, targetDir);
  8021. }
  8022. }
  8023. // Remove profile marker so a clean reinstall defaults to full surface.
  8024. try {
  8025. fs.unlinkSync(path.join(targetDir, '.gsd-profile'));
  8026. removedCount++;
  8027. } catch {}
  8028. // 1. Remove GSD commands/skills (layout-driven)
  8029. // #2870: scope id resolved ONCE here and reused below (was two independent
  8030. // isGlobal-derived re-derivations). Routed through the Install Scope
  8031. // Module (src/install-scope.cts) when the capability registry is
  8032. // available; degrades to the plain id on failure (unknown/non-installable
  8033. // runtime, broken bundle) so this function's scope-id uses — which never
  8034. // depended on registry availability before this migration — keep working
  8035. // exactly as they did pre-migration.
  8036. const _uninstallScopeId = isGlobal ? 'global' : 'local';
  8037. const _resolvedUninstallScope = _resolveScopeSafe(_uninstallScopeId, runtime);
  8038. const scope = _resolvedUninstallScope ? _resolvedUninstallScope.id : _uninstallScopeId;
  8039. // ADR-1239 / #2086: drive uninstall through the public Host-Integration Interface.
  8040. // Fail-open to the engine directly if the composed-registry adapter can't load.
  8041. const _uninstallAdapter = _runtimeAdapter(runtime);
  8042. if (_uninstallAdapter) {
  8043. _uninstallAdapter.uninstall({ configDir: targetDir, scope });
  8044. } else {
  8045. uninstallRuntimeArtifacts(runtime, targetDir, scope);
  8046. }
  8047. removedCount++;
  8048. // ADR-1239 split-home migration: the adapter/plan uninstall targets the new
  8049. // `home` location (e.g. Codex → ~/.agents/skills). A user who installed
  8050. // BEFORE the move and never reinstalled still has managed gsd-* skill dirs at
  8051. // the old configDir-rooted location (~/.codex/skills) — remove those too so
  8052. // uninstall leaves nothing behind. User-owned content is preserved.
  8053. {
  8054. const _movedOldSkillsDir = _resolveMovedSkillsOldDir(runtime, targetDir, scope);
  8055. if (_movedOldSkillsDir) {
  8056. const migrated = cleanupMovedSkillsOldLocation(_movedOldSkillsDir, 'gsd-');
  8057. if (migrated > 0) {
  8058. removedCount++;
  8059. console.log(` ${green}✓${reset} Removed ${migrated} legacy skill dir(s) from ${_movedOldSkillsDir}`);
  8060. }
  8061. }
  8062. }
  8063. // 1a. Non-layout Codex side-effects: agent .toml files, config.toml sections, hooks.json
  8064. if (hostBehaviorsFor(runtime).tomlConfigInstall) {
  8065. const codexAgentsDir = path.join(targetDir, 'agents');
  8066. if (fs.existsSync(codexAgentsDir)) {
  8067. const tomlFiles = fs.readdirSync(codexAgentsDir);
  8068. let tomlCount = 0;
  8069. for (const file of tomlFiles) {
  8070. if (file.startsWith('gsd-') && file.endsWith('.toml')) {
  8071. fs.unlinkSync(path.join(codexAgentsDir, file));
  8072. tomlCount++;
  8073. }
  8074. }
  8075. if (tomlCount > 0) {
  8076. removedCount++;
  8077. console.log(` ${green}✓${reset} Removed ${tomlCount} agent .toml configs`);
  8078. }
  8079. }
  8080. // Codex: clean GSD sections from config.toml
  8081. const codexConfigPath = path.join(targetDir, 'config.toml');
  8082. if (fs.existsSync(codexConfigPath)) {
  8083. const content = fs.readFileSync(codexConfigPath, 'utf8');
  8084. const cleaned = stripGsdFromCodexConfig(content);
  8085. if (cleaned === null) {
  8086. fs.unlinkSync(codexConfigPath);
  8087. removedCount++;
  8088. console.log(` ${green}✓${reset} Removed config.toml (was GSD-only)`);
  8089. } else if (cleaned !== content) {
  8090. fs.writeFileSync(codexConfigPath, cleaned);
  8091. removedCount++;
  8092. console.log(` ${green}✓${reset} Cleaned GSD sections from config.toml`);
  8093. }
  8094. }
  8095. const hooksJsonCleanup = removeCodexHooksJsonSessionStart(targetDir);
  8096. if (hooksJsonCleanup.changed) {
  8097. removedCount++;
  8098. console.log(` ${green}✓${reset} Removed managed Codex SessionStart hook from hooks.json`);
  8099. }
  8100. // #772/#2088: remove every managed Codex extended hook-event registration.
  8101. // Shares CODEX_EXTENDED_HOOK_EVENTS with the install loop — removal set ==
  8102. // registration set, so no managed event is ever orphaned.
  8103. for (const eventName of CODEX_EXTENDED_HOOK_EVENTS) {
  8104. const eventCleanup = removeCodexHooksJsonEvent(targetDir, eventName);
  8105. if (eventCleanup.changed) {
  8106. removedCount++;
  8107. console.log(` ${green}✓${reset} Removed managed Codex ${eventName} hook from hooks.json`);
  8108. }
  8109. }
  8110. // #2586: uninstall's own symmetric half of the orphaned-script cleanup —
  8111. // same GSD-owned + unreferenced gate as the install-time call.
  8112. const uninstallMonitorCleanup = hooksSurface.cleanupOrphanedCodexContextMonitorScript(targetDir);
  8113. for (const deletedPath of uninstallMonitorCleanup.deleted) {
  8114. removedCount++;
  8115. console.log(` ${green}✓${reset} Removed orphaned Codex hook script (${path.basename(deletedPath)})`);
  8116. }
  8117. for (const warning of uninstallMonitorCleanup.warnings) {
  8118. console.warn(` ${yellow}⚠${reset} Could not remove orphaned Codex hook script ${warning.path}: ${warning.reason}`);
  8119. }
  8120. }
  8121. // 1a-kimi. Non-layout Kimi side-effect (#2095 EoS/kimi Upgrade 1): kimi's
  8122. // native config.toml lives outside targetDir entirely (resolveKimiHooksTomlDir
  8123. // resolves ~/.kimi for kimi and ~/.kimi-code for kimi-code (#2755), a sibling
  8124. // of targetDir's ~/.config/agents), so its
  8125. // cleanup can't be driven by anything under targetDir the way every other
  8126. // hook surface above is.
  8127. if (resolveInstallPlan(runtime).hooksSurface === 'kimi-hooks-toml') {
  8128. removedCount += reclaimKimiHooksRoot(resolveKimiHooksTomlDir({ runtime }));
  8129. }
  8130. // 1b. Non-layout Copilot side-effect: copilot-instructions.md cleanup
  8131. // #2099: descriptor-driven via resolveInstallPlan(runtime).installSurface ===
  8132. // 'copilot-instructions' (was hardcoded `isCopilot`), mirroring the same
  8133. // gate used at the install-time 'copilot-instructions' branch.
  8134. if (resolveInstallPlan(runtime).installSurface === 'copilot-instructions') {
  8135. const instructionsPath = path.join(targetDir, 'copilot-instructions.md');
  8136. if (fs.existsSync(instructionsPath)) {
  8137. const content = fs.readFileSync(instructionsPath, 'utf8');
  8138. const cleaned = stripGsdFromCopilotInstructions(content);
  8139. if (cleaned === null) {
  8140. fs.unlinkSync(instructionsPath);
  8141. removedCount++;
  8142. console.log(` ${green}✓${reset} Removed copilot-instructions.md (was GSD-only)`);
  8143. } else if (cleaned !== content) {
  8144. fs.writeFileSync(instructionsPath, cleaned);
  8145. removedCount++;
  8146. console.log(` ${green}✓${reset} Cleaned GSD section from copilot-instructions.md`);
  8147. }
  8148. }
  8149. // #786: remove the GSD-managed Copilot lifecycle hook config and prune the
  8150. // hooks dir if we left it empty.
  8151. const hookPath = path.join(targetDir, 'hooks', GSD_COPILOT_HOOK_FILE);
  8152. if (fs.existsSync(hookPath)) {
  8153. fs.unlinkSync(hookPath);
  8154. removedCount++;
  8155. console.log(` ${green}✓${reset} Removed Copilot lifecycle hook (${GSD_COPILOT_HOOK_FILE})`);
  8156. try {
  8157. const hooksDir = path.join(targetDir, 'hooks');
  8158. if (fs.existsSync(hooksDir) && fs.readdirSync(hooksDir).length === 0) {
  8159. fs.rmdirSync(hooksDir);
  8160. }
  8161. } catch { /* non-fatal: leave a non-empty/locked hooks dir in place */ }
  8162. }
  8163. // Note: AGENTS.md (repo root) is cleaned earlier, before the targetDir
  8164. // existence early-return, since it lives outside targetDir (#786).
  8165. }
  8166. // 1b-cline. Non-layout Cline side-effects (issue #787): remove the
  8167. // directory-form rules + PreToolUse hook, and strip the GSD block from the
  8168. // global cross-tool ~/.agents/AGENTS.md target.
  8169. // Descriptor-driven (ADR-1239 / #2090): folded from `runtime === 'cline'`
  8170. // into hostBehaviors.clineRulesSurface.
  8171. if (hostBehaviorsFor(runtime).clineRulesSurface) {
  8172. const clinerulesDir = path.join(targetDir, '.clinerules');
  8173. for (const rel of ['gsd.md', path.join('hooks', 'PreToolUse')]) {
  8174. const p = path.join(clinerulesDir, rel);
  8175. try {
  8176. if (fs.existsSync(p)) {
  8177. fs.unlinkSync(p);
  8178. removedCount++;
  8179. }
  8180. } catch { /* best-effort */ }
  8181. }
  8182. // Also remove a legacy single-file .clinerules left by pre-#787 installs.
  8183. try {
  8184. if (fs.existsSync(clinerulesDir) && fs.statSync(clinerulesDir).isFile()) {
  8185. fs.unlinkSync(clinerulesDir);
  8186. removedCount++;
  8187. }
  8188. } catch { /* best-effort */ }
  8189. // Prune now-empty GSD-created directories (leave any user-added rule files).
  8190. for (const dir of [path.join(clinerulesDir, 'hooks'), clinerulesDir]) {
  8191. try {
  8192. if (fs.existsSync(dir) && fs.statSync(dir).isDirectory() && fs.readdirSync(dir).length === 0) {
  8193. fs.rmdirSync(dir);
  8194. }
  8195. } catch { /* best-effort */ }
  8196. }
  8197. if (isGlobal) {
  8198. const agentsPath = path.join(os.homedir(), '.agents', 'AGENTS.md');
  8199. try {
  8200. if (fs.existsSync(agentsPath)) {
  8201. const content = fs.readFileSync(agentsPath, 'utf8');
  8202. const cleaned = stripGsdFromAgentsMd(content);
  8203. if (cleaned === null) {
  8204. fs.unlinkSync(agentsPath);
  8205. removedCount++;
  8206. console.log(` ${green}✓${reset} Removed ~/.agents/AGENTS.md (was GSD-only)`);
  8207. } else if (cleaned !== content) {
  8208. fs.writeFileSync(agentsPath, cleaned);
  8209. removedCount++;
  8210. console.log(` ${green}✓${reset} Cleaned GSD section from ~/.agents/AGENTS.md`);
  8211. }
  8212. }
  8213. } catch { /* best-effort */ }
  8214. }
  8215. }
  8216. // 1b-cursor. Descriptor-driven hook-bus cleanup (ADR-1239 / #2089): remove
  8217. // GSD-managed hook entries from hooks.json and clean up the managed hook
  8218. // scripts. Gated by the hostBehaviors.hooksJsonSurface descriptor axis, not a
  8219. // hardcoded `isCursor` branch.
  8220. if (hostBehaviorsFor(runtime).hooksJsonSurface) {
  8221. const hooksJsonCleanup = removeCursorHooksJson(targetDir);
  8222. if (hooksJsonCleanup.changed) {
  8223. removedCount++;
  8224. console.log(` ${green}✓${reset} Removed GSD-managed Cursor hooks from hooks.json`);
  8225. }
  8226. // Remove all GSD-managed hook scripts (sessionStart, postToolUse, preToolUse,
  8227. // stop, subagentStart, subagentStop — AC4a, #2089).
  8228. const hooksDir = path.join(targetDir, 'hooks');
  8229. for (const script of GSD_CURSOR_HOOK_SCRIPTS) {
  8230. const p = path.join(hooksDir, script);
  8231. try {
  8232. if (fs.existsSync(p)) {
  8233. fs.unlinkSync(p);
  8234. removedCount++;
  8235. }
  8236. } catch { /* best-effort */ }
  8237. }
  8238. // Prune hooks/ if empty.
  8239. try {
  8240. if (fs.existsSync(hooksDir) && fs.readdirSync(hooksDir).length === 0) {
  8241. fs.rmdirSync(hooksDir);
  8242. }
  8243. } catch { /* best-effort */ }
  8244. }
  8245. // 1b-windsurf. Descriptor-driven hook-bus cleanup (ADR-1239 / #2100 Stage 2):
  8246. // remove GSD-managed Cascade hook entries from hooks.json and clean up the
  8247. // managed hook scripts. Gated on resolveInstallPlan(runtime).hooksSurface
  8248. // === 'windsurf-hooks-json' (mirrors the kimi-hooks-toml gate above) —
  8249. // NOT the shared hostBehaviors.hooksJsonSurface flag the Cursor block above
  8250. // uses, since that flag drives Cursor's own remove function + script list
  8251. // and is not (and must not be) set for Windsurf.
  8252. if (resolveInstallPlan(runtime).hooksSurface === 'windsurf-hooks-json') {
  8253. const windsurfHooksJsonCleanup = removeWindsurfHooksJson(targetDir);
  8254. if (windsurfHooksJsonCleanup.changed) {
  8255. removedCount++;
  8256. console.log(` ${green}✓${reset} Removed GSD-managed Windsurf hooks from hooks.json`);
  8257. }
  8258. // Remove all GSD-managed hook scripts (pre_write_code, pre_run_command).
  8259. const windsurfHooksDir = path.join(targetDir, 'hooks');
  8260. for (const script of GSD_WINDSURF_HOOK_SCRIPTS) {
  8261. const p = path.join(windsurfHooksDir, script);
  8262. try {
  8263. if (fs.existsSync(p)) {
  8264. fs.unlinkSync(p);
  8265. removedCount++;
  8266. }
  8267. } catch { /* best-effort */ }
  8268. }
  8269. // Prune hooks/ if empty.
  8270. try {
  8271. if (fs.existsSync(windsurfHooksDir) && fs.readdirSync(windsurfHooksDir).length === 0) {
  8272. fs.rmdirSync(windsurfHooksDir);
  8273. }
  8274. } catch { /* best-effort */ }
  8275. }
  8276. // 1c. Claude local: remove flat gsd-*.md commands from commands/ (current layout,
  8277. // #1367 fix). Also remove legacy commands/gsd/ subdirectory from prior installs.
  8278. if (!isGlobal && hostBehaviorsFor(runtime).localInstallStyle === 'legacy-flat') {
  8279. const commandsDir = path.join(targetDir, 'commands');
  8280. // Remove flat gsd-*.md files (current layout after #1367 fix)
  8281. if (fs.existsSync(commandsDir)) {
  8282. let removed = 0;
  8283. for (const f of fs.readdirSync(commandsDir)) {
  8284. if (f.startsWith('gsd-') && f.endsWith('.md')) {
  8285. fs.rmSync(path.join(commandsDir, f), { force: true });
  8286. removed++;
  8287. }
  8288. }
  8289. if (removed > 0) {
  8290. removedCount++;
  8291. console.log(` ${green}✓${reset} Removed ${removed} flat gsd-*.md commands from commands/`);
  8292. }
  8293. }
  8294. // Remove legacy commands/gsd/ subdirectory if it still exists (pre-#1367 layout).
  8295. // Preserve user-owned dev-preferences.md if present (#1423 parity).
  8296. const legacyGsdCommandsDir = path.join(targetDir, 'commands', 'gsd');
  8297. if (fs.existsSync(legacyGsdCommandsDir)) {
  8298. // Stage user-owned dev-preferences.md DURABLY before wiping (#2875 /
  8299. // #1874-F19 "site 7" — found by sweeping bin/install.js for the
  8300. // read-then-wipe-then-write PATTERN, not for preserveUserArtifacts'
  8301. // callers; this uninstall-path block open-coded the same round-trip).
  8302. // #2875 defect fix: DEGRADE, never abort uninstall, when the staging
  8303. // root cannot be resolved — skip this legacy-cleanup block entirely
  8304. // (leave the stale dir in place) rather than wipe without a durable
  8305. // backup for dev-preferences.md.
  8306. const _legacyGsdCommandsStagingRoot = _tryResolveUserArtifactStagingRoot(targetDir);
  8307. if (_legacyGsdCommandsStagingRoot !== null) {
  8308. const stagedDevPrefs = stageUserArtifacts(legacyGsdCommandsDir, ['dev-preferences.md'], _legacyGsdCommandsStagingRoot);
  8309. // Preserve the ORIGINAL truthy-content check exactly: an existing but
  8310. // EMPTY dev-preferences.md was (and still is) silently not restored.
  8311. const savedDevPrefs = stagedDevPrefs.names.includes('dev-preferences.md')
  8312. ? fs.readFileSync(path.join(stagedDevPrefs.filesDir, 'dev-preferences.md'), 'utf8')
  8313. : null;
  8314. fs.rmSync(legacyGsdCommandsDir, { recursive: true });
  8315. removedCount++;
  8316. console.log(` ${green}✓${reset} Removed legacy commands/gsd/`);
  8317. if (savedDevPrefs) {
  8318. try {
  8319. restoreStagedUserArtifacts(legacyGsdCommandsDir, stagedDevPrefs);
  8320. discardStagedUserArtifacts(stagedDevPrefs);
  8321. console.log(` ${green}✓${reset} Preserved commands/gsd/dev-preferences.md`);
  8322. } catch (err) {
  8323. console.error(` ${red}✗${reset} Failed to restore dev-preferences.md: ${err.message}`);
  8324. }
  8325. } else {
  8326. // #2875 defect fix: an existing-but-EMPTY dev-preferences.md was (and
  8327. // still is) never restored — the original truthy-content check is
  8328. // preserved byte-for-byte above — but the staged batch was never
  8329. // discarded either, leaking a <configDir>/.gsd-staging/ record
  8330. // forever and re-materializing the just-deleted file on a future
  8331. // install's orphan-recovery pass. Discard unconditionally when there
  8332. // is nothing to restore.
  8333. discardStagedUserArtifacts(stagedDevPrefs);
  8334. }
  8335. }
  8336. }
  8337. }
  8338. // 1d. Qwen/Hermes: migrate dev-preferences.md from legacy commands/gsd/ location
  8339. // during uninstall. _runLegacyUninstallCleanup (called by uninstallRuntimeArtifacts)
  8340. // removes the directory; we must preserve/restore user artifacts before that path.
  8341. // This block runs AFTER uninstallRuntimeArtifacts, so we check if the directory
  8342. // was already removed and skip if so (idempotent).
  8343. if (hostBehaviorsFor(runtime).legacyCommandsGsdCleanup === true) {
  8344. // dev-preferences may have survived in skills/ as SKILL.md — nothing to do for
  8345. // that case. If a stale commands/gsd/ still exists (e.g. legacy was not removed),
  8346. // attempt migration. In practice _runLegacyUninstallCleanup removes it first,
  8347. // so this is a best-effort guard.
  8348. const legacyDir = path.join(targetDir, 'commands', 'gsd');
  8349. if (fs.existsSync(legacyDir)) {
  8350. // #2875 (#1874-F19): staged DURABLY to disk before the wipe below,
  8351. // instead of an in-memory Map only — a crash between the wipe and the
  8352. // restore-on-failure branch below now survives via
  8353. // recoverOrphanedUserArtifacts on the next run.
  8354. // #2875 defect fix: DEGRADE, never abort uninstall, when the staging
  8355. // root cannot be resolved — skip this legacy-migration block entirely
  8356. // (leave the stale dir in place) rather than wipe without a durable
  8357. // backup.
  8358. const stagingRoot = _tryResolveUserArtifactStagingRoot(targetDir);
  8359. if (stagingRoot !== null) {
  8360. const stagedLegacyArtifacts = stageUserArtifacts(legacyDir, ['dev-preferences.md'], stagingRoot);
  8361. fs.rmSync(legacyDir, { recursive: true });
  8362. removedCount++;
  8363. console.log(` ${green}✓${reset} Removed legacy commands/gsd/`);
  8364. const _uninstallScope = scope;
  8365. // migrateLegacyDevPreferencesToSkill's Map<string,string> contract is
  8366. // unchanged — read the staged content back from disk (not an in-memory
  8367. // value held across the wipe above).
  8368. //
  8369. // #2875 defect fix (readFileSync following a staged symlink) — matches
  8370. // install-engine.cts's _runLegacyInstallMigrations call site 1 exactly:
  8371. // readFileSync ALWAYS follows a symlink, so a staged artifact that is
  8372. // itself a symlink (user-artifact-staging.cts's "Symlink safety": a
  8373. // symlinked user artifact is recreated AS a symlink in the staging
  8374. // tree, never copied by content) would have its REFERENT's bytes read
  8375. // here and land in SKILL.md. Excluded from migration below and
  8376. // restored to its original location unchanged instead.
  8377. // #2875 defect fix (regression closed — was previously unguarded and
  8378. // BRICKED uninstall, the very command that should recover from this):
  8379. // legacyDir was already removed above, so stagedLegacyArtifacts is
  8380. // the only surviving copy. migrateLegacyDevPreferencesToSkill
  8381. // correctly THROWS when it finds a planted/dangling symlink at the
  8382. // skill-file leaf (security fix); a raw `fs.lstatSync` in the loop
  8383. // below can also throw on a TOCTOU-vanished staged file. Either one,
  8384. // left unguarded, propagated straight out of uninstall, aborting it
  8385. // WITHOUT ever reaching the restore-or-discard branch below — the
  8386. // staged batch was orphaned on disk and every retry hit the same
  8387. // throw again. Degrade identically to every other #2875 staging step
  8388. // in this function: catch, warn once, and treat the batch as
  8389. // unmigrated so the restore branch below always fires.
  8390. let _legacyMigrated = false;
  8391. let migratableLegacyNames = [];
  8392. try {
  8393. const savedLegacyArtifacts = new Map();
  8394. for (const name of stagedLegacyArtifacts.names) {
  8395. const stagedPath = path.join(stagedLegacyArtifacts.filesDir, name);
  8396. if (fs.lstatSync(stagedPath).isSymbolicLink()) continue;
  8397. savedLegacyArtifacts.set(name, fs.readFileSync(stagedPath, 'utf8'));
  8398. migratableLegacyNames.push(name);
  8399. }
  8400. _legacyMigrated = migrateLegacyDevPreferencesToSkill(targetDir, savedLegacyArtifacts, runtime, _uninstallScope);
  8401. } catch (err) {
  8402. console.warn(` ${yellow}!${reset} dev-preferences.md migration skipped (${err.message}) — restoring the legacy copy instead.`);
  8403. _legacyMigrated = false;
  8404. migratableLegacyNames = [];
  8405. }
  8406. if (_legacyMigrated && migratableLegacyNames.length === stagedLegacyArtifacts.names.length) {
  8407. // Compute the actual path written so the log line is accurate per-runtime
  8408. const _layout = resolveRuntimeArtifactLayout(runtime, targetDir, _uninstallScope);
  8409. const _sk = _layout.kinds.find((k) => k.kind === 'skills');
  8410. const _stem = _sk && _sk.prefix === '' ? 'dev-preferences' : 'gsd-dev-preferences';
  8411. const _skillRelPath = _sk ? `${_sk.destSubpath}/${_stem}/SKILL.md` : 'skills/gsd-dev-preferences/SKILL.md';
  8412. console.log(` ${green}✓${reset} Migrated dev-preferences.md → ${_skillRelPath} (#2973)`);
  8413. discardStagedUserArtifacts(stagedLegacyArtifacts);
  8414. } else {
  8415. // Migration failed, already exists, or a symlinked name was excluded
  8416. // above — restore the WHOLE batch to the legacy location so no user
  8417. // content is silently lost.
  8418. restoreStagedUserArtifacts(legacyDir, stagedLegacyArtifacts);
  8419. discardStagedUserArtifacts(stagedLegacyArtifacts);
  8420. }
  8421. }
  8422. }
  8423. }
  8424. // 2. Remove gsd-core directory
  8425. const gsdDir = path.join(targetDir, 'gsd-core');
  8426. if (fs.existsSync(gsdDir)) {
  8427. // Stage user-generated files DURABLY to disk before wipe (#1423; #2875 /
  8428. // #1874-F19 "site 5" — this block open-coded its own preserve/restore
  8429. // instead of calling preserveUserArtifacts, which is why it was missed
  8430. // by the original symbol-search measurement).
  8431. // #2875 defect fix: this IS the core uninstall step (removing gsd-core/)
  8432. // — unlike the optional legacy-cleanup blocks above, uninstall must
  8433. // still be able to proceed and actually remove gsd-core/ even when the
  8434. // staging root cannot be resolved. Degrade by skipping ONLY the
  8435. // USER-PROFILE.md preserve/restore wrapper (warn), never the removal
  8436. // itself.
  8437. const _gsdDirStagingRoot = _tryResolveUserArtifactStagingRoot(targetDir);
  8438. if (_gsdDirStagingRoot === null) {
  8439. console.warn(` ${yellow}!${reset} Skipping gsd-core/USER-PROFILE.md preservation (staging unavailable) — it will be lost if present.`);
  8440. fs.rmSync(gsdDir, { recursive: true });
  8441. removedCount++;
  8442. console.log(` ${green}✓${reset} Removed gsd-core/`);
  8443. } else {
  8444. const stagedProfile = stageUserArtifacts(gsdDir, USER_OWNED_ARTIFACTS, _gsdDirStagingRoot);
  8445. // Preserve the ORIGINAL truthy-content check exactly: an existing but
  8446. // EMPTY USER-PROFILE.md was (and still is) silently not restored —
  8447. // matching prior behavior byte-for-byte rather than widening scope.
  8448. const preservedProfile = stagedProfile.names.includes('USER-PROFILE.md')
  8449. ? fs.readFileSync(path.join(stagedProfile.filesDir, 'USER-PROFILE.md'), 'utf8')
  8450. : null;
  8451. fs.rmSync(gsdDir, { recursive: true });
  8452. removedCount++;
  8453. console.log(` ${green}✓${reset} Removed gsd-core/`);
  8454. // Restore user-generated files
  8455. if (preservedProfile) {
  8456. try {
  8457. restoreStagedUserArtifacts(gsdDir, stagedProfile);
  8458. discardStagedUserArtifacts(stagedProfile);
  8459. console.log(` ${green}✓${reset} Preserved gsd-core/USER-PROFILE.md`);
  8460. } catch (err) {
  8461. console.error(` ${red}✗${reset} Failed to restore USER-PROFILE.md: ${err.message}`);
  8462. }
  8463. } else {
  8464. // #2875 defect fix: same empty-file orphan leak as the legacy
  8465. // commands/gsd/ site above — discard the staging batch regardless of
  8466. // whether the staged content was truthy.
  8467. discardStagedUserArtifacts(stagedProfile);
  8468. }
  8469. }
  8470. }
  8471. // 3. Remove GSD agents (gsd-*.md files only)
  8472. const agentsDir = path.join(targetDir, 'agents');
  8473. if (fs.existsSync(agentsDir)) {
  8474. const files = fs.readdirSync(agentsDir);
  8475. let agentCount = 0;
  8476. for (const file of files) {
  8477. if (file.startsWith('gsd-') && file.endsWith('.md')) {
  8478. fs.unlinkSync(path.join(agentsDir, file));
  8479. agentCount++;
  8480. }
  8481. }
  8482. if (agentCount > 0) {
  8483. removedCount++;
  8484. console.log(` ${green}✓${reset} Removed ${agentCount} GSD agents`);
  8485. }
  8486. }
  8487. // 4. Remove GSD hooks
  8488. // #3023: mirror the install site's descriptor-driven bundle dir name.
  8489. const hooksDir = path.join(targetDir, resolveSharedHooksDirName(runtime));
  8490. if (fs.existsSync(hooksDir)) {
  8491. let hookCount = 0;
  8492. for (const hook of GSD_UNINSTALL_HOOKS) {
  8493. const hookPath = path.join(hooksDir, hook);
  8494. if (fs.existsSync(hookPath)) {
  8495. fs.unlinkSync(hookPath);
  8496. hookCount++;
  8497. }
  8498. }
  8499. if (hookCount > 0) {
  8500. removedCount++;
  8501. console.log(` ${green}✓${reset} Removed ${hookCount} GSD hooks`);
  8502. }
  8503. // Remove only the GSD-managed files from hooks/lib/ (git-cmd.js + gsd-graphify-rebuild.sh).
  8504. // hooks/lib/ lives inside the user's runtime hooks directory (shared space) and
  8505. // may contain user-owned custom helpers. We must not recursively delete the dir.
  8506. const hooksLibDir = path.join(hooksDir, 'lib');
  8507. if (fs.existsSync(hooksLibDir)) {
  8508. let removedLibFiles = 0;
  8509. for (const file of gsdHookLibFiles()) {
  8510. const filePath = path.join(hooksLibDir, file);
  8511. try {
  8512. fs.unlinkSync(filePath);
  8513. removedLibFiles++;
  8514. } catch (_) {
  8515. // Ignore missing files (best effort, non-fatal)
  8516. }
  8517. }
  8518. // Only remove the directory itself if it is now empty (preserve any user files)
  8519. try {
  8520. fs.rmdirSync(hooksLibDir);
  8521. } catch (_) {
  8522. // Directory not empty or other error — leave it alone
  8523. }
  8524. if (removedLibFiles > 0) {
  8525. removedCount++;
  8526. console.log(` ${green}✓${reset} Removed ${removedLibFiles} hooks/lib/ helper(s)`);
  8527. }
  8528. }
  8529. // Retire the CommonJS marker staged into hooks/. hooks/ is shared space and
  8530. // is deliberately never rmdir'd here, so the marker must be removed
  8531. // explicitly or it would be left behind. Removed ONLY when it still carries
  8532. // GSD's exact content — a user-authored package.json is never deleted.
  8533. //
  8534. // #2717 reaches the runtimes that stage .js hooks via dedicated paths
  8535. // (cursor/windsurf/codex); #2544 reaches the shared-bundle runtimes, whose
  8536. // marker this PR moves out of the config root and into hooks/. Both land in
  8537. // the same directory, so one guarded call covers both.
  8538. try {
  8539. if (hooksSurface.removeCommonJsMarkerIfGsdOwned(hooksDir)) {
  8540. removedCount++;
  8541. console.log(` ${green}✓${reset} Removed GSD hooks/package.json (CommonJS marker)`);
  8542. }
  8543. } catch { /* best-effort */ }
  8544. // Once GSD's hooks, helpers and marker are gone, an empty hooks dir is GSD's own leftover (#5335).
  8545. // rmdir fails on a non-empty dir, so a user's own hook scripts keep it in place.
  8546. try { fs.rmdirSync(hooksDir); } catch { /* not empty or absent */ }
  8547. }
  8548. // 4z. Remove the native plugin adapter (#1914, extended to Kilo by #2093).
  8549. // Descriptor-driven via hostBehaviors.nativePlugin — covers every runtime
  8550. // that declares the block (OpenCode, Kilo, ...), not just OpenCode. Only
  8551. // GSD's own plugin file is removed; the plugins/ dir is pruned only if it
  8552. // becomes empty, preserving any user-authored plugins for that host.
  8553. const _np = hostBehaviorsFor(runtime).nativePlugin;
  8554. if (_np) {
  8555. const pluginsDir = path.join(targetDir, _np.dir);
  8556. const pluginPath = path.join(pluginsDir, _np.file);
  8557. // Tracks whether GSD actually removed anything from pluginsDir. The rmdir
  8558. // below is gated on it: pruning a directory GSD never wrote to is the same
  8559. // "don't touch territory GSD didn't fill" violation this issue is about,
  8560. // just inverted — a user-created but empty plugin/ or extensions/ dir is
  8561. // theirs, and an uninstall that never removed anything has no business
  8562. // deleting it.
  8563. let removedFromPluginsDir = false;
  8564. if (fs.existsSync(pluginPath)) {
  8565. try {
  8566. fs.unlinkSync(pluginPath);
  8567. removedCount++;
  8568. removedFromPluginsDir = true;
  8569. console.log(` ${green}✓${reset} Removed native plugin adapter (${runtime})`);
  8570. } catch (_) { /* best-effort */ }
  8571. }
  8572. // #2544: the adapter's CommonJS marker sits beside it. Cleaned up OUTSIDE
  8573. // the adapter-exists guard above — a partial install (or a hand-deleted
  8574. // adapter) would otherwise strand GSD's marker forever and keep the dir
  8575. // from ever pruning. Conditioned on the adapter being GONE, though: if the
  8576. // unlink above failed, pulling the marker out from under a still-present
  8577. // CommonJS adapter would leave it unloadable. The exact content match
  8578. // still leaves any user-authored package.json in place.
  8579. // The terminal-client plugin directory (OpenCode 2.x statusline): GSD's file, then its now-empty directory.
  8580. const _cliU = hostBehaviorsFor(runtime).nativeCliPlugin;
  8581. if (_cliU) {
  8582. const cliFile = path.join(targetDir, _cliU.dir, _cliU.file);
  8583. if (fs.existsSync(cliFile)) {
  8584. try {
  8585. fs.unlinkSync(cliFile);
  8586. removedCount++;
  8587. removedFromPluginsDir = true;
  8588. console.log(` ${green}✓${reset} Removed terminal-client plugin (${runtime})`);
  8589. } catch (_) { /* best-effort */ }
  8590. }
  8591. try { fs.rmdirSync(path.join(targetDir, _cliU.dir)); } catch (_) { /* not empty or absent */ }
  8592. }
  8593. if (!fs.existsSync(pluginPath) && removeCommonJsMarker(pluginsDir)) {
  8594. removedCount++;
  8595. removedFromPluginsDir = true;
  8596. console.log(` ${green}✓${reset} Removed GSD package.json from ${_np.dir}/`);
  8597. }
  8598. // Only prune a dir GSD emptied. Pre-fix this rmdir sat inside the
  8599. // adapter-exists guard, so it could never fire on a dir GSD had not
  8600. // written to; hoisting it out to catch the marker-only case must not
  8601. // silently widen it to "any empty plugin dir".
  8602. if (removedFromPluginsDir) {
  8603. try { fs.rmdirSync(pluginsDir); } catch (_) { /* not empty — user plugins present */ }
  8604. }
  8605. }
  8606. // 4a. Remove scripts/changeset/ and scripts/lib/ (#935)
  8607. // GSD-managed files only: enumerate the exact set the installer writes.
  8608. // Any file NOT in this set is user-owned and must survive uninstall.
  8609. // After removing GSD files, attempt to rmdir — if the directory is still
  8610. // non-empty (user has custom helpers) it stays; otherwise it goes cleanly.
  8611. // GSD_CHANGESET_FILES / GSD_SCRIPTS_LIB_FILES are module-scoped (#3184) so
  8612. // tests can assert their parity against the real directory contents.
  8613. const changesetUninstallDir = path.join(targetDir, 'scripts', 'changeset');
  8614. if (fs.existsSync(changesetUninstallDir)) {
  8615. let removedChangeset = 0;
  8616. for (const file of GSD_CHANGESET_FILES) {
  8617. const fp = path.join(changesetUninstallDir, file);
  8618. try { fs.unlinkSync(fp); removedChangeset++; } catch (_) { /* best-effort */ }
  8619. }
  8620. // Remove directory if empty after our cleanup
  8621. try { fs.rmdirSync(changesetUninstallDir); } catch (_) { /* Not empty — user content present */ }
  8622. if (removedChangeset > 0) {
  8623. removedCount++;
  8624. console.log(` ${green}✓${reset} Removed scripts/changeset/ GSD files`);
  8625. }
  8626. }
  8627. const scriptsLibUninstallDir = path.join(targetDir, 'scripts', 'lib');
  8628. if (fs.existsSync(scriptsLibUninstallDir)) {
  8629. let removedScriptsLib = 0;
  8630. for (const file of GSD_SCRIPTS_LIB_FILES) {
  8631. const fp = path.join(scriptsLibUninstallDir, file);
  8632. try { fs.unlinkSync(fp); removedScriptsLib++; } catch (_) { /* best-effort */ }
  8633. }
  8634. // Remove directory if empty after our cleanup
  8635. try { fs.rmdirSync(scriptsLibUninstallDir); } catch (_) { /* Not empty — user content present */ }
  8636. if (removedScriptsLib > 0) {
  8637. removedCount++;
  8638. console.log(` ${green}✓${reset} Removed scripts/lib/ GSD files`);
  8639. }
  8640. }
  8641. // Remove scripts/fix-slash-commands.cjs (#1223) — must come before the scripts/ rmdir
  8642. const fixSlashUninstallPath = path.join(targetDir, 'scripts', 'fix-slash-commands.cjs');
  8643. try { fs.unlinkSync(fixSlashUninstallPath); } catch (_) { /* best-effort */ }
  8644. // Remove the capability registry generator scripts (#1920) — before the scripts/ rmdir
  8645. for (const gen of ['gen-capability-registry.cjs', 'gen-loop-host-contract.cjs']) {
  8646. try { fs.unlinkSync(path.join(targetDir, 'scripts', gen)); } catch (_) { /* best-effort */ }
  8647. }
  8648. // If scripts/ dir is now empty, remove it too
  8649. const scriptsUninstallDir = path.join(targetDir, 'scripts');
  8650. if (fs.existsSync(scriptsUninstallDir)) {
  8651. try { fs.rmdirSync(scriptsUninstallDir); } catch (_) { /* Not empty — leave it */ }
  8652. }
  8653. // 5. Remove GSD package.json (CommonJS mode marker)
  8654. // Since #2544 the marker is staged into hooks/ (and the nativePlugin dir,
  8655. // handled at 4z above) rather than at targetDir. The targetDir removal is
  8656. // retained to retire the marker written by pre-#2544 installs — same exact
  8657. // content match as before, so a user-authored package.json is still never
  8658. // touched.
  8659. if (removeCommonJsMarker(targetDir)) {
  8660. removedCount++;
  8661. console.log(` ${green}✓${reset} Removed GSD package.json (pre-#2544 config-root marker)`);
  8662. }
  8663. // 6. Clean up settings.json (remove GSD hooks and statusline)
  8664. const settingsPath = path.join(targetDir, 'settings.json');
  8665. if (fs.existsSync(settingsPath)) {
  8666. let settings = readSettings(settingsPath);
  8667. if (settings === null) {
  8668. console.log(` ${yellow}i${reset} Skipping settings.json cleanup — file could not be parsed`);
  8669. settings = {}; // prevent downstream crashes, but don't write back
  8670. }
  8671. let settingsModified = false;
  8672. // Remove GSD statusline if it references our hook
  8673. if (settings.statusLine && settings.statusLine.command &&
  8674. settings.statusLine.command.includes('gsd-statusline')) {
  8675. delete settings.statusLine;
  8676. settingsModified = true;
  8677. console.log(` ${green}✓${reset} Removed GSD statusline from settings`);
  8678. }
  8679. // Remove GSD hooks from settings — per-hook granularity to preserve
  8680. // user hooks that share an entry with a GSD hook (#1755 followup).
  8681. // Includes the 3 Qwen-only events added in #788 (SubagentStop, Stop,
  8682. // PreCompact, also registered for Claude in #770), the 3 Antigravity-only
  8683. // events added in #776 (BeforeAgent, AfterAgent, BeforeModel), and the
  8684. // Claude-only FileChanged event added in #770 — safe to iterate for all
  8685. // runtimes; installs that don't register these events simply find no
  8686. // entries and skip.
  8687. for (const eventName of ['SessionStart', 'PostToolUse', 'AfterTool', 'PreToolUse', 'BeforeTool', 'SubagentStop', 'Stop', 'PreCompact', 'BeforeAgent', 'AfterAgent', 'BeforeModel', 'FileChanged']) {
  8688. if (settings.hooks && settings.hooks[eventName]) {
  8689. const before = JSON.stringify(settings.hooks[eventName]);
  8690. settings.hooks[eventName] = settings.hooks[eventName]
  8691. .map(entry => {
  8692. if (!entry || typeof entry !== 'object' || !Array.isArray(entry.hooks)) return entry;
  8693. // Filter out individual GSD hooks, keep user hooks
  8694. entry.hooks = entry.hooks.filter((h) => {
  8695. if (!h || typeof h.command !== 'string') return true;
  8696. return !isManagedHookCommand(h.command, {
  8697. surface: 'settings-json',
  8698. });
  8699. });
  8700. return entry.hooks.length > 0 ? entry : null;
  8701. })
  8702. .filter(Boolean);
  8703. if (JSON.stringify(settings.hooks[eventName]) !== before) {
  8704. settingsModified = true;
  8705. }
  8706. if (settings.hooks[eventName].length === 0) {
  8707. delete settings.hooks[eventName];
  8708. }
  8709. }
  8710. }
  8711. if (settingsModified) {
  8712. console.log(` ${green}✓${reset} Removed GSD hooks from settings`);
  8713. }
  8714. // Clean up empty hooks object
  8715. if (settings.hooks && Object.keys(settings.hooks).length === 0) {
  8716. delete settings.hooks;
  8717. }
  8718. // #768 — Remove GSD-owned Claude permissions from settings.json.
  8719. // Applies only to Claude uninstalls. Filter only the exact GSD-owned entries
  8720. // to preserve any user-added allow/deny entries.
  8721. // Uses a local flag to avoid the shared `settingsModified` producing a false
  8722. // "Removed GSD permissions" message when only hooks/statusline changed.
  8723. if (hostBehaviorsFor(runtime).permissionsSchema === 'claude' && settings.permissions) {
  8724. let permissionsModified = false;
  8725. if (Array.isArray(settings.permissions.allow)) {
  8726. const before = settings.permissions.allow.length;
  8727. // #2278 — filter against the union of the current allow-rule forms
  8728. // AND the retired legacy forms, so uninstall still cleans up
  8729. // pre-fix installs that still carry the stale `Write(...)` entries.
  8730. settings.permissions.allow = settings.permissions.allow.filter(
  8731. (e) => !GSD_CLAUDE_ALLOW_PERMISSIONS.includes(e) && !GSD_CLAUDE_LEGACY_ALLOW_PERMISSIONS.includes(e)
  8732. );
  8733. if (settings.permissions.allow.length !== before) {
  8734. permissionsModified = true;
  8735. // #4221: an array this filter emptied was GSD-only \u2014 remove the
  8736. // key rather than leave an empty array behind (Antigravity symmetry).
  8737. if (settings.permissions.allow.length === 0) {
  8738. delete settings.permissions.allow;
  8739. }
  8740. }
  8741. }
  8742. if (Array.isArray(settings.permissions.deny)) {
  8743. const before = settings.permissions.deny.length;
  8744. // #4221: the deny rules are retired, so this is a legacy-only filter.
  8745. settings.permissions.deny = settings.permissions.deny.filter(
  8746. (e) => !GSD_CLAUDE_LEGACY_DENY_PERMISSIONS.includes(e)
  8747. );
  8748. if (settings.permissions.deny.length !== before) {
  8749. permissionsModified = true;
  8750. if (settings.permissions.deny.length === 0) {
  8751. delete settings.permissions.deny;
  8752. }
  8753. }
  8754. }
  8755. if (permissionsModified && Object.keys(settings.permissions).length === 0) {
  8756. delete settings.permissions;
  8757. }
  8758. if (permissionsModified) {
  8759. settingsModified = true;
  8760. console.log(` ${green}✓${reset} Removed GSD permissions from settings.json`);
  8761. }
  8762. }
  8763. // #2096 Phase B Upgrade 1 — Remove GSD-owned Antigravity permissions.allow
  8764. // rules from settings.json. Symmetric to the Claude branch above: filters
  8765. // only the exact GSD-owned rule strings (regenerated from the current
  8766. // configDir) to preserve any user-added allow entries and all deny/ask.
  8767. if (resolveInstallPlan(runtime).finishPermissionWriter === 'antigravity' && settings.permissions) {
  8768. let antigravityPermissionsModified = false;
  8769. if (Array.isArray(settings.permissions.allow)) {
  8770. const gsdRules = new Set(buildAntigravityAllowRules(targetDir));
  8771. const before = settings.permissions.allow.length;
  8772. settings.permissions.allow = settings.permissions.allow.filter((e) => !gsdRules.has(e));
  8773. if (settings.permissions.allow.length !== before) {
  8774. antigravityPermissionsModified = true;
  8775. }
  8776. if (settings.permissions.allow.length === 0) {
  8777. delete settings.permissions.allow;
  8778. }
  8779. }
  8780. if (Object.keys(settings.permissions).length === 0) {
  8781. delete settings.permissions;
  8782. }
  8783. if (antigravityPermissionsModified) {
  8784. settingsModified = true;
  8785. console.log(` ${green}✓${reset} Removed GSD permissions from settings.json`);
  8786. }
  8787. }
  8788. // #2097 UPGRADE 3 — Remove the MCP companion entry from settings.json for
  8789. // runtimes that host MCP there (Augment), symmetric to the mcp_config.json
  8790. // removal for Antigravity below. Only the GSD-owned mcpServers.gsd key is
  8791. // removed — any other user-configured MCP servers are preserved.
  8792. if (hostBehaviorsFor(runtime).mcpCompanion === 'settings-json' &&
  8793. settings.mcpServers && typeof settings.mcpServers === 'object' &&
  8794. settings.mcpServers.gsd !== undefined) {
  8795. delete settings.mcpServers.gsd;
  8796. if (Object.keys(settings.mcpServers).length === 0) {
  8797. delete settings.mcpServers;
  8798. }
  8799. settingsModified = true;
  8800. console.log(` ${green}✓${reset} Removed GSD MCP companion server from settings.json`);
  8801. }
  8802. if (settingsModified) {
  8803. writeSettings(settingsPath, settings);
  8804. removedCount++;
  8805. }
  8806. }
  8807. // 6. For OpenCode, clean up permissions and the companion MCP entry from opencode.json or opencode.jsonc
  8808. if (resolveInstallPlan(runtime).finishPermissionWriter === 'opencode') {
  8809. const configPath = resolveOpencodeConfigPath(targetDir);
  8810. if (fs.existsSync(configPath)) {
  8811. try {
  8812. const originalText = fs.readFileSync(configPath, 'utf8');
  8813. const config = parseJsonc(originalText);
  8814. const edits = [];
  8815. // Remove GSD permission entries
  8816. if (config.permission && typeof config.permission === 'object') {
  8817. for (const permType of ['read', 'external_directory']) {
  8818. const section = config.permission[permType];
  8819. if (!section || typeof section !== 'object') continue;
  8820. for (const key of Object.keys(section)) {
  8821. if (key.includes('gsd-core')) {
  8822. delete section[key];
  8823. edits.push({ path: ['permission', permType, key], remove: true });
  8824. }
  8825. }
  8826. // Clean up empty objects
  8827. if (Object.keys(section).length === 0) delete config.permission[permType];
  8828. }
  8829. if (Object.keys(config.permission).length === 0) delete config.permission;
  8830. }
  8831. // #5333: remove the companion MCP entry, but only while it is still the entry GSD wrote — a
  8832. // user-edited or user-defined `gsd` server stays. Both OpenCode generations' shapes: the 1.x
  8833. // `mcp.gsd` and the 2.x native `mcp.servers.gsd`.
  8834. let mcpRemoved = false;
  8835. if (config.mcp && typeof config.mcp === 'object') {
  8836. if (isGsdMcpEntry(config.mcp.gsd)) {
  8837. delete config.mcp.gsd;
  8838. edits.push({ path: ['mcp', 'gsd'], remove: true });
  8839. mcpRemoved = true;
  8840. }
  8841. const servers = config.mcp.servers;
  8842. if (servers && typeof servers === 'object' && isGsdMcpEntry(servers.gsd)) {
  8843. delete servers.gsd;
  8844. edits.push({ path: ['mcp', 'servers', 'gsd'], remove: true });
  8845. if (Object.keys(servers).length === 0) delete config.mcp.servers;
  8846. mcpRemoved = true;
  8847. }
  8848. if (Object.keys(config.mcp).length === 0) delete config.mcp;
  8849. }
  8850. if (edits.length > 0) {
  8851. writeJsoncConfig(configPath, originalText, config, edits);
  8852. removedCount++;
  8853. console.log(` ${green}✓${reset} Removed GSD permissions${mcpRemoved ? ' and MCP server' : ''} from ${path.basename(configPath)}`);
  8854. }
  8855. } catch (e) {
  8856. // Ignore JSON parse errors
  8857. }
  8858. }
  8859. }
  8860. // 7. For Kilo, clean up permissions from kilo.json or kilo.jsonc
  8861. // #2093: descriptor-driven via resolveInstallPlan(runtime).finishPermissionWriter,
  8862. // mirroring the OpenCode branch above (was hardcoded `isKilo`).
  8863. if (resolveInstallPlan(runtime).finishPermissionWriter === 'kilo') {
  8864. const configPath = resolveKiloConfigPath(targetDir);
  8865. if (fs.existsSync(configPath)) {
  8866. try {
  8867. const originalText = fs.readFileSync(configPath, 'utf8');
  8868. const config = parseJsonc(originalText);
  8869. const edits = [];
  8870. // Remove GSD permission entries
  8871. if (config.permission) {
  8872. for (const permType of ['read', 'external_directory']) {
  8873. if (config.permission[permType]) {
  8874. const keys = Object.keys(config.permission[permType]);
  8875. for (const key of keys) {
  8876. if (key.includes('gsd-core')) {
  8877. delete config.permission[permType][key];
  8878. edits.push({ path: ['permission', permType, key], remove: true });
  8879. }
  8880. }
  8881. // Clean up empty objects
  8882. if (Object.keys(config.permission[permType]).length === 0) {
  8883. delete config.permission[permType];
  8884. }
  8885. }
  8886. }
  8887. if (Object.keys(config.permission).length === 0) {
  8888. delete config.permission;
  8889. }
  8890. }
  8891. if (edits.length > 0) {
  8892. writeJsoncConfig(configPath, originalText, config, edits);
  8893. removedCount++;
  8894. console.log(` ${green}✓${reset} Removed GSD permissions from ${path.basename(configPath)}`);
  8895. }
  8896. } catch (e) {
  8897. // Ignore JSON parse errors
  8898. }
  8899. }
  8900. }
  8901. // 8. For Antigravity, remove the MCP companion entry from mcp_config.json
  8902. // (#2096 Phase B Upgrade 2). Only the GSD-owned mcpServers.gsd key is
  8903. // removed — any other user-configured MCP servers are preserved.
  8904. if (resolveInstallPlan(runtime).finishPermissionWriter === 'antigravity') {
  8905. const mcpConfigPath = path.join(targetDir, 'mcp_config.json');
  8906. if (fs.existsSync(mcpConfigPath)) {
  8907. try {
  8908. const mcpConfig = JSON.parse(fs.readFileSync(mcpConfigPath, 'utf8'));
  8909. if (mcpConfig && typeof mcpConfig === 'object' && mcpConfig.mcpServers && mcpConfig.mcpServers.gsd !== undefined) {
  8910. delete mcpConfig.mcpServers.gsd;
  8911. if (Object.keys(mcpConfig.mcpServers).length === 0) {
  8912. delete mcpConfig.mcpServers;
  8913. }
  8914. fs.writeFileSync(mcpConfigPath, JSON.stringify(mcpConfig, null, 2) + '\n');
  8915. removedCount++;
  8916. console.log(` ${green}✓${reset} Removed GSD MCP companion server from mcp_config.json`);
  8917. }
  8918. } catch (e) {
  8919. // Ignore JSON parse errors
  8920. }
  8921. }
  8922. }
  8923. // Remove the file manifest that the installer wrote at install time.
  8924. // Without this step the metadata file persists after uninstall (#1908).
  8925. const manifestPath = path.join(targetDir, MANIFEST_NAME);
  8926. if (fs.existsSync(manifestPath)) {
  8927. fs.rmSync(manifestPath, { force: true });
  8928. removedCount++;
  8929. console.log(` ${green}✓${reset} Removed ${MANIFEST_NAME}`);
  8930. }
  8931. // #5335: the installer's own bookkeeping goes with it — the applied-migrations state and the migration
  8932. // journal. The journal's `-backups/` folders hold copies of files the USER had modified, so a folder that
  8933. // still has content is kept; everything GSD generated for itself (run records, rollback snapshots, empty
  8934. // folders) is removed.
  8935. const installStatePath = path.join(targetDir, 'gsd-install-state.json');
  8936. if (fs.existsSync(installStatePath)) {
  8937. fs.rmSync(installStatePath, { force: true });
  8938. removedCount++;
  8939. console.log(` ${green}✓${reset} Removed gsd-install-state.json`);
  8940. }
  8941. const journalDir = path.join(targetDir, 'gsd-migration-journal');
  8942. if (fs.existsSync(journalDir)) {
  8943. let journalEntriesRemoved = 0;
  8944. try {
  8945. for (const entry of fs.readdirSync(journalDir, { withFileTypes: true })) {
  8946. const full = path.join(journalDir, entry.name);
  8947. if (entry.isSymbolicLink()) continue;
  8948. if (entry.isFile() && entry.name.endsWith('.json')) {
  8949. fs.rmSync(full, { force: true });
  8950. journalEntriesRemoved++;
  8951. } else if (entry.isDirectory() && entry.name.endsWith('-rollback')) {
  8952. fs.rmSync(full, { recursive: true, force: true });
  8953. journalEntriesRemoved++;
  8954. } else if (entry.isDirectory() && entry.name.endsWith('-backups')) {
  8955. try { fs.rmdirSync(full); journalEntriesRemoved++; } catch { /* holds the user's backed-up files: keep */ }
  8956. }
  8957. }
  8958. fs.rmdirSync(journalDir);
  8959. } catch { /* a non-empty journal dir (kept backups) stays */ }
  8960. if (journalEntriesRemoved > 0) {
  8961. removedCount++;
  8962. console.log(` ${green}✓${reset} Removed gsd-migration-journal/ records`);
  8963. }
  8964. }
  8965. // #5335: the installer's user-artifact staging area is empty once the install it served is over. rmdir only
  8966. // succeeds on an empty directory, so anything still staged there is left for its owner.
  8967. try {
  8968. fs.rmdirSync(path.join(targetDir, '.gsd-staging', 'user-artifacts'));
  8969. fs.rmdirSync(path.join(targetDir, '.gsd-staging'));
  8970. } catch { /* absent or not empty */ }
  8971. // #5335: OpenCode never reads settings.json, but the shared-settings install step creates it as `{}`.
  8972. // An empty one carries nothing of the user's; a populated one is left alone.
  8973. if (resolveInstallPlan(runtime).finishPermissionWriter === 'opencode') {
  8974. const emptySettingsPath = path.join(targetDir, 'settings.json');
  8975. try {
  8976. const parsed = JSON.parse(fs.readFileSync(emptySettingsPath, 'utf8'));
  8977. if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && Object.keys(parsed).length === 0) {
  8978. fs.rmSync(emptySettingsPath, { force: true });
  8979. removedCount++;
  8980. console.log(` ${green}✓${reset} Removed empty settings.json`);
  8981. }
  8982. } catch { /* absent, unreadable or populated: leave it */ }
  8983. }
  8984. // #5335: the machine-wide defaults the install wrote for this runtime, when nothing else needs them.
  8985. if (revertNonClaudeDefaults(runtime)) {
  8986. removedCount++;
  8987. }
  8988. if (removedCount === 0) {
  8989. console.log(` ${yellow}⚠${reset} No GSD files found to remove.`);
  8990. }
  8991. console.log(`
  8992. ${green}Done!${reset} GSD has been uninstalled from ${runtimeLabel}.
  8993. Your other files and settings have been preserved.
  8994. `);
  8995. }
  8996. /**
  8997. * Write back an OpenCode/Kilo config the installer changed (#5334).
  8998. *
  8999. * A file that carries JSONC syntax (a `.jsonc` name, comments or trailing commas) is edited as text, so
  9000. * only the keys GSD owns change and the user's annotations and layout survive. Anything the text editor
  9001. * cannot handle, and plain JSON, keeps the previous `JSON.stringify` rewrite.
  9002. *
  9003. * @param {string} configPath
  9004. * @param {string|null} originalText current file text, or null when the file is new
  9005. * @param {object} config the mutated parsed config (used for the fallback)
  9006. * @param {Array<{path: string[], value?: unknown, remove?: boolean}>} edits
  9007. */
  9008. function writeJsoncConfig(configPath, originalText, config, edits) {
  9009. if (typeof originalText === 'string' && (configPath.endsWith('.jsonc') || hasJsoncFeatures(originalText))) {
  9010. let text = originalText;
  9011. for (const edit of edits) {
  9012. text = edit.remove ? removeJsoncValue(text, edit.path) : setJsoncValue(text, edit.path, edit.value);
  9013. if (text === null) break;
  9014. }
  9015. if (text !== null) {
  9016. fs.writeFileSync(configPath, text);
  9017. return;
  9018. }
  9019. }
  9020. fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
  9021. }
  9022. /**
  9023. * Configure OpenCode permissions to allow reading GSD reference docs
  9024. * This prevents permission prompts when GSD accesses the gsd-core directory
  9025. * @param {boolean} isGlobal - Whether this is a global or local install
  9026. * @param {string|null} configDir - Resolved config directory when already known
  9027. */
  9028. function configureOpencodePermissions(isGlobal = true, configDir = null) {
  9029. // For local installs, use ./.opencode/
  9030. // For global installs, use ~/.config/opencode/
  9031. const opencodeConfigDir = configDir || (isGlobal
  9032. ? getGlobalConfigDir('opencode', explicitConfigDir)
  9033. : path.join(process.cwd(), '.opencode'));
  9034. // Ensure config directory exists
  9035. fs.mkdirSync(opencodeConfigDir, { recursive: true });
  9036. const configPath = resolveOpencodeConfigPath(opencodeConfigDir);
  9037. // Read existing config or create empty object
  9038. let config = {};
  9039. let originalText = null;
  9040. if (fs.existsSync(configPath)) {
  9041. try {
  9042. const content = fs.readFileSync(configPath, 'utf8');
  9043. originalText = content;
  9044. config = parseJsonc(content);
  9045. } catch (e) {
  9046. // Cannot parse - DO NOT overwrite user's config
  9047. const configFile = path.basename(configPath);
  9048. console.log(` ${yellow}⚠${reset} Could not parse ${configFile} - skipping permission config`);
  9049. console.log(` ${dim}Reason: ${e.message}${reset}`);
  9050. console.log(` ${dim}Your config was NOT modified. Fix the syntax manually if needed.${reset}`);
  9051. return;
  9052. }
  9053. }
  9054. // OpenCode also allows a top-level string permission like "allow".
  9055. // In that case, path-specific permission entries are unnecessary.
  9056. if (typeof config.permission === 'string') {
  9057. return;
  9058. }
  9059. // Ensure permission structure exists
  9060. if (!config.permission || typeof config.permission !== 'object') {
  9061. config.permission = {};
  9062. }
  9063. // Build the GSD path using the actual config directory
  9064. // Use ~ shorthand if it's in the default location, otherwise use full path
  9065. const defaultConfigDir = path.join(os.homedir(), '.config', 'opencode');
  9066. const gsdPath = opencodeConfigDir === defaultConfigDir
  9067. ? '~/.config/opencode/gsd-core/*'
  9068. : `${opencodeConfigDir.replace(/\\/g, '/')}/gsd-core/*`;
  9069. let modified = false;
  9070. const edits = [];
  9071. // Configure read permission
  9072. if (!config.permission.read || typeof config.permission.read !== 'object') {
  9073. config.permission.read = {};
  9074. }
  9075. if (config.permission.read[gsdPath] !== 'allow') {
  9076. config.permission.read[gsdPath] = 'allow';
  9077. edits.push({ path: ['permission', 'read', gsdPath], value: 'allow' });
  9078. modified = true;
  9079. }
  9080. // Configure external_directory permission (the safety guard for paths outside)
  9081. if (!config.permission.external_directory || typeof config.permission.external_directory !== 'object') {
  9082. config.permission.external_directory = {};
  9083. }
  9084. if (config.permission.external_directory[gsdPath] !== 'allow') {
  9085. config.permission.external_directory[gsdPath] = 'allow';
  9086. edits.push({ path: ['permission', 'external_directory', gsdPath], value: 'allow' });
  9087. modified = true;
  9088. }
  9089. // ADR-1239 Phase D / #1682 — register the companion MCP server (Phase 4) so
  9090. // OpenCode connects to GSD's command (point 1) + state-IO (point 5) surface
  9091. // with NO bespoke plugin. Idempotent + non-clobbering: only added when
  9092. // `mcp.gsd` is absent (a user-defined `mcp.gsd` is respected — Hyrum's Law).
  9093. // Local-stdio schema per OpenCode config (packages/core/src/config/mcp.ts).
  9094. // `-p @opengsd/gsd-core` resolves the `gsd-mcp-server` bin from this package
  9095. // (bin name != package name) regardless of global-install state.
  9096. if (!config.mcp || typeof config.mcp !== 'object') {
  9097. config.mcp = {};
  9098. }
  9099. if (config.mcp.gsd === undefined) {
  9100. config.mcp.gsd = {
  9101. type: 'local',
  9102. command: ['npx', '-y', '-p', PACKAGE_NAME, 'gsd-mcp-server', GSD_MCP_NO_PROMPTS_FLAG],
  9103. enabled: true,
  9104. };
  9105. edits.push({ path: ['mcp', 'gsd'], value: config.mcp.gsd });
  9106. modified = true;
  9107. }
  9108. if (!modified) {
  9109. return; // Already configured
  9110. }
  9111. // Write config back
  9112. writeJsoncConfig(configPath, originalText, config, edits);
  9113. console.log(` ${green}✓${reset} Configured read permission for GSD docs`);
  9114. }
  9115. /**
  9116. * Configure Kilo permissions to allow reading GSD reference docs
  9117. * This prevents permission prompts when GSD accesses the gsd-core directory
  9118. * @param {boolean} isGlobal - Whether this is a global or local install
  9119. * @param {string|null} configDir - Resolved config directory when already known
  9120. */
  9121. function configureKiloPermissions(isGlobal = true, configDir = null) {
  9122. // For local installs, use ./.kilo/
  9123. // For global installs, use ~/.config/kilo/
  9124. const kiloConfigDir = configDir || (isGlobal
  9125. ? getGlobalConfigDir('kilo', explicitConfigDir)
  9126. : path.join(process.cwd(), '.kilo'));
  9127. // Ensure config directory exists
  9128. fs.mkdirSync(kiloConfigDir, { recursive: true });
  9129. const configPath = resolveKiloConfigPath(kiloConfigDir);
  9130. // Read existing config or create empty object
  9131. let config = {};
  9132. let originalText = null;
  9133. if (fs.existsSync(configPath)) {
  9134. try {
  9135. const content = fs.readFileSync(configPath, 'utf8');
  9136. originalText = content;
  9137. config = parseJsonc(content);
  9138. } catch (e) {
  9139. // Cannot parse - DO NOT overwrite user's config
  9140. const configFile = path.basename(configPath);
  9141. console.log(` ${yellow}⚠${reset} Could not parse ${configFile} - skipping permission config`);
  9142. console.log(` ${dim}Reason: ${e.message}${reset}`);
  9143. console.log(` ${dim}Your config was NOT modified. Fix the syntax manually if needed.${reset}`);
  9144. return;
  9145. }
  9146. }
  9147. // Ensure permission structure exists
  9148. if (!config.permission || typeof config.permission !== 'object') {
  9149. config.permission = {};
  9150. }
  9151. // Build the GSD path using the actual config directory
  9152. // Use ~ shorthand if it's in the default location, otherwise use full path
  9153. const defaultConfigDir = path.join(os.homedir(), '.config', 'kilo');
  9154. const gsdPath = kiloConfigDir === defaultConfigDir
  9155. ? '~/.config/kilo/gsd-core/*'
  9156. : `${kiloConfigDir.replace(/\\/g, '/')}/gsd-core/*`;
  9157. let modified = false;
  9158. const edits = [];
  9159. // Configure read permission
  9160. if (!config.permission.read || typeof config.permission.read !== 'object') {
  9161. config.permission.read = {};
  9162. }
  9163. if (config.permission.read[gsdPath] !== 'allow') {
  9164. config.permission.read[gsdPath] = 'allow';
  9165. edits.push({ path: ['permission', 'read', gsdPath], value: 'allow' });
  9166. modified = true;
  9167. }
  9168. // Configure external_directory permission (the safety guard for paths outside project)
  9169. if (!config.permission.external_directory || typeof config.permission.external_directory !== 'object') {
  9170. config.permission.external_directory = {};
  9171. }
  9172. if (config.permission.external_directory[gsdPath] !== 'allow') {
  9173. config.permission.external_directory[gsdPath] = 'allow';
  9174. edits.push({ path: ['permission', 'external_directory', gsdPath], value: 'allow' });
  9175. modified = true;
  9176. }
  9177. if (!modified) {
  9178. return; // Already configured
  9179. }
  9180. // Write config back
  9181. writeJsoncConfig(configPath, originalText, config, edits);
  9182. console.log(` ${green}✓${reset} Configured read permission for GSD docs`);
  9183. }
  9184. /**
  9185. * Convert an absolute path to a `~`-relative form when it lives under the
  9186. * user's home directory (generalizes configureKiloPermissions'
  9187. * single-default-dir shorthand to Antigravity's three probed sibling config
  9188. * dirs — antigravity/antigravity-ide/antigravity-cli under ~/.gemini — none of
  9189. * which is a single fixed "default").
  9190. */
  9191. function toTildePosixPath(absPath) {
  9192. const posixPath = absPath.replace(/\\/g, '/');
  9193. const posixHome = os.homedir().replace(/\\/g, '/');
  9194. return posixPath === posixHome || posixPath.startsWith(`${posixHome}/`)
  9195. ? `~${posixPath.slice(posixHome.length)}`
  9196. : posixPath;
  9197. }
  9198. /**
  9199. * Antigravity permission rule strings this installer contributes.
  9200. * Schema: antigravity.google/docs/cli/permissions — "action(target)" rule
  9201. * strings in permissions.{allow,deny,ask}, evaluated deny > ask > allow. GSD
  9202. * only ever contributes to `allow` — never deny/ask (those are user-owned risk
  9203. * decisions this installer has no business making).
  9204. */
  9205. function buildAntigravityAllowRules(configDir) {
  9206. const gsdPath = toTildePosixPath(configDir);
  9207. return [
  9208. `read_file(${gsdPath}/gsd-core/*)`,
  9209. `read_file(${gsdPath}/agents/gsd-*)`,
  9210. `read_file(${gsdPath}/skills/gsd-*)`,
  9211. `command(node ${gsdPath}/hooks/*)`,
  9212. ];
  9213. }
  9214. /**
  9215. * Configure Antigravity permissions to allow reading/executing GSD's installed
  9216. * tree without per-call approval prompts (#2096 Phase B Upgrade 1 — mirrors
  9217. * configureKiloPermissions/configureOpencodePermissions).
  9218. *
  9219. * Antigravity's permission schema (antigravity.google/docs/cli/permissions) is
  9220. * `{"permissions":{"allow":[...],"deny":[...],"ask":[...]}}`, living in the
  9221. * SAME settings.json GSD's own hook registration writes for this runtime
  9222. * (installSurface: 'settings-json', writesSharedSettings: true) — unlike
  9223. * Kilo/OpenCode, which write a separate native config file. This function
  9224. * re-reads the file (already containing GSD's hooks by the time finishInstall
  9225. * reaches this call) and only appends to permissions.allow.
  9226. *
  9227. * Non-destructive + idempotent: only `permissions.allow` is touched; an
  9228. * existing user permissions block (including any deny/ask entries, or
  9229. * unrelated allow entries) is preserved untouched.
  9230. *
  9231. * @param {boolean} isGlobal - Whether this is a global or local install
  9232. * @param {string|null} configDir - Resolved config directory when already known
  9233. */
  9234. function configureAntigravityPermissions(isGlobal = true, configDir = null) {
  9235. // For local installs, use ./.agents/ (GSD's antigravity localConfigDir)
  9236. // For global installs, use the resolved ~/.gemini/antigravity{,-ide,-cli}
  9237. const antigravityConfigDir = configDir || (isGlobal
  9238. ? getGlobalConfigDir('antigravity', explicitConfigDir)
  9239. : path.join(process.cwd(), '.agents'));
  9240. // Ensure config directory exists
  9241. fs.mkdirSync(antigravityConfigDir, { recursive: true });
  9242. const configPath = path.join(antigravityConfigDir, 'settings.json');
  9243. // Read existing settings.json (readSettings tolerates JSONC + missing file;
  9244. // returns null — and warns — only when the file exists but fails to parse).
  9245. const config = readSettings(configPath);
  9246. if (config === null) {
  9247. // Cannot parse — DO NOT overwrite user's config (readSettings already warned).
  9248. return;
  9249. }
  9250. // Ensure permission structure exists
  9251. if (!config.permissions || typeof config.permissions !== 'object' || Array.isArray(config.permissions)) {
  9252. config.permissions = {};
  9253. }
  9254. if (!Array.isArray(config.permissions.allow)) {
  9255. config.permissions.allow = [];
  9256. }
  9257. let modified = false;
  9258. for (const rule of buildAntigravityAllowRules(antigravityConfigDir)) {
  9259. if (!config.permissions.allow.includes(rule)) {
  9260. config.permissions.allow.push(rule);
  9261. modified = true;
  9262. }
  9263. }
  9264. if (!modified) {
  9265. return; // Already configured
  9266. }
  9267. writeSettings(configPath, config);
  9268. console.log(` ${green}✓${reset} Configured Antigravity permissions for GSD paths`);
  9269. }
  9270. /**
  9271. * Configure Antigravity's MCP companion server config (#2096 Phase B
  9272. * Upgrade 2).
  9273. *
  9274. * Antigravity CLI manages MCP servers via standalone `mcp_config.json`
  9275. * profiles rather than nesting them in settings.json (antigravity.google/docs/
  9276. * cli/gcli-migration: "Antigravity CLI uses standalone mcp_config.json
  9277. * profiles in ~/.gemini/config/ for global servers and .agents/mcp_config.json
  9278. * for workspace servers"). The raw schema for the Antigravity IDE surface
  9279. * itself is unpublished (docs are JS-rendered), so this follows the CLI's
  9280. * documented standalone-profile convention plus the standard Gemini/MCP
  9281. * `mcpServers` shape.
  9282. *
  9283. * BEST-EFFORT PATH CHOICE: rather than the CLI doc's separate `~/.gemini/config/`
  9284. * directory for global scope, this writes `<configDir>/mcp_config.json` — the
  9285. * SAME resolved configDir as settings.json (configureAntigravityPermissions) —
  9286. * because (1) GSD's own antigravity configDir resolution already varies
  9287. * per-user across three sibling dirs (antigravity/antigravity-ide/
  9288. * antigravity-cli — see resolveAntigravityGlobalDir), so a hardcoded separate
  9289. * shared path would not track that resolution, and (2) it matches the doc's
  9290. * OWN workspace-scope convention exactly (`.agents/mcp_config.json`, which IS
  9291. * GSD's local configDir for antigravity), keeping global/local symmetric and
  9292. * consistent with the configDir-relative convention every other GSD
  9293. * permission writer (kilo/opencode) already uses.
  9294. *
  9295. * Non-destructive + idempotent: only adds mcpServers.gsd when entirely absent;
  9296. * any other user-configured mcpServers entries (or a user's OWN "gsd" override)
  9297. * are preserved untouched (Hyrum's Law — mirrors OpenCode's config.mcp.gsd guard).
  9298. *
  9299. * @param {boolean} isGlobal - Whether this is a global or local install
  9300. * @param {string|null} configDir - Resolved config directory when already known
  9301. */
  9302. function configureAntigravityMcpConfig(isGlobal = true, configDir = null) {
  9303. const antigravityConfigDir = configDir || (isGlobal
  9304. ? getGlobalConfigDir('antigravity', explicitConfigDir)
  9305. : path.join(process.cwd(), '.agents'));
  9306. fs.mkdirSync(antigravityConfigDir, { recursive: true });
  9307. const configPath = path.join(antigravityConfigDir, 'mcp_config.json');
  9308. let config = {};
  9309. if (fs.existsSync(configPath)) {
  9310. try {
  9311. const parsed = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  9312. config = (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) ? parsed : {};
  9313. } catch (e) {
  9314. // Cannot parse - DO NOT overwrite user's config
  9315. console.log(` ${yellow}⚠${reset} Could not parse mcp_config.json - skipping MCP companion config`);
  9316. console.log(` ${dim}Reason: ${e.message}${reset}`);
  9317. console.log(` ${dim}Your config was NOT modified. Fix the syntax manually if needed.${reset}`);
  9318. return;
  9319. }
  9320. }
  9321. if (!config.mcpServers || typeof config.mcpServers !== 'object' || Array.isArray(config.mcpServers)) {
  9322. config.mcpServers = {};
  9323. }
  9324. if (config.mcpServers.gsd !== undefined) {
  9325. return; // Already configured (or a user-owned override) — never clobber.
  9326. }
  9327. config.mcpServers.gsd = {
  9328. command: 'npx',
  9329. args: ['-y', '-p', PACKAGE_NAME, 'gsd-mcp-server'],
  9330. };
  9331. fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
  9332. console.log(` ${green}✓${reset} Configured Antigravity MCP companion server (gsd)`);
  9333. }
  9334. /**
  9335. * #2097 (ADR-1239 transport:mcp): register the GSD companion MCP server inside a
  9336. * runtime's settings.json (Augment hosts MCP in settings.json.mcpServers, unlike
  9337. * Antigravity's standalone mcp_config.json). Mutates the in-memory settings object
  9338. * that finishInstall already writes — non-destructive + idempotent: only sets
  9339. * mcpServers.gsd, preserving any user-defined servers (a user's own `gsd` override
  9340. * is respected — Hyrum's Law).
  9341. * @param {object} settings - the in-memory settings object finishInstall will write
  9342. */
  9343. function mergeGsdMcpServerIntoSettings(settings) {
  9344. if (!settings.mcpServers || typeof settings.mcpServers !== 'object' || Array.isArray(settings.mcpServers)) {
  9345. settings.mcpServers = {};
  9346. }
  9347. if (settings.mcpServers.gsd === undefined) {
  9348. settings.mcpServers.gsd = {
  9349. command: 'npx',
  9350. args: ['-y', '-p', PACKAGE_NAME, 'gsd-mcp-server'],
  9351. };
  9352. }
  9353. }
  9354. /**
  9355. * Verify a directory exists and contains files
  9356. */
  9357. function verifyInstalled(dirPath, description) {
  9358. if (!fs.existsSync(dirPath)) {
  9359. console.error(` ${yellow}✗${reset} Failed to install ${description}: directory not created`);
  9360. return false;
  9361. }
  9362. try {
  9363. const entries = fs.readdirSync(dirPath);
  9364. if (entries.length === 0) {
  9365. console.error(` ${yellow}✗${reset} Failed to install ${description}: directory is empty`);
  9366. return false;
  9367. }
  9368. } catch (e) {
  9369. console.error(` ${yellow}✗${reset} Failed to install ${description}: ${e.message}`);
  9370. return false;
  9371. }
  9372. return true;
  9373. }
  9374. /**
  9375. * Verify a file exists
  9376. */
  9377. function verifyFileInstalled(filePath, description) {
  9378. if (!fs.existsSync(filePath)) {
  9379. console.error(` ${yellow}✗${reset} Failed to install ${description}: file not created`);
  9380. return false;
  9381. }
  9382. return true;
  9383. }
  9384. /**
  9385. * Install to the specified directory for a specific runtime
  9386. * @param {boolean} isGlobal - Whether to install globally or locally
  9387. * @param {string} runtime - Target runtime ('claude', 'opencode', 'codex')
  9388. */
  9389. // ──────────────────────────────────────────────────────
  9390. // Local Patch Persistence
  9391. // ──────────────────────────────────────────────────────
  9392. const PATCHES_DIR_NAME = 'gsd-local-patches';
  9393. const MANIFEST_NAME = 'gsd-file-manifest.json';
  9394. /**
  9395. * Compute SHA256 hash of file contents
  9396. */
  9397. function fileHash(filePath) {
  9398. // #5683: single owner of the per-file hash, shared with `effort sync`.
  9399. return require('../gsd-core/bin/lib/install-manifest-record.cjs').fileHash(filePath);
  9400. }
  9401. /**
  9402. * Recursively collect all files in dir with their hashes
  9403. */
  9404. function generateManifest(dir, baseDir) {
  9405. if (!baseDir) baseDir = dir;
  9406. const manifest = {};
  9407. if (!fs.existsSync(dir)) return manifest;
  9408. const entries = fs.readdirSync(dir, { withFileTypes: true });
  9409. for (const entry of entries) {
  9410. const fullPath = path.join(dir, entry.name);
  9411. const relPath = path.relative(baseDir, fullPath).replace(/\\/g, '/');
  9412. if (entry.isDirectory()) {
  9413. Object.assign(manifest, generateManifest(fullPath, baseDir));
  9414. } else {
  9415. manifest[relPath] = fileHash(fullPath);
  9416. }
  9417. }
  9418. return manifest;
  9419. }
  9420. function normalizeInstallRelativePath(relPath) {
  9421. if (typeof relPath !== 'string' || relPath.trim() === '' || relPath.includes('\0')) {
  9422. return null;
  9423. }
  9424. if (path.isAbsolute(relPath) || path.win32.isAbsolute(relPath)) {
  9425. return null;
  9426. }
  9427. const normalized = relPath.replace(/\\/g, '/');
  9428. const segments = normalized.split('/');
  9429. if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {
  9430. return null;
  9431. }
  9432. return segments.join('/');
  9433. }
  9434. function resolveInstallRelativePath(baseDir, relPath) {
  9435. const normalized = normalizeInstallRelativePath(relPath);
  9436. if (!normalized) return null;
  9437. const root = path.resolve(baseDir);
  9438. const fullPath = path.resolve(root, normalized);
  9439. if (fullPath !== root && !fullPath.startsWith(root + path.sep)) {
  9440. return null;
  9441. }
  9442. if (hasExistingSymlinkBetween(root, fullPath, { allowOptInFollow: isSymlinkedDestOptIn() })) {
  9443. return null;
  9444. }
  9445. return { relPath: normalized, fullPath };
  9446. }
  9447. // hasExistingSymlinkBetween: moved to src/install-engine.cts (ADR-1239 Phase B).
  9448. // Imported from installEngine above.
  9449. /**
  9450. * Write file manifest after installation for future modification detection
  9451. */
  9452. function writeManifest(configDir, runtime = DEFAULT_RUNTIME, options = {}) {
  9453. // #2093: isKilo dropped — unused in this function.
  9454. // #2094: isTrae dropped — was only used in the hooks-tracking conditional
  9455. // above, now covered by hostBehaviors.skipSharedHooksInstall.
  9456. // #2095: isKimi dropped — kimi is now a hooks/ consumer like every other
  9457. // settings-json-adjacent runtime, so the `&& !isKimi` term below was removed.
  9458. // #2096: isAntigravity dropped — unused in this function.
  9459. // #2098: isCodebuddy dropped — unused in this function.
  9460. // #2099: isCopilot dropped — was only used in the hooks-tracking conditional
  9461. // above, now covered by hostBehaviors.skipSharedHooksInstall.
  9462. // #2100: isWindsurf dropped — was only used in the hooks-tracking conditional
  9463. // above, now covered by hostBehaviors.skipSharedHooksInstall.
  9464. const { isOpencode, isCodex, isCursor, isAugment, isQwen, isHermes, isCline } = runtimeFlags(runtime);
  9465. const gsdDir = path.join(configDir, 'gsd-core');
  9466. // #1367: Claude local now writes flat gsd-*.md files at commands/ (not commands/gsd/).
  9467. // Claude local uses flatCommandsDir instead for manifest recording.
  9468. const flatCommandsDir = path.join(configDir, 'commands');
  9469. const opencodeCommandDir = path.join(configDir, hostBehaviorsFor(runtime).flatCommandDir || 'command');
  9470. // Hermes nests GSD skills under skills/gsd/ as a single category (#2841) —
  9471. // already encoded in its layout descriptor's destSubpath ('skills/gsd').
  9472. // All other runtimes that use the Codex-style skills layout use a flat skills/ root.
  9473. // ADR-1239 upgrade 3 (#2088): honor a skills-kind `home` override (e.g. Codex
  9474. // skills -> $HOME/.agents/skills instead of configDir/skills) via the same
  9475. // descriptor-driven helper used by the snapshot/rollback/verification paths,
  9476. // so the manifest records what's actually on disk. _resolveSkillsRootDir already
  9477. // resolves destSubpath (which includes hermes's 'skills/gsd' nesting) — do not
  9478. // re-append 'gsd' or the hermes dir gets double-nested to skills/gsd/gsd.
  9479. // #2872 (ADR-2866 Phase 3): the scope used to pick the skills root and the
  9480. // scope RECORDED in the manifest are one value, resolved once. Two reads of
  9481. // `options.scope` could drift; one cannot.
  9482. const resolvedScope = options.scope === 'local' ? 'local' : 'global';
  9483. const codexSkillsDir = _resolveSkillsRootDir(runtime, configDir, resolvedScope);
  9484. const codexSkillsManifestPrefix = hostBehaviorsFor(runtime).skillsManifestPrefix || 'skills/';
  9485. // #3738: resolve the ACTUAL agents-install dir honoring an agents-kind `home`
  9486. // override (antigravity global → $HOME/.gemini/config/agents), mirroring
  9487. // _resolveSkillsRootDir for skills. Hardcoding configDir/agents left the
  9488. // manifest blind to the whole agents surface the moment the override landed —
  9489. // no drift detection, no patch backup. Falls back to <configDir>/agents.
  9490. const agentsDir = _kindDestDirSafe(runtime, configDir, resolvedScope, 'agents')
  9491. || _kindDestDirSafe(runtime, configDir, resolvedScope, 'kimi-agents')
  9492. || path.join(configDir, 'agents');
  9493. const manifest = {
  9494. // Schema version of this DOCUMENT (#2872) — distinct from `version`
  9495. // below, which is the GSD package version. Absent ⇒ a pre-#2872 (v1)
  9496. // manifest, which readInstallManifest still reads without error and
  9497. // without requiring a reinstall. Read from the Installer Migration
  9498. // Module rather than repeated as a second literal: the writer here and
  9499. // the reader's normalizeManifestVersion are two surfaces over one
  9500. // constant, and this repo's "generative fix divergence" class is exactly
  9501. // two such literals drifting apart.
  9502. manifestVersion: MANIFEST_SCHEMA_VERSION,
  9503. version: pkg.version,
  9504. timestamp: new Date().toISOString(),
  9505. mode: options.mode === 'minimal' ? 'minimal' : 'full',
  9506. // Recorded so an Installed Surface Resolver can answer "which surfaces
  9507. // are installed, at which scopes, for which runtimes" without re-deriving
  9508. // it from the directory it happened to be found in (#2872).
  9509. runtime,
  9510. scope: resolvedScope,
  9511. // #4377: a surface re-apply is a separate process and cannot rely on the
  9512. // installer's environment. Persist only a safe project-relative prefix.
  9513. relativeIncludePrefix: resolvedScope === 'local' && hasRelativeIncludes
  9514. ? runtimeArtifactConversion._projectRelativePrefixFromProjectRoot(process.cwd(), configDir)
  9515. : undefined,
  9516. files: {},
  9517. };
  9518. const gsdHashes = generateManifest(gsdDir);
  9519. for (const [rel, hash] of Object.entries(gsdHashes)) {
  9520. // Skip user-owned artifacts (e.g. USER-PROFILE.md). They are staged
  9521. // durably and restored across reinstalls (user-artifact-staging.cts,
  9522. // #2875) and must NOT be hashed into the manifest — otherwise
  9523. // saveLocalPatches() would flag every refresh as a "local patch"
  9524. // (bug #2771). Single source of truth: USER_OWNED_ARTIFACTS at top of file.
  9525. if (USER_OWNED_ARTIFACTS.includes(rel)) continue;
  9526. manifest.files['gsd-core/' + rel] = hash;
  9527. }
  9528. // Record commands surface for runtimes that emit it:
  9529. // Claude local (#1367 fix): flat gsd-<cmd>.md at commands/ level
  9530. // Manifest must reflect everything on disk so saveLocalPatches() can detect
  9531. // user edits and per-runtime minimal-mode assertions can read manifest.files.
  9532. // Claude local (#1367): flat gsd-*.md files at commands/ level.
  9533. // Only claude local writes gsd-*.md here; global installs don't emit commands,
  9534. // so this branch is a no-op for global (no matching files to find).
  9535. if (hostBehaviorsFor(runtime).localInstallStyle === 'legacy-flat' && fs.existsSync(flatCommandsDir)) {
  9536. for (const file of fs.readdirSync(flatCommandsDir)) {
  9537. if (file.startsWith('gsd-') && file.endsWith('.md')) {
  9538. manifest.files['commands/' + file] = fileHash(path.join(flatCommandsDir, file));
  9539. }
  9540. }
  9541. }
  9542. if (hostBehaviorsFor(runtime).flatCommandDir && fs.existsSync(opencodeCommandDir)) {
  9543. // #2329: derive the manifest key prefix from the SAME descriptor value used
  9544. // to compute opencodeCommandDir above, instead of a separately-hardcoded
  9545. // literal — a divergence here would silently break the manifest even after
  9546. // the destSubpath descriptor is corrected (Generative Fix Divergence guard).
  9547. const flatCommandDirPrefix = hostBehaviorsFor(runtime).flatCommandDir || 'command';
  9548. for (const file of fs.readdirSync(opencodeCommandDir)) {
  9549. if (file.startsWith('gsd-') && file.endsWith('.md')) {
  9550. manifest.files[flatCommandDirPrefix + '/' + file] = fileHash(path.join(opencodeCommandDir, file));
  9551. }
  9552. }
  9553. }
  9554. if (!hostBehaviorsFor(runtime).skipCodexSkillsManifest && fs.existsSync(codexSkillsDir)) {
  9555. // All runtimes (including Hermes post-#947) use the canonical 'gsd-' prefix.
  9556. const skillListPrefix = 'gsd-';
  9557. // #5161: record only skill dirs GSD owns. A user's gsd-* dir the prune
  9558. // preserved must not enter the manifest, or the next install reads it back
  9559. // as GSD-owned and deletes it. includeManifest:false keeps the previous
  9560. // manifest from vouching for itself; manifestIfSourceUnresolved keeps an
  9561. // unreadable install source from dropping every GSD skill from the manifest
  9562. // by carrying the previous manifest's entries forward instead of recording
  9563. // every gsd-* dir present.
  9564. const ownsSkillDir = createSkillDirOwnership(runtime, configDir, codexSkillsDir, skillListPrefix, { includeManifest: false, manifestIfSourceUnresolved: true, includeWritten: true });
  9565. for (const skillName of listCodexSkillNames(codexSkillsDir, skillListPrefix)) {
  9566. if (!ownsSkillDir(skillName) && !USER_OWNED_SKILL_DIRS.includes(skillName)) continue;
  9567. const skillRoot = path.join(codexSkillsDir, skillName);
  9568. const skillHashes = generateManifest(skillRoot);
  9569. for (const [rel, hash] of Object.entries(skillHashes)) {
  9570. manifest.files[`${codexSkillsManifestPrefix}${skillName}/${rel}`] = hash;
  9571. }
  9572. }
  9573. // Descriptor-driven (#2090): hash the category DESCRIPTION.md so reinstall detects drift.
  9574. if (hostBehaviorsFor(runtime).trackCategoryDescription) {
  9575. const descPath = path.join(codexSkillsDir, 'DESCRIPTION.md');
  9576. if (fs.existsSync(descPath)) {
  9577. manifest.files['skills/gsd/DESCRIPTION.md'] = fileHash(descPath);
  9578. }
  9579. }
  9580. }
  9581. if (hostBehaviorsFor(runtime).agentManifestStyle === 'kimi-nested' && fs.existsSync(agentsDir)) {
  9582. const agentHashes = generateManifest(agentsDir);
  9583. for (const [rel, hash] of Object.entries(agentHashes)) {
  9584. const isRootAgent = rel === 'gsd.yaml' || rel === 'gsd.md';
  9585. const isSubagent = /^subagents\/gsd-[^/]+\.(yaml|md)$/.test(rel);
  9586. if (isRootAgent || isSubagent) {
  9587. manifest.files['agents/' + rel] = hash;
  9588. }
  9589. }
  9590. } else if (fs.existsSync(agentsDir)) {
  9591. for (const file of fs.readdirSync(agentsDir)) {
  9592. if (file.startsWith('gsd-') && (file.endsWith('.md') || file.endsWith('.toml'))) {
  9593. manifest.files['agents/' + file] = fileHash(path.join(agentsDir, file));
  9594. }
  9595. }
  9596. }
  9597. // Track Cline directory-form artifacts in the manifest (issue #787): the
  9598. // rules file and the PreToolUse hook. (~/.agents/AGENTS.md is tracked via its
  9599. // marker block, not the per-configDir manifest, since it lives outside it.)
  9600. // Descriptor-driven (ADR-1239 / #2090): folded from `isCline` into
  9601. // hostBehaviors.clineRulesSurface.
  9602. if (hostBehaviorsFor(runtime).clineRulesSurface) {
  9603. for (const rel of ['.clinerules/gsd.md', '.clinerules/hooks/PreToolUse']) {
  9604. const dest = path.join(configDir, rel);
  9605. if (fs.existsSync(dest)) {
  9606. manifest.files[rel] = fileHash(dest);
  9607. }
  9608. }
  9609. }
  9610. // Track hook files so saveLocalPatches() can detect user modifications
  9611. // Hooks are only installed for runtimes that use settings.json (not Codex/Copilot/Cline)
  9612. // Descriptor-driven (ADR-1239 / #2089+#2090): cline's exclusion is via
  9613. // hostBehaviors.skipSharedHooksInstall (was hardcoded !isCline).
  9614. // #2094: Trae's exclusion is likewise descriptor-driven (trae declares
  9615. // skipSharedHooksInstall:true) — the redundant `&& !isTrae` was removed.
  9616. // #2095: kimi is now a hooks/ consumer (native config.toml [[hooks]] bus) —
  9617. // the redundant `&& !isKimi` was removed so its hook files are tracked too.
  9618. // #2099: Copilot's exclusion is likewise descriptor-driven (copilot declares
  9619. // skipSharedHooksInstall:true) — the redundant `&& !isCopilot` was removed.
  9620. // #2100: Windsurf's exclusion is likewise descriptor-driven (windsurf declares
  9621. // skipSharedHooksInstall:true) — the redundant `&& !isWindsurf` was removed.
  9622. if (!isCodex && hostBehaviorsFor(runtime).skipSharedHooksInstall !== true) {
  9623. // #3023: manifest keys must track the bundle wherever the descriptor put it,
  9624. // or uninstall/saveLocalPatches silently orphan the tree.
  9625. const sharedHooksDirName = resolveSharedHooksDirName(runtime);
  9626. const hooksDir = path.join(configDir, sharedHooksDirName);
  9627. if (fs.existsSync(hooksDir)) {
  9628. // Drive from INSTALLED_HOOK_FILES (the canonical HOOKS_TO_COPY set from
  9629. // scripts/build-hooks.js) rather than a prefix/extension regex, so the
  9630. // manifest set is structurally identical to the build set. The old regex
  9631. // `file.startsWith('gsd-') && (file.endsWith('.js') || file.endsWith('.sh'))`
  9632. // missed managed-hooks-registry.cjs (wrong prefix, .cjs extension), causing
  9633. // detect-custom-files to flag it as a perpetual false-positive custom file
  9634. // on every /gsd-update. See #941.
  9635. for (const hook of INSTALLED_HOOK_FILES) {
  9636. const hookPath = path.join(hooksDir, hook);
  9637. if (fs.existsSync(hookPath)) {
  9638. manifest.files[sharedHooksDirName + '/' + hook] = fileHash(hookPath);
  9639. }
  9640. }
  9641. // Track hooks/lib/ helpers so saveLocalPatches() can back up user edits
  9642. // to git-cmd.js (validate-commit classifier) and gsd-graphify-rebuild.sh.
  9643. const hooksLibDir = path.join(hooksDir, 'lib');
  9644. if (fs.existsSync(hooksLibDir)) {
  9645. const hookLibNames = new Set(gsdHookLibFiles());
  9646. for (const file of fs.readdirSync(hooksLibDir)) {
  9647. if (hookLibNames.has(file)) {
  9648. manifest.files[sharedHooksDirName + '/lib/' + file] = fileHash(path.join(hooksLibDir, file));
  9649. }
  9650. }
  9651. }
  9652. }
  9653. }
  9654. // Track scripts/changeset/ and scripts/lib/ so saveLocalPatches() can detect drift
  9655. const changesetInstallDir = path.join(configDir, 'scripts', 'changeset');
  9656. if (fs.existsSync(changesetInstallDir)) {
  9657. for (const file of fs.readdirSync(changesetInstallDir)) {
  9658. if (file.endsWith('.cjs')) {
  9659. manifest.files['scripts/changeset/' + file] = fileHash(path.join(changesetInstallDir, file));
  9660. }
  9661. }
  9662. }
  9663. const scriptsLibInstallDir = path.join(configDir, 'scripts', 'lib');
  9664. if (fs.existsSync(scriptsLibInstallDir)) {
  9665. for (const file of fs.readdirSync(scriptsLibInstallDir)) {
  9666. if (file.endsWith('.cjs')) {
  9667. manifest.files['scripts/lib/' + file] = fileHash(path.join(scriptsLibInstallDir, file));
  9668. }
  9669. }
  9670. }
  9671. // Track scripts/fix-slash-commands.cjs (top-level scripts/ file, not covered by changeset/lib loops)
  9672. const fixSlashInstallPath = path.join(configDir, 'scripts', 'fix-slash-commands.cjs');
  9673. if (fs.existsSync(fixSlashInstallPath)) {
  9674. manifest.files['scripts/fix-slash-commands.cjs'] = fileHash(fixSlashInstallPath);
  9675. }
  9676. // Track the capability registry generator scripts (#1920) — top-level scripts/ files
  9677. // not covered by the changeset/lib loops.
  9678. for (const gen of ['gen-capability-registry.cjs', 'gen-loop-host-contract.cjs']) {
  9679. const genInstallPath = path.join(configDir, 'scripts', gen);
  9680. if (fs.existsSync(genInstallPath)) {
  9681. manifest.files['scripts/' + gen] = fileHash(genInstallPath);
  9682. }
  9683. }
  9684. // Track the OpenCode native plugin adapter (#1914) so update/drift detection
  9685. // and uninstall can account for it.
  9686. const _npM = hostBehaviorsFor(runtime).nativePlugin;
  9687. if (_npM) {
  9688. const pluginInstallPath = path.join(configDir, _npM.dir, _npM.file);
  9689. if (fs.existsSync(pluginInstallPath)) {
  9690. manifest.files[`${_npM.dir}/${_npM.file}`] = fileHash(pluginInstallPath);
  9691. }
  9692. }
  9693. // The OpenCode 2.x terminal-client plugin (statusline / update banner) is tracked beside it.
  9694. const _cliM = hostBehaviorsFor(runtime).nativeCliPlugin;
  9695. if (_cliM) {
  9696. const cliInstallPath = path.join(configDir, _cliM.dir, _cliM.file);
  9697. if (fs.existsSync(cliInstallPath)) {
  9698. manifest.files[`${_cliM.dir}/${_cliM.file}`] = fileHash(cliInstallPath);
  9699. }
  9700. }
  9701. fs.writeFileSync(path.join(configDir, MANIFEST_NAME), JSON.stringify(manifest, null, 2));
  9702. return manifest;
  9703. }
  9704. /**
  9705. * Populate gsd-pristine/ with the transformed pristine versions of every
  9706. * `modified` file, derived from the current package's source tree by
  9707. * running the install transform pipeline (`copyWithPathReplacement`)
  9708. * into a tmp directory, then copying out only the relevant paths.
  9709. *
  9710. * Pristine semantically represents "what the install would write to
  9711. * configDir/<relPath> if the user had not modified it." This is what the
  9712. * /gsd-reapply-patches Step 5 verifier (#2972) uses as the diff base
  9713. * for "user-added lines" — lines in the user's backup that are NOT in
  9714. * the pristine baseline. Without this dir, the verifier degrades to its
  9715. * over-broad fallback ("every significant backup line"), exactly the
  9716. * silent-success-on-lost-content failure mode #2969 was designed to
  9717. * prevent (#2998).
  9718. *
  9719. * Implementation note: we run the FULL transform pipeline against a tmp
  9720. * staging dir (one-time, only when modified.length > 0), then copy out
  9721. * just the modified paths. This re-uses the existing transform code
  9722. * exactly — pristine is byte-identical to what `copyWithPathReplacement`
  9723. * would have written under normal install. Cost: one extra full transform
  9724. * pass per install where local patches were detected; acceptable.
  9725. */
  9726. function populatePristineDir({ packageSrc, pristineDir, modified, runtime, pathPrefix, isGlobal }) {
  9727. if (!modified || modified.length === 0) return 0;
  9728. // Modified paths come from manifest.files which can live under several
  9729. // install roots: gsd-core/, commands/gsd/, command/, skills/, agents/,
  9730. // hooks/, plus runtime-specific root files (#3004 CR). Stage every
  9731. // top-level dir that actually contains a modified path; root-level files
  9732. // are copied directly without the transform pipeline (they don't need
  9733. // path replacement).
  9734. const stageRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-pristine-stage-'));
  9735. let written = 0;
  9736. try {
  9737. const topLevels = new Set();
  9738. const safeModified = [];
  9739. for (const relPath of modified) {
  9740. const norm = normalizeInstallRelativePath(relPath);
  9741. if (!norm) continue;
  9742. safeModified.push(norm);
  9743. const slash = norm.indexOf('/');
  9744. topLevels.add(slash === -1 ? '' : norm.slice(0, slash));
  9745. }
  9746. for (const top of topLevels) {
  9747. if (top === '') {
  9748. // Root-level files — copy directly from package source. The transform
  9749. // pipeline is directory-oriented; root files don't need path-prefix
  9750. // substitution (they're not markdown content with embedded paths).
  9751. for (const relPath of safeModified) {
  9752. const norm = normalizeInstallRelativePath(relPath);
  9753. if (!norm) continue;
  9754. if (norm.includes('/')) continue;
  9755. const srcRef = resolveInstallRelativePath(packageSrc, norm);
  9756. const stagedRef = resolveInstallRelativePath(stageRoot, norm);
  9757. if (!srcRef || !stagedRef || !fs.existsSync(srcRef.fullPath)) continue;
  9758. const stagedFile = stagedRef.fullPath;
  9759. fs.mkdirSync(path.dirname(stagedFile), { recursive: true });
  9760. fs.copyFileSync(srcRef.fullPath, stagedFile);
  9761. }
  9762. continue;
  9763. }
  9764. const srcDir = path.join(packageSrc, top);
  9765. const stageDir = path.join(stageRoot, top);
  9766. if (!fs.existsSync(srcDir)) continue;
  9767. copyWithPathReplacement(srcDir, stageDir, pathPrefix, runtime, false, isGlobal, stageRoot);
  9768. }
  9769. for (const relPath of safeModified) {
  9770. // Only populate pristine for paths we successfully staged. If a path's
  9771. // source dir does not exist (obsolete manifest entry), skip silently
  9772. // rather than corrupting pristine with stale data.
  9773. const stagedRef = resolveInstallRelativePath(stageRoot, relPath);
  9774. const outRef = resolveInstallRelativePath(pristineDir, relPath);
  9775. if (!stagedRef || !outRef || !fs.existsSync(stagedRef.fullPath)) continue;
  9776. fs.mkdirSync(path.dirname(outRef.fullPath), { recursive: true });
  9777. fs.copyFileSync(stagedRef.fullPath, outRef.fullPath);
  9778. written++;
  9779. }
  9780. } finally {
  9781. try { fs.rmSync(stageRoot, { recursive: true, force: true }); } catch { /* best-effort cleanup */ }
  9782. }
  9783. return written;
  9784. }
  9785. /**
  9786. * #4145: recover a pristine baseline from a hash-matching orphan stored at an
  9787. * unexpected path under gsd-pristine/ (e.g. without the gsd-core/ prefix an
  9788. * earlier release's writer dropped).
  9789. *
  9790. * The preserve-check's strict join (pristineDir + manifest-keyed relPath)
  9791. * misses such snapshots, so they were pushed into regeneration from the
  9792. * incoming release — and when the file changed upstream, the candidate's hash
  9793. * could never satisfy the recorded outgoing hash, leaving the correct
  9794. * baseline permanently unconsumed and unpruned (the self-perpetuating state
  9795. * #4145 reports). Hash equality with pristine_hashes is the same authority
  9796. * the #3657 drift guard trusts, so an exact match cannot be the wrong
  9797. * baseline no matter where under gsd-pristine/ it lives.
  9798. *
  9799. * Recovery = relocation: copy the orphan to the canonical manifest-keyed path
  9800. * (hash-verified after the copy) and remove the orphan only once the
  9801. * canonical copy is verified in place. Returns true when the canonical path
  9802. * ended up holding recorded-hash bytes. Never deletes anything it cannot
  9803. * vouch for by hash, and never consumes a path that is the canonical path of
  9804. * ANY manifest file (see canonicalSkip below) — only genuine orphans, which
  9805. * no strict-join reader ever consults, are eligible for removal.
  9806. */
  9807. function recoverOrphanedPristine(pristineDir, relPath, recordedHash, canonicalSkip) {
  9808. if (!recordedHash) return false;
  9809. let orphanRel;
  9810. try {
  9811. // canonicalSkip = the normalized manifest keys: a file already sitting at
  9812. // any canonical path can never be (re-)adopted through the scan. Without
  9813. // this, two modified files sharing byte-identical outgoing content would
  9814. // repeatedly "rescue" each other's canonical away (relocate + delete at
  9815. // its home path) in alternating updates — bytes identical, state unstable.
  9816. // It also keeps drift (#3657) / stale (#3407) territory with the caller.
  9817. orphanRel = gsdFindPristineByHash(pristineDir, recordedHash, canonicalSkip);
  9818. } catch {
  9819. return false;
  9820. }
  9821. if (!orphanRel) return false;
  9822. const outRef = resolveInstallRelativePath(pristineDir, relPath);
  9823. if (!outRef) return false;
  9824. try {
  9825. fs.mkdirSync(path.dirname(outRef.fullPath), { recursive: true });
  9826. fs.copyFileSync(path.join(pristineDir, orphanRel), outRef.fullPath);
  9827. // Verify the relocated copy before removing the orphan — only a
  9828. // hash-matching canonical counts as recovered.
  9829. if (fileHash(outRef.fullPath) !== recordedHash) {
  9830. try { fs.rmSync(outRef.fullPath, { force: true }); } catch { /* best-effort */ }
  9831. return false;
  9832. }
  9833. // Orphan removal is best-effort: the canonical copy is already verified,
  9834. // so a failed unlink leaves a harmless duplicate, never data loss.
  9835. try { fs.rmSync(path.join(pristineDir, orphanRel), { force: true }); } catch { /* best-effort */ }
  9836. return true;
  9837. } catch {
  9838. return false;
  9839. }
  9840. }
  9841. /**
  9842. * #4135: honest N-of-M accounting for gsd-pristine/ baselines after an
  9843. * update. The #3407 promotion rule keeps only hash-validated candidates
  9844. * (byte-identical across the version span), so a multi-version update
  9845. * legitimately ends with near-zero baselines — the collapse itself is NOT a
  9846. * bug to hide; hiding it is. This renders the covered-of-total line the
  9847. * update output prints either way, so "1 of 13" can never present like a
  9848. * fully-covered run. Pure function (typed return) so tests lock the exact
  9849. * contract without matching console prose.
  9850. */
  9851. function describeBaselineCoverage(totalModified, covered) {
  9852. const total = Math.max(0, totalModified);
  9853. const have = Math.min(Math.max(0, covered), total);
  9854. const uncovered = total - have;
  9855. return {
  9856. complete: uncovered === 0,
  9857. uncovered,
  9858. text: uncovered === 0
  9859. ? `gsd-pristine/ baselines cover ${have} of ${total} modified file(s)`
  9860. : `gsd-pristine/ baselines cover ${have} of ${total} modified file(s) — ${uncovered} will be reported no_baseline by the reapply verifier`,
  9861. };
  9862. }
  9863. /**
  9864. * Detect user-modified GSD files by comparing against install manifest.
  9865. * Backs up modified files to gsd-local-patches/ for reapply after update.
  9866. * Also saves pristine copies (from manifest) to gsd-pristine/ to enable
  9867. * three-way merge during reapply-patches (pristine vs user vs new).
  9868. *
  9869. * The optional `pristineCtx` parameter (set by the install entry point)
  9870. * carries the source package root, runtime, pathPrefix, and isGlobal
  9871. * needed to populate gsd-pristine/. If omitted (legacy callers), pristine
  9872. * stays empty — the verifier falls back to its over-broad heuristic, same
  9873. * behavior as before #2998.
  9874. */
  9875. function saveLocalPatches(configDir, pristineCtx) {
  9876. const manifestPath = path.join(configDir, MANIFEST_NAME);
  9877. if (!fs.existsSync(manifestPath)) return [];
  9878. let manifest;
  9879. try { manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); } catch { return []; }
  9880. // Normalize legacy manifests written before #2771 fix: strip user-owned artifacts
  9881. // that were incorrectly recorded so refreshes don't surface false patches warnings.
  9882. if (manifest.files) {
  9883. for (const artifact of USER_OWNED_ARTIFACTS) {
  9884. delete manifest.files[`gsd-core/${artifact}`];
  9885. }
  9886. }
  9887. const patchesDir = path.join(configDir, PATCHES_DIR_NAME);
  9888. const pristineDir = path.join(configDir, 'gsd-pristine');
  9889. const modified = [];
  9890. const pristineHashes = {};
  9891. // #4086: skills/ manifest keys may live OUTSIDE configDir at the runtime's
  9892. // ACTUAL skills root — codex global installs to $HOME/.agents/skills (the
  9893. // ADR-1239 skills-kind `home` override), which writeManifest() already
  9894. // hashes from via _resolveSkillsRootDir (#2088/#3738). Resolving every key
  9895. // against configDir alone made every skills/ key miss here, so user
  9896. // modifications to Codex skills were never hash-compared, never backed up,
  9897. // and were silently overwritten by the next update. configDir stays FIRST
  9898. // (Postel: runtimes whose skills genuinely live under configDir resolve
  9899. // byte-identically to before); the skills root is a fallback, only for keys
  9900. // under the SAME descriptor-driven manifest prefix writeManifest uses, and
  9901. // only when that root resolves outside configDir. Containment + symlink
  9902. // guards apply to the alternate root too (resolveInstallRelativePath).
  9903. const patchRuntime = (pristineCtx && pristineCtx.runtime) || manifest.runtime || null;
  9904. const patchScope = manifest.scope === 'local' ? 'local' : 'global';
  9905. let skillsRedirect = null;
  9906. if (patchRuntime) {
  9907. const skillsRoot = _resolveSkillsRootDir(patchRuntime, configDir, patchScope);
  9908. const resolvedConfig = path.resolve(configDir);
  9909. if (
  9910. skillsRoot &&
  9911. skillsRoot !== resolvedConfig &&
  9912. !skillsRoot.startsWith(resolvedConfig + path.sep)
  9913. ) {
  9914. const prefix = hostBehaviorsFor(patchRuntime).skillsManifestPrefix || 'skills/';
  9915. skillsRedirect = { root: skillsRoot, prefix };
  9916. }
  9917. }
  9918. for (const [relPath, originalHash] of Object.entries(manifest.files || {})) {
  9919. const safeRef = resolveInstallRelativePath(configDir, relPath);
  9920. if (!safeRef) continue;
  9921. const { relPath: safeRelPath, fullPath } = safeRef;
  9922. let installedPath = fullPath;
  9923. if (!fs.existsSync(installedPath) && skillsRedirect && safeRelPath.startsWith(skillsRedirect.prefix)) {
  9924. const altRef = resolveInstallRelativePath(
  9925. skillsRedirect.root,
  9926. safeRelPath.slice(skillsRedirect.prefix.length)
  9927. );
  9928. if (altRef && fs.existsSync(altRef.fullPath)) {
  9929. installedPath = altRef.fullPath;
  9930. }
  9931. }
  9932. if (!fs.existsSync(installedPath)) continue;
  9933. const currentHash = fileHash(installedPath);
  9934. if (currentHash !== originalHash) {
  9935. // Back up the user's modified version
  9936. const backupRef = resolveInstallRelativePath(patchesDir, safeRelPath);
  9937. if (!backupRef) continue;
  9938. const backupPath = backupRef.fullPath;
  9939. fs.mkdirSync(path.dirname(backupPath), { recursive: true });
  9940. fs.copyFileSync(installedPath, backupPath);
  9941. modified.push(safeRelPath);
  9942. pristineHashes[safeRelPath] = originalHash;
  9943. }
  9944. }
  9945. // Save pristine copies of modified files from the CURRENT install (before wipe).
  9946. // Pristine semantically represents "what the install would write to configDir
  9947. // if the user had not modified it" — used by /gsd-reapply-patches Step 5
  9948. // (#2972) as the diff baseline for the user-added-lines computation. Without
  9949. // this dir the verifier degrades to its over-broad fallback heuristic (#2998).
  9950. if (modified.length > 0) {
  9951. const meta = {
  9952. backed_up_at: new Date().toISOString(),
  9953. from_version: manifest.version,
  9954. from_manifest_timestamp: manifest.timestamp,
  9955. files: modified,
  9956. pristine_hashes: {}
  9957. };
  9958. // Record the original (pristine) hash for each modified file
  9959. // This lets the reapply workflow verify reconstructed pristine files
  9960. for (const relPath of modified) {
  9961. meta.pristine_hashes[relPath] = pristineHashes[relPath];
  9962. }
  9963. fs.writeFileSync(path.join(patchesDir, 'backup-meta.json'), JSON.stringify(meta, null, 2));
  9964. console.log(' ' + yellow + 'i' + reset + ' Found ' + modified.length + ' locally modified GSD file(s) — backed up to ' + PATCHES_DIR_NAME + '/');
  9965. for (const f of modified) {
  9966. console.log(' ' + dim + f + reset);
  9967. }
  9968. // #2998 / #3407: maintain gsd-pristine/ as the diff baseline for the
  9969. // reapply-patches verifier (#2972).
  9970. //
  9971. // #3407 root-cause fix: the prior approach (#3004 CR) wiped gsd-pristine/
  9972. // and re-populated it from pristineCtx.packageSrc (the NEW release source).
  9973. // For files that changed between the old and new release this wrote NEW-
  9974. // release bytes as the pristine baseline while backup-meta.json recorded
  9975. // OLD-release hashes — a hash mismatch that caused the #3657 verifier guard
  9976. // (OK_PRISTINE_DRIFT_DETECTED) to skip the baseline and fall back to over-
  9977. // broad mode on every upgrade.
  9978. //
  9979. // Correct approach: `gsd-pristine/` is populated lazily by saveLocalPatches'
  9980. // regenerate branch (not by a separate install-time step); the fix works by
  9981. // induction across upgrades — each clean upgrade persists hash-validated
  9982. // entries for the next run. During this call we must PRESERVE entries whose
  9983. // hash matches originalHash, not overwrite them with new-release bytes.
  9984. //
  9985. // Per-file decision:
  9986. // - sha256(gsd-pristine/X) === originalHash → correct; keep it
  9987. // - gsd-pristine/X exists but hash mismatch → stale from a previous
  9988. // buggy run (#3407); remove so verifier falls back cleanly
  9989. // - gsd-pristine/X absent → attempt hash-validated
  9990. // regeneration: generate candidate from new-release source; if
  9991. // sha256(candidate) === originalHash the file is identical between
  9992. // old and new releases so candidate bytes ARE the old-release pristine
  9993. // and can be used; discard otherwise (over-broad fallback)
  9994. if (pristineCtx) {
  9995. let preserved = 0;
  9996. // Track which relPaths had stale pristine entries (hash mismatch) that we
  9997. // removed. After the regeneration pass we compute `removed` = stale entries
  9998. // that could NOT be recovered (over-broad fallback applies to those only).
  9999. const stalePaths = new Set();
  10000. // Track which relPaths were successfully regenerated (from either missing or stale).
  10001. const regeneratedPaths = new Set();
  10002. // #4145: track which relPaths were recovered by relocating a hash-matching
  10003. // orphan (stored at an unexpected path, e.g. without the gsd-core/ prefix).
  10004. const rescuedPaths = new Set();
  10005. // #4145: the set of paths that are SOME file's canonical pristine path
  10006. // (every normalized manifest key). The orphan scan must never consume
  10007. // these — see recoverOrphanedPristine.
  10008. const canonicalSkip = new Set(
  10009. Object.keys(manifest.files || {}).map((k) => normalizeInstallRelativePath(k)).filter(Boolean),
  10010. );
  10011. const missingPaths = [];
  10012. for (const relPath of modified) {
  10013. const outRef = resolveInstallRelativePath(pristineDir, relPath);
  10014. if (!outRef) continue;
  10015. const { fullPath: pristinePath } = outRef;
  10016. if (fs.existsSync(pristinePath)) {
  10017. try {
  10018. const onDiskHash = fileHash(pristinePath);
  10019. if (onDiskHash === pristineHashes[relPath]) {
  10020. preserved++;
  10021. continue; // correct old-release bytes already in place — keep them
  10022. }
  10023. } catch { /* read error — treat as mismatch */ }
  10024. // Hash mismatch or read error: stale pristine from a previous buggy
  10025. // run (#3407). Remove so verifier falls back to over-broad mode.
  10026. try { fs.rmSync(pristinePath, { force: true, recursive: true }); } catch { /* best-effort */ }
  10027. // Only count as removed if the file is actually gone post-removal.
  10028. if (!fs.existsSync(pristinePath)) {
  10029. stalePaths.add(relPath);
  10030. }
  10031. }
  10032. // #4145: canonical absent (or just removed as stale) — before falling
  10033. // into regeneration, try to recover the baseline from a hash-matching
  10034. // orphan elsewhere under gsd-pristine/ and relocate it to the canonical
  10035. // path. This is the self-heal for snapshots an earlier release stored
  10036. // without the gsd-core/ prefix: without it the state repeats forever
  10037. // (regeneration candidates from the incoming release can never satisfy
  10038. // the recorded outgoing hash when upstream changed the file).
  10039. if (recoverOrphanedPristine(pristineDir, relPath, pristineHashes[relPath], canonicalSkip)) {
  10040. rescuedPaths.add(relPath);
  10041. continue;
  10042. }
  10043. // File absent from gsd-pristine/ (or just removed above as stale):
  10044. // attempt hash-validated regeneration from new-release source.
  10045. missingPaths.push(relPath);
  10046. }
  10047. // Regenerate missing entries into a temp dir, then validate each hash
  10048. // before promoting. Only files whose new-release generated bytes hash to
  10049. // originalHash are safe to use — they were unchanged between releases.
  10050. if (missingPaths.length > 0) {
  10051. let tempPristineDir = null;
  10052. try {
  10053. tempPristineDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-pristine-regen-'));
  10054. populatePristineDir({
  10055. packageSrc: pristineCtx.packageSrc,
  10056. pristineDir: tempPristineDir,
  10057. modified: missingPaths,
  10058. runtime: pristineCtx.runtime,
  10059. pathPrefix: pristineCtx.pathPrefix,
  10060. isGlobal: pristineCtx.isGlobal,
  10061. });
  10062. for (const relPath of missingPaths) {
  10063. const tempRef = resolveInstallRelativePath(tempPristineDir, relPath);
  10064. const outRef = resolveInstallRelativePath(pristineDir, relPath);
  10065. if (!tempRef || !outRef || !fs.existsSync(tempRef.fullPath)) continue;
  10066. try {
  10067. const candidateHash = fileHash(tempRef.fullPath);
  10068. if (candidateHash !== pristineHashes[relPath]) continue; // new-release differs — discard
  10069. fs.mkdirSync(path.dirname(outRef.fullPath), { recursive: true });
  10070. fs.copyFileSync(tempRef.fullPath, outRef.fullPath);
  10071. regeneratedPaths.add(relPath);
  10072. } catch { /* hash or copy error — skip; over-broad fallback applies */ }
  10073. }
  10074. } catch (err) {
  10075. // Match the pre-fix behavior: log a warning and continue (verifier falls back to over-broad mode for missing files).
  10076. console.warn(`gsd-pristine regen skipped: ${err.message}`);
  10077. } finally {
  10078. if (tempPristineDir) {
  10079. try { fs.rmSync(tempPristineDir, { recursive: true, force: true }); } catch { /* best-effort */ }
  10080. }
  10081. }
  10082. }
  10083. // `regenerated` = total files successfully regenerated (from missing OR stale).
  10084. const regenerated = regeneratedPaths.size;
  10085. // `rescued` = files recovered by relocating a hash-matching orphan to its
  10086. // canonical path (#4145) — distinct from preservation (canonical already
  10087. // correct) and regeneration (bytes re-derived from new-release source).
  10088. const rescued = rescuedPaths.size;
  10089. // `removed` = stale entries that were deleted and NOT subsequently regenerated.
  10090. // Entries that were stale-deleted but then successfully regenerated are counted
  10091. // only in `regenerated`; stale-deleted-then-orphan-rescued entries are counted
  10092. // only in `rescued` — the counts are non-overlapping.
  10093. const removed = [...stalePaths].filter(p => !regeneratedPaths.has(p) && !rescuedPaths.has(p)).length;
  10094. if (preserved > 0) {
  10095. console.log(' ' + green + '✓' + reset + ' Preserved ' + cyan + 'gsd-pristine/' + reset + ' (' + preserved + ' file(s)) for three-way merge');
  10096. }
  10097. if (rescued > 0) {
  10098. console.log(' ' + green + '✓' + reset + ' Recovered ' + cyan + 'gsd-pristine/' + reset + ' (' + rescued + ' file(s)) by recorded hash from a legacy-path snapshot and relocated them (#4145)');
  10099. }
  10100. if (regenerated > 0) {
  10101. console.log(' ' + green + '✓' + reset + ' Regenerated ' + cyan + 'gsd-pristine/' + reset + ' (' + regenerated + ' file(s)) via hash-validated new-release source');
  10102. }
  10103. if (removed > 0) {
  10104. console.log(' ' + yellow + 'i' + reset + ' Removed ' + removed + ' stale gsd-pristine/ snapshot(s); regenerated ' + regenerated + ' of those — falls back to over-broad verify heuristic for the rest');
  10105. }
  10106. // #4135: the honest N-of-M coverage line. Preserved/rescued/regenerated
  10107. // are disjoint buckets (see their accounting comments above), so their
  10108. // sum is exactly the files that ended this update with a hash-valid
  10109. // baseline. A partial result renders as an info line, not an error:
  10110. // the collapse is legitimate (#3407), hiding it was the bug.
  10111. const coverage = describeBaselineCoverage(modified.length, preserved + rescued + regenerated);
  10112. if (coverage.complete) {
  10113. console.log(' ' + green + '✓' + reset + ' ' + coverage.text);
  10114. } else {
  10115. console.log(' ' + yellow + 'i' + reset + ' ' + coverage.text);
  10116. }
  10117. }
  10118. }
  10119. return modified;
  10120. }
  10121. /**
  10122. * After install, report backed-up patches for user to reapply.
  10123. */
  10124. function reportLocalPatches(configDir, runtime = DEFAULT_RUNTIME) {
  10125. const patchesDir = path.join(configDir, PATCHES_DIR_NAME);
  10126. const metaPath = path.join(patchesDir, 'backup-meta.json');
  10127. if (!fs.existsSync(metaPath)) return [];
  10128. let meta;
  10129. try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf8')); } catch { return []; }
  10130. if (meta.files && meta.files.length > 0) {
  10131. const reapplyCommand = hostBehaviorsFor(runtime).reapplyCommand || '/gsd-update --reapply';
  10132. console.log('');
  10133. const fromLabel = meta.from_version ? ' (from v' + meta.from_version + ')' : ' (from a first install)';
  10134. console.log(' ' + yellow + 'Local patches detected' + reset + fromLabel + ':');
  10135. for (const f of meta.files) {
  10136. console.log(' ' + cyan + f + reset);
  10137. }
  10138. console.log('');
  10139. console.log(' Your modifications are saved in ' + cyan + PATCHES_DIR_NAME + '/' + reset);
  10140. console.log(' Run ' + cyan + reapplyCommand + reset + ' to merge them into the new version.');
  10141. console.log(' Or manually compare and merge the files.');
  10142. console.log('');
  10143. }
  10144. return meta.files || [];
  10145. }
  10146. /**
  10147. * #5522: the first-time baseline reports a user's `skills/gsd-<stem>/SKILL.md` as preserved, but the
  10148. * skills writer owns a dir by its first-party name and replaces it. Before the writers run, set aside a copy of
  10149. * every baseline-preserved file in the shipped-name namespaces (bounded to BASELINE_SNAPSHOT_MAX_BYTES) in
  10150. * gsd-migration-backups/ — an installer-internal dir, so it can never collide with a user's existing
  10151. * gsd-local-patches/ content — so the user's content is on disk before anything can replace it.
  10152. * backUpReplacedBaselineFiles then moves the copies of replaced files into gsd-local-patches/.
  10153. * Returns Map<relPath, { fullPath, content, stagedPath }>.
  10154. */
  10155. const BASELINE_SNAPSHOT_MAX_BYTES = 1024 * 1024;
  10156. const BASELINE_SNAPSHOT_DIR = path.join('gsd-migration-backups', 'first-install-5522');
  10157. const SHIPPED_NAME_NAMESPACE = /^(skills|commands?)\/gsd([-/]|$)/;
  10158. function snapshotBaselinePreservedFiles(configDir, migrationResult) {
  10159. const snapshots = new Map();
  10160. const plan = migrationResult && migrationResult.plan;
  10161. const actions = plan && Array.isArray(plan.actions) ? plan.actions : [];
  10162. const stagingDir = path.join(configDir, BASELINE_SNAPSHOT_DIR);
  10163. for (const action of actions) {
  10164. if (!action || action.type !== 'baseline-preserve-user' || typeof action.relPath !== 'string') continue;
  10165. const ref = resolveInstallRelativePath(configDir, action.relPath);
  10166. if (!ref || !SHIPPED_NAME_NAMESPACE.test(ref.relPath)) continue;
  10167. try {
  10168. const st = fs.lstatSync(ref.fullPath);
  10169. if (!st.isFile()) continue;
  10170. if (st.size > BASELINE_SNAPSHOT_MAX_BYTES) {
  10171. console.warn(` ${yellow}⚠${reset} ${action.relPath} is larger than ${BASELINE_SNAPSHOT_MAX_BYTES} bytes, so it is not copied aside; if the install replaces it, the original is not kept`);
  10172. continue;
  10173. }
  10174. const content = fs.readFileSync(ref.fullPath);
  10175. const stagedRef = resolveInstallRelativePath(stagingDir, ref.relPath);
  10176. if (!stagedRef) continue;
  10177. fs.mkdirSync(path.dirname(stagedRef.fullPath), { recursive: true });
  10178. fs.writeFileSync(stagedRef.fullPath, content);
  10179. snapshots.set(ref.relPath, { fullPath: ref.fullPath, content, stagedPath: stagedRef.fullPath });
  10180. } catch (err) {
  10181. console.warn(` ${yellow}⚠${reset} Could not set aside ${action.relPath} before install (${err.message}); if the install replaces it, the original is not kept`);
  10182. }
  10183. }
  10184. return snapshots;
  10185. }
  10186. /**
  10187. * #5522: after the artifact writers ran, a snapshotted file that is gone or different was replaced. Its
  10188. * pre-install copy moves into gsd-local-patches/ (next to, never over, an existing backup) and is recorded in
  10189. * backup-meta.json, so the standard "Local patches detected" report names it as it does on the update path.
  10190. * The staging dir is always removed. Never throws: bookkeeping must not abort the install.
  10191. * Returns [{ relPath, backupRel }] for the files kept.
  10192. */
  10193. function backUpReplacedBaselineFiles(configDir, snapshots) {
  10194. const replaced = [];
  10195. const patchesDir = path.join(configDir, PATCHES_DIR_NAME);
  10196. for (const [relPath, snap] of snapshots) {
  10197. let current = null;
  10198. try { current = fs.readFileSync(snap.fullPath); } catch { current = null; }
  10199. if (current !== null && current.equals(snap.content)) continue;
  10200. try {
  10201. let backupRel = relPath;
  10202. if (fs.existsSync(path.join(patchesDir, backupRel))) backupRel = `${relPath}.first-install`;
  10203. const backupRef = resolveInstallRelativePath(patchesDir, backupRel);
  10204. if (!backupRef) throw new Error('backup path escapes the config dir');
  10205. fs.mkdirSync(path.dirname(backupRef.fullPath), { recursive: true });
  10206. fs.writeFileSync(backupRef.fullPath, snap.content);
  10207. replaced.push({ relPath, backupRel });
  10208. } catch (err) {
  10209. console.warn(` ${yellow}⚠${reset} Could not back up ${relPath} to ${PATCHES_DIR_NAME}/ (${err.message}); the original is kept in ${BASELINE_SNAPSHOT_DIR}/`);
  10210. return replaced;
  10211. }
  10212. }
  10213. if (replaced.length > 0) {
  10214. try {
  10215. const metaPath = path.join(patchesDir, 'backup-meta.json');
  10216. let meta = {};
  10217. try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf8')) || {}; } catch { meta = {}; }
  10218. const files = Array.from(new Set([...(Array.isArray(meta.files) ? meta.files : []), ...replaced.map((r) => r.backupRel)]));
  10219. fs.writeFileSync(metaPath, JSON.stringify({
  10220. ...meta,
  10221. backed_up_at: new Date().toISOString(),
  10222. from_version: meta.from_version ?? null,
  10223. files,
  10224. pristine_hashes: { ...(meta.pristine_hashes || {}) },
  10225. }, null, 2));
  10226. } catch (err) {
  10227. console.warn(` ${yellow}⚠${reset} Could not record ${PATCHES_DIR_NAME}/backup-meta.json (${err.message}); your copies are in ${PATCHES_DIR_NAME}/`);
  10228. }
  10229. }
  10230. try { fs.rmSync(path.join(configDir, BASELINE_SNAPSHOT_DIR), { recursive: true, force: true }); } catch { /* leftover is harmless */ }
  10231. return replaced;
  10232. }
  10233. /** relPaths in the snapshot whose name is a shipped skill/command the writers will lay down (#5522). */
  10234. function predictShippedNameReplacements(snapshots, skillsManifest) {
  10235. const out = [];
  10236. for (const relPath of snapshots.keys()) {
  10237. const m = /^skills\/gsd-([^/]+)\//.exec(relPath) || /^commands?\/gsd\/([^/]+?)\.md$/.exec(relPath);
  10238. if (m && skillsManifest.has(m[1])) out.push(relPath);
  10239. }
  10240. return out;
  10241. }
  10242. /** A copy of the migration result without the baseline-preserve rows for paths the install replaced (#5522). */
  10243. function withoutReplacedBaselineFiles(migrationResult, replaced) {
  10244. if (!replaced || replaced.length === 0 || !migrationResult || !migrationResult.plan) return migrationResult;
  10245. const norm = (p) => String(p).replace(/\\/g, '/').replace(/^\/+/, '');
  10246. const gone = new Set(replaced.map((r) => norm(r.relPath)));
  10247. const actions = (migrationResult.plan.actions || []).filter((a) => !(a && a.type === 'baseline-preserve-user' && gone.has(norm(a.relPath))));
  10248. return { ...migrationResult, plan: { ...migrationResult.plan, actions } };
  10249. }
  10250. function reportInstallerMigrationResult(result) {
  10251. const summary = summarizeInstallerMigrationResult(result);
  10252. if (!summary.hasReportableActions) return;
  10253. console.log(` ${green}✓${reset} Installer migrations`);
  10254. for (const row of summary.rows) {
  10255. const reason = row.reason ? ` — ${row.reason}` : '';
  10256. console.log(` ${row.label} ${dim}${row.relPath}${reset}${reason}`);
  10257. }
  10258. }
  10259. function install(isGlobal, runtime = DEFAULT_RUNTIME, options = {}) {
  10260. // #2093: isKilo dropped — Kilo's agent/model-override handling below reads
  10261. // hostBehaviorsFor(runtime).frontmatterDialect === 'kilo' instead of this flag.
  10262. // #2095: isKimi dropped — kimi is now a hooks/ consumer like every other
  10263. // settings-json-adjacent runtime; the two `&& !isKimi` hooks-copy guards
  10264. // below were removed, leaving isKimi unused in this function (the kimi
  10265. // local-install-deferred branch above already reads
  10266. // hostBehaviorsFor(runtime).localInstallDeferred instead of this flag).
  10267. // #2096: isAntigravity dropped — antigravity's agents were already
  10268. // descriptor-driven (installRuntimeArtifacts), so its two legacy-agent-loop
  10269. // branches (the path-rewrite skip and the converter dispatch) were
  10270. // unreachable dead code; both were removed rather than re-gated on
  10271. // hostBehaviors. (#2875 Part 2 later deleted that legacy loop and its
  10272. // `_DESCRIPTOR_AGENTS_RUNTIMES` gate entirely — EVERY runtime is now
  10273. // descriptor-driven for agents, not just this subset.)
  10274. // #2098: isCodebuddy dropped — codebuddy's agents were likewise already
  10275. // descriptor-dr
hooks/gsd-windsurf-pre-command.js · Bundled script · 280 lines · 4 findings marked
  1. #!/usr/bin/env node
  2. // gsd-hook-version: {{GSD_VERSION}}
  3. // gsd-windsurf-pre-command.js — Windsurf/Cascade pre_run_command hook (ADR-1239 / #2100)
  4. //
  5. // Cascade (Windsurf's agent) invokes this script before each shell-command
  6. // tool call executes, via the workspace/global hooks.json hook bus.
  7. //
  8. // Input schema (Cascade pre_run_command envelope, JSON on stdin):
  9. // { agent_action_name: 'pre_run_command', trajectory_id, execution_id,
  10. // timestamp, model_name,
  11. // tool_info: { command_line } }
  12. //
  13. // Decision protocol — DISTINCT from Cursor's stdout-JSON form:
  14. // - exit 0 -> allow the command to run (no stdout contract)
  15. // - exit 2 -> BLOCK the command; the printed stderr text is the reason
  16. // shown to the agent/user
  17. //
  18. // Behaviour: blocks a small, CONSERVATIVE, well-scoped, BEST-EFFORT deny-list
  19. // of obviously destructive commands. This is intentionally not exhaustive —
  20. // a broad deny-list would false-positive on legitimate agent/tooling work,
  21. // and Cascade honors exit 2 unconditionally, so a false positive blocks the
  22. // user's real work. When in doubt, this script allows:
  23. // - a fork-bomb pattern
  24. // - `rm -rf` (or equivalent combined/long flags), including through common
  25. // prefixed forms (`sudo rm -rf /`, `/bin/rm -rf /`, `env FOO=1 rm -rf /`),
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 25 on GitHub
  26. // targeting the filesystem root, the user's home directory, or a Windows
  27. // drive root/profile root
  28. // - `git push` with a force flag (`-f`/`--force`/`--force-with-lease`) or a
  29. // `+`-prefixed refspec, explicitly targeting a protected branch
  30. // (main / master / next) as the push destination — not merely mentioning
  31. // that name elsewhere in a longer branch name or a trailing comment
  32. // Everything else — including force-pushes to feature branches and `rm -rf`
  33. // against ordinary project subdirectories — is intentionally left alone.
  34. // Fails OPEN on any error, timeout, or unrecognized shape — a hook bug must
  35. // never wedge Cascade.
  36. //
  37. // Classification is TOKENIZE-based (split into shell segments, then
  38. // whitespace-split tokens), not a single mega-regex over the raw string —
  39. // this keeps every check linear in input length. `command_line` longer than
  40. // MAX_COMMAND_LENGTH is allowed outright before any pattern matching runs:
  41. // no realistic destructive command is anywhere near that long, so the cap
  42. // both fails open on pathological input and bounds the worst-case cost of
  43. // every classifier below (defense-in-depth against regex-based DoS).
  44. //
  45. // Cascade hooks docs (reference): https://docs.windsurf.com/llms-full.txt ,
  46. // https://docs.devin.ai/desktop/cascade/hooks
  47. 'use strict';
  48. const { allow, deny } = require('./lib/hook-exit.js');
  49. // #3911 (ADR-3889 Phase 7): the exit(2) call site (block(), below) is
  50. // migrated to hook-exit.js's deny(undefined, reason) now that
  51. // hooks/lib/cli-exit.js's terminateNow emits fd 1 and fd 2 (stderrPayload)
  52. // in INDEPENDENT try/catch blocks — `payload=undefined` cleanly skips the
  53. // fd 1 write (preserving "nothing written to stdout") instead of throwing
  54. // into a shared catch that used to also swallow the fd 2 write, which is
  55. // what silently dropped the deny reason before this fix.
  56. // No realistic destructive command comes anywhere close to this length.
  57. const MAX_COMMAND_LENGTH = 4096;
  58. // Classic bash fork bomb: `:(){ :|:& };:`
    • Note: Quoted as data in code: Matches a classic shell fork-bomb pattern
    • Line 63 on GitHub
  59. const FORK_BOMB_RE = /:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/;
  60. // Command-prefix wrappers to look through when locating the "real" command at
  61. // the head of a segment: `sudo rm -rf /`, `/bin/rm -rf /` (basename strip),
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 67 on GitHub
  62. // `env FOO=1 rm -rf /` (env's leading VAR=val args are skipped too).
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 68 on GitHub
  63. const CMD_PREFIXES = new Set(['sudo', 'env', 'command', 'nice', 'nohup', 'time', 'doas']);
  64. // Bare filesystem-root-class tokens for `rm`'s target. Ordinary paths like
  65. // `/tmp/foo` or `/home/user/project` never match this set.
  66. const ROOT_SENTINELS = new Set(['/', '/*', '~', '~/', '$HOME', '${HOME}']);
  67. const PROTECTED_BRANCHES = new Set(['main', 'master', 'next']);
  68. // ---------------------------------------------------------------------------
  69. // Tokenizing helpers
  70. // ---------------------------------------------------------------------------
  71. // Split a command line into shell segments on `;`, `&&`, `||`, `|`, newline —
  72. // each segment is classified independently.
  73. function splitSegments(cmd) {
  74. return cmd.split(/\|\||&&|[;\n|]/);
  75. }
  76. // A `#` starts a bash comment when it's the first character of a "word"
  77. // (preceded by whitespace, or at the very start of the segment). Strip it
  78. // before classifying, so a comment mentioning a protected branch name never
  79. // counts as a real command argument.
  80. function stripBashComment(segment) {
  81. const m = segment.match(/(^|\s)#/);
  82. if (!m) return segment;
  83. const idx = m.index + m[1].length;
  84. return segment.slice(0, idx).replace(/\s+$/, '');
  85. }
  86. function tokenize(segment) {
  87. return segment.split(/\s+/).filter(Boolean);
  88. }
  89. // Strip any directory path from a token: `/bin/rm` -> `rm`.
  90. function basename(tok) {
  91. const parts = tok.split(/[\\/]/);
  92. return parts[parts.length - 1] || tok;
  93. }
  94. // Find the index of the "real" command token in a token list, skipping past
  95. // known command-prefix wrappers (and, for `env`, its leading VAR=val args).
  96. function indexOfCommandAfterPrefixes(tokens) {
  97. let i = 0;
  98. while (i < tokens.length) {
  99. const base = basename(tokens[i]).toLowerCase();
  100. if (!CMD_PREFIXES.has(base)) return i;
  101. const wasEnv = base === 'env';
  102. i++;
  103. if (wasEnv) {
  104. while (i < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[i])) i++;
  105. }
  106. }
  107. return i;
  108. }
  109. // True if `tokens` contains a flag matching either the exact long form, or a
  110. // combined/short `-xyz` cluster containing `shortChar` (e.g. `-rf`, `-fr`,
  111. // `-r`). A single `[a-zA-Z]+` quantifier with no nested ambiguity — linear,
  112. // no catastrophic backtracking regardless of token length.
  113. function hasFlag(tokens, shortChar, longFlag) {
  114. return tokens.some((t) => {
  115. if (t === longFlag) return true;
  116. if (t.length > 1 && t[0] === '-' && t[1] !== '-' && /^[a-zA-Z]+$/.test(t.slice(1))) {
  117. return t.slice(1).toLowerCase().includes(shortChar);
  118. }
  119. return false;
  120. });
  121. }
  122. function isRootSentinel(tok) {
  123. if (ROOT_SENTINELS.has(tok)) return true;
  124. // Bare Windows drive root: `C:\` or `C:/`.
  125. if (/^[A-Za-z]:[\\/]$/.test(tok)) return true;
  126. return false;
  127. }
  128. // ---------------------------------------------------------------------------
  129. // Classifiers (each operates on one already comment-stripped segment)
  130. // ---------------------------------------------------------------------------
  131. // `rm` (any flag order/spelling, optionally through `sudo`/`env FOO=1`/an
  132. // absolute path/etc.) with BOTH a recursive flag and a force flag, targeting
  133. // a bare filesystem-root-class token.
  134. function isDestructiveRmRf(segment) {
  135. const tokens = tokenize(segment);
  136. const cmdIdx = indexOfCommandAfterPrefixes(tokens);
  137. if (cmdIdx >= tokens.length) return null;
  138. if (basename(tokens[cmdIdx]) !== 'rm') return null;
  139. const args = tokens.slice(cmdIdx + 1);
  140. const hasRecursive = hasFlag(args, 'r', '--recursive');
  141. const hasForce = hasFlag(args, 'f', '--force');
  142. if (!hasRecursive || !hasForce) return null;
  143. const rootTok = args.find(isRootSentinel);
  144. if (rootTok) return `rm -rf targeting the filesystem root or home directory ('${rootTok}')`;
  145. return null;
  146. }
  147. function isWindowsRootSentinel(tok) {
  148. if (/^[A-Za-z]:\\?$/.test(tok)) return true;
  149. if (/^\$env:userprofile\\?$/i.test(tok)) return true;
  150. if (/^~\\?$/.test(tok)) return true;
  151. return false;
  152. }
  153. function isWindowsDriveRoot(tok) {
  154. return /^[A-Za-z]:\\?$/.test(tok);
  155. }
  156. // Windows equivalents: `Remove-Item -Recurse -Force <drive-root|profile-root>`
  157. // and `rd /s /q <drive-root>` / `rmdir /s /q <drive-root>`.
  158. function isDestructiveWindowsRmRf(segment) {
  159. const tokens = tokenize(segment);
  160. if (tokens.length === 0) return null;
  161. const first = basename(tokens[0]).toLowerCase();
  162. const rest = tokens.slice(1);
  163. if (first === 'remove-item') {
  164. const hasRecurse = rest.some((t) => t.toLowerCase() === '-recurse');
  165. const hasForce = rest.some((t) => t.toLowerCase() === '-force');
  166. if (hasRecurse && hasForce && rest.some(isWindowsRootSentinel)) {
  167. return 'Remove-Item -Recurse -Force targeting a drive root or user-profile root';
  168. }
  169. return null;
  170. }
  171. if (first === 'rd' || first === 'rmdir') {
  172. const hasS = rest.some((t) => t.toLowerCase() === '/s');
  173. const hasQ = rest.some((t) => t.toLowerCase() === '/q');
  174. if (hasS && hasQ) {
  175. const rootTok = rest.find(isWindowsDriveRoot);
  176. if (rootTok) return `rd /s /q targeting drive root '${rootTok}'`;
  177. }
  178. return null;
  179. }
  180. return null;
  181. }
  182. function isForceToken(tok) {
  183. if (tok === '--force' || tok === '-f') return true;
  184. if (/^--force-with-lease(=.*)?$/i.test(tok)) return true;
  185. if (tok.startsWith('+')) return true;
  186. return false;
  187. }
  188. // Resolve the branch a push-argument token targets, honoring `+<dst>` and
  189. // `<src>:<dst>` refspec forms and an optional `refs/heads/` prefix. Returns
  190. // the lower-cased protected branch name, or null. Whole-token comparison
  191. // only — `feature/main-fix` never matches `main`.
  192. function protectedTargetFromToken(tok) {
  193. let t = tok;
  194. if (t.startsWith('+')) t = t.slice(1);
  195. const colonIdx = t.lastIndexOf(':');
  196. const candidate = colonIdx !== -1 ? t.slice(colonIdx + 1) : t;
  197. const stripped = candidate.replace(/^refs\/heads\//i, '');
  198. const lower = stripped.toLowerCase();
  199. return PROTECTED_BRANCHES.has(lower) ? lower : null;
  200. }
  201. // `git push` with a force flag/refspec AND an explicit protected-branch push
  202. // target (main / master / next — see scripts/setup-branch-protection.sh).
  203. function isProtectedBranchForcePush(segment) {
  204. const tokens = tokenize(segment);
  205. for (let i = 0; i < tokens.length - 1; i++) {
  206. if (tokens[i].toLowerCase() === 'git' && tokens[i + 1].toLowerCase() === 'push') {
  207. const rest = tokens.slice(i + 2);
  208. if (!rest.some(isForceToken)) return null;
  209. for (const tok of rest) {
  210. const target = protectedTargetFromToken(tok);
  211. if (target) return `git push --force targeting protected branch '${target}'`;
  212. }
  213. return null;
  214. }
  215. }
  216. return null;
  217. }
  218. function destructiveReason(cmd) {
  219. if (FORK_BOMB_RE.test(cmd)) return 'fork-bomb pattern';
  220. for (const rawSegment of splitSegments(cmd)) {
  221. const segment = stripBashComment(rawSegment).trim();
  222. if (!segment) continue;
  223. const reason = isDestructiveRmRf(segment)
  224. || isDestructiveWindowsRmRf(segment)
  225. || isProtectedBranchForcePush(segment);
  226. if (reason) return reason;
  227. }
  228. return null;
  229. }
  230. function block(reason) {
  231. deny(undefined, `GSD windsurf pre_run_command guard: ${reason}\n`);
  232. }
  233. let input = '';
  234. const stdinTimeout = setTimeout(() => allow(undefined), 10000);
  235. process.stdin.setEncoding('utf8');
  236. process.stdin.on('data', (chunk) => { input += chunk; });
  237. process.stdin.on('end', () => {
  238. clearTimeout(stdinTimeout);
  239. try {
  240. const data = JSON.parse(input || '{}');
  241. const toolInfo = (data && typeof data.tool_info === 'object' && data.tool_info) || {};
  242. const commandLine = typeof toolInfo.command_line === 'string' ? toolInfo.command_line : '';
  243. if (!commandLine) { allow(undefined); return; }
  244. if (commandLine.length > MAX_COMMAND_LENGTH) { allow(undefined); return; }
  245. const reason = destructiveReason(commandLine);
  246. if (reason) { block(reason); return; }
  247. allow(undefined);
  248. } catch {
  249. // Silent fail-open — never block a valid tool call due to a hook bug.
  250. allow(undefined);
  251. }
  252. });

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.