Merge branch 'next' into feat/1346-enhance-verify-phase-project-a-check-vio

This commit is contained in:
Rezolv
2026-06-21 17:41:37 -04:00
committed by GitHub
29 changed files with 1454 additions and 129 deletions

View File

@@ -0,0 +1,5 @@
---
type: Fixed
pr: 1537
---
**Non-Claude runtime installs now resolve their own runtime and never attempt Claude-only worktree isolation** — on any non-Claude install (Cursor, Gemini, Qwen, etc.) a runtime-neutral `.planning/config.json` previously resolved `runtime=claude` and enabled git worktree isolation, which only Claude Code's `isolation="worktree"` can honor — risking main-checkout edits while the workflow believed agents were isolated. Every non-Claude install now resolves its own runtime identity, defaults `workflow.use_worktrees` to `false`, fails closed if worktrees are forced on, and runs plan/execute inline in the manager/autonomous flows since only Codex can background-nest the pipeline's subagents. (#1521)

View File

@@ -0,0 +1,5 @@
---
type: Fixed
pr: 1519
---
**Codex installs no longer run with unsafe Claude-style worktree isolation** — a Codex install with a runtime-neutral `.planning/config.json` was resolving its runtime as Claude and enabling git worktree isolation, which Codex's `spawn_agent` cannot honor; the Codex fail-closed guard was also silently dead because runtime/worktree config was read JSON-quoted and broke shell equality checks. Codex-emitted workflows now resolve `runtime=codex`, default `workflow.use_worktrees` to `false`, and fail closed when worktrees are forced on. (#1515)

View File

@@ -0,0 +1,5 @@
---
type: Added
pr: 1448
---
Added a validated `gsd-tools worktree record-agent` writer verb that appends a per-agent entry to the wave cleanup manifest, validating every field at write time with the same rules the `cleanup-wave` reader enforces (write-strict `--agent-id`) and failing loudly with a recovery hint instead of silently appending an under-populated entry. The execute-phase orchestrator now records each spawned worktree through this verb. (#1448)

View File

@@ -101,7 +101,7 @@ Cross-seam principle (ADR-1411, epic #1411): context resolution — config loadi
Diagnostic-output convention for the Resolution Provenance principle (ADR-1411 P3, #1416). Config-interpreting read verbs expose `Resolution<T> { value, configured, reason, warnings }` (`src/resolution.cts`); agent-skills is the first adopter, where `value = { block, skills_count }` and `source`/`degraded` remain config-provenance extras outside the envelope. Other read verbs expose at least `warnings[]` (e.g. capability-state `{ runtimeConfigDir, capabilities, warnings? }`) without `configured`/`reason`, which are meaningful only for config-interpreting verbs. Mutation verbs expose `warnings[]` (advisory) PLUS `errors[]` (operation-not-applied), e.g. capability-writer `{ capabilities, warnings, errors }`. The shared seam across all shapes is `warnings: string[]`; a single generic `Resolution<T>` across read+write verbs was rejected by the deletion test (`configured`/`reason` are meaningless for capability verbs; `errors[]` cannot fold into `warnings[]`) — ADR-1411 P3 amendment. Recurrence prevention is delivered by P4's CI guard (a configured input resolving empty must carry a `reason`), not by a shared envelope. A CI guard (`scripts/lint-resolution-provenance.cjs`, wired into `lint:ci`) enforces that every registered config-interpreting read verb keeps a `configured_empty`/`not_configured` contract test; the registry in that script is the registration point for future verbs (ADR-1411 P4 / #1417).
### Worktree Safety Policy Module
CJS Module owning worktree lifecycle safety policy for the GSD orchestration layer. Interface: `resolveWorktreeContext(cwd, deps) → WorktreeContext` (linked-worktree root mapping), `parseWorktreePorcelain(output) → WorktreeEntry[]` (porcelain parser, skips detached HEAD), `planWorktreePrune(repoRoot, opts, deps) → PrunePlan` (metadata-prune plan, never destructive by default), `executeWorktreePrunePlan(plan, deps) → PruneResult` (executes prune; degrades gracefully on git timeout), `listLinkedWorktreePaths(repoRoot, deps) → LinkedPathsResult`, `inspectWorktreeHealth(repoRoot, opts, deps) → HealthResult` (orphan + stale detection), `snapshotWorktreeInventory(repoRoot, opts, deps) → InventoryResult`, `planWorktreeWaveCleanup(repoRoot, manifest) → CleanupPlan` (manifest-scoped, fail-closed), `executeWorktreeWaveCleanupPlan(plan, deps) → CleanupResult`. Source of truth: `gsd-core/bin/lib/worktree-safety.cjs`. Timeout path: all git subprocess calls are bounded; callers receive `ok:false, reason:'git_timed_out'` rather than a thrown exception. Test anchor: `tests/worktree-safety.test.cjs`. The `core.cjs` re-export spine was retired in epic #1267: this module absorbed the two thin compositional wrappers that squatted in Core — `resolveWorktreeRoot(cwd, deps)` (a projection over `resolveWorktreeContext`) and `pruneOrphanedWorktrees(...)` (sequences `planWorktreePrune` + `executeWorktreePrunePlan` with a timeout warning) — so callers reach this single worktree-lifecycle seam directly. `gitWorktreeInfoInternal` did NOT move here — worktree-info detection belongs to the Git Query Module.
CJS Module owning worktree lifecycle safety policy for the GSD orchestration layer. Interface: `resolveWorktreeContext(cwd, deps) → WorktreeContext` (linked-worktree root mapping), `parseWorktreePorcelain(output) → WorktreeEntry[]` (porcelain parser, skips detached HEAD), `planWorktreePrune(repoRoot, opts, deps) → PrunePlan` (metadata-prune plan, never destructive by default), `executeWorktreePrunePlan(plan, deps) → PruneResult` (executes prune; degrades gracefully on git timeout), `listLinkedWorktreePaths(repoRoot, deps) → LinkedPathsResult`, `inspectWorktreeHealth(repoRoot, opts, deps) → HealthResult` (orphan + stale detection), `snapshotWorktreeInventory(repoRoot, opts, deps) → InventoryResult`, `planWorktreeWaveCleanup(repoRoot, manifest) → CleanupPlan` (manifest-scoped, fail-closed), `executeWorktreeWaveCleanupPlan(plan, deps) → CleanupResult`, `planWorktreeRecordAgent(manifestRaw, fields) → RecordAgentPlan` (write-strict per-agent manifest append; validates each field at write time via the same `normalizeCleanupManifestEntry` rules the reader enforces; fail-closed on a missing/garbled field or a duplicate `(worktree_path, branch)` the reader would dedup away), `cmdWorktreeRecordAgent(cwd, args, deps) → RecordAgentCmdResult` (thin deps-injectable IO wrapper for the `worktree record-agent` verb). Source of truth: `gsd-core/bin/lib/worktree-safety.cjs`. Timeout path: all git subprocess calls are bounded; callers receive `ok:false, reason:'git_timed_out'` rather than a thrown exception. Test anchor: `tests/worktree-safety.test.cjs`. The `core.cjs` re-export spine was retired in epic #1267: this module absorbed the two thin compositional wrappers that squatted in Core — `resolveWorktreeRoot(cwd, deps)` (a projection over `resolveWorktreeContext`) and `pruneOrphanedWorktrees(...)` (sequences `planWorktreePrune` + `executeWorktreePrunePlan` with a timeout warning) — so callers reach this single worktree-lifecycle seam directly. `gitWorktreeInfoInternal` did NOT move here — worktree-info detection belongs to the Git Query Module.
### Worktree Lifecycle Module
Workflow contract seam covering agent worktree lifecycle orchestration rules. The `worktree_branch_check` block lives in one canonical fragment (`gsd-core/references/worktree-branch-check.md`) that `execute-phase.md`, `quick.md`, `diagnose-issues.md`, and `execute-plan.md` embed at dispatch. Key invariants: `worktree_branch_check` is **verify-only and fail-closed** — the orchestrator owns worktree lifecycle and base recovery, so the sub-agent holds no state-correction primitives; HEAD attachment verified via `git symbolic-ref`; positive allow-list `^worktree-agent-*` enforced; `git update-ref` on protected refs is prohibited; on base mismatch the sub-agent halts with `exit 42` and surfaces to the orchestrator (#48); the orchestrator runs a cwd-drift guard at `execute_waves` entry that resolves the worktree root and refuses drift into an agent worktree (#48); cleanup is manifest-scoped (`WAVE_WORKTREE_MANIFEST`) not global-discovery-based; worktree spawning is sequential (one `run_in_background` at a time to avoid `config.lock` contention). Test anchor: `tests/worktree.test.cjs`.
@@ -155,7 +155,7 @@ Module owning which skills and agents are written to runtime config directories
Module owning the per-runtime mapping from artifact kind to filesystem placement. ADR-3660 defines the typed `kinds` per runtime (`commands`, `agents`, `skills`) with destination subpath, prefix, and stage adapter (with per-runtime converters in `bin/install.js`: `convertClaudeCommandToClaudeSkill`, `…CodexSkill`, `…CopilotSkill`, `…AntigravitySkill`). Owns the per-runtime `nested` skill-bundle decision (#69): a `skillsKind` flag in `src/runtime-artifact-layout.cts` drives whether a runtime receives the nested router layout (6 `gsd-ns-*` routers + concrete skills under `<router>/skills/<name>/`) or the flat `skills/gsd-<stem>/` layout; the evidence/doc-link matrix is recorded in a comment above `resolveRuntimeArtifactLayout`. Phase 1 applies this seam to the Runtime Surface Module (`surface.cjs:applySurface`); as of #813, `applySurface` applies the same per-runtime skill-body path rewrites as `installRuntimeArtifacts` for `skills` kinds — re-surfacing no longer overwrites installed SKILL.md bodies with converter-default `~/.claude` paths. Per ADR-1508 / #1511 the former `getInstallExports`/`loadInstallExports` relay (a `GSD_TEST_MODE`-guarded `require('bin/install.js')` by which `surface.cjs` reached `computePathPrefix`/`applyRuntimeContentRewritesInPlace`) was DELETED from this module; content rewriting now lives in the Runtime Artifact Conversion Module and `surface.cjs:applySurface` calls its `rewriteStagedSkillBodies` directly. The resolved `scope` is still carried on the `Layout` object so `applySurface` derives the same `pathPrefix` (global `$HOME` form vs. absolute) as a fresh install. Phase 2 is planned to migrate install/uninstall in `bin/install.js` so all lifecycle sites iterate one shared layout table instead of re-encoding runtime layout logic. This design is intended to remove the #3659 class of omissions. Migrations remain under the Installer Migration Module (ADR-0008). See ADR-3660.
### Runtime Artifact Conversion Module
Sibling Module to Runtime Artifact Layout Module. Owns projection from canonical Claude-authored command/agent/skill markdown into runtime-specific artifact bodies, including converter selection, frontmatter/body normalization, runtime path rewrites, and staged artifact generation. Runtime Artifact Layout remains responsible for filesystem placement (`kind`, destination subpath, prefix, nesting); Runtime Artifact Conversion owns the content Implementation behind that placement seam so install, uninstall/surface parity, and future plugin/package projections stop reaching back through `bin/install.js` for converter functions or `GSD_TEST_MODE`-guarded installer exports. Chosen direction: sibling Module, not an expanded Layout Module, to preserve ADR-3660's narrow placement responsibility while deepening artifact content locality. First slice: relocate only the layout-reached conversion family (`convertClaudeCommandTo*Skill`, converted command-file emitters, `buildKimiAgentArtifacts`) plus the minimal helper closure they need; do not leave helper dependencies in `bin/install.js` because that would preserve the same shallow seam under a new filename. Installer integration decision: `bin/install.js` imports the conversion Module at top level and re-exports the moved names for compatibility; the conversion Module must not import `bin/install.js` or Runtime Artifact Layout, so the dependency direction becomes installer/layout Adapters -> conversion Module, never conversion -> installer. First-slice Interface decision: export the existing compatibility names only; do not introduce a grouped `convertRuntimeArtifact` Interface until after relocation proves byte-for-byte behavior. SHIPPED (ADR-1508): the converter family relocated in #1510 Phase 1 (`getDirName`→runtime-name-policy, `processAttribution` here); #1511 Phase 2 moved the content-rewrite engine here in full — `_applyRuntimeRewrites` (per-runtime switch, injected attribution), the staged-content walkers `applyRuntimeContentRewritesInPlace`/`applyRuntimeContentRewritesForCommandsInPlace`, `computePathPrefix` (private; `_computePathPrefix` for tests), and the deep public seam `rewriteStagedSkillBodies`/`rewriteStagedCommandBodies({runtime,configDir,scope,homedir?,platform?,resolveAttribution?})`. `bin/install.js` binds these back (single owner, exports preserved); `getCommitAttribution` stays in `bin/install.js` (impure install-time config I/O) and is injected. The `getInstallExports` relay in Runtime Artifact Layout Module was deleted; the dependency direction installer/layout → conversion (never upward) is now enforced. Source: `gsd-core/bin/lib/runtime-artifact-conversion.cjs` (generated from `src/runtime-artifact-conversion.cts`).
Sibling Module to Runtime Artifact Layout Module. Owns projection from canonical Claude-authored command/agent/skill markdown into runtime-specific artifact bodies, including converter selection, frontmatter/body normalization, runtime path rewrites, and staged artifact generation. Runtime Artifact Layout remains responsible for filesystem placement (`kind`, destination subpath, prefix, nesting); Runtime Artifact Conversion owns the content Implementation behind that placement seam so install, uninstall/surface parity, and future plugin/package projections stop reaching back through `bin/install.js` for converter functions or `GSD_TEST_MODE`-guarded installer exports. Chosen direction: sibling Module, not an expanded Layout Module, to preserve ADR-3660's narrow placement responsibility while deepening artifact content locality. First slice: relocate only the layout-reached conversion family (`convertClaudeCommandTo*Skill`, converted command-file emitters, `buildKimiAgentArtifacts`) plus the minimal helper closure they need; do not leave helper dependencies in `bin/install.js` because that would preserve the same shallow seam under a new filename. Installer integration decision: `bin/install.js` imports the conversion Module at top level and re-exports the moved names for compatibility; the conversion Module must not import `bin/install.js` or Runtime Artifact Layout, so the dependency direction becomes installer/layout Adapters -> conversion Module, never conversion -> installer. First-slice Interface decision: export the existing compatibility names only; do not introduce a grouped `convertRuntimeArtifact` Interface until after relocation proves byte-for-byte behavior. SHIPPED (ADR-1508): the converter family relocated in #1510 Phase 1 (`getDirName`→runtime-name-policy, `processAttribution` here); #1511 Phase 2 moved the content-rewrite engine here in full — `_applyRuntimeRewrites` (per-runtime switch, injected attribution), the staged-content walkers `applyRuntimeContentRewritesInPlace`/`applyRuntimeContentRewritesForCommandsInPlace`, `computePathPrefix` (private; `_computePathPrefix` for tests), and the deep public seam `rewriteStagedSkillBodies`/`rewriteStagedCommandBodies({runtime,configDir,scope,homedir?,platform?,resolveAttribution?})`. `bin/install.js` binds these back (single owner, exports preserved); `getCommitAttribution` stays in `bin/install.js` (impure install-time config I/O) and is injected. The `getInstallExports` relay in Runtime Artifact Layout Module was deleted; the dependency direction installer/layout → conversion (never upward) is now enforced. Exception: opencode and kilo path-prefix rewriting is a deliberate `bin/install.js`-owned pre-conversion step (`applyOpencodeFamilyPathPrefix`) per #784, not a violation of the single-owner rule. Source: `gsd-core/bin/lib/runtime-artifact-conversion.cjs` (generated from `src/runtime-artifact-conversion.cts`).
### Command Roster Module
Tiny read-only helper Module owning discovery of canonical `commands/gsd/*.md` command stems for artifact conversion and runtime projection. It is a sibling dependency of Runtime Artifact Conversion Module, not part of conversion itself: conversion consumes a roster to safely rewrite `gsd:` / `/gsd-` references, while roster discovery owns filesystem/catalog knowledge. First slice: extract existing `readGsdCommandNames` behavior behind this Module instead of moving it into Runtime Artifact Conversion Module or keeping it as installer-owned state.
@@ -424,7 +424,7 @@ A legal deferred state of an Execute step (`external_job_waiting`): the executor
`WORKTREE.SEAM.current=Worktree Safety Policy Module`
`WORKTREE.SEAM.files=[gsd-core/bin/lib/worktree-safety.cjs]`
`WORKTREE.SEAM.interface=[resolveWorktreeContext, parseWorktreePorcelain, planWorktreePrune, executeWorktreePrunePlan]`
`WORKTREE.SEAM.interface=[resolveWorktreeContext, parseWorktreePorcelain, planWorktreePrune, executeWorktreePrunePlan, planWorktreeRecordAgent, cmdWorktreeRecordAgent]`
`WORKTREE.SEAM.default-prune-policy=metadata_prune_only (non-destructive)`
`WORKTREE.SEAM.decision-1=retain non-destructive default; destructive path only as explicit future opt-in scaffold`

View File

@@ -834,7 +834,7 @@ Defensive normalization at trust boundaries must validate both the value's type
- **CommonJS** (`.cjs`) — the project uses `require()`, not ESM `import`
- **No external dependencies in core** — `gsd-tools.cjs` and all lib files use only Node.js built-ins
- **Conventional commits** — `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `ci:`
- **Conventional commits** — `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `ci:`. The full grammar is `<type>(<scope>): <subject>` (enforced by `hooks/gsd-validate-commit.sh`; subject ≤72 chars, lowercase, imperative mood, no trailing period). When the work resolves a tracked issue, put the issue number in the scope: `fix(#1520): randomize mktemp temp paths on BSD/macOS`. The same convention applies to PR titles — release notes are grouped by the title's type prefix (`feat` → Feature, `fix` → Fix, everything else → Enhancement).
## File Structure

View File

@@ -6698,6 +6698,7 @@ function migrateLegacyDevPreferencesToSkill(targetDir, saved, runtime, scope = '
// reference-identical to the conversion module (consistent with the walkers above).
// All call sites are below this line → no TDZ hazard.
const _applyRuntimeRewrites = runtimeArtifactConversion._applyRuntimeRewrites;
const _stampNonClaudeRuntimeDefaults = runtimeArtifactConversion._stampNonClaudeRuntimeDefaults;
/**
* Copy a staged directory's contents into destDir.
@@ -7289,6 +7290,15 @@ function copyWithPathReplacement(srcDir, destDir, pathPrefix, runtime, isCommand
}
content = processAttribution(content, getCommitAttribution(runtime));
// #1521: stamp the workflow runtime-resolution block so every non-Claude
// install resolves its own runtime identity and defaults use_worktrees=false.
// copyWithPathReplacement is the emit path for gsd-core/workflows/*.md;
// _applyRuntimeRewrites is NOT invoked here, so this is what makes the fix
// live in real installs (it is a no-op for files without those lines).
if (runtime !== 'claude') {
content = _stampNonClaudeRuntimeDefaults(content, runtime);
}
// #3683 — normalize /gsd:<cmd> → /gsd-<cmd> in any body passing through
// copyWithPathReplacement for runtimes that register commands under the
// hyphen form; normalizeAgentBodyForRuntime self-gates on

View File

@@ -546,6 +546,20 @@ node gsd-tools.cjs worktree set-baseref
**`worktree set-baseref`** applies a no-clobber write of `worktree.baseRef:"head"` to `.claude/settings.local.json`. If the file already contains an explicit `baseRef` value other than `"head"`, the existing value is preserved and `skipped:"explicit-other"` is returned. Malformed JSON causes an error rather than a silent overwrite. Both fresh installs and upgrades of GSD Core run this automatically when `workflow.use_worktrees` is enabled (the default); the command is also available for manual use — for example, to apply the setting when worktrees were toggled on after installation, or to re-apply it after a settings change.
### Wave-manifest recording
The execute-phase orchestrator records each spawned executor's worktree identity into a wave cleanup manifest so the matching `cleanup-wave` reader can later merge and remove exactly those worktrees.
```bash
# Append a validated per-agent entry to the wave cleanup manifest.
# Returns JSON: { ok, reason, entry, manifest_path } (exit 0), or
# { ok:false, reason, hint } with a non-zero exit on a rejected entry.
node gsd-tools.cjs worktree record-agent \
--manifest <path> --agent-id <id> --path <worktree> --branch <branch> --base <sha>
```
**`worktree record-agent`** appends one `{agent_id, worktree_path, branch, expected_base}` entry to an already-initialized manifest, validating every field **at write time using the same rules the `cleanup-wave` reader enforces** — `--branch` must match the disposable `^worktree-agent-[A-Za-z0-9._/-]+$` namespace, and `--path`/`--branch`/`--base` must be non-empty. `--agent-id` is required (write-strict), even though the reader treats it as optional. A missing or garbled field — or a duplicate `(worktree_path, branch)` the reader would dedup away — fails loudly with a recovery hint and a non-zero exit **without** writing, instead of appending an under-populated or silently-dropped entry. Whitespace-only `--path`/`--base` are rejected (values are trimmed). The on-disk manifest shape is unchanged (the reader re-derives `allowed_bases`); the orchestrator still initializes the empty `{orchestrator_root, worktrees: []}` shell inline before any agent is recorded.
---
## Graphify

View File

@@ -248,7 +248,7 @@ All workflow toggles follow the **absent = enabled** pattern. If a key is missin
| `workflow.max_discuss_passes` | number | `3` | Maximum number of question rounds in discuss-phase before the workflow stops asking. Useful in headless/auto mode to prevent infinite discussion loops. |
| `workflow.skip_discuss` | boolean | `false` | When `true`, `/gsd-autonomous` bypasses the discuss-phase entirely, writing minimal CONTEXT.md from the ROADMAP phase goal. Useful for projects where developer preferences are fully captured in PROJECT.md/REQUIREMENTS.md. Added in v1.28 |
| `workflow.text_mode` | boolean | `false` | Replaces AskUserQuestion TUI menus with plain-text numbered lists. Required for Claude Code remote sessions (`/rc` mode) where TUI menus don't render. Can also be set per-session with `--text` flag on discuss-phase. Added in v1.28 |
| `workflow.use_worktrees` | boolean | `true` | When `false`, disables git worktree isolation for parallel execution. Users who prefer sequential execution or whose environment does not support worktrees can disable this. Added in v1.31. **Branch-divergence note:** when your branch has diverged from `origin/HEAD`, GSD auto-degrades to sequential and prints a warning. See [`worktree.baseRef`](#worktree-settings) to restore parallel execution on a diverged branch. |
| `workflow.use_worktrees` | boolean | `true` | When `false`, disables git worktree isolation for parallel execution. Users who prefer sequential execution or whose environment does not support worktrees can disable this. Added in v1.31. **Branch-divergence note:** when your branch has diverged from `origin/HEAD`, GSD auto-degrades to sequential and prints a warning. See [`worktree.baseRef`](#worktree-settings) to restore parallel execution on a diverged branch. **Non-Claude note:** git worktree isolation uses Claude Code's `isolation="worktree"` agent primitive, which no other runtime honors. On any non-Claude install (Codex, Cursor, Gemini, Qwen, etc.) a runtime-neutral `.planning/config.json` resolves the runtime to that install's own id and defaults this key to `false`; forcing `use_worktrees: true` on a non-Claude install fails closed before any executor dispatch (#1515, #1521). |
| `workflow.worktree_skip_hooks` | boolean | `false` | When `true`, executor agents in worktree mode pass `--no-verify` (skipping pre-commit hooks) and post-wave hook validation runs against the merged result instead. Opt-in escape hatch for projects whose hooks cannot run in agent worktrees. Default `false` runs hooks on every commit (#2924). |
| `workflow.code_review` | boolean | `true` | Enable `/gsd-code-review` and `/gsd-code-review --fix` commands. When `false`, the commands exit with a configuration gate message. Added in v1.34 |
| `workflow.code_review_depth` | string | `standard` | Default review depth for `/gsd-code-review`: `quick` (pattern-matching only), `standard` (per-file analysis), or `deep` (cross-file with import graphs). Can be overridden per-run with `--depth=`. Added in v1.34 |

View File

@@ -14,7 +14,7 @@ This is the **last upward dependency from the `.cts` source tree into the hand-a
## Decision
- Promote the `[Planned]` **Runtime Artifact Conversion Module** (`src/runtime-artifact-conversion.cts`) to the single owner of per-runtime **content rewriting**: the per-runtime converters (already relocated as ADR-3660's "first slice", #1099), **plus** the rewrite engine `_applyRuntimeRewrites`, the staged-content walkers, path-prefix derivation, and commit attribution. The **Runtime Artifact Layout Module** keeps owning **placement** only.
- Promote the `[Planned]` **Runtime Artifact Conversion Module** (`src/runtime-artifact-conversion.cts`) to the single owner of per-runtime **content rewriting**: the per-runtime converters (already relocated as ADR-3660's "first slice", #1099), **plus** the rewrite engine `_applyRuntimeRewrites`, the staged-content walkers, path-prefix derivation, and commit attribution. The **Runtime Artifact Layout Module** keeps owning **placement** only. **Exception:** opencode and kilo path-prefix rewriting remains a deliberate `bin/install.js`-owned pre-conversion step (see `applyOpencodeFamilyPathPrefix`); this is intentional per #784 and is not a violation of the single-owner rule.
- **Public seam** — two deep calls; the caller passes only what it has, the module derives the rest:
- `rewriteStagedSkillBodies(stagedDir, { runtime, configDir, scope }, env?)` — in-place walk (skills / kimi-agents).
- `rewriteStagedCommandBodies(stagedDir, { runtime, configDir, scope }, env?) → tempDir` — copy-to-temp (commands).

View File

@@ -2128,6 +2128,8 @@ async function runCommand(command, args, cwd, raw, defaultValue, originalCommand
const worktreeSafety = require('./lib/worktree-safety.cjs');
if (subcommand === 'cleanup-wave') {
worktreeSafety.cmdWorktreeCleanupWave(cwd, args.slice(2));
} else if (subcommand === 'record-agent') {
worktreeSafety.cmdWorktreeRecordAgent(cwd, args.slice(2));
} else if (subcommand === 'reap-orphans') {
worktreeSafety.cmdWorktreeReapOrphans(cwd);
} else if (subcommand === 'base-check') {
@@ -2135,7 +2137,7 @@ async function runCommand(command, args, cwd, raw, defaultValue, originalCommand
} else if (subcommand === 'set-baseref') {
require('./lib/worktree-base-ref.cjs').cmdWorktreeSetBaseRef(cwd, args.slice(2));
} else {
error('Unknown worktree subcommand. Available: cleanup-wave, reap-orphans, base-check, set-baseref', ERROR_REASON.SDK_UNKNOWN_COMMAND);
error('Unknown worktree subcommand. Available: cleanup-wave, record-agent, reap-orphans, base-check, set-baseref', ERROR_REASON.SDK_UNKNOWN_COMMAND);
}
break;
}

View File

@@ -61,7 +61,7 @@ fi
When `--only` is set, also set `FROM_PHASE` to the same value so existing filter logic applies.
When `--interactive` is set, discuss runs inline with questions (not auto-answered). On runtimes where a backgrounded agent can spawn subagents, plan and execute are dispatched as background agents — keeping the main context lean (only discuss conversations accumulate) and enabling overlap. On Claude Code, where a backgrounded agent cannot nest subagents, plan and execute run inline to preserve worktree isolation and independent verification, so they run sequentially and their work accumulates in the main context. Either way, user input is preserved on all design decisions.
When `--interactive` is set, discuss runs inline with questions (not auto-answered). On Codex, where a backgrounded agent can still spawn subagents, plan and execute are dispatched as background agents — keeping the main context lean (only discuss conversations accumulate) and enabling overlap. On every other runtime (Claude Code and all other non-Codex runtimes), backgrounded agents cannot reliably nest subagents, so plan and execute run inline to preserve worktree isolation and independent verification, and phases run sequentially with their work accumulating in the main context. Either way, user input is preserved on all design decisions.
When `PLAN_STRATEGY=converge`, the planning step MUST invoke the plan-review convergence workflow instead of `gsd-plan-phase`. `--cross-ai` is an alias for `--converge`. Forward `CONVERGENCE_ARGS` exactly as parsed so reviewer flags and `--max-cycles N` retain the same meaning as they have on `/gsd:plan-review-convergence`.
@@ -111,7 +111,7 @@ Display startup banner:
If `ONLY_PHASE` is set, display: `Single phase mode: Phase ${ONLY_PHASE}`
Else if `FROM_PHASE` is set, display: `Starting from phase ${FROM_PHASE}`
If `TO_PHASE` is set, display: `Stopping after phase ${TO_PHASE}`
If `INTERACTIVE` is set, display: `Mode: Interactive (discuss inline, plan+execute in background)`
If `INTERACTIVE` is set, display: `Mode: Interactive (discuss inline, plan+execute inline — background on Codex only)`
If `PLAN_STRATEGY` is `converge`, display: `Planning: Plan-review convergence enabled`
</step>
@@ -357,27 +357,13 @@ UI_SPEC_FILE=$(ls "${PHASE_DIR}"/*-UI-SPEC.md 2>/dev/null | head -1)
**3b. Plan**
**If `INTERACTIVE` is set:** Background dispatch is only safe where a backgrounded agent can still spawn subagents. On Claude Code a backgrounded agent has no `Agent`/`Task` tool, so the plan-checker never runs and `workflow.plan_check` silently degrades to a self-check. Resolve the runtime first:
**If `INTERACTIVE` is set:** Background dispatch is only safe on a runtime where a backgrounded agent can still nest the pipeline's subagents (plan-checker / worktree executors / verifier). Among supported runtimes only **Codex** (`spawn_agent`) can do this; Claude Code's backgrounded agents have no `Agent`/`Task` tool, and every other runtime either prohibits nested subagents or disables them by default. So run **inline** everywhere except Codex, which is dispatched in the background. Resolve the runtime first:
```bash
RUNTIME=$(gsd_run query config-get runtime --default claude 2>/dev/null || echo "claude")
RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")
```
- **On Claude Code (`RUNTIME` is `claude`):** Run plan **inline** (do NOT background) so the plan-checker runs. The next phase's discuss does not overlap planning here — correctness over overlap.
- If `PLAN_STRATEGY=converge`:
```
Skill(skill="gsd-plan-review-convergence", args="${PHASE_NUM} ${CONVERGENCE_ARGS}")
```
- Otherwise (local planning):
```
Skill(skill="gsd-plan-phase", args="${PHASE_NUM}")
```
- **On other runtimes:** Dispatch plan as a background agent to keep the main context lean. While plan runs, the workflow can immediately start discussing the next phase (see step 4).
- **If `RUNTIME` is `codex`:** Dispatch plan as a background agent to keep the main context lean. While plan runs, the workflow can immediately start discussing the next phase (see step 4).
- If `PLAN_STRATEGY=converge`, print: `◆ Spawning background plan-convergence loop for phase ${PHASE_NUM}... (runs in a subagent — no output until it returns, ~1–5 min; expected, not a freeze)`
@@ -401,6 +387,20 @@ RUNTIME=$(gsd_run query config-get runtime --default claude 2>/dev/null || echo
Store the agent task_id. After discuss for the next phase completes (or if no next phase), wait for the plan agent to finish before proceeding to execute.
- **Otherwise (Claude Code or any other non-Codex runtime):** Run plan **inline** (do NOT background) so the plan-checker runs. The next phase's discuss does not overlap planning here — correctness over overlap.
- If `PLAN_STRATEGY=converge`:
```
Skill(skill="gsd-plan-review-convergence", args="${PHASE_NUM} ${CONVERGENCE_ARGS}")
```
- Otherwise (local planning):
```
Skill(skill="gsd-plan-phase", args="${PHASE_NUM}")
```
**If `INTERACTIVE` is NOT set (default):** Run plan inline.
If `PLAN_STRATEGY=converge`, run the convergence loop:
@@ -419,19 +419,13 @@ Verify plan produced output — re-run `init phase-op` and check `has_plans`. If
**3c. Execute**
**If `INTERACTIVE` is set:** Wait for the plan agent to complete (if not already) and verify plans exist. Background dispatch is only safe where a backgrounded agent can still spawn subagents. On Claude Code a backgrounded agent has no `Agent`/`Task` tool, so the per-plan worktree-isolated executors and the verifier never run (`workflow.use_worktrees` and `workflow.verifier` silently degrade). Resolve the runtime first:
**If `INTERACTIVE` is set:** Wait for the plan agent to complete (if not already) and verify plans exist. Background dispatch is only safe on a runtime where a backgrounded agent can still nest the pipeline's subagents (plan-checker / worktree executors / verifier). Among supported runtimes only **Codex** (`spawn_agent`) can do this; Claude Code's backgrounded agents have no `Agent`/`Task` tool, and every other runtime either prohibits nested subagents or disables them by default. So run **inline** everywhere except Codex, which is dispatched in the background. Resolve the runtime first:
```bash
RUNTIME=$(gsd_run query config-get runtime --default claude 2>/dev/null || echo "claude")
RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")
```
- **On Claude Code (`RUNTIME` is `claude`):** Run execute **inline** (do NOT background) so worktree isolation and verification run:
```
Skill(skill="gsd-execute-phase", args="${PHASE_NUM} --no-transition")
```
- **On other runtimes:** Dispatch execute as a background agent:
- **If `RUNTIME` is `codex`:** Dispatch execute as a background agent:
```
Agent(
@@ -443,6 +437,12 @@ Agent(
Store the agent task_id. The workflow can now start discussing the next phase while this phase executes in the background. Before starting post-execution routing for this phase, wait for the execute agent to complete.
- **Otherwise (Claude Code or any other non-Codex runtime):** Run execute **inline** (do NOT background) so worktree isolation and verification run:
```
Skill(skill="gsd-execute-phase", args="${PHASE_NUM} --no-transition")
```
**If `INTERACTIVE` is NOT set (default):** Run execute inline as before.
```
@@ -656,12 +656,12 @@ Check for blockers in the Blockers/Concerns section. If blockers are found, go t
If incomplete phases remain: proceed to next phase, loop back to execute_phase.
**Interactive mode overlap:** When `INTERACTIVE` is set, the iterate step enables pipeline parallelism **on runtimes where a backgrounded agent can spawn subagents** (on Claude Code, plan/execute run inline — see 3b/3c — so there is no overlap and phases run sequentially):
**Interactive mode overlap:** When `INTERACTIVE` is set, the iterate step enables pipeline parallelism **on Codex** (on every other runtime, plan/execute run inline — see 3b/3c — so there is no overlap and phases run sequentially):
1. After discuss completes for Phase N, dispatch plan+execute as background agents
2. Immediately start discuss for Phase N+1 (the next incomplete phase) while Phase N builds
3. Before starting plan for Phase N+1, wait for Phase N's execute agent to complete and handle its post-execution routing (verification, gap closure, etc.)
This means the user is always answering discuss questions (lightweight, interactive) while the heavy work (planning, code generation) runs in the background. The main context only accumulates discuss conversations — plan and execute contexts are isolated in their agents. (On Claude Code, plan and execute run inline, so they run sequentially and their work accumulates in the main context.)
This means the user is always answering discuss questions (lightweight, interactive) while the heavy work (planning, code generation) runs in the background. The main context only accumulates discuss conversations — plan and execute contexts are isolated in their agents. (On Claude Code and all other non-Codex runtimes, plan and execute run inline, so they run sequentially and their work accumulates in the main context.)
If all phases complete, proceed to lifecycle step.
@@ -873,9 +873,9 @@ When any phase operation fails or a blocker is detected, present 3 options via A
- [ ] `--to N` handle_blocker resume message preserves --to flag
- [ ] `--to N` skips lifecycle when not all milestone phases complete
- [ ] `--interactive` runs discuss inline via gsd-discuss-phase (asks questions, waits for user)
- [ ] `--interactive` dispatches plan and execute as background agents on runtimes that support nested background dispatch; runs them inline on Claude Code
- [ ] `--interactive` enables pipeline parallelism (discuss Phase N+1 while Phase N builds) on runtimes with background dispatch; phases run sequentially on Claude Code
- [ ] `--interactive` main context only accumulates discuss conversations on runtimes with background dispatch (on Claude Code, inline plan/execute also accumulate)
- [ ] `--interactive` dispatches plan and execute as background agents on Codex (the only runtime where a backgrounded agent can nest subagents); runs them inline on all other runtimes
- [ ] `--interactive` enables pipeline parallelism (discuss Phase N+1 while Phase N builds) on Codex; phases run sequentially on all other runtimes
- [ ] `--interactive` main context only accumulates discuss conversations on Codex (on all other runtimes, inline plan/execute also accumulate)
- [ ] `--interactive` waits for background agents before post-execution routing
- [ ] `--interactive` compatible with `--only`, `--from`, and `--to` flags
- [ ] `--converge` routes planning through `gsd-plan-review-convergence`

View File

@@ -59,7 +59,12 @@ gaps = [
```bash
_GSD_SHIM_NAME="gsd-tools.cjs"; _GSD_RUNTIME_ROOT="${RUNTIME_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"; GSD_TOOLS="${_GSD_RUNTIME_ROOT}/gsd-core/bin/${_GSD_SHIM_NAME}"; if [ -f "$GSD_TOOLS" ]; then gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${_GSD_RUNTIME_ROOT}/.claude/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${_GSD_RUNTIME_ROOT}/.claude/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${_GSD_RUNTIME_ROOT}/.codex/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${_GSD_RUNTIME_ROOT}/.codex/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif command -v gsd-tools >/dev/null 2>&1; then GSD_TOOLS="$(command -v gsd-tools)"; gsd_run() { "$GSD_TOOLS" "$@"; }; elif [ -f "$HOME/.claude/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="$HOME/.claude/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${HERMES_HOME:-$HOME/.hermes}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${HERMES_HOME:-$HOME/.hermes}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${CURSOR_CONFIG_DIR:-$HOME/.cursor}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${CURSOR_CONFIG_DIR:-$HOME/.cursor}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${CODEX_HOME:-$HOME/.codex}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${CODEX_HOME:-$HOME/.codex}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${GEMINI_CONFIG_DIR:-$HOME/.gemini}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${GEMINI_CONFIG_DIR:-$HOME/.gemini}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${COPILOT_CONFIG_DIR:-$HOME/.copilot}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${COPILOT_CONFIG_DIR:-$HOME/.copilot}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${WINDSURF_CONFIG_DIR:-$HOME/.codeium/windsurf}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${WINDSURF_CONFIG_DIR:-$HOME/.codeium/windsurf}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${AUGMENT_CONFIG_DIR:-$HOME/.augment}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${AUGMENT_CONFIG_DIR:-$HOME/.augment}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${TRAE_CONFIG_DIR:-$HOME/.trae}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${TRAE_CONFIG_DIR:-$HOME/.trae}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${QWEN_CONFIG_DIR:-$HOME/.qwen}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${QWEN_CONFIG_DIR:-$HOME/.qwen}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${CODEBUDDY_CONFIG_DIR:-$HOME/.codebuddy}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${CODEBUDDY_CONFIG_DIR:-$HOME/.codebuddy}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${CLINE_CONFIG_DIR:-$HOME/.cline}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${CLINE_CONFIG_DIR:-$HOME/.cline}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${GROK_AGENTS_HOME:-$HOME/.agents}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${GROK_AGENTS_HOME:-$HOME/.agents}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${ANTIGRAVITY_CONFIG_DIR:-$HOME/.gemini/antigravity}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${ANTIGRAVITY_CONFIG_DIR:-$HOME/.gemini/antigravity}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${OPENCODE_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/opencode}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; elif [ -f "${KILO_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/kilo}/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="${KILO_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/kilo}/gsd-core/bin/${_GSD_SHIM_NAME}"; gsd_run() { node "$GSD_TOOLS" "$@"; }; else echo "ERROR: gsd-tools.cjs not found at $GSD_TOOLS and gsd-tools is not on PATH. Run: npx -y @opengsd/gsd-core@latest --claude --local" >&2; exit 1; fi; if [ -n "${CLAUDE_ENV_FILE:-}" ] && [ -n "${GSD_TOOLS:-}" ]; then printf "export PATH='%s':\"\$PATH\"\n" "${GSD_TOOLS%/*}" >> "$CLAUDE_ENV_FILE" 2>/dev/null || true; fi
USE_WORKTREES=$(gsd_run query config-get workflow.use_worktrees 2>/dev/null || echo "true")
USE_WORKTREES=$(gsd_run query config-get workflow.use_worktrees --raw 2>/dev/null || echo "true")
RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")
if [ "$RUNTIME" != "claude" ] && [ "$USE_WORKTREES" != "false" ]; then
echo "FATAL: git worktree isolation (isolation=\"worktree\") is unsupported on runtime '$RUNTIME' — it would run executor agents unisolated against the main checkout. Set workflow.use_worktrees=false." >&2
exit 1
fi
```
**Report diagnosis plan to user:**

View File

@@ -91,13 +91,13 @@ Parse JSON for: `executor_model`, `verifier_model`, `commit_docs`, `parallelizat
Read runtime/worktree config and fail closed before any executor dispatch:
```bash
RUNTIME=$(gsd_run query config-get runtime --default claude 2>/dev/null || echo "claude")
USE_WORKTREES=$(gsd_run query config-get workflow.use_worktrees 2>/dev/null || echo "true")
RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")
USE_WORKTREES=$(gsd_run query config-get workflow.use_worktrees --raw 2>/dev/null || echo "true")
EXECUTOR_STALL_INTERVAL_MINUTES=$(gsd_run query config-get executor.stall_detect_interval_minutes 2>/dev/null || echo "5")
EXECUTOR_STALL_THRESHOLD_MINUTES=$(gsd_run query config-get executor.stall_threshold_minutes 2>/dev/null || echo "10")
if [ "$RUNTIME" = "codex" ] && [ "$USE_WORKTREES" != "false" ]; then
echo "FATAL: Codex execute-phase worktree isolation is unsupported. Set workflow.use_worktrees=false or use a runtime with Agent isolation=\"worktree\" support." >&2
if [ "$RUNTIME" != "claude" ] && [ "$USE_WORKTREES" != "false" ]; then
echo "FATAL: git worktree isolation (isolation=\"worktree\") is unsupported on runtime '$RUNTIME' — it would run executor agents unisolated against the main checkout. Set workflow.use_worktrees=false." >&2
exit 1
fi
# Sweep orphaned locked worktrees from prior crashed sessions before spawning executors (#3707).
@@ -113,7 +113,7 @@ if [ "$RUNTIME" = "claude" ] && [ "$USE_WORKTREES" != "false" ]; then
fi
fi
```
Codex maps subagents to `spawn_agent`, which has no direct Codex mapping for Claude Code's `isolation="worktree"` parameter. Failing closed prevents main-checkout edits while the workflow believes agents are isolated.
`isolation="worktree"` is a Claude-Code-specific agent primitive; no other runtime can honor it (Codex maps subagents to `spawn_agent`, others prohibit or omit worktree binding). Failing closed prevents main-checkout edits while the workflow believes agents are isolated.
If the project uses git submodules, worktree isolation is unsafe **only when a plan touches a submodule path** — the executor commit protocol cannot correctly handle submodule commits inside isolated worktrees. The previous behavior unconditionally disabled worktree isolation whenever `.gitmodules` existed, which penalised every plan in a submodule project even when the plan was nowhere near a submodule. Compute submodule paths once and intersect them per-plan with the plan's declared `files_modified` frontmatter.
@@ -687,7 +687,7 @@ increases monotonically across waves. `{status}` is `complete` (success),
)
```
After each `Agent()` returns, parse executor-returned worktree metadata (`<worktree_metadata>`) before harness metadata, then atomically append `{agent_id, worktree_path, branch, expected_base}` to `WAVE_WORKTREE_MANIFEST`. Missing: stop and ask for recovery instead of scanning worktrees.
After each `Agent()` returns, parse executor-returned worktree metadata (`<worktree_metadata>`) before harness metadata, then record the `{agent_id, worktree_path, branch, expected_base}` entry with `gsd_run query worktree.record-agent --manifest "$WAVE_WORKTREE_MANIFEST" --agent-id … --path … --branch … --base …`. The verb validates every field at write time using the same rules the `cleanup-wave` reader enforces (write-strict `--agent-id`), failing loudly with a non-zero exit and recovery hint rather than appending an under-populated entry the reader would later drop silently. On a non-zero exit or any missing field: stop and ask for recovery instead of scanning worktrees.
> **Worktree recovery policy (#48 + #1292):** See `execute-phase/steps/worktree-recovery-policy.md` — FAIL-CLOSED rule for base/HEAD-namespace mismatches AND isolated-run fail-safe recovery.

View File

@@ -1,6 +1,6 @@
<purpose>
Interactive command center for managing a milestone from a single terminal. Shows a dashboard of all phases with visual status, dispatches discuss inline and plan/execute as background agents, and loops back to the dashboard after each action. Enables parallel phase work from one terminal.
Interactive command center for managing a milestone from a single terminal. Shows a dashboard of all phases with visual status, dispatches discuss inline and runs plan/execute inline (backgrounded only on Codex), and loops back to the dashboard after each action. Enables parallel phase work from one terminal.
</purpose>
@@ -45,7 +45,7 @@ Display startup banner:
{milestone_version} — {milestone_name}
{phase_count} phases · {completed_count} complete
✓ Discuss → inline ◆ Plan/Execute → background
✓ Discuss → inline ◆ Plan/Execute → inline (background on Codex)
Dashboard auto-refreshes when background work is active.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
@@ -221,8 +221,8 @@ Go to exit step.
When the user selects a compound option, behavior depends on the runtime — the Plan Phase N / Execute Phase N handlers below resolve it via `gsd_run query config-get runtime`:
- **On Claude Code:** a backgrounded agent cannot nest the pipeline's subagents, so run the chosen plan/execute step(s) **inline** via their handlers below (in order), then run the inline discuss. There is no overlap.
- **On other runtimes:** **Spawn all background agents first** (plan/execute) — dispatch them in parallel using the Plan Phase N / Execute Phase N handlers below — then run the inline discuss; the background agents continue while you discuss.
- **On Codex:** **Spawn all background agents first** (plan/execute) — dispatch them in parallel using the Plan Phase N / Execute Phase N handlers below — then run the inline discuss; the background agents continue while you discuss.
- **Otherwise (Claude Code or any other non-Codex runtime):** a backgrounded agent cannot reliably nest the pipeline's subagents, so run the chosen plan/execute step(s) **inline** via their handlers below (in order), then run the inline discuss. There is no overlap.
Inline discuss:
@@ -244,27 +244,13 @@ After discuss completes, loop back to dashboard step.
### Plan Phase N
Planning runs autonomously. **First resolve the runtime.** On Claude Code a backgrounded agent has no `Agent`/`Task` tool, so it cannot spawn the plan-checker the pipeline relies on — backgrounding it there silently turns `workflow.plan_check` into a self-check. So run plan **inline** on Claude Code, and **background** it only on runtimes where a backgrounded agent can still nest subagents.
Planning runs autonomously. **First resolve the runtime.** Background dispatch is only safe on a runtime where a backgrounded agent can still nest the pipeline's subagents (plan-checker / worktree executors / verifier). Among supported runtimes only **Codex** (`spawn_agent`) can do this; Claude Code's backgrounded agents have no `Agent`/`Task` tool, and every other runtime either prohibits nested subagents or disables them by default. So run **inline** everywhere except Codex, which is dispatched in the background.
```bash
RUNTIME=$(gsd_run query config-get runtime --default claude 2>/dev/null || echo "claude")
RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")
```
**If `RUNTIME` is `claude` (Claude Code):** Run plan inline so the plan-checker and quality gates actually run — do NOT wrap it in `Agent(run_in_background=true, …)`:
```
Skill(skill="gsd-plan-phase", args="{N} --auto {manager_flags.plan}")
```
Display while it runs:
```
◆ Planning Phase {N}: {phase_name}... (runs inline so the plan-checker runs — the dashboard resumes when it returns, ~1–5 min; expected, not a freeze)
```
Then loop back to dashboard step.
**If `RUNTIME` is not `claude` (e.g. Codex):** Spawn a background agent that delegates to the Skill pipeline with any configured flags:
**If `RUNTIME` is `codex`:** Spawn a background agent that delegates to the Skill pipeline with any configured flags:
```
Agent(
@@ -286,7 +272,7 @@ Important: You are running in the background. Do NOT use AskUserQuestion — mak
)
```
> **ORCHESTRATOR RULE — NON-CLAUDE RUNTIME**: After calling Agent() above with `run_in_background=true`, do NOT do any planning work for this phase independently. Return to the dashboard immediately and wait for the background agent to report back. Only resume planning-related work when the subagent result is available.
> **ORCHESTRATOR RULE — CODEX RUNTIME**: After calling Agent() above with `run_in_background=true`, do NOT do any planning work for this phase independently. Return to the dashboard immediately and wait for the background agent to report back. Only resume planning-related work when the subagent result is available.
Display:
@@ -296,29 +282,29 @@ Display:
Loop back to dashboard step.
### Execute Phase N
Execution runs autonomously. **First resolve the runtime.** On Claude Code a backgrounded agent has no `Agent`/`Task` tool, so it cannot spawn the per-plan worktree-isolated executors or the verifier — backgrounding it there silently disables `workflow.use_worktrees` isolation and `workflow.verifier`. So run execute **inline** on Claude Code, and **background** it only on runtimes where a backgrounded agent can still nest subagents.
```bash
RUNTIME=$(gsd_run query config-get runtime --default claude 2>/dev/null || echo "claude")
```
**If `RUNTIME` is `claude` (Claude Code):** Run execute inline so worktree isolation and the verifier actually run — do NOT wrap it in `Agent(run_in_background=true, …)`:
**Otherwise (Claude Code or any other non-Codex runtime):** Run plan inline so the plan-checker and quality gates actually run — do NOT wrap it in `Agent(run_in_background=true, …)`:
```
Skill(skill="gsd-execute-phase", args="{N} {manager_flags.execute}")
Skill(skill="gsd-plan-phase", args="{N} --auto {manager_flags.plan}")
```
Display while it runs:
```
◆ Executing Phase {N}: {phase_name}... (runs inline so worktree isolation and verification run — the dashboard resumes when it returns; expected, not a freeze)
◆ Planning Phase {N}: {phase_name}... (runs inline so the plan-checker runs — the dashboard resumes when it returns, ~1–5 min; expected, not a freeze)
```
Then loop back to dashboard step.
**If `RUNTIME` is not `claude` (e.g. Codex):** Spawn a background agent that delegates to the Skill pipeline with any configured flags:
### Execute Phase N
Execution runs autonomously. **First resolve the runtime.** Background dispatch is only safe on a runtime where a backgrounded agent can still nest the pipeline's subagents (plan-checker / worktree executors / verifier). Among supported runtimes only **Codex** (`spawn_agent`) can do this; Claude Code's backgrounded agents have no `Agent`/`Task` tool, and every other runtime either prohibits nested subagents or disables them by default. So run **inline** everywhere except Codex, which is dispatched in the background.
```bash
RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")
```
**If `RUNTIME` is `codex`:** Spawn a background agent that delegates to the Skill pipeline with any configured flags:
```
Agent(
@@ -340,7 +326,7 @@ Important: You are running in the background. Do NOT use AskUserQuestion — mak
)
```
> **ORCHESTRATOR RULE — NON-CLAUDE RUNTIME**: After calling Agent() above with `run_in_background=true`, do NOT do any execution work for this phase independently. Return to the dashboard immediately and wait for the background agent to report back. Only resume execution-related work when the subagent result is available.
> **ORCHESTRATOR RULE — CODEX RUNTIME**: After calling Agent() above with `run_in_background=true`, do NOT do any execution work for this phase independently. Return to the dashboard immediately and wait for the background agent to report back. Only resume execution-related work when the subagent result is available.
Display:
@@ -350,6 +336,20 @@ Display:
Loop back to dashboard step.
**Otherwise (Claude Code or any other non-Codex runtime):** Run execute inline so worktree isolation and the verifier actually run — do NOT wrap it in `Agent(run_in_background=true, …)`:
```
Skill(skill="gsd-execute-phase", args="{N} {manager_flags.execute}")
```
Display while it runs:
```
◆ Executing Phase {N}: {phase_name}... (runs inline so worktree isolation and verification run — the dashboard resumes when it returns; expected, not a freeze)
```
Then loop back to dashboard step.
</step>
<step name="background_completion">
@@ -422,8 +422,8 @@ Display final status with progress bar:
- [ ] Dependency resolution: blocked phases show which deps are missing
- [ ] Recommendations prioritize: execute > plan > discuss
- [ ] Discuss phases run inline via Skill() — interactive questions work
- [ ] Plan phases spawn background Task agents — return to dashboard immediately
- [ ] Execute phases spawn background Task agents — return to dashboard immediately
- [ ] Plan phases run inline (or as background Task agents on Codex) — dashboard resumes when complete
- [ ] Execute phases run inline (or as background Task agents on Codex) — dashboard resumes when complete
- [ ] Dashboard refreshes pick up changes from background agents via disk state
- [ ] Background agent completion triggers notification and dashboard refresh
- [ ] Background agent errors present retry/skip options

View File

@@ -137,7 +137,12 @@ AGENT_SKILLS_VERIFIER=$(gsd_run query agent-skills gsd-verifier)
Parse JSON for: `planner_model`, `executor_model`, `checker_model`, `verifier_model`, `commit_docs`, `branch_name`, `quick_id`, `slug`, `date`, `timestamp`, `quick_dir`, `task_dir`, `roadmap_exists`, `planning_exists`.
```bash
USE_WORKTREES=$(gsd_run query config-get workflow.use_worktrees 2>/dev/null || echo "true")
USE_WORKTREES=$(gsd_run query config-get workflow.use_worktrees --raw 2>/dev/null || echo "true")
RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")
if [ "$RUNTIME" != "claude" ] && [ "$USE_WORKTREES" != "false" ]; then
echo "FATAL: git worktree isolation (isolation=\"worktree\") is unsupported on runtime '$RUNTIME' — it would run executor agents unisolated against the main checkout. Set workflow.use_worktrees=false." >&2
exit 1
fi
```
If `USE_WORKTREES` is not `"false"`, run a startup orphan sweep before spawning any executors. This reaps locked worktrees whose lock-owner process is dead, whose branch is merged into the default branch, and whose lock file mtime is older than 5 minutes. Running it at startup prevents accumulation of orphaned worktrees from prior sessions that exited without cleanup (#3707).

View File

@@ -2119,6 +2119,40 @@ function computePathPrefix({ isGlobal, isOpencode, isWindowsHost: _isWindowsHost
return `${resolvedTarget}/`;
}
/**
* Canonical list of every non-Claude runtime that gsd-core emits artifacts for.
* Exported so test files can import this single source of truth rather than
* maintaining divergent hand-rolled arrays (#1521).
*
* Keep in sync with the runtime flags in bin/install.js and getDirName().
*/
const NON_CLAUDE_RUNTIMES: string[] = [
'codex', 'opencode', 'kilo', 'gemini', 'copilot', 'antigravity',
'cursor', 'windsurf', 'augment', 'trae', 'qwen', 'hermes', 'kimi',
'codebuddy', 'cline',
];
/**
* #1521: Every non-Claude runtime resolves its own runtime identity from a
* runtime-neutral config, and defaults workflow.use_worktrees to false —
* GSD's worktree isolation uses Claude Code's isolation="worktree" spawn
* parameter, which no other runtime honors. Stamped into the emitted
* workflow runtime-resolution blocks. (Generalizes the Codex-only #1515 fix.)
*
* @private — exported as `_stampNonClaudeRuntimeDefaults` for tests.
*/
function _stampNonClaudeRuntimeDefaults(content: string, runtime: string): string {
content = content.replace(
/config-get workflow\.use_worktrees --raw 2>\/dev\/null \|\| echo "true"/g,
'config-get workflow.use_worktrees --default false --raw 2>/dev/null || echo "false"',
);
content = content.replace(
/config-get runtime --default claude --raw 2>\/dev\/null \|\| echo "claude"/g,
`config-get runtime --default ${runtime} --raw 2>/dev/null || echo "${runtime}"`,
);
return content;
}
/**
* Apply the per-runtime rewrite table to a single content string.
* Relocated from bin/install.js `_applyRuntimeRewrites`.
@@ -2133,12 +2167,20 @@ function _applyRuntimeRewrites(content, runtime, pathPrefix, isGlobal = false, a
const dirName = getDirName(runtime);
const normalizedPathPrefix = pathPrefix.replace(/\/$/, '');
// #1521: stamp runtime identity + use_worktrees=false for every non-Claude runtime
// before brand-specific path rewrites, so the replace operates on the pristine
// source line and is idempotent regardless of subsequent path substitutions.
if (runtime !== 'claude') {
content = _stampNonClaudeRuntimeDefaults(content, runtime);
}
switch (runtime) {
case 'codex':
content = content.replace(/~\/\.claude\//g, pathPrefix);
content = content.replace(/\$HOME\/\.claude\//g, pathPrefix);
content = content.replace(/\.\/\.claude\//g, `./${dirName}/`);
content = content.replace(/~\/\.codex\//g, pathPrefix);
// #1515 stamp moved to _stampNonClaudeRuntimeDefaults (#1521 generalisation).
content = processAttribution(content, attribution);
break;
@@ -2402,6 +2444,11 @@ function rewriteStagedSkillBodies(stagedDir, opts) {
* attribution from opts, then delegates to applyRuntimeContentRewritesForCommandsInPlace
* (single copy+rewrite owner).
*
* @internal — symmetric companion to rewriteStagedSkillBodies; retained as the deep-seam
* API for command bodies. No production caller today (install rewrites commands via
* copyWithPathReplacement → applyRuntimeContentRewritesForCommandsInPlace). Kept for
* API symmetry + test coverage.
*
* @returns {string} path to the temp dir (caller is responsible for cleanup)
*/
function rewriteStagedCommandBodies(stagedDir, opts) {
@@ -2517,4 +2564,7 @@ export = {
rewriteStagedCommandBodies,
_computePathPrefix: computePathPrefix,
_applyRuntimeRewrites,
_stampNonClaudeRuntimeDefaults,
// #1521: canonical non-Claude runtime list for test files and tooling
NON_CLAUDE_RUNTIMES,
};

View File

@@ -868,6 +868,241 @@ function cmdWorktreeCleanupWave(cwd: string, args: string[] = []): void {
}
}
interface RecordAgentFields {
agentId: string;
worktreePath: string;
branch: string;
base: string;
}
interface RecordAgentPlan {
ok: boolean;
reason: string;
hint?: string;
entry: CleanupManifestEntry | null;
/** Serialized manifest to write back (with trailing newline); null when ok === false. */
manifest: string | null;
}
/**
* Pure planner for the per-agent wave-manifest append.
*
* Validates the candidate entry at write time using the SAME rules the
* cleanup-wave reader enforces (via `normalizeCleanupManifestEntry`), so an
* entry that `record-agent` accepts is guaranteed to survive
* `normalizeCleanupManifest` on read — a field that would be silently dropped
* at cleanup time fails loudly here instead.
*
* `agent_id` is treated write-strict (required) even though the reader is
* lenient (nullable): the whole point of this verb is to catch an
* under-populated entry at write time, and an entry whose author cannot be
* identified defeats that. A duplicate `(worktree_path, branch)` is also
* rejected loudly — the reader dedups on that key, so a re-record would be
* silently dropped (the failure mode this verb exists to eliminate). The
* on-disk shape stays the existing 4-field entry (`agent_id`, `worktree_path`,
* `branch`, `expected_base`) — no schema change; the reader re-derives
* `allowed_bases`.
*/
function planWorktreeRecordAgent(manifestRaw: string, fields: RecordAgentFields): RecordAgentPlan {
// 1. Write-strict required-field check (loud, with which flag is missing).
// Trim first so a whitespace-only value (" ") is rejected here rather
// than deferred to a guaranteed `git worktree remove` failure at cleanup.
const agentId = (fields.agentId || '').trim();
const worktreePath = (fields.worktreePath || '').trim();
const branch = (fields.branch || '').trim();
const base = (fields.base || '').trim();
const missing: string[] = [];
if (!agentId) missing.push('--agent-id');
if (!worktreePath) missing.push('--path');
if (!branch) missing.push('--branch');
if (!base) missing.push('--base');
if (missing.length > 0) {
return {
ok: false,
reason: 'missing_field',
hint: `record-agent requires ${missing.join(', ')}. Re-run with all of --agent-id, --path, --branch, --base set to non-empty (non-whitespace) values.`,
entry: null,
manifest: null,
};
}
// 2. Shared validation: run the candidate through the reader's normalizer.
// If it returns null the reader would drop this entry on read — reject now.
const candidate = {
agent_id: agentId,
worktree_path: worktreePath,
branch,
expected_base: base,
};
const entry = normalizeCleanupManifestEntry(candidate);
if (!entry) {
return {
ok: false,
reason: 'invalid_entry',
hint: `Entry failed cleanup-manifest validation: --path/--branch/--base must be non-empty and --branch must match ^worktree-agent-[A-Za-z0-9._/-]+$ (got branch="${branch}"). Fix the field and re-run.`,
entry: null,
manifest: null,
};
}
// 3. Parse the existing manifest. The init shell ({orchestrator_root, worktrees: []})
// is written inline by the orchestrator before any agent spawns; a missing or
// malformed manifest is a loud failure here, not a silent under-populated write.
let parsed: unknown;
try {
parsed = JSON.parse(manifestRaw);
} catch {
return {
ok: false,
reason: 'invalid_manifest_json',
hint: 'Manifest is not valid JSON. The orchestrator must initialize it as {"orchestrator_root": "...", "worktrees": []} before recording agents.',
entry: null,
manifest: null,
};
}
// Accept the canonical {worktrees: []} shell or a bare top-level array (both
// are read by normalizeCleanupManifest); preserve any other top-level keys.
let worktrees: unknown[];
let writeBack: unknown;
if (Array.isArray(parsed)) {
worktrees = parsed;
writeBack = worktrees;
} else if (parsed && typeof parsed === 'object') {
const container = parsed as Record<string, unknown>;
if (container.worktrees === undefined) container.worktrees = [];
if (!Array.isArray(container.worktrees)) {
return {
ok: false,
reason: 'manifest_shape_invalid',
hint: 'Manifest "worktrees" must be an array. Re-initialize as {"orchestrator_root": "...", "worktrees": []}.',
entry: null,
manifest: null,
};
}
worktrees = container.worktrees;
writeBack = container;
} else {
return {
ok: false,
reason: 'manifest_shape_invalid',
hint: 'Manifest must be a JSON object {"worktrees": []} or a top-level array.',
entry: null,
manifest: null,
};
}
// 4. Reject a duplicate (worktree_path, branch). The reader dedups on this
// exact key, but only over entries that NORMALIZE successfully — so an
// existing malformed same-key entry (which the reader would drop) must NOT
// block recording a valid one. Run each existing entry through the reader's
// own normalizer and compare only the entries the reader would keep; this
// matches its dedup behavior exactly. A real duplicate signals an upstream
// double-spawn — surface it loudly instead of silently dropping it.
const dupKey = `${entry.worktree_path}\0${entry.branch}`;
const isDuplicate = worktrees.some((existing) => {
const normalized = normalizeCleanupManifestEntry(existing);
return normalized !== null && `${normalized.worktree_path}\0${normalized.branch}` === dupKey;
});
if (isDuplicate) {
return {
ok: false,
reason: 'duplicate_entry',
hint: `The manifest already records worktree_path="${entry.worktree_path}" branch="${entry.branch}". The cleanup reader dedups on (worktree_path, branch), so re-recording would be silently dropped — this usually signals an upstream double-spawn. Investigate rather than re-record.`,
entry: null,
manifest: null,
};
}
// 5. Append the minimal 4-field entry, matching the existing on-disk format.
const recorded: CleanupManifestEntry = {
agent_id: entry.agent_id,
worktree_path: entry.worktree_path,
branch: entry.branch,
expected_base: entry.expected_base,
};
worktrees.push(recorded);
return {
ok: true,
reason: 'ok',
entry: recorded,
manifest: `${JSON.stringify(writeBack, null, 2)}\n`,
};
}
interface RecordAgentCmdDeps {
readFile?: (p: string) => string;
writeFile?: (p: string, content: string) => void;
write?: (s: string) => void;
writeErr?: (s: string) => void;
}
interface RecordAgentCmdResult {
ok: boolean;
reason: string;
hint?: string;
entry: CleanupManifestEntry | null;
manifest_path?: string;
}
/**
* CLI command: append a validated per-agent entry to a wave cleanup manifest.
*
* Usage: worktree record-agent --manifest <path> --agent-id <id> --path <worktree> --branch <branch> --base <sha>
*
* Fails loudly (non-zero exit + recovery hint on stderr) when a field is
* missing/garbled or the manifest is absent/malformed, rather than appending an
* under-populated entry that the cleanup reader would silently drop.
*/
function cmdWorktreeRecordAgent(cwd: string, args: string[] = [], deps: RecordAgentCmdDeps = {}): RecordAgentCmdResult {
const flag = (name: string): string => {
const i = args.indexOf(name);
return i >= 0 && i + 1 < args.length ? args[i + 1] : '';
};
const write = deps.write || ((s: string) => process.stdout.write(s));
const writeErr = deps.writeErr || ((s: string) => process.stderr.write(s));
const manifestPath = flag('--manifest');
if (!manifestPath) {
writeErr('Usage: worktree record-agent --manifest <path> --agent-id <id> --path <worktree> --branch <branch> --base <sha>\n');
process.exitCode = 2;
return { ok: false, reason: 'usage', entry: null };
}
const resolved = path.resolve(cwd, manifestPath);
const readFile = deps.readFile || ((p: string) => fs.readFileSync(p, 'utf8'));
let manifestRaw: string;
try {
manifestRaw = readFile(resolved);
} catch (err) {
const hint = `Manifest not found or unreadable at ${manifestPath}. The orchestrator must initialize it ({"orchestrator_root": "...", "worktrees": []}) before recording agents.`;
writeErr(`[gsd] worktree.record-agent: manifest_read_failed — ${hint}\n`);
write(`${JSON.stringify({ ok: false, reason: 'manifest_read_failed', hint, error: (err as Error).message }, null, 2)}\n`);
process.exitCode = 1;
return { ok: false, reason: 'manifest_read_failed', hint, entry: null };
}
const plan = planWorktreeRecordAgent(manifestRaw, {
agentId: flag('--agent-id'),
worktreePath: flag('--path'),
branch: flag('--branch'),
base: flag('--base'),
});
if (!plan.ok || plan.manifest === null) {
writeErr(`[gsd] worktree.record-agent: ${plan.reason} — ${plan.hint || ''}\n`);
write(`${JSON.stringify({ ok: false, reason: plan.reason, hint: plan.hint }, null, 2)}\n`);
process.exitCode = 1;
return { ok: false, reason: plan.reason, hint: plan.hint, entry: null };
}
const writeFile = deps.writeFile || ((p: string, content: string) => fs.writeFileSync(p, content, 'utf8'));
writeFile(resolved, plan.manifest);
write(`${JSON.stringify({ ok: true, reason: 'ok', entry: plan.entry, manifest_path: resolved }, null, 2)}\n`);
return { ok: true, reason: 'ok', entry: plan.entry, manifest_path: resolved };
}
/**
* Reap orphaned linked worktrees whose lock owner process is dead, whose
* branch tip is fully merged into the default branch, and whose lock file
@@ -1167,6 +1402,8 @@ export = {
planWorktreeWaveCleanup,
executeWorktreeWaveCleanupPlan,
cmdWorktreeCleanupWave,
planWorktreeRecordAgent,
cmdWorktreeRecordAgent,
reapOrphanWorktrees,
cmdWorktreeReapOrphans,
resolveWorktreeRoot,

View File

@@ -28,7 +28,8 @@ function parseWorkflowSteps(content) {
name: match[1],
// After #3797 architectural fix, callsites use gsd_run
readsRuntimeConfig: body.includes('RUNTIME=$(gsd_run query config-get runtime --default claude'),
codexWorktreeGuard: body.includes('Codex execute-phase worktree isolation is unsupported'),
// #1521: guard generalized from Codex-specific to all non-Claude runtimes
codexWorktreeGuard: body.includes('git worktree isolation') && body.includes('unsupported on runtime'),
worktreeDispatchGuidance: body.includes('isolation="worktree"'),
};
});

View File

@@ -5,7 +5,8 @@
* dispatched Plan/Execute via Agent(run_in_background=true). On Claude Code a
* backgrounded agent has no Agent/Task tool, so it cannot spawn the nested
* subagents (worktree executors, plan-checker, verifier). The workflows must
* now resolve the runtime and run inline on Claude Code.
* now resolve the runtime and run inline everywhere except Codex, which is the
* only supported runtime where a backgrounded agent can still nest subagents.
*/
const { describe, test } = require('node:test');
@@ -24,23 +25,47 @@ describe('bug-853 — manager/autonomous gate background dispatch by runtime', (
assert.ok(matches.length >= 2, 'manager.md must resolve runtime for both plan and execute dispatch');
});
test('manager.md documents why Claude Code cannot background-dispatch', () => {
assert.match(MANAGER, /backgrounded agent has no `Agent`\/`Task` tool/);
test('manager.md documents why most runtimes cannot background-dispatch', () => {
// Accept both old singular form (backgrounded agent has no) and new plural form (backgrounded agents have no)
assert.match(MANAGER, /backgrounded agents? ha(?:s|ve) no `Agent`\/`Task` tool/);
});
test('manager.md runs plan/execute inline on Claude Code', () => {
assert.match(MANAGER, /If `RUNTIME` is `claude`[\s\S]{0,400}?Skill\(skill="gsd-plan-phase"/);
assert.match(MANAGER, /If `RUNTIME` is `claude`[\s\S]{0,400}?Skill\(skill="gsd-execute-phase"/);
test('manager.md gates background dispatch on codex and runs plan/execute inline otherwise', () => {
// Codex takes the background path
assert.match(MANAGER, /If `RUNTIME` is `codex`[\s\S]{0,400}?run_in_background=true/);
// Inline is the default/else branch for plan — anchored on the explicit non-Codex label
assert.match(
MANAGER,
/Otherwise \(Claude Code or any other non-Codex runtime\)[\s\S]{0,400}?Skill\(skill="gsd-plan-phase"/,
);
// Inline is the default/else branch for execute — anchored on the explicit non-Codex label
assert.match(
MANAGER,
/Otherwise \(Claude Code or any other non-Codex runtime\)[\s\S]{0,400}?Skill\(skill="gsd-execute-phase"/,
);
});
test('autonomous.md gates interactive background dispatch by runtime', () => {
const autoRuntimeMatches = AUTONOMOUS.match(/config-get runtime/g) || [];
assert.ok(autoRuntimeMatches.length >= 2, 'autonomous.md must resolve runtime in both 3b (plan) and 3c (execute) interactive branches');
assert.match(AUTONOMOUS, /backgrounded agent has no `Agent`\/`Task` tool/);
// Accept both old singular form (backgrounded agent has no) and new plural form (backgrounded agents have no)
assert.match(AUTONOMOUS, /backgrounded agents? ha(?:s|ve) no `Agent`\/`Task` tool/);
});
test('autonomous.md runs plan/execute inline on Claude Code in interactive mode', () => {
assert.match(AUTONOMOUS, /On Claude Code \(`RUNTIME` is `claude`\)[\s\S]{0,400}?Skill\(skill="gsd-plan-phase"/);
assert.match(AUTONOMOUS, /On Claude Code \(`RUNTIME` is `claude`\)[\s\S]{0,400}?Skill\(skill="gsd-execute-phase"/);
test('autonomous.md gates interactive background dispatch on codex; runs plan/execute inline otherwise', () => {
// Codex block: run_in_background=true appears within the codex branch and gsd-plan-phase is nearby
assert.match(AUTONOMOUS, /If `RUNTIME` is `codex`[\s\S]{0,1200}?run_in_background=true[\s\S]{0,600}?gsd-plan-phase/);
// Codex block: run_in_background=true appears within the codex branch and gsd-execute-phase is nearby
assert.match(AUTONOMOUS, /If `RUNTIME` is `codex`[\s\S]{0,3000}?run_in_background=true[\s\S]{0,200}?gsd-execute-phase/);
// Inline is the otherwise/else branch for plan — anchored on the explicit non-Codex label
assert.match(
AUTONOMOUS,
/Otherwise \(Claude Code or any other non-Codex runtime\)[\s\S]{0,400}?Skill\(skill="gsd-plan-phase"/,
);
// Inline is the otherwise/else branch for execute — anchored on the explicit non-Codex label
assert.match(
AUTONOMOUS,
/Otherwise \(Claude Code or any other non-Codex runtime\)[\s\S]{0,400}?Skill\(skill="gsd-execute-phase"/,
);
});
});

View File

@@ -68,6 +68,29 @@ describe('_computePathPrefix', () => {
});
assert.equal(prefix, '/opt/custom-cursor/');
});
test('isWindowsHost tripwire — Windows paths collapse to $HOME/ same as POSIX (no-op today)', () => {
// Documents CURRENT behavior: isWindowsHost is accepted but not branched on.
// Both win32=true and win32=false return '$HOME/.cursor/' for a home-relative target.
// If a future Windows-specific branch is added, this tripwire fails and forces
// an explicit decision about what to return on Windows.
const withWindows = conversion._computePathPrefix({
isGlobal: true,
isOpencode: false,
isWindowsHost: true,
resolvedTarget: 'C:/Users/matte/.cursor',
homeDir: 'C:/Users/matte',
});
const withoutWindows = conversion._computePathPrefix({
isGlobal: true,
isOpencode: false,
isWindowsHost: false,
resolvedTarget: 'C:/Users/matte/.cursor',
homeDir: 'C:/Users/matte',
});
assert.equal(withWindows, '$HOME/.cursor/');
assert.strictEqual(withWindows, withoutWindows);
});
});
// ---------------------------------------------------------------------------
@@ -231,6 +254,52 @@ describe('rewriteStagedCommandBodies', () => {
});
});
// ---------------------------------------------------------------------------
// Error-path: applyRuntimeContentRewritesForCommandsInPlace must rm the tempDir
// on any exception and NOT leave an orphaned gsd-cmd-rewrites-* directory.
// ---------------------------------------------------------------------------
describe('applyRuntimeContentRewritesForCommandsInPlace — error-path tempDir cleanup', () => {
test('rmSync is called on the tempDir when readFileSync throws (deterministic monkeypatch)', () => {
// Asserting the injected error propagates proves the throw happens AFTER the tempDir is
// created (the function creates tempDir, then reads .md), so the catch's rmSync cleanup
// is genuinely exercised — deterministic on every platform/uid.
const stagedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-test-error-path-'));
fs.writeFileSync(path.join(stagedDir, 'x.md'), '# test\n');
const before = new Set(
fs.readdirSync(os.tmpdir()).filter(n => n.startsWith('gsd-cmd-rewrites-'))
);
const origReadFileSync = fs.readFileSync;
let leaked = [];
try {
fs.readFileSync = () => { throw new Error('injected read failure'); };
assert.throws(
() => conversion.applyRuntimeContentRewritesForCommandsInPlace(stagedDir, 'cursor', '/tmp/x/', false),
/injected read failure/,
);
// Restore before any further fs use so the snapshot read is trustworthy.
fs.readFileSync = origReadFileSync;
const after = fs.readdirSync(os.tmpdir()).filter(n => n.startsWith('gsd-cmd-rewrites-'));
leaked = after.filter(n => !before.has(n));
assert.deepStrictEqual(leaked, [], `tempDir not cleaned up on error: ${leaked.join(',')}`);
} finally {
// Idempotent restore — guard against early-throw paths above.
fs.readFileSync = origReadFileSync;
// Clean up the staged dir created for this test.
cleanup(stagedDir);
// Clean up any genuinely leaked gsd-cmd-rewrites-* dirs so the runner stays clean.
for (const n of leaked) {
cleanup(path.join(os.tmpdir(), n));
}
}
});
});
// ---------------------------------------------------------------------------
// Guard: runtime-artifact-layout no longer exports getInstallExports
// ---------------------------------------------------------------------------

View File

@@ -0,0 +1,135 @@
'use strict';
/**
* Regression tests for bug #1515: Codex install with runtime-neutral
* .planning/config.json resolves runtime as 'claude' and enables worktree
* isolation (unsafe for Codex).
*
* Root causes:
* A) config-get reads in workflows lacked --raw → output JSON-quoted →
* every comparison like [ "$RUNTIME" = "codex" ] failed silently.
* B) The conversion engine emitted --default claude for every runtime →
* neutral Codex config fell back to claude default.
*
* All tests assert on the SUT's RETURN VALUE (engine output), not raw file reads,
* except the integration test (test 4) which is explicitly the source↔engine
* parity guard and carries the allow-test-rule exemption.
*/
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const fc = require('fast-check');
const conversion = require('../gsd-core/bin/lib/runtime-artifact-conversion.cjs');
// ---------------------------------------------------------------------------
// Unit tests: engine stamps codex-specific defaults into emitted workflows
// ---------------------------------------------------------------------------
test('codex emit stamps its own runtime default into the runtime-resolution line', () => {
const line =
'RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")\n';
const out = conversion._applyRuntimeRewrites(line, 'codex', '$HOME/.codex/', true, undefined);
assert.ok(
out.includes('config-get runtime --default codex --raw'),
`Expected 'config-get runtime --default codex --raw' in output; got:\n${out}`,
);
assert.ok(
out.includes('|| echo "codex")'),
`Expected '|| echo "codex")' in output; got:\n${out}`,
);
assert.ok(
!out.includes('--default claude'),
`Expected '--default claude' to be fully rewritten; got:\n${out}`,
);
assert.ok(
!out.includes('echo "claude"'),
`Expected 'echo "claude"' to be fully rewritten; got:\n${out}`,
);
});
test('codex emit defaults workflow.use_worktrees to false', () => {
const line =
'USE_WORKTREES=$(gsd_run query config-get workflow.use_worktrees --raw 2>/dev/null || echo "true")\n';
const out = conversion._applyRuntimeRewrites(line, 'codex', '$HOME/.codex/', true, undefined);
assert.ok(
out.includes('config-get workflow.use_worktrees --default false --raw'),
`Expected 'config-get workflow.use_worktrees --default false --raw' in output; got:\n${out}`,
);
assert.ok(
out.includes('|| echo "false")'),
`Expected '|| echo "false")' in output; got:\n${out}`,
);
assert.ok(
!out.includes('|| echo "true")'),
`Expected '|| echo "true")' to be fully rewritten; got:\n${out}`,
);
});
test('claude runtime does NOT rewrite the runtime default — stamping is non-claude-scoped (#1521 inversion)', () => {
// #1521 generalizes stamping to ALL non-Claude runtimes. The negative case
// (no stamping) is now the 'claude' runtime, not other non-Claude runtimes.
const line =
'RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")\n';
const out = conversion._applyRuntimeRewrites(line, 'claude', '$HOME/.claude/', true, undefined);
assert.ok(
out.includes('--default claude --raw'),
`Expected claude output to preserve '--default claude --raw'; got:\n${out}`,
);
assert.ok(
!out.includes('--default codex'),
`Expected claude output NOT to contain '--default codex'; got:\n${out}`,
);
});
// ---------------------------------------------------------------------------
// Integration / parity guard: real source ↔ engine output for codex (all surfaces)
// ---------------------------------------------------------------------------
test('regression: every edited workflow gets codex-stamped (source↔engine parity, all surfaces) (#1515)', () => {
// allow-test-rule: emitted workflow runtime-resolution shell block is the runtime contract surface (#1515) — asserts on engine-transformed output of the real source
const WORKFLOWS = ['execute-phase.md', 'autonomous.md', 'manager.md', 'diagnose-issues.md', 'quick.md'];
const CLAUDE_RUNTIME = 'config-get runtime --default claude --raw 2>/dev/null || echo "claude"';
const CODEX_RUNTIME = 'config-get runtime --default codex --raw 2>/dev/null || echo "codex"';
const TRUE_WT = 'config-get workflow.use_worktrees --raw 2>/dev/null || echo "true"';
const FALSE_WT = 'config-get workflow.use_worktrees --default false --raw 2>/dev/null || echo "false"';
for (const wf of WORKFLOWS) {
const src = fs.readFileSync(path.join(__dirname, '..', 'gsd-core', 'workflows', wf), 'utf8');
const out = conversion._applyRuntimeRewrites(src, 'codex', '$HOME/.codex/', true, undefined);
// No un-stamped claude/true resolution line may survive codex emit on ANY surface.
assert.ok(!out.includes(CLAUDE_RUNTIME), `${wf}: residual un-stamped runtime read — engine regex no longer matches source line (parity drift)`);
assert.ok(!out.includes(TRUE_WT), `${wf}: residual un-stamped use_worktrees read — parity drift`);
// If the source HAS such a read, the codex form must be present.
if (src.includes(CLAUDE_RUNTIME)) assert.ok(out.includes(CODEX_RUNTIME), `${wf}: runtime read not stamped to codex`);
if (src.includes(TRUE_WT)) assert.ok(out.includes(FALSE_WT), `${wf}: use_worktrees read not defaulted to false`);
}
});
// ---------------------------------------------------------------------------
// Property tests (RULESET.TESTS.property-based-testing)
// ---------------------------------------------------------------------------
test('property: runtime stamping applies for ALL non-claude runtimes; only claude leaves --default claude unchanged (#1521)', () => {
// #1521: generalised from codex-only to all non-claude runtimes.
// Use the canonical list from the conversion module to avoid hand-rolled array drift.
const { NON_CLAUDE_RUNTIMES } = conversion;
const RUNTIMES = ['claude', ...NON_CLAUDE_RUNTIMES];
const line = 'RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")\n';
fc.assert(fc.property(fc.constantFrom(...RUNTIMES), (rt) => {
const out = conversion._applyRuntimeRewrites(line, rt, `$HOME/.${rt}/`, true, undefined);
return rt === 'claude'
? out.includes('--default claude --raw') && !out.includes('--default codex')
: out.includes(`--default ${rt} --raw`) && !out.includes('--default claude');
}));
});
test('property: codex stamping is idempotent on resolution lines (#1515)', () => {
fc.assert(fc.property(fc.constantFrom('runtime', 'use_worktrees'), (which) => {
const line = which === 'runtime'
? 'RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")\n'
: 'USE_WORKTREES=$(gsd_run query config-get workflow.use_worktrees --raw 2>/dev/null || echo "true")\n';
const once = conversion._applyRuntimeRewrites(line, 'codex', '$HOME/.codex/', true, undefined);
const twice = conversion._applyRuntimeRewrites(once, 'codex', '$HOME/.codex/', true, undefined);
return once === twice;
}));
});

View File

@@ -0,0 +1,228 @@
'use strict';
/**
* Regression tests for #1521: every non-Claude runtime stamps its own runtime
* identity + workflow.use_worktrees=false into emitted workflows.
*
* GSD's worktree isolation relies on Claude Code's isolation="worktree" spawn
* parameter, which no other runtime honors. #1519 (Codex-only fix) is
* generalized here to ALL non-Claude runtimes.
*
* All tests assert on the SUT's RETURN VALUE (engine output), not raw file reads,
* except the parity integration test which carries the allow-test-rule exemption.
*/
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const fc = require('fast-check');
const conversion = require('../gsd-core/bin/lib/runtime-artifact-conversion.cjs');
// #1521: use the canonical list from the conversion module rather than a hand-rolled
// local array that can drift from the real runtime set.
const { NON_CLAUDE_RUNTIMES: NON_CLAUDE } = conversion;
const WORKFLOWS = [
'execute-phase.md', 'autonomous.md', 'manager.md', 'diagnose-issues.md', 'quick.md',
];
const CLAUDE_RUNTIME_LINE = 'config-get runtime --default claude --raw 2>/dev/null || echo "claude"';
const TRUE_WT_LINE = 'config-get workflow.use_worktrees --raw 2>/dev/null || echo "true"';
const FALSE_WT_LINE = 'config-get workflow.use_worktrees --default false --raw 2>/dev/null || echo "false"';
// ---------------------------------------------------------------------------
// Parity across ALL non-Claude runtimes × all 5 workflows
// ---------------------------------------------------------------------------
test('parity: every non-Claude runtime stamps its own runtime default and use_worktrees=false on all workflows (#1521)', () => {
// allow-test-rule: emitted workflow runtime-resolution shell block is the runtime contract surface (#1521)
for (const rt of NON_CLAUDE) {
for (const wf of WORKFLOWS) {
const src = fs.readFileSync(
path.join(__dirname, '..', 'gsd-core', 'workflows', wf),
'utf8',
);
const out = conversion._applyRuntimeRewrites(src, rt, `$HOME/.${rt}/`, true, undefined);
// No un-stamped claude runtime line may survive
assert.ok(
!out.includes(CLAUDE_RUNTIME_LINE),
`${rt}/${wf}: residual un-stamped claude runtime read — _stampNonClaudeRuntimeDefaults not applied`,
);
// No un-stamped use_worktrees=true line may survive
assert.ok(
!out.includes(TRUE_WT_LINE),
`${rt}/${wf}: residual un-stamped use_worktrees=true read — _stampNonClaudeRuntimeDefaults not applied`,
);
// If the source had a runtime read, the output must have --default <rt>
if (src.includes(CLAUDE_RUNTIME_LINE)) {
assert.ok(
out.includes(`config-get runtime --default ${rt} --raw 2>/dev/null || echo "${rt}"`),
`${rt}/${wf}: runtime line not stamped to --default ${rt}`,
);
}
// If the source had a use_worktrees read, the output must have --default false
if (src.includes(TRUE_WT_LINE)) {
assert.ok(
out.includes(FALSE_WT_LINE),
`${rt}/${wf}: use_worktrees line not defaulted to false`,
);
}
}
}
});
// ---------------------------------------------------------------------------
// Claude unchanged — no stamping for the native runtime
// ---------------------------------------------------------------------------
test('claude runtime leaves runtime default and use_worktrees=true unchanged (#1521)', () => {
const src = fs.readFileSync(
path.join(__dirname, '..', 'gsd-core', 'workflows', 'execute-phase.md'),
'utf8',
);
const out = conversion._applyRuntimeRewrites(src, 'claude', '$HOME/.claude/', true, undefined);
// Claude emit must preserve the original --default claude line
if (src.includes(CLAUDE_RUNTIME_LINE)) {
assert.ok(
out.includes(CLAUDE_RUNTIME_LINE),
`claude/execute-phase.md: expected original claude runtime line to survive; got mutated`,
);
}
// Claude emit must NOT gain --default false for use_worktrees
assert.ok(
!out.includes(FALSE_WT_LINE),
`claude/execute-phase.md: use_worktrees line must NOT be stamped false for claude runtime`,
);
});
// ---------------------------------------------------------------------------
// fc property — identity: each runtime stamps itself, claude stays unchanged
// ---------------------------------------------------------------------------
test('property: _stampNonClaudeRuntimeDefaults stamps each non-claude runtime and leaves claude unchanged (#1521)', () => {
const line =
'RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")\n';
fc.assert(
fc.property(fc.constantFrom(...NON_CLAUDE, 'claude'), (rt) => {
const out = conversion._applyRuntimeRewrites(line, rt, `$HOME/.${rt}/`, true, undefined);
if (rt === 'claude') {
return out.includes('--default claude') && !/--default (?!claude)/.test(out);
}
return out.includes(`--default ${rt}`) && !out.includes('--default claude');
}),
);
});
// ---------------------------------------------------------------------------
// fc property — idempotence: stamping twice equals once
// ---------------------------------------------------------------------------
test('property: _stampNonClaudeRuntimeDefaults is idempotent (#1521)', () => {
fc.assert(
fc.property(
fc.constantFrom(...NON_CLAUDE),
fc.constantFrom('runtime', 'use_worktrees'),
(rt, which) => {
const line =
which === 'runtime'
? 'RUNTIME=$(gsd_run query config-get runtime --default claude --raw 2>/dev/null || echo "claude")\n'
: 'USE_WORKTREES=$(gsd_run query config-get workflow.use_worktrees --raw 2>/dev/null || echo "true")\n';
const once = conversion._applyRuntimeRewrites(line, rt, `$HOME/.${rt}/`, true, undefined);
const twice = conversion._applyRuntimeRewrites(once, rt, `$HOME/.${rt}/`, true, undefined);
return once === twice;
},
),
);
});
// ---------------------------------------------------------------------------
// Guard generalization: execute-phase.md uses != "claude" not = "codex"
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Guard generalization: execute-phase.md, quick.md, and diagnose-issues.md
// all use != "claude" (not = "codex") for the worktree guard (#1521)
// ---------------------------------------------------------------------------
test('execute-phase.md, quick.md, and diagnose-issues.md guards are generalized to != "claude" (not Codex-specific) (#1521)', () => {
// allow-test-rule: emitted workflow runtime-resolution shell block is the runtime contract surface (#1521)
const GUARD_WORKFLOWS = ['execute-phase.md', 'quick.md', 'diagnose-issues.md'];
for (const wf of GUARD_WORKFLOWS) {
const src = fs.readFileSync(
path.join(__dirname, '..', 'gsd-core', 'workflows', wf),
'utf8',
);
assert.ok(
src.includes('[ "$RUNTIME" != "claude" ] && [ "$USE_WORKTREES" != "false" ]'),
`${wf}: expected generalized guard [ "$RUNTIME" != "claude" ] && [ "$USE_WORKTREES" != "false" ]`,
);
assert.ok(
!src.includes('[ "$RUNTIME" = "codex" ] && [ "$USE_WORKTREES" != "false" ]'),
`${wf}: found Codex-specific guard — should have been generalized to != "claude"`,
);
}
});
// ---------------------------------------------------------------------------
// Orchestration gating: manager.md + autonomous.md now gate on codex for
// background dispatch, not on "not claude". (#1521 Stage 2)
// ---------------------------------------------------------------------------
test('manager.md and autonomous.md gate run_in_background on codex specifically (#1521)', () => {
// allow-test-rule: orchestration dispatch gating in manager/autonomous .md is the runtime contract surface (#1521)
const manager = fs.readFileSync(
path.join(__dirname, '..', 'gsd-core', 'workflows', 'manager.md'),
'utf8',
);
const autonomous = fs.readFileSync(
path.join(__dirname, '..', 'gsd-core', 'workflows', 'autonomous.md'),
'utf8',
);
// Both files must gate run_in_background on codex (not on a generic "not claude" condition)
assert.ok(
/`RUNTIME` is `codex`[\s\S]{0,500}?run_in_background=true/.test(manager),
'manager.md: expected run_in_background dispatch gated on RUNTIME=codex specifically',
);
assert.ok(
/`RUNTIME` is `codex`[\s\S]{0,700}?run_in_background=true/.test(autonomous),
'autonomous.md: expected run_in_background dispatch gated on RUNTIME=codex specifically',
);
// Inline is the default/else branch (not just claude)
assert.ok(
/Otherwise[\s\S]{0,200}?Claude Code or any other non-Codex runtime/.test(manager),
'manager.md: expected "Otherwise (Claude Code or any other non-Codex runtime)" inline branch',
);
assert.ok(
/Otherwise[\s\S]{0,200}?Claude Code or any other non-Codex runtime/.test(autonomous),
'autonomous.md: expected "Otherwise (Claude Code or any other non-Codex runtime)" inline branch',
);
});
test('manager.md and autonomous.md no longer contain old "not claude" background-dispatch gating (#1521)', () => {
// allow-test-rule: orchestration dispatch gating in manager/autonomous .md is the runtime contract surface (#1521)
const manager = fs.readFileSync(
path.join(__dirname, '..', 'gsd-core', 'workflows', 'manager.md'),
'utf8',
);
const autonomous = fs.readFileSync(
path.join(__dirname, '..', 'gsd-core', 'workflows', 'autonomous.md'),
'utf8',
);
// The old phrasing that unconditionally sent every non-claude runtime to background must be gone
assert.ok(
!manager.includes('If `RUNTIME` is not `claude` (e.g. Codex)'),
'manager.md: old "If `RUNTIME` is not `claude` (e.g. Codex)" gating must be replaced',
);
assert.ok(
!autonomous.includes('On other runtimes:'),
'autonomous.md: old "On other runtimes:" branch label must be replaced',
);
});

View File

@@ -0,0 +1,95 @@
'use strict';
/**
* E2E regression tests for #1521: real install path (copyWithPathReplacement)
* MUST stamp non-Claude runtime defaults into emitted gsd-core/workflows/*.md.
*
* The earlier unit tests in fix-1521-non-claude-runtime-default-resolution.test.cjs
* only verify the engine (_applyRuntimeRewrites). This test verifies the wiring:
* that a REAL `node bin/install.js --codex/--cursor --global` actually emits
* execute-phase.md with --default codex / --default cursor (not --default claude).
*
* Root cause: copyWithPathReplacement is the emit path for gsd-core/workflows/*.md;
* it did its own inline path rewrites but never called _stampNonClaudeRuntimeDefaults,
* so the stamping was dead-on-arrival in real installs.
*
* This test must be RED before the fix is applied (Step 1) and GREEN after (Step 2).
*/
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { cleanup } = require('./helpers.cjs');
const INSTALL = path.join(__dirname, '..', 'bin', 'install.js');
/**
* Run a real install into a temp config dir and return the emitted
* execute-phase.md content.
* @param {string} runtime e.g. 'codex', 'cursor', 'claude'
* @returns {string}
*/
function installAndRead(runtime) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), `gsd-inst-${runtime}-`));
const res = spawnSync(
process.execPath,
[INSTALL, `--${runtime}`, '--global', '--config-dir', dir],
{ encoding: 'utf8', timeout: 120000 },
);
assert.strictEqual(res.status, 0, `install --${runtime} failed: ${res.stderr || res.stdout}`);
const wf = path.join(dir, 'gsd-core', 'workflows', 'execute-phase.md');
assert.ok(fs.existsSync(wf), `emitted workflow missing for ${runtime}: ${wf}`);
const content = fs.readFileSync(wf, 'utf8');
cleanup(dir);
return content;
}
// ---------------------------------------------------------------------------
// RED tests: these MUST FAIL before the copyWithPathReplacement wiring is added
// ---------------------------------------------------------------------------
test('real install: codex-emitted execute-phase.md resolves runtime=codex and defaults worktrees off (#1521)', () => {
const c = installAndRead('codex');
assert.ok(
c.includes('config-get runtime --default codex --raw'),
'codex runtime default not stamped in real install',
);
assert.ok(
c.includes('config-get workflow.use_worktrees --default false --raw'),
'codex use_worktrees not defaulted false in real install',
);
assert.ok(
!c.includes('config-get runtime --default claude --raw'),
'residual claude default in codex install',
);
});
test('real install: cursor-emitted execute-phase.md resolves runtime=cursor (#1521)', () => {
const c = installAndRead('cursor');
assert.ok(
c.includes('config-get runtime --default cursor --raw'),
'cursor runtime default not stamped in real install',
);
assert.ok(
!c.includes('config-get runtime --default claude --raw'),
'residual claude default in cursor install',
);
});
test('real install: claude-emitted execute-phase.md keeps claude default + worktrees on (#1521)', () => {
const c = installAndRead('claude');
assert.ok(
c.includes('config-get runtime --default claude --raw'),
'claude default changed in claude install',
);
assert.ok(
c.includes('config-get workflow.use_worktrees --raw 2>/dev/null || echo "true"'),
'claude worktrees default changed (should still be true)',
);
assert.ok(
!c.includes('config-get workflow.use_worktrees --default false --raw'),
'claude install must NOT have use_worktrees=false stamped',
);
});

View File

@@ -11,6 +11,7 @@ const { test } = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const ROOT = path.resolve(__dirname, '..');
@@ -32,7 +33,10 @@ function walk(dir, acc) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.isDirectory()) {
if (!SKIP_DIRS.has(entry.name)) walk(path.join(dir, entry.name), acc);
} else if (SCAN_EXT.has(path.extname(entry.name))) {
// entry.isFile() excludes symlinks (and other non-regular dirents) so a broken symlink like
// a gitignored CLAUDE.md worktree symlink is skipped deterministically on every platform —
// it can't be read and isn't shipped repo text (#1545).
} else if (entry.isFile() && SCAN_EXT.has(path.extname(entry.name))) {
acc.push(path.join(dir, entry.name));
}
}
@@ -56,3 +60,41 @@ test('no phantom pre-migration issue references remain in repo text (#1073)', ()
`successor (#717/#720) or rewrite as prose (see #1073):\n` + offenders.join('\n'),
);
});
test('walk() skips broken symlinks and does not throw ENOENT (#1545)', (t) => {
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'nophantom-symlink-'));
let symlinkCreated = false;
try {
fs.writeFileSync(path.join(fixture, 'real.md'), '# real, no phantom refs\n');
try {
fs.symlinkSync(
path.join(fixture, 'does-not-exist-target'),
path.join(fixture, 'broken.md'),
);
// Verify the symlink actually exists (lstat succeeds even for dangling symlinks)
fs.lstatSync(path.join(fixture, 'broken.md'));
symlinkCreated = true;
} catch (e) {
// Windows without symlink privilege — genuine skip
}
if (!symlinkCreated) {
t.skip('platform cannot create symlinks unprivileged');
return;
}
const found = walk(fixture, []).map((f) => path.basename(f));
assert.ok(found.includes('real.md'), 'walk() must include real.md');
assert.ok(!found.includes('broken.md'), 'walk() must NOT include broken.md (broken symlink)');
// Mirror the production read loop — must not throw ENOENT
assert.doesNotThrow(
() => found.length && walk(fixture, []).forEach((fp) => fs.readFileSync(fp, 'utf8')),
'readFileSync on every walk() result must not throw (no broken symlinks returned)',
);
} finally {
// eslint-disable-next-line local/no-raw-rmsync-in-tests -- local cleanup in standalone guard test; no helpers import available (would introduce a test-dep cycle)
fs.rmSync(fixture, { recursive: true, force: true });
}
});

View File

@@ -20,14 +20,19 @@ const os = require('os');
const repoRoot = path.join(__dirname, '..');
// Simulate the pathPrefix computation from install.js (global install)
// Thin adapter over the REAL _computePathPrefix (ADR-1508 Phase 2: deleted hand-copy).
// Old signature: computePathPrefix(homedir, targetDir) assumed isGlobal=true, isOpencode=false.
// This adapter preserves that contract so existing call-sites stay unchanged.
process.env['GSD_TEST_MODE'] = '1';
const { _computePathPrefix } = require('../gsd-core/bin/lib/runtime-artifact-conversion.cjs');
function computePathPrefix(homedir, targetDir) {
const resolvedTarget = path.resolve(targetDir).replace(/\\/g, '/');
const homeDir = homedir.replace(/\\/g, '/');
if (resolvedTarget.startsWith(homeDir)) {
return '$HOME' + resolvedTarget.slice(homeDir.length) + '/';
}
return resolvedTarget + '/';
return _computePathPrefix({
isGlobal: true,
isOpencode: false,
isWindowsHost: process.platform === 'win32',
resolvedTarget: path.resolve(targetDir).replace(/\\/g, '/'),
homeDir: homedir.replace(/\\/g, '/'),
});
}
// Detect whether `content` leaks a resolved absolute homedir path (e.g.
@@ -65,29 +70,28 @@ describe('pathPrefix computation', () => {
});
test('Windows-style paths produce $HOME/ not C:/', () => {
// On Windows, path.resolve returns the input unchanged when it's already absolute.
// Simulate the string operation directly (can't use path.resolve for Windows paths on macOS/Linux).
const winHomedir = 'C:\\Users\\matte';
const winTargetDir = 'C:\\Users\\matte\\.claude';
const resolvedTarget = winTargetDir.replace(/\\/g, '/');
const homeDir = winHomedir.replace(/\\/g, '/');
const prefix = resolvedTarget.startsWith(homeDir)
? '$HOME' + resolvedTarget.slice(homeDir.length) + '/'
: resolvedTarget + '/';
// Call the REAL _computePathPrefix with Windows-style paths.
// isWindowsHost=true is passed; today the function ignores it (no-op) and
// the $HOME shorthand is determined by the startsWith(homeDir) check alone.
const prefix = _computePathPrefix({
isGlobal: true,
isOpencode: false,
isWindowsHost: true,
resolvedTarget: 'C:/Users/matte/.claude',
homeDir: 'C:/Users/matte',
});
assert.strictEqual(prefix, '$HOME/.claude/');
assert.ok(!prefix.includes('C:'), `Should not contain drive letter, got: ${prefix}`);
});
test('target outside home uses absolute path', () => {
const homedir = '/home/user';
const targetDir = '/opt/gsd/.claude';
// path.resolve won't change an already-absolute path on the same OS,
// so simulate the string operation directly
const resolvedTarget = targetDir.replace(/\\/g, '/');
const homeDir = homedir.replace(/\\/g, '/');
const prefix = resolvedTarget.startsWith(homeDir)
? '$HOME' + resolvedTarget.slice(homeDir.length) + '/'
: resolvedTarget + '/';
const prefix = _computePathPrefix({
isGlobal: true,
isOpencode: false,
isWindowsHost: false,
resolvedTarget: '/opt/gsd/.claude',
homeDir: '/home/user',
});
assert.strictEqual(prefix, '/opt/gsd/.claude/');
assert.ok(!prefix.includes('$HOME'), `Should not contain $HOME for non-home paths`);
});

View File

@@ -193,8 +193,15 @@ describe('ADR-857 Phase 6 capstone conformance (#1139)', () => {
// extract to capabilities. Frozen pre-phase-6 sizes (LF bytes); the files must
// drop strictly below these. This also defeats double-run gaming — declaring a
// hook while leaving the inline block keeps the file from shrinking -> red.
//
// #1298: the execute-phase.md ceiling was raised from 93166 to accommodate
// wiring the mandatory `worktree record-agent` writer verb into the per-agent
// wave-manifest append. That verb is privileged host machinery (ADR-857
// Decision #1) — NOT the optional-feature inline logic this budget ratchets
// toward capabilities — so its footprint legitimately raises the host-loop
// ceiling rather than signalling an un-extracted optional feature.
const { lfByteCount } = require('../scripts/workflow-size.cjs');
const PRE_PHASE6 = { 'plan-phase.md': 94519, 'execute-phase.md': 93166 };
const PRE_PHASE6 = { 'plan-phase.md': 94519, 'execute-phase.md': 93600 };
const notShrunk = [];
for (const [file, frozen] of Object.entries(PRE_PHASE6)) {
const now = lfByteCount(path.join(ROOT, 'gsd-core', 'workflows', file));

View File

@@ -8,14 +8,14 @@
"audit-fix.md": 10988,
"audit-milestone.md": 17637,
"audit-uat.md": 7425,
"autonomous.md": 42263,
"autonomous.md": 42778,
"check-todos.md": 9431,
"cleanup.md": 9897,
"code-review-fix.md": 23890,
"code-review.md": 31602,
"complete-milestone.md": 29987,
"debug.md": 13505,
"diagnose-issues.md": 12425,
"diagnose-issues.md": 12820,
"discovery-phase.md": 8651,
"discuss-phase-assumptions.md": 26984,
"discuss-phase-power.md": 11273,
@@ -24,7 +24,7 @@
"docs-update.md": 55662,
"edit-phase.md": 12883,
"eval-review.md": 9923,
"execute-phase.md": 92914,
"execute-phase.md": 93426,
"execute-plan.md": 31365,
"explore.md": 10497,
"extract-learnings.md": 12849,
@@ -39,7 +39,7 @@
"insert-phase.md": 8943,
"list-phase-assumptions.md": 4305,
"list-workspaces.md": 5655,
"manager.md": 25937,
"manager.md": 26265,
"map-codebase.md": 20789,
"milestone-summary.md": 11774,
"mvp-phase.md": 13582,
@@ -57,7 +57,7 @@
"pr-branch.md": 9561,
"profile-user.md": 20650,
"progress.md": 29387,
"quick.md": 48435,
"quick.md": 48830,
"reapply-patches.md": 20393,
"remove-phase.md": 8469,
"remove-workspace.md": 7507,

View File

@@ -677,7 +677,9 @@ describe('bug #3384: worktree cleanup workflow contracts', () => {
const content = fs.readFileSync(EXECUTE_PHASE_PATH, 'utf8');
assert.match(content, /WAVE_WORKTREE_MANIFEST/);
assert.match(content, /worktree\.cleanup-wave/);
assert.match(content, /atomically append `\{agent_id, worktree_path, branch, expected_base\}`/);
// #1298: the per-agent manifest write now goes through the validated
// `worktree record-agent` writer verb (was a prose "atomically append").
assert.match(content, /record the `\{agent_id, worktree_path, branch, expected_base\}` entry with `gsd_run query worktree\.record-agent/);
assert.match(content, /try\{if\(!p\)throw new Error\("WAVE_WORKTREE_MANIFEST is unset"\)/);
assert.match(content, /WT_PATHS_FILE=.*gsd-worktree-paths-/);
assert.doesNotMatch(content, /done < <\(node -e 'const fs=require\("fs"\);const p=process\.env\.WAVE_WORKTREE_MANIFEST/);

View File

@@ -18,6 +18,7 @@
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const fc = require('fast-check');
const { createTempGitProject, createTempDir, cleanup } = require('./helpers.cjs');
const WORKTREE_SAFETY_PATH = path.join(
@@ -37,6 +38,8 @@ const {
snapshotWorktreeInventory,
planWorktreeWaveCleanup,
executeWorktreeWaveCleanupPlan,
planWorktreeRecordAgent,
cmdWorktreeRecordAgent,
} = require(WORKTREE_SAFETY_PATH);
const isWindows = process.platform === 'win32';
@@ -562,6 +565,382 @@ describe('planWorktreeWaveCleanup', () => {
});
});
// ─── planWorktreeRecordAgent (#1298 writer verb) ──────────────────────────────
// These tests pin the verb's reason for existing: a per-agent entry that
// record-agent ACCEPTS must survive the cleanup-wave reader, and one it REJECTS
// is exactly what the reader would have dropped silently. If write- and
// read-side validation ever diverge, the round-trip tests below fail.
describe('planWorktreeRecordAgent', () => {
const VALID = {
agentId: 'a1',
worktreePath: '/repo/.claude/worktrees/agent-a1',
branch: 'worktree-agent-a1',
base: 'abc123',
};
test('appends a validated entry that the cleanup-wave reader accepts (write/read parity)', () => {
const plan = planWorktreeRecordAgent('{"orchestrator_root":"/repo/main","worktrees":[]}', VALID);
assert.equal(plan.ok, true);
assert.deepEqual(plan.entry, {
agent_id: 'a1',
worktree_path: '/repo/.claude/worktrees/agent-a1',
branch: 'worktree-agent-a1',
expected_base: 'abc123',
});
// The serialized manifest must round-trip through the reader the cleanup
// path uses — proving write and read validate identically.
const written = JSON.parse(plan.manifest);
assert.equal(written.orchestrator_root, '/repo/main'); // preserved, no schema change
const readBack = planWorktreeWaveCleanup('/repo/main', written);
assert.equal(readBack.ok, true);
assert.equal(readBack.entries.length, 1);
assert.equal(readBack.entries[0].agent_id, 'a1');
});
test('preserves existing entries and other top-level keys when appending', () => {
const existing = JSON.stringify({
orchestrator_root: '/repo/main',
worktrees: [{
agent_id: 'a0',
worktree_path: '/repo/.claude/worktrees/agent-a0',
branch: 'worktree-agent-a0',
expected_base: 'aaa000',
}],
});
const plan = planWorktreeRecordAgent(existing, VALID);
assert.equal(plan.ok, true);
const written = JSON.parse(plan.manifest);
assert.equal(written.orchestrator_root, '/repo/main');
assert.equal(written.worktrees.length, 2);
assert.deepEqual(written.worktrees.map((w) => w.agent_id), ['a0', 'a1']);
});
test('accepts a bare top-level array manifest', () => {
const plan = planWorktreeRecordAgent('[]', VALID);
assert.equal(plan.ok, true);
const written = JSON.parse(plan.manifest);
assert.ok(Array.isArray(written));
assert.equal(written.length, 1);
assert.equal(written[0].branch, 'worktree-agent-a1');
});
// Write-strict agent_id: the reader treats agent_id as nullable, but the
// writer requires it — an entry whose author cannot be identified defeats the
// verb's purpose. This is the deliberate write-strict-vs-read-lenient decision.
test('fails loudly when --agent-id is empty (write-strict, unlike the lenient reader)', () => {
const plan = planWorktreeRecordAgent('{"worktrees":[]}', { ...VALID, agentId: '' });
assert.equal(plan.ok, false);
assert.equal(plan.reason, 'missing_field');
assert.match(plan.hint, /--agent-id/);
assert.equal(plan.manifest, null);
});
test('reports every missing field, not just the first', () => {
const plan = planWorktreeRecordAgent('{"worktrees":[]}', {
agentId: '', worktreePath: '', branch: '', base: '',
});
assert.equal(plan.reason, 'missing_field');
for (const flag of ['--agent-id', '--path', '--branch', '--base']) {
assert.match(plan.hint, new RegExp(flag.replace(/[-]/g, '\\$&')));
}
});
// Branch-regex consistency caveat: a branch outside the disposable namespace
// is what the reader drops silently — record-agent must reject it at write time.
test('rejects a branch outside the worktree-agent-* namespace (the entry the reader would drop)', () => {
const plan = planWorktreeRecordAgent('{"worktrees":[]}', { ...VALID, branch: 'feature/user-work' });
assert.equal(plan.ok, false);
assert.equal(plan.reason, 'invalid_entry');
assert.match(plan.hint, /worktree-agent-/);
assert.equal(plan.manifest, null);
// Confirm the rejected entry is genuinely one the reader drops.
const readBack = planWorktreeWaveCleanup('/repo/main', {
worktrees: [{ agent_id: 'a1', worktree_path: VALID.worktreePath, branch: 'feature/user-work', expected_base: 'abc123' }],
});
assert.equal(readBack.ok, false);
assert.equal(readBack.reason, 'empty_manifest');
});
test('fails loudly on malformed manifest JSON instead of clobbering it', () => {
const plan = planWorktreeRecordAgent('{not valid json', VALID);
assert.equal(plan.ok, false);
assert.equal(plan.reason, 'invalid_manifest_json');
assert.equal(plan.manifest, null);
});
test('rejects a manifest whose worktrees field is not an array', () => {
const plan = planWorktreeRecordAgent('{"worktrees":{}}', VALID);
assert.equal(plan.ok, false);
assert.equal(plan.reason, 'manifest_shape_invalid');
assert.equal(plan.manifest, null);
});
// The reader dedups on (worktree_path, branch); a re-record would be silently
// dropped at cleanup — exactly the failure mode the verb exists to eliminate —
// so the writer must reject it loudly rather than swallow it.
test('rejects a duplicate (worktree_path, branch) loudly instead of writing a droppable entry', () => {
const existing = JSON.stringify({
worktrees: [{
agent_id: 'a1',
worktree_path: '/repo/.claude/worktrees/agent-a1',
branch: 'worktree-agent-a1',
expected_base: 'abc123',
}],
});
// Same path+branch, different agent_id/base — still a duplicate by the reader's key.
const plan = planWorktreeRecordAgent(existing, { ...VALID, agentId: 'a1-retry', base: 'deadbee' });
assert.equal(plan.ok, false);
assert.equal(plan.reason, 'duplicate_entry');
assert.match(plan.hint, /worktree-agent-a1/);
assert.equal(plan.manifest, null);
});
test('detects a duplicate stored under the legacy `path` field too', () => {
const existing = JSON.stringify({
worktrees: [{ path: '/repo/.claude/worktrees/agent-a1', branch: 'worktree-agent-a1', expected_base: 'abc123' }],
});
const plan = planWorktreeRecordAgent(existing, VALID);
assert.equal(plan.reason, 'duplicate_entry');
});
// Reader-alignment: the cleanup reader dedups only over entries that normalize
// successfully, so a malformed same-key entry it would DROP must not block a
// valid recording — otherwise the writer is stricter than the reader and
// blocks legitimate recovery.
test('a malformed same-key existing entry does not block recording a valid one', () => {
const existing = JSON.stringify({
// Same path+branch as VALID but no expected_base — the reader drops this.
worktrees: [{ worktree_path: '/repo/.claude/worktrees/agent-a1', branch: 'worktree-agent-a1' }],
});
const plan = planWorktreeRecordAgent(existing, VALID);
assert.equal(plan.ok, true);
const readBack = planWorktreeWaveCleanup('/repo/main', JSON.parse(plan.manifest));
assert.equal(readBack.ok, true);
assert.equal(readBack.entries.length, 1); // reader keeps only the valid one
assert.equal(readBack.entries[0].expected_base, 'abc123');
});
test('rejects whitespace-only --path/--base (values are trimmed)', () => {
const wsPath = planWorktreeRecordAgent('{"worktrees":[]}', { ...VALID, worktreePath: ' ' });
assert.equal(wsPath.reason, 'missing_field');
assert.match(wsPath.hint, /--path/);
const wsBase = planWorktreeRecordAgent('{"worktrees":[]}', { ...VALID, base: ' \t ' });
assert.equal(wsBase.reason, 'missing_field');
assert.match(wsBase.hint, /--base/);
});
test('trims incidental surrounding whitespace on accepted values', () => {
const plan = planWorktreeRecordAgent('{"worktrees":[]}', {
agentId: ' a1 ', worktreePath: ' /repo/wt-a1 ', branch: ' worktree-agent-a1 ', base: ' abc123 ',
});
assert.equal(plan.ok, true);
assert.deepEqual(plan.entry, {
agent_id: 'a1', worktree_path: '/repo/wt-a1', branch: 'worktree-agent-a1', expected_base: 'abc123',
});
});
});
// ─── planWorktreeRecordAgent — property-based write/read parity (#1298) ────────
// The verb's reason for existing is the write→read parity invariant, so it must
// carry a fast-check property test (RULESET.TESTS.property-based-testing): an
// entry the writer ACCEPTS must survive the cleanup reader unchanged, and an
// entry with an invalid branch must be REJECTED symmetrically.
describe('planWorktreeRecordAgent — fast-check parity invariant (#1298)', () => {
const seg = fc.stringMatching(/^[A-Za-z0-9._/-]+$/); // include '/' — the namespace allows it
const agentBranch = seg.map((s) => `worktree-agent-${s}`);
const nonEmpty = fc.stringMatching(/^\S[\S ]*$/); // no leading whitespace, not blank
test('any writer-accepted entry round-trips through the cleanup reader unchanged', () => {
fc.assert(fc.property(
fc.record({ agentId: nonEmpty, worktreePath: nonEmpty, branch: agentBranch, base: nonEmpty }),
(fields) => {
const plan = planWorktreeRecordAgent('{"worktrees":[]}', fields);
if (!plan.ok) return; // rejection is fine; this property is about accepted entries
const readBack = planWorktreeWaveCleanup('/repo/main', JSON.parse(plan.manifest));
assert.equal(readBack.ok, true);
assert.equal(readBack.entries.length, 1);
const e = readBack.entries[0];
assert.equal(e.worktree_path, fields.worktreePath.trim());
assert.equal(e.branch, fields.branch.trim());
assert.equal(e.expected_base, fields.base.trim());
assert.equal(e.agent_id, fields.agentId.trim());
},
));
});
test('an entry with a branch outside the worktree-agent-* namespace is always rejected', () => {
fc.assert(fc.property(
fc.record({
agentId: nonEmpty,
worktreePath: nonEmpty,
// Any branch that does NOT match the disposable namespace.
branch: fc.string({ minLength: 1 }).filter((b) => !/^worktree-agent-[A-Za-z0-9._/-]+$/.test(b.trim())),
base: nonEmpty,
}),
(fields) => {
const plan = planWorktreeRecordAgent('{"worktrees":[]}', fields);
assert.equal(plan.ok, false);
assert.equal(plan.manifest, null);
},
));
});
});
// ─── cmdWorktreeRecordAgent (#1298 CLI wrapper) ───────────────────────────────
describe('cmdWorktreeRecordAgent', () => {
// process.exitCode is global; each failure-path test resets it so a failing
// exit code does not leak into the test runner's own exit status.
function withExitCode(fn) {
const saved = process.exitCode;
try { return fn(); } finally { process.exitCode = saved; }
}
const okArgs = [
'--manifest', 'manifest.json',
'--agent-id', 'a1',
'--path', '/repo/.claude/worktrees/agent-a1',
'--branch', 'worktree-agent-a1',
'--base', 'abc123',
];
test('writes the manifest and reports ok on the happy path', () => {
let writtenPath = null;
let writtenContent = null;
const out = [];
const result = cmdWorktreeRecordAgent('/repo/main', okArgs, {
readFile: () => '{"orchestrator_root":"/repo/main","worktrees":[]}',
writeFile: (p, c) => { writtenPath = p; writtenContent = c; },
write: (s) => out.push(s),
writeErr: () => {},
});
assert.equal(result.ok, true);
assert.equal(writtenPath, path.resolve('/repo/main', 'manifest.json'));
const written = JSON.parse(writtenContent);
assert.equal(written.worktrees.length, 1);
assert.equal(written.worktrees[0].agent_id, 'a1');
assert.match(out.join(''), /"ok": true/);
});
test('exits 2 with usage when --manifest is missing', () => {
withExitCode(() => {
const errs = [];
const result = cmdWorktreeRecordAgent('/repo/main', ['--agent-id', 'a1'], {
writeErr: (s) => errs.push(s),
write: () => {},
});
assert.equal(result.ok, false);
assert.equal(result.reason, 'usage');
assert.equal(process.exitCode, 2);
assert.match(errs.join(''), /Usage: worktree record-agent/);
});
});
test('exits 1 loudly when the manifest cannot be read', () => {
withExitCode(() => {
const errs = [];
const result = cmdWorktreeRecordAgent('/repo/main', okArgs, {
readFile: () => { throw new Error('ENOENT'); },
writeErr: (s) => errs.push(s),
write: () => {},
});
assert.equal(result.ok, false);
assert.equal(result.reason, 'manifest_read_failed');
assert.equal(process.exitCode, 1);
assert.match(errs.join(''), /manifest_read_failed/);
});
});
test('does not write the manifest when the entry is invalid', () => {
withExitCode(() => {
let wrote = false;
const errs = [];
const result = cmdWorktreeRecordAgent('/repo/main',
['--manifest', 'm.json', '--agent-id', 'a1', '--path', '/p', '--branch', 'feature/x', '--base', 'abc123'], {
readFile: () => '{"worktrees":[]}',
writeFile: () => { wrote = true; },
writeErr: (s) => errs.push(s),
write: () => {},
});
assert.equal(result.ok, false);
assert.equal(result.reason, 'invalid_entry');
assert.equal(wrote, false); // must NOT append an under-populated entry
assert.equal(process.exitCode, 1);
assert.match(errs.join(''), /worktree-agent-/);
});
});
});
// ─── record-agent: real CLI dispatch + workflow wiring (#1298 integration) ────
// The unit tests above inject IO; these pin the live `gsd-tools.cjs query
// worktree.record-agent` dispatch and the execute-phase.md call site, so a
// future typo in the dotted command or the workflow wiring fails loudly.
describe('worktree record-agent — real CLI dispatch (#1298)', () => {
const fs = require('node:fs');
const { execFileSync } = require('node:child_process');
const GSD_TOOLS = path.join(__dirname, '..', 'gsd-core', 'bin', 'gsd-tools.cjs');
test('the dotted `query worktree.record-agent` path writes an entry the cleanup reader accepts', () => {
const dir = createTempDir();
try {
const manifest = path.join(dir, 'wave-manifest.json');
fs.writeFileSync(manifest, `${JSON.stringify({ orchestrator_root: dir, worktrees: [] })}\n`);
const out = execFileSync(process.execPath, [
GSD_TOOLS, 'query', 'worktree.record-agent',
'--manifest', manifest,
'--agent-id', 'a1',
'--path', path.join(dir, 'wt-a1'),
'--branch', 'worktree-agent-a1',
'--base', 'abc123',
], { encoding: 'utf8' });
assert.match(out, /"ok": true/);
const written = JSON.parse(fs.readFileSync(manifest, 'utf8'));
assert.equal(written.worktrees.length, 1);
assert.equal(written.worktrees[0].agent_id, 'a1');
// What the live CLI wrote must read back through the cleanup reader.
const readBack = planWorktreeWaveCleanup(dir, written);
assert.equal(readBack.ok, true);
assert.equal(readBack.entries[0].branch, 'worktree-agent-a1');
} finally {
cleanup(dir);
}
});
test('a missing field fails loudly via the real CLI (non-zero exit, manifest untouched)', () => {
const dir = createTempDir();
try {
const manifest = path.join(dir, 'wave-manifest.json');
fs.writeFileSync(manifest, `${JSON.stringify({ worktrees: [] })}\n`);
let threw = false;
try {
execFileSync(process.execPath, [
GSD_TOOLS, 'query', 'worktree.record-agent',
'--manifest', manifest,
'--path', path.join(dir, 'wt'), '--branch', 'worktree-agent-x', '--base', 'abc123',
], { encoding: 'utf8', stdio: 'pipe' });
} catch (err) {
threw = true;
assert.equal(err.status, 1);
assert.match(String(err.stderr), /record-agent: missing_field/);
}
assert.ok(threw, 'CLI must exit non-zero when --agent-id is missing');
assert.deepEqual(JSON.parse(fs.readFileSync(manifest, 'utf8')).worktrees, []);
} finally {
cleanup(dir);
}
});
test('the execute-phase.md per-agent append calls the record-agent verb', () => {
const wf = fs.readFileSync(
path.join(__dirname, '..', 'gsd-core', 'workflows', 'execute-phase.md'), 'utf8',
);
assert.match(wf, /worktree\.record-agent/, 'execute-phase.md must wire the record-agent verb');
});
});
// ─── executeWorktreeWaveCleanupPlan ───────────────────────────────────────────
describe('executeWorktreeWaveCleanupPlan', () => {