chore: merge release v1.4.0 to main (#884)
* fix(#663): resolve open CodeQL/Dependabot security alerts (ReDoS, prototype pollution, workflow perms, qs DoS) (#665) * fix(#663): resolve open CodeQL/Dependabot security alerts - ReDoS: collapse ambiguous nested quantifiers in phase-heading regexes (verify/validate/commands) and the plan-filename lookahead (phase) to provably-equivalent non-backtracking forms - prototype pollution: guard __proto__/constructor/prototype in setConfigValue - remove dead no-op .replace(/-/g,'-') in phase.cts - escape all regex metachars in bug-2839 test - add contents:read permissions to security-scan + install-smoke workflows - pin qs >= 6.15.2 via overrides (DoS GHSA) - broaden prompt-injection allowlist to translated security-model docs Closes #663 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#663): regression tests for prototype-pollution guard and roadmap-phase ReDoS Behavioral test that config-set rejects __proto__/constructor/prototype keys without polluting Object.prototype, plus a ReDoS guard (timing-bound) and behavior-preservation assertions for the collapsed phase-heading regexes. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#663): make ReDoS regression assert structured result, not elapsed time Replace elapsed-time assertions (which tripped local/no-elapsed-assertion ESLint rule and were unsound for synchronous ReDoS) with structured-result assertions on adversarial inputs: assert that malformed phase headings/ unchecked-item lines without a terminating colon/space yield an empty Set, which is both the correct behavior and an exercise of the fixed linear regex on the catastrophic-backtracking input shape. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#663): add Security changeset fragment for #665 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#663): fold prototype-pollution regression into config.test.cjs The standalone bug-663-config-prototype-pollution.test.cjs was a 9th config-module test file, tripping lint-test-file-count (the allowlist is ratcheted and must not grow). Consolidated into config.test.cjs instead. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * chore(#660): bump next to 1.3.1-dev.0 (-dev stream per ADR 660) (#672) After the 1.3.0 release, next moves onto the -dev prerelease stream so the trunk self-identifies as unreleased (floor = next patch). First manual exercise of the ADR-660 release model. Refs #660 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * ci(#660): use scoped GSD_BOT_PR_TOKEN for backmerge & release merge-back PR creation (#673) The open-gsd org blocks the Actions GITHUB_TOKEN from creating PRs, so auto-backmerge and the release finalize merge-back PR steps can't open their PRs (must be done manually). Point those two steps at a scoped secret (pull-requests:write + contents:write), falling back to GITHUB_TOKEN so behavior is unchanged until the secret is added. Refs #660 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix: accept published installer migration checksums * fix(#670): self-healing recovery for installer-migration checksum drift (#675) Editing the body of an already-released installer migration drifts its computed checksum (it hashes plan.toString()). The integrity guard then hard-aborted every prior install on upgrade with "applied migration checksum changed" — a 100% reproducible blocker (v1.3.0, all platforms). Already-applied migrations are filtered out of `pending` and never re-run, so a drifted checksum is functionally inert. ADR-0008 anticipates checksum-mismatch state as something the install-state layer must handle gracefully (plan -> apply -> recover/report), not abort on. This supersedes the published-checksum allowlist merged in #674 (per-release maintenance debt — every historical checksum hand-pinned, still throws for any unregistered value) with a general, self-healing recovery: - Replace the throwing guard with non-fatal `collectAppliedChecksumDrift`, surfaced on `plan.checksumDrift`. - Reconcile drifted stored checksums durably on the next state write (`reconcileDriftedChecksums`), idempotently (no perpetual writes). - Relocate the "shipped migration bodies are immutable" rule to a CI baseline test that locks every shipped migration's checksum and fails on body drift — where #615 should have been caught, instead of blocking users. Removes #674's legacyChecksums field, per-migration checksum pins, published-checksums.json fixture, and compat test. Fixes #670 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#676): consolidate hotfix into release.yml (delete standalone hotfix workflow) (#678) * fix(#676): consolidate hotfix into release.yml; delete standalone hotfix workflow npm allows only one trusted publisher per package and it is release.yml, so the standalone hotfix.yml (token-auth) could never publish via OIDC (ENEEDAUTH on the v1.3.1 finalize). Fold the patch/hotfix path into release.yml — the sole OIDC trusted publisher — and delete hotfix.yml. - validate-version accepts X.Y.Z (Z>0) → hotfix/X.Y.Z + base_tag; rejects rc for hotfixes; X.Y.0 still → release/X.Y.0. - create branches hotfix/X.Y.Z from the base tag with optional auto-cherry-pick (default on) of fix:/chore: from next; release path unchanged. - finalize is branch-agnostic already and publishes @latest via the existing OIDC trusted publisher (no NODE_AUTH_TOKEN). - CONTRIBUTING branching table updated; hotfix.yml removed. Fixes #676 Supersedes #677. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#676): add hotfix/patch path to release.yml (OIDC trusted publisher) The companion to the hotfix.yml deletion: release.yml now handles patch versions (X.Y.Z) via hotfix/X.Y.Z branches and publishes @latest through the existing OIDC trusted publisher. CONTRIBUTING branching table updated. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#676): update tests/docs referencing deleted hotfix.yml (#680) hotfix.yml was deleted (folded into release.yml). Remove the now-broken release-coverage-scope and policy-release-no-npm-self-upgrade assertions that readFileSync'd hotfix.yml (release.yml equivalents retained), drop the dead install-smoke.yml path trigger, and update VERSIONING.md / docs/branching.md prose to describe hotfixes via the Release workflow with a patch version. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix: bump hono to 4.12.23 on next to clear moderate advisory Same moderate hono advisory (GHSA-3hrh-pfw6-9m5x et al.) that blocked the 1.3.1 hotfix is present on next (was 4.12.19); bump to keep the npm-audit gate green. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#690): promote CHANGELOG 1.3.x + gate release-notes promotion (#694) * fix(#690): promote CHANGELOG 1.3.x + gate release-notes promotion /gsd:update showed an empty "What's New" preview after updating to 1.3.1 because CHANGELOG.md's 1.3.x content was never promoted out of [Unreleased] into dated sections, so `scripts/changeset/cli.cjs extract` returned exit 2 ("no releases in range"). - CHANGELOG.md: split [Unreleased] into dated [1.3.0] and [1.3.1] sections (1.3.1 = hono advisory bump + installer-migration checksum self-heal, #670; 1.3.0 = the feature release), restoring an empty [Unreleased]. - scripts/changeset/cli.cjs: new `verify` subcommand that exits non-zero when CHANGELOG has no dated `## [x.y.z]` heading for a version; hoist shared stripV/resolveChangelogPath helpers used by extract + verify. - .github/workflows/release.yml: gate the finalize job on `verify` (after the build, before tag/publish) so an unpromoted CHANGELOG can never ship again. - gsd-core/workflows/update.md: move `rm -f $CHANGELOG_TMP` after the human-readable extract re-run so the preview no longer degrades to "(changelog unavailable)". - tests: regression guard for the 1.3.x headings + extract range + verify command coverage (present/absent/undated/v-prefixed/--json/prerelease). Closes #690 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#690): add changeset fragment for #694 Fixed-type fragment for the user-facing /gsd:update preview fix and the release-notes promotion gate. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#698): make auto-backmerge main→next actually land (admin-merge via PAT) (#699) The Auto Back-Merge workflow could open a back-merge PR but never landed it, and silently reported success on failure. Fixes: - Merge via admin bypass using GSD_BOT_PR_TOKEN (the PAT) instead of auto-merge, since back-merge PRs structurally can't satisfy next's required checks (Issue-link / PR-template / changeset-lint). - Stop swallowing create/merge failures with "|| echo ::warning" — real failures now fail the job. (That greenwashing hid the whole bug.) - Resolve the PR number with `--jq '.[0].number // empty'` (a no-match returns the string "null", not empty) and capture a freshly-created PR's number from the create URL to avoid GitHub API eventual-consistency races. - Merge the exact PR number (env-bound) rather than by branch name. - Force-push the disposable SHA-named bot branch, guarded by a chore/backmerge-main-to-next-* name check so a mislabeled PR can't redirect the force-push. - Apply labels non-fatally so a missing label can't abort PR creation. - On a genuine merge conflict, fail loudly (::error + exit 1) instead of pushing an empty branch and opening a PR with no diff. Closes #698 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#637): route 3 more workflows through gsd_run launcher (hardcoded $HOME sweep) (#642) * fix(#637): route 3 more workflows through gsd_run launcher (hardcoded $HOME sweep) The hardcoded `node "$HOME/.claude/gsd-core/bin/gsd-tools.cjs"` invocation form fixed in plan-phase.md (#621) survived in three more workflows. Same bug class: on a global/shim-only install with no project-local runtime, the hardcoded path can miss a working install, so the step reports the tool "not found" instead of resolving it via the launcher. #3668 introduced gsd_run resolution; these sites were missed. - plan-review-convergence.md: convert the 3 hardcoded invocations (init, roadmap get-phase, state planned-phase) to gsd_run. File already carried the canonical preamble (first gsd_run is the earlier convergence-enabled check). - ingest-docs.md, spec-phase.md: convert their hardcoded invocations to gsd_run and inject the canonical launcher preamble via `node scripts/sync-runtime-launcher.cjs` (these files previously had no gsd_run and no preamble). The injected preamble is byte-equal to _runtime-launcher.snippet.sh and precedes the first gsd_run call, per runtime-launcher-parity invariant (B). - Add tests/bug-637-workflow-no-hardcoded-home-tool.test.cjs: repo-wide regression guard asserting NO workflow .md invokes gsd-tools via a hardcoded $HOME path. Generalizes the plan-phase-only guard from #621 — the parity test guards retired $GSD_SDK / bare /gsd-tools tokens but not this form, which is how it survived across four files. Fails on the pre-fix files, passes after. runtime-launcher-parity 7/7; full unit suite green (3477 pass / 0 fail). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore(#637): add changeset fragment for PR #642 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(#637): update stale bug-2801 assertion to expect gsd_run bug-2801 pinned ingest-docs.md to the hardcoded node "$HOME/.../gsd-tools.cjs" init form, which #637 replaces with the gsd_run launcher. Flip the assertion to expect gsd_run init ingest-docs; the bare-gsd-tools rejection and CLI-handler tests are unchanged, and bug-637's repo-wide guard now owns the no-hardcoded-$HOME invariant. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Tom Boucher <trekkie@nomorestars.com> * fix(#705): route hardcoded $HOME gsd-tools invocations in agents/commands through gsd_run (#707) * fix(#705): route hardcoded $HOME gsd-tools invocations in agents/commands through gsd_run The hardcoded `node "$HOME/.claude/gsd-core/bin/gsd-tools.cjs" <cmd>` form (fixed for workflows in #621/#637) survived in agent/command surfaces and misresolves on global/shim-only installs. Route every agent-executed invocation through the resolved `gsd_run` launcher in gsd-phase-researcher, gsd-planner (load_graph_context extracted to a shared reference to stay under the planner size budget), import, and graphify. Add a regression guard over agents/ + commands/ + gsd-core/references/ bash blocks. User-facing display messages and docs are intentionally left untouched. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#705): use repo changeset fragment format (type: Fixed, pr: 707) The hand-written fragment used the standard changesets package format (package: bump) which lacks the type:/pr: frontmatter the repo's docs-required lint consumes (fail_malformed_fragment / missing_type). Regenerated via scripts/changeset/new.cjs. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#685): set windowsHide on all Windows child-process spawns (#688) * fix(#685): set windowsHide on all Windows child-process spawns A visible "gsd-core" console window flashed on Windows whenever a gsd-core child process spawned without `windowsHide: true`. The most visible offenders fire on every SessionStart / `/clear` (execNpm's `shell:true` npm view via the update-check worker) and on every Edit/Write/MultiEdit in a worktree (the worktree-path guard's git probe). Add `windowsHide: true` to every external-binary spawn in the runtime source: - hooks/gsd-context-monitor.js (record-session spawn) - hooks/gsd-worktree-path-guard.js (SPAWNOPT) - hooks/gsd-workflow-guard.js (git branch --show-current) - src/shell-command-projection.cts (execGit / execNpm / execTool) - src/check-command-router.cts (git log execFileSync) - src/roadmap-upgrade.cts (git status/rev-parse/reset/clean execSync) gsd-check-update.js already had it (the precedent). probeTty's tty call is POSIX-only and intentionally untouched. Adds a regression test that asserts each site plus a repo-wide completeness guard so a future external-binary spawn that omits windowsHide fails CI. No behavior change off-Windows. Closes #685 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#685): set changeset pr number to 688 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#687): bound agy print mode with its native --print-timeout (#689) `/gsd-review --agy` hung indefinitely on large prompts. agy's print mode runs the full tool-enabled agent, and on a big, file-path-rich prompt its agentic Cascade loops on the code_search/grep tool and never converges; the transcript fallback only runs after agy exits, so it can't recover a run that never exits. The agy CLI exposes no per-tool deny (that lives in the Antigravity SDK), but it does expose --print-timeout — agy's native print-mode cap. Pass it explicitly so a stalled run self-terminates through the tool's own mechanism; a non-zero exit discards any partial output so the existing transcript fallback / "review failed" stub take over. Adds a regression test. Closes #687 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#669): /gsd-review --cursor actually invokes cursor-agent (#686) * fix(#669): /gsd-review --cursor actually invokes cursor-agent The Cursor reviewer branch in review.md never ran the agent: - detection probed `cursor` (the IDE launcher) instead of the headless `cursor-agent` binary - the invocation used the two-token `cursor agent` (the IDE treats `agent` as a file-path argument, so the agent never starts) - the prompt was piped via stdin, but `cursor-agent -p` reads the prompt from a command-line argument, and `2>/dev/null` hid the empty result Probe `cursor-agent`; invoke `cursor-agent -p --mode ask --trust --output-format text` with the prompt passed as a file-path-reference argument (avoids the OS arg-length limit on large prompts); capture stderr so failures are diagnosable. Invert tests/cursor-reviewer.test.cjs to assert the corrected contract, with negative guards against the two-token form and the stdin pipe. The sibling `agy` reviewer already used the argument form. Closes #669 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#669): set changeset pr number to 686 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * chore: archive 463 shipped changeset fragments before wiring render (#714) CHANGELOG promotion was a manual operator step that was never run, so 463 fragments for work already shipped in <=1.3.1 accumulated in .changeset/. Their notes were already hand-curated into the dated [1.2.0]/[1.3.0]/[1.3.1] CHANGELOG sections (#690 backfill, PR #694). Rendering them now would duplicate and mis-attribute shipped work. Move them to .changeset/archived/ (read non-recursively by all changeset tooling, so never rendered), keeping only the 3 genuinely-unreleased fragments at the top level. Prep for wiring `render` into the release finalize job (#690 follow-up). Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * chore(release): wire CHANGELOG render into release finalize job (#690 follow-up) (#715) * feat(#690): wire CHANGELOG render into release finalize job CHANGELOG promotion has always been a manual operator step, which is why 1.3.0/1.3.1 shipped unpromoted (#690). PR #694 added a `verify` latch that fails a release lacking a dated heading, but nothing performed the promotion. Wire `changeset render` into the finalize job, after build/test and before the verify gate, committing the promoted CHANGELOG so it ships with the release. Add a `--allow-empty` flag to cmdRender so a zero-fragment release still emits a dated heading (with a '_No notable changes._' placeholder) instead of writing nothing and tripping the verify gate. Note: requires the changeset-archive cleanup (separate PR) to land first, so the first render consumes only genuinely-unreleased fragments. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#713): set changeset pr number to 715 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * docs: document --only and --text flags for /gsd-autonomous (#695) (#716) Adds --only N and --text to the COMMANDS.md reference table and the run-phases-autonomously how-to guide, revised to fit the Diataxis framework (reference: factual/parallel rows; how-to: goal-framed sections). * feat(#656): Research module — content-addressed cache + provider seam + registry-API legitimacy (#664) * feat(#656): add Research Store module (content-addressed cache, TTL staleness) Content-addressed research cache behind a clock seam: researchKey (sha256, deterministic), putResearch/getResearch ({hit,stale}, never throws), ttlForSource (curated HIGH 30d / MED 7d / web LOW 1d), two-tier resolveStorePath (curated -> ~/.gsd/research-cache, web/synthesis -> project .planning/research/.cache). 28 behavioral + property tests; boundary coverage at ttl-1/ttl/ttl+1. Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(#656): add Research Provider module (waterfall + confidence + plan) Single source of truth for the Balanced provider waterfall (docs Context7->Ref->Jina, web Exa+Tavily, fallback Perplexity/Brave, Firecrawl scrape-only). classifyConfidence stamps HIGH|MEDIUM|LOW by provider (never throws). providerAvailability maps config flags to usable providers. planResearch checks the Research Store (injected seam) and returns cache-hits + a per-question fetch plan, falling through the waterfall to the always-available websearch terminal. 22 behavioral + property tests. Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(#656): add Package Legitimacy module (registry-API verdicts, slopcheck optional) Replaces the pip-install-or-degrade slopcheck prose gate with code: classifyPackage (pure, never throws) computes OK|SUS|SLOP from tunable thresholds (minAgeDays 30, minWeeklyDownloads 1000, requireRepo). checkPackages queries injectable npm/PyPI/crates registry adapters (real https with 5s timeout, degraded-not-thrown on failure); slopcheck is one optional adapter that can only escalate severity, never degrade to [ASSUMED]. 34 behavioral + property tests; boundary coverage on age and downloads (limit-1/limit/limit+1). Known follow-up: real npm adapter must add api.npmjs.org last-week downloads fetch (currently null -> unknown-downloads). Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(#656): detect Tavily/Ref/Perplexity/Jina provider keys; complete npm downloads adapter config: add tavily_search/ref_search/perplexity/jina availability flags (env var or ~/.gsd/<x>_api_key), mirroring brave_search/exa_search/firecrawl, so the Research Provider waterfall can gate them. package-legitimacy: real npm adapter now fetches api.npmjs.org last-week downloads (bounded, degraded-not-thrown) so weeklyDownloads is populated. +12 config tests; 34 legitimacy tests unchanged. Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(#656): expose Research seam via gsd-tools query (research-plan, research-store, package-legitimacy) Routes the L2-hybrid surface so agents reach it as CLI: 'query research-store get/put' (cache, HOME-sandboxable), 'query research-plan --input' (cache-hits + fetch plan from planResearch), 'query package-legitimacy check --ecosystem' (async registry verdicts). Commands skip .planning root resolution and appear in top-level usage. 5 behavioral runGsdTools tests; command-contract unchanged (335). Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(#656): document Research module (CONTEXT predicates, ADR-0656, architecture, changeset) Adds GSD-RESEARCH.* + DEFECT.RESEARCH-PROVIDER-PROSE-DRIFT predicates to CONTEXT.md, ADR-0656 recording the L2-hybrid seam decision, a docs/ARCHITECTURE.md Research Module subsection, and an Added changeset fragment (pr:0, backfill on PR). Notes the #657 deferrals (agent collapse + install.js MCP mapping). Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore(#656): sync inventory for research modules Regenerate INVENTORY-MANIFEST.json and bump docs/INVENTORY.md CLI Modules count 82->85 with rows for research-store/research-provider/package-legitimacy (DEFECT.INVENTORY-DRIFT). Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore(#656): eslint-ignore generated research .cjs artifacts (ADR-457) research-store/research-provider/package-legitimacy .cjs are tsc-generated from src/*.cts, so they belong in the ESLint ignore block (lint the .cts source, not the emitted .cjs). Fixes tests/551-eslint-bin-lib-coverage. Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore(#656): backfill changeset pr number to #664 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore(#656): satisfy eslint lint-tests gate Fix 20 eslint errors in the new research files: use helpers.cleanup() instead of raw fs.rmSync() in tests (local/no-raw-rmsync-in-tests, Windows-EBUSY retry budget); drop redundant '| string' union members and unnecessary type assertions; deterministic object normalization in researchKey (no-base-to-string). Logic unchanged; 6180 tests still green. Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(#656): harden package legitimacy per review (W1/W2/I3/I4) W1: httpsGet now reads statusCode; npm/PyPI/crates map 404 -> exists:false -> SLOP (registry-existence is the #1 slopsquatting defense; previously only npm caught it). Transport made injectable (_setHttpGet) for hermetic 404 tests. W2: suspicious-postinstall is now terminal SLOP independent of the optional slopcheck adapter, and the regex drops the bare https?:// arm (over-fired on esbuild/sharp/node-gyp) for shell-exec/download-exec signatures only. I3: checkPackages now threads version to registry.lookup and adapters verify that specific version exists. I4: moreServerVerdict -> moreSevereVerdict. +11 regression tests (all RED-first); 45 total green. Addresses review by @davesienkowski on #664. Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(#656): research-store tier coherence + freshness + version TTL (W4/I1/I2/I4) I1: tier now derives from source (curated -> user ~/.gsd, else -> project .planning), not kind, so put-tier and get-tier can't diverge; kind is a key component only. W4: getResearch searches both tiers and returns the freshest (non-stale preferred), never letting a stale curated entry shadow a fresh web one; blank version caps TTL at 1 day (no 30d on version-blind keys). I2: atomic platformWriteSync instead of raw fs.writeFileSync on the shared global path. I4: dropped the dead ttlForSource arm. CLI get now searches both tiers. +5 RED-first regression tests; 38 green. Addresses review by @davesienkowski on #664. Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(#656): expose classifyConfidence as a CLI route, killing dead code (W3) Adds 'gsd-tools query classify-confidence --provider X [--verified]' so research agents get the confidence tier FROM CODE (provider waterfall + verification lever) instead of asserting it in prose. classifyConfidence previously had no runtime caller. HIGH means 'trusted provider'; --verified raises web results to MEDIUM (verification semantics documented in ADR-0656). +4 behavioral tests. Addresses review by @davesienkowski on #664 (W3). Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(#656): close Codex adversarial-review findings (path-traversal, version-age, malformed-cache) HIGH: research key must be 64-hex sha256 (isValidResearchKey) + resolved-path containment check in put/get + CLI validation -> blocks '../../x' arbitrary-file-write. HIGH: package legitimacy now derives publishedAt from the REQUESTED version (npm time[version], PyPI releases[version] upload_time, crates versions[].created_at) so a new malicious version of an old package can't inherit old age and evade 'too-new'. MEDIUM: getResearch validates entry shape (finite fetched_at + positive ttl + required fields) -> malformed cache entry is a miss, not fresh-forever. +regression tests (RED-first); 111 green. Codex adversarial review (required pre-PR gate). Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(#656): close code-review correctness findings (1) package-legitimacy CLI now rejects unknown --flags instead of silently consuming the following package as a flag value; only --ecosystem takes a value. (2) crates recent_downloads (90-day) normalized to a weekly figure before the minWeeklyDownloads threshold (was ~13x too lenient). (3) research-plan --input validates parsed JSON is an object with an Array questions before destructuring -> clean usage error instead of an uncaught TypeError on null/bad input. (4) research-store put rejects a flag value that is itself a --flag (no more storing '--source' as content). (5) planResearch skips questions whose text is not a non-empty string instead of emitting question:undefined. +13 RED-first regression tests; 143 green. Code-review gate. Issue #656. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor(#657): extract researcher documentation_lookup to shared @-reference 6 researcher agents carried a near-duplicate <documentation_lookup> block; consolidate into gsd-core/references/research-documentation-lookup.md (@-included). Unifies the ctx7 CLI fallback to the safer 'command -v ctx7' guard (drops silent 'npx --yes ctx7@latest' execution in 5 agents). Behavior-preserving dedup; inventory 63->64 references. Phase A of the agent collapse. Issue #657. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor(#657): extract researcher philosophy + verification-protocol to shared @-references philosophy and the pitfalls+pre-submission-checklist common-core were near-duplicated in project/phase researchers; consolidate into gsd-core/references/research-{philosophy,verification-protocol}.md (@-included). phase-researcher keeps its 3 extra checklist items inline. Pre-submission domains checklist made agent-agnostic so project-researcher doesn't lose features/architecture coverage. Write-contract intentionally left inline (bug-214 tests assert it verbatim). Inventory 64->66 refs. Behavior-preserving. Phase A. Issue #657. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(#657): wire gsd-phase-researcher to the Research seam (Phase B / S1) The phase researcher now CALLS the code seam instead of carrying inline mechanics: provider waterfall -> 'gsd-tools query research-plan' (+ research-store put to cache digests); confidence-tier prose -> 'gsd-tools query classify-confidence'; slopcheck pip-install protocol -> 'gsd-tools query package-legitimacy check'. This makes the Research module a real runtime consumer (validates the seam end-to-end, addresses reviewer S1) and removes the duplicated waterfall/confidence/slopcheck prose. RESEARCH.md output contract, commit step, structured returns, and Phase-A @-includes unchanged. package-legitimacy-gate.test.cjs rewritten prose-grep -> behavioral (asserts the seam invocation). Issue #657. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(#657): wire gsd-project-researcher to the seam + add tavily/ref/jina MCP tools (Phase C.1) project-researcher now calls gsd-tools query research-plan / classify-confidence (+ research-store put) instead of the inline provider waterfall + confidence-tier prose (mirrors the phase-researcher rewire; no package-legitimacy — phase-only). Output contract (STACK/FEATURES/ARCHITECTURE/PITFALLS/SUMMARY.md + sections, no-commit, structured returns, Phase-A @-includes) unchanged. Adds mcp__tavily/ref/jina__* to the project/phase/ui researcher tools frontmatter (Balanced provider set) so install.js MCP mapping (C.2) has a consumer. Issue #657. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(#657): cover tavily/ref/jina MCP install handling + frontmatter parity guard (Phase C.2) Investigation: exa/firecrawl have no explicit per-runtime tool-mapping — every mcp__<server>__* except context7 rides the generic passthrough (Copilot lowercases; OpenCode/Cursor/Windsurf/Augment keep as-is; Gemini auto-discovers). tavily/ref/jina are handled identically, no install path broken. Added 12 copilot-install passthrough tests + a mcp-tool-inheritance parity guard (tavily co-declared with exa, jina with firecrawl, ref present across the 3 web researchers) so the MCP set can't drift. No io.github registry ids invented (none sourceable in-repo); documented as a follow-up. 488 tests green. Issue #657. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(#657): profiles as source of truth for researcher agents + drift-guard (Phase C.3) scripts/research-profiles.cjs declares each of the 7 researcher agents' identity + contract (name, description, color, tools, required @-includes, required gsd-tools seam calls, output-contract markers). scripts/gen-research-agents.cjs --check validates every committed agent against its profile; --write regenerates ONLY the frontmatter from profiles (body untouched) and is a verified no-op against the current agents (zero diff = fidelity). tests/research-agent-profiles.test.cjs is the DEFECT.GENERATIVE-FIX drift guard. Design note: profiles govern the generatable/contract surface rather than destructively regenerating the disparate operational prose bodies (those were deduped via @-includes in Phase A). scripts/ is not inventoried (no inventory change). Issue #657. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(#657): complete agent provider-dispatch + parity guard; align legitimacy field; validate profiles Adversarial-review findings: (HIGH) the seam-wired agents' Step-C dispatch only mapped 6 providers, so a planResearch result of jina/ref/perplexity/brave (reachable via the waterfall fallbacks) had no handling -> agent stall; completed both agents' dispatch to all 9 PROVIDER_WATERFALL ids + a catch-all, and added a parity test asserting agent dispatch stays in sync with research-provider PROVIDER_WATERFALL (DEFECT.GENERATIVE-FIX). (MEDIUM) phase-researcher package-legitimacy JSON example used 'package' but the module returns 'name' -> aligned. (LOW) gen-research-agents checkAgent now returns a clear failure for a malformed profile instead of throwing. +parity/validation tests (RED-first). Issue #657. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(#656): make classifyConfidence verification-evidence-driven (W3) Confidence conflated provider authority with claim verification — context7/ref stamped HIGH purely by provider identity, and the only verification lever was a self-set --verified flag. Split into two axes: provider authority (static) + verification evidence (code-computed). HIGH now requires ground-truth corroboration (legitimacyVerdict OK), independent of provider; authority alone caps at MEDIUM; SLOP caps at LOW; the self-reported --verified is demoted to a MEDIUM-only web lever. HIGH = corroborated-against-authoritative-source, not a correctness guarantee. Adds --legitimacy-verdict to the classify-confidence CLI; updates CONTEXT.md predicate + ADR-0656 (tier set unchanged, ADR-consistent). Addresses davesienkowski's W3 review on #664. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#656): bind classify-confidence verdict to code, closing CLI self-grading Adversarial review found the new --legitimacy-verdict flag was caller-supplied, so an agent could self-assert OK->HIGH without any real legitimacy check — reintroducing the exact self-grading hole W3 closes. Remove the free flag; the CLI now computes the verdict via checkPackages only when --package/--ecosystem is given (code-computed, not agent-asserted). Update the stale CLI test (context7 alone -> MEDIUM) and extend the property test to vary legitimacyVerdict. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(#717): re-base workflow size budget on bytes + document quality rationale (#719) * feat(#717): re-base workflow size budget on bytes + document quality rationale Re-base tests/workflow-size-budget.test.cjs from line counts to byte counts (matches Codex's 32,768-byte project_doc_max_bytes cap; deterministic, no tokenizer). Tier ceilings: XL=90000, LARGE=54000, DEFAULT=38000, GRACE=3000; discuss-phase target re-expressed as <30 KB. The #597 tighten-only ratchet and per-file budget semantics are preserved unchanged — only the unit swaps. byteCount() uses fs.statSync().size to match `wc -c` (includes trailing newline), deliberately not lineCount()'s newline-stripping. Document the context-rot / attention-budget QUALITY rationale (independent of prompt caching) in the test JSDoc and docs/ARCHITECTURE.md, plus the Goodhart caveat: the byte budget measures one file, so the real goal is bounded *loaded* context — eager @-imports game the proxy; legitimate extraction is lazy. Update CONTEXT.md RULESET.WORKFLOW_SIZE_BUDGET to bytes and remove a stale duplicate ruleset entry that still said "1800 lines". Defers the #3182 MVP-mode split (tracked separately): MVP is a cross-cutting concern woven through plan-phase/execute-phase, not a discrete extractable mode. Closes #717 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs(#717): add changeset fragment for byte-budget re-base Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#159): auto-use existing RESEARCH.md in /gsd:plan-phase --research-phase (#718) * feat(#159): auto-use existing RESEARCH.md in /gsd:plan-phase --research-phase When RESEARCH.md already exists in research-only mode and neither --research nor --view is passed, emit a one-line notice and exit cleanly instead of prompting update/view/skip. This matches the promptless auto-use of standard /gsd:plan-phase <N> (§5.1) and removes the §5.0/§5.1 inconsistency, making AI-agent and CLI invocations non-interactive in the common case. The two explicit-flag escape hatches (--research to refresh, --view to print) cover any deviation. Closes #159 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#159): point changeset fragment at PR #718 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs(#159): tighten research-phase reference register (Diataxis) Make the 'no modifier' research-phase entries descriptive rather than imperative and drop the trailing 'pass --research/--view' clauses, which duplicated the adjacent --research/--view documentation. Reference docs describe; the recovery flags are documented in their own entries. The emitted runtime notice in the workflow keeps naming the flags (in-band recovery), unchanged. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * chore: clean up clear-cut ESLint warnings (#732) (#734) Pay down pre-existing error→warn lint debt. Removes dead imports/vars, unused functions, redundant regex/string escapes, and stale eslint-disable directives; converts unused `catch (_e)` to optional catch binding (src/*.cts). No behavior change. Lint 345→125 warnings (0 errors); deferred categories (n/no-process-exit, test-sleeps, control-regex) tracked in #732 for follow-up. Full test suite green (0 failures); code-review verified all removals unused and all escape fixes semantics-preserving. Closes #732 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * chore(lint): justify intentional no-control-regex (ANSI strip) + ratchet to error (#737) The 5 no-control-regex warnings are all the same intentional ANSI-color-strip pattern /\x1b\[[0-9;]*m/g across 5 test files. The \x1b (ESC) control char is the required leading byte of an ANSI SGR sequence, so matching it is the whole point of stripping color codes from captured CLI/console output. Add an inline eslint-disable-next-line with justification at each site (not a refactor — the control char is essential, not accidental), then flip no-control-regex from warn to error so the debt can't regrow. Refs #736 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * chore(lint): refactor magic-sleep tests to async waits + ratchet rules to error (#735) Replace raw setTimeout/Atomics.wait synchronization sleeps in 4 test files with a shared async delay()/waitFor() poll-for-condition helper in tests/helpers.cjs, then flip local/no-magic-sleep-in-tests and no-restricted-syntax from warn to error so the debt can't regrow. - tests/helpers.cjs: add delay(ms) + waitFor(predicate, opts), exported - bug-1974: setTimeout backoff -> await delay() - config.test: drop Atomics.wait sleep(); async retry via await delay() - graphify: waitForBuildStatus/cleanupHookRepo async via await delay() - locking-bugs: 3 Atomics.wait poll loops -> await waitFor() - eslint.config.mjs: ratchet both rules warn -> error Refs #733 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#704): exclude } and ) from Codex path-rewrite lookbehind (no literal $gsd-core in installs) (#710) * fix(#704): exclude } and ) from Codex path-rewrite lookbehind Shell variable expressions like \${VAR}/gsd-core/ and command-substitution paths like \$(cmd)/gsd-local-patches were being rewritten to \$gsd-core and \$gsd-local-patches respectively because the negative lookbehind in convertSlashCommandsToCodexSkillMentions did not include } or ). Add both characters to the lookbehind set: (?<![a-zA-Z0-9./})]) Also adds regression test: tests/bug-704-codex-launcher-path-corruption.test.cjs Closes #704 * chore: add changeset for #704 * test: use RUNTIME_ROOT_PATH in assertion to eliminate dead-code lint warning Replace the partial hard-coded fragment '}/gsd-core/bin/' with the existing RUNTIME_ROOT_PATH const so the assertion both compiles clean (no unused variable) and self-documents which canonical launcher path must survive Codex conversion intact (#704). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore: link changeset to PR #710 --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#706): skip rescue of already-committed SUMMARY to avoid worktree cleanup merge_failed (#709) * fix(#706): skip rescueSummaryArtifacts when SUMMARY is already committed rescueSummaryArtifacts now probes `git cat-file -e HEAD:<path>` before copying a SUMMARY.md into the main checkout. When the file is already committed on the worktree branch, copying it as an untracked file causes `git merge --no-ff` to abort with "untracked working tree files would be overwritten by merge" — a permanent merge_failed cleanup-wave failure. Fail-closed on timeout: if cat-file is unreliable we skip rescue (the merge will surface the collision as it did before, which is recoverable). Adds 4 new test cases in worktree-safety.test.cjs covering: - committed SUMMARY skipped, merge succeeds (#706 regression case) - committed SUMMARY skipped even when timeout (fail-closed) - uncommitted SUMMARY still rescued (existing contract preserved) - rescue failure on ENOSPC still propagates (unchanged) Closes #706 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore: add changeset for #706 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#706): treat cat-file exit 128 as uncertain — skip rescue (fail-closed) The previous guard skipped rescue only when `exitCode === 0` (committed) or `timedOut`. Any other non-zero exit, including `128` (fatal git error: corrupt object store, unborn HEAD, missing repo), fell through and PROCEEDED with rescue — potentially re-creating the #706 untracked-file merge collision. Fix: rescue ONLY when `exitCode === 1` (cat-file definitively reports the object absent). All other outcomes — 0 (committed), 128 (fatal), null/SIGTERM (timeout), or any other code — are treated as "uncertain → skip rescue". Also corrects the JSDoc bullet that still referenced `git ls-files --error-unmatch` (the old mechanism); updated to `git cat-file -e HEAD:<relPath>`. Regression test added: asserts rescue is SKIPPED when cat-file returns exit 128, leaving the merge to surface the issue safely rather than silently copying an already-committed file. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore: link changeset to PR #709 --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor(scripts): replace process.exit() with ExitError + runMain handler (#739) (#740) Part 1 of 2 of the n/no-process-exit cleanup (umbrella #738): convert every process.exit() call in standalone scripts/** CLIs to the rule-compliant pattern. - New shared helper scripts/lib/cli-exit.cjs: ExitError(code,message) + runMain() which translates a thrown ExitError / returned number into process.exitCode (never process.exit()), flushing output and still firing process.on('exit'). - main()-based entrypoints: throw new ExitError(code) for errors, return <code> for verdicts; invoked via runMain(main). Child exit codes preserved via return. - top-level-only scripts: imperative body extracted into main() so mid-flow aborts (throw ExitError) actually halt; pure consts/helpers stay at module scope. - diff-touches-shipped-paths.cjs: stdin event handling restructured to an async read so the whole flow runs under runMain; uncaughtException/unhandledRejection nets replaced by an in-band catch that preserves EXIT_ERROR=2. Exit codes verified unchanged for every converted script (success/error/help and the 0/1/2 semantic codes in diff-touches). Rule stays warn here; flipped to error in part 2 (#738) once gsd-core/bin/** is also clean. Refs #739 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * refactor(bin): replace process.exit() in CLI entrypoints + ratchet rule to error (#738) (#741) Part 2 of 2 of the n/no-process-exit cleanup (completes umbrella #738; part 1 was #739/scripts). Converts the 20 flagged process.exit() calls in the three hand-written gsd-core/bin CLI entrypoints and flips n/no-process-exit to error. - New src/cli-exit.cts -> gsd-core/bin/lib/cli-exit.cjs (ExitError + runMain), the gsd-core-side equivalent of scripts/lib/cli-exit.cjs; registered in .gitignore, eslint ignores, and the inventory manifest like its siblings. - gsd-tools.cjs: 13 apply-prompt-budget exits -> throw ExitError; main()->runMain. - verify-reapply-patches.cjs: 6 exits -> throw ExitError / return verdict; runMain. - check-latest-version.cjs: 1 exit -> return verdict; runMain. - eslint.config.mjs: n/no-process-exit warn -> error. Scope note: the gsd-core/bin/lib/*.cjs modules (core, state, profile-pipeline, roadmap-command-router, adr-parser, ui-safety-gate) are tsc-generated and eslint-ignored (ADR-457), so their process.exit calls were never flagged and are intentionally left untouched. Only the linted hand-written entrypoints are in scope. Exit codes verified unchanged for all three entrypoints. Closes #738 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * refactor(#720): lazy-load MVP-only reference bodies on non-MVP runs (#746) * refactor(#720): lazy-load MVP-only reference bodies (eager @-import → gated Read) Convert eager @-imports of MVP-only reference bodies into lazy "Read" instructions gated on MVP_MODE / WALKING_SKELETON / MVP+TDD, so non-MVP planning/execution runs no longer pull MVP guidance into context. Covers both the workflow files and the planner/executor agent definitions (the dominant context-cost path): - workflows/plan-phase.md: planner-mvp-mode.md + skeleton-template.md (L146/936/937/941) - workflows/execute-phase.md: execute-mvp-tdd.md halt-report ref, now gated on gate-trip (L191) - agents/gsd-planner.md: planner-mvp-mode.md, user-story-template.md, skeleton-template.md - agents/gsd-executor.md: execute-mvp-tdd.md The dedicated always-MVP mvp-phase workflow keeps its eager imports (intentional). Behaviour is unchanged; non-MVP runs simply carry less loaded context. Adds a regression guard mirroring the discuss-phase lazy-load test, and documents the conformance in docs/ARCHITECTURE.md. Refs #720 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs(#720): add changeset fragment (pr #746) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * refactor(#712): replace Codex slash-command denylist lookbehind with positive-boundary match (#747) * refactor(#712): replace Codex slash-command denylist lookbehind with positive-boundary match The hyphen-style /gsd-<cmd> -> $gsd-<cmd> conversion in convertSlashCommandsToCodexSkillMentions used a negative-lookbehind DENYLIST enumerating characters that must NOT precede a real mention. #637 -> #704 showed this is an unbounded treadmill: each new unanticipated preceding char (/, ., word chars, then }, )) leaked the same path-corruption bug class, and a backtick-wrapped path (`/gsd-core/workflows/update.md`) still leaked through. Replace it with a POSITIVE two-boundary definition of a mention: 1. Left: opens at start-of-string, whitespace, or an inline-prose delimiter (backtick/quote/paren/bracket). 2. Right: the command token is not followed by a path separator `/` (a path continues, a command does not). The (?![a-z0-9/-]) lookahead also blocks regex backtracking to a shorter command. This closes the whole class by construction (no preceding-char denylist to maintain) and fixes the backtick-wrapped-path corruption the #704 test documented as a pre-existing gap, while preserving conversion of legitimate backtick-wrapped mentions (e.g. CONTEXT.md's `/gsd-execute-phase` lists). The colon-style /gsd: replace is intentionally left unguarded (it never appears as a filesystem path segment) and is annotated as such. Tests assert the regex directly (function now exported) across a convert/ don't-convert matrix plus one end-to-end pipeline assertion for the headline backtick-path case. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#712): add changeset fragment for PR #747 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#730): scope current-milestone Phase Details section in roadmap parser (#748) `extractCurrentMilestone()` scoped the current-milestone window to its `## Phases` checklist subsection and terminated at the milestone's own `## Milestone … (Phase Details)` heading, so the `### Phase N:` detail headers fell outside scope. Every parser-backed command — `init.phase-op` (and thus `/gsd:discuss-phase`, `/gsd:plan-phase`), `state`, `roadmap list`, and `validate health` (W006) — therefore could not resolve phases of any milestone after the first until a `.planning/phases/` directory already existed, blocking discuss/plan. The parser now additionally includes the current milestone's `(Phase Details)` section in scope, located via the already-computed version matches and anchored (boundary-aware) to the selected milestone's version token so sibling sub-milestones sharing a version prefix do not cross-pollinate. The existing heading selection and primary window are unchanged. Adds tests/bug-730-milestone-phase-details-scope.test.cjs covering the two-milestone reproduction, first-milestone non-regression, direct getRoadmapPhaseInternal resolution, validate-health W006 visibility, a three-milestone roadmap, and the closed-sibling sub-milestone case. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#683): auto-degrade phase execution to sequential on worktree base mismatch (#749) * fix(#683): auto-degrade phase execution to sequential on worktree base mismatch Claude Code forks worktree-isolated executors off the repository default branch (origin/HEAD), not the orchestrator's HEAD. Running /gsd-execute-phase on a branch diverged from the default (unmerged milestone/feature branch) left every executor without the phase's plan files and tripped the worktree-branch-check guard with `exit 42` — 100% reproducible, all OSes. - New module src/worktree-base-ref.cts: HEAD-vs-fork-base drift detection (origin/HEAD with symbolic-ref fallback) and no-clobber worktree.baseRef management, exposed as `worktree base-check` / `worktree set-baseref`. - execute-phase.md: pre-dispatch, for Claude Code with worktrees enabled, auto-degrades the run to sequential on the main tree when a base mismatch is detected, recommending worktree.baseRef:"head". The exit-42 guard stays as a backstop. - Installer: fresh local Claude installs set worktree.baseRef:"head" in .claude/settings.local.json (no-clobber, respecting an explicit shared settings.json value); upgrades print an opt-in notice pointing at `gsd-tools worktree set-baseref`. - Docs: how-to guide, CLI/config reference, planning-config cross-ref. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#683): auto-apply worktree.baseRef on upgrade; gate fresh+upgrade on use_worktrees Per maintainer direction: on a local Claude Code UPGRADE, set worktree.baseRef:"head" automatically (no opt-in notice) when the project's workflow.use_worktrees is enabled, instead of merely printing a remediation notice. For consistency the FRESH path is now gated the same way: both paths compute worktrees-enabled once (bounded walk-up read of .planning/config.json, default enabled unless workflow.use_worktrees === false) and apply the no-clobber baseRef only when enabled — never overwriting an explicit value in settings.local.json or a shared settings.json. gsd-tools worktree set-baseref remains for manual use. Docs + changeset updated; tests hardened (file-exists assertions, fresh+disabled case, upgrade idempotency). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#683): measure workflow byte-budget on LF, fixing Windows-only CI failure The workflow-size-budget test failed only on Windows: git checks out the .md files as CRLF (no eol=lf in .gitattributes) and byteCount used fs.statSync().size (raw on-disk bytes), counting an extra \r per line. That inflated execute-phase.md — the XL high-water-mark file pinned near its ceiling by the tighten-only ratchet — from 88492 LF bytes to ~90245 on Windows, over the 90000 XL ceiling, while passing on the LF-checkout Mac/Linux runners. The ceilings are explicitly "calibrated against raw `wc -c`" on an LF checkout, so the measurement should be LF-based on every platform. byteCount now reads the file and counts Buffer.byteLength after stripping CR, making the budget platform-independent (a no-op on LF checkouts; verified statSync === normalized for all 88 workflow files). No ceilings changed. Added a regression test asserting CRLF and LF content of the same file count identically. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#683): make worktree-base-ref test path mocks Windows-safe (path.join) tests/worktree-base-ref.test.cjs keyed its injected readFile/writeFile mocks (and a few expected `file` values) with forward-slash template literals like `${claudeDir}/settings.local.json`. The module composes those paths with path.join(), which emits backslashes on Windows, so the mock keys never matched the module's lookup → readFile returned null → resolveEffectiveBaseRef / cmdWorktreeBaseCheck / cmdWorktreeSetBaseRef (and the JSONC variants) failed on the Windows full-test runner only (they passed on Mac/Linux, and the install tests passed because they use the real filesystem). The module is correct; only the test fixtures hardcoded '/'. All mock keys and path assertions now use path.join(base, ...) mirroring the module, so they match on every platform (no-op on POSIX). 19 path references across 16 lines. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#703): add --granularity override flag to /gsd:plan-phase (#750) * feat(#703): add --granularity override flag to /gsd:plan-phase Add a `--granularity <coarse|standard|fine>` flag to /gsd:plan-phase that overrides the configured planning granularity for a single invocation. The override is a new highest-priority tier above the existing precedence chain (granularities[phaseType] -> granularity -> planning.granularity -> 'standard') in resolveGranularityInternal; when the flag is absent, resolution is byte-for-byte unchanged. cmdInitPlanPhase now resolves with phaseType 'planning' so granularities.planning participates, and emits the resolved value in the init JSON, which the plan-phase workflow forwards to the planner prompt. Invalid values are rejected at the CLI boundary via a shared assertValidGranularityOverride helper. Closes #703 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#703): set changeset pr to 750 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#751): recognise config-set prototype-pollution guard in CodeQL + test dynamic-key vectors (#752) CodeQL alert #26 (js/prototype-pollution-utility) kept firing on setConfigValue because its dataflow does not trace the #663 Set-based, pre-loop keys.some(...) forbidden-key check as a sanitising barrier on the write site. - src/config.cts: replace the Set + pre-loop check with inline literal comparisons (key === '__proto__' || 'prototype' || 'constructor') on the exact key used to index `current`, immediately before each write (intermediate keys in the descent loop, plus the final key). Same forbidden set, same error message and ERROR_REASON.CONFIG_PARSE_FAILED — behaviour unchanged from #663, but the barrier is now CodeQL-recognised. - tests/config.test.cjs: add regression tests for schema-valid dynamic-prefix keys (agent_skills.__proto__, agent_skills.constructor, agent_skills.prototype, features.__proto__, review.models.constructor) that pass the isValidConfigKey schema gate and reach the guard. Each asserts the guard's own message fires (not the schema gate's "Unknown config key") and Object.prototype is not polluted. The prior #663 tests never reached the guard — their keys are rejected by the schema gate first — so the guard's real attack surface was untested. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#25): scope gsd-verifier Step 7b to enumerate-or-single-test; forbid full-suite re-runs (#753) * feat(#25): scope gsd-verifier Step 7b to enumerate-or-single-test; forbid full-suite re-runs Step 7b's lone test example (`npm test -- --grep "$PHASE_TEST_PATTERN"`) is mocha/vitest/jest-specific, where `--grep` filters which tests *execute*. Models generalized it to `cargo test --workspace 2>&1 | grep X` (runs the whole suite, filters only *output*) and repeated it once per must-have, adding minutes per verification with no new evidence after the first run. Replace the example with language-agnostic guidance: prove a test EXISTS via enumeration (`cargo test -- --list` / `pytest --collect-only` / `npx vitest list` / `go test -list`), and prove it PASSES via a single named test (`cargo test <name> -- --exact` / `pytest -k` / `npx vitest run -t`). Add a Spot-check constraint forbidding more than one full-suite run per verification or piping a full run through grep per must-have, while still permitting one saved run + grep when a full run is genuinely required. docs/AGENTS.md gains a one-line Key-behaviors note, and a new test asserts the Step 7b content. Scoped per the maintainer decision on the issue: folded into Step 7b (no new top-level Step 7a) with no VERIFICATION.md label changes. Closes #25 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#25): add Changed changeset fragment for PR #753 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#52): add agent_skills_security.trusted_global_roots allowlist for global skills (#754) * feat(#52): add agent_skills_security.trusted_global_roots allowlist Opt-in allowlist so a global: agent skill whose SKILL.md realpath resolves outside the default global skills base (e.g. ~/.claude/skills) is accepted when its real target lies under a user-declared trusted root. Default [] is byte-identical to prior behavior; the symlink-escape guard is preserved and simply re-applied against each declared root. - src/security.cts: loadTrustedGlobalRoots — tilde-expand (~ and ~/), reject project-relative and dangerously broad roots (filesystem/UNC root, homedir), realpath-canonicalize each root every run and drop non-existent ones. - src/init.cts: on base-check failure the guard consults the trusted roots (hoisted out of the loop); emits a stderr NOTE when a skill is accepted via a trusted root so the widened boundary is visible. - src/core.cts: thread agent_skills_security through loadConfig. - config-schema.manifest.json: allow the new key path. - docs/CONFIGURATION.md: document the option and its security model. - tests/agent-skills.test.cjs: unit + end-to-end CLI coverage (regression, feature, negative, broad-root hardening, stderr NOTE). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs(#52): add changeset fragment for trusted_global_roots (#754) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * refactor(#651): consolidate verification-status routing into one queryable seam (#755) * refactor(#651): consolidate verification-status routing into one queryable seam The passed/gaps_found/human_needed verification status was re-encoded as bare strings across three prose surfaces (gsd-verifier emits, execute-phase routes, ship gates), each independently deciding the per-status next action with no parity coupling — the DEFECT.GENERATIVE-FIX class. Give the enum one home: src/verification.cts (-> bin/lib/verification.cjs) exposing `gsd_run query verification.status <phaseDir>` returning a typed {status, next_action, next_command}. ship.md and execute-phase.md now consume the query instead of re-deriving the routing in prose; gsd-verifier.md points at the shared vocabulary as the single emitter (values unchanged). Also fixes the latent broad-grep status misread (DEFECT.FRONTMATTER-SCALAR- BROAD-GREP): execute-phase.md read `grep "^status:"` over the whole report, so a body `status:` line could misroute a valid phase. Extraction is now frontmatter-scoped in one place. A parity test fails if a verifier status gains no route. Lands the two CONTEXT.md DEFECT entries captured on the issue. Closes #651 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#651): set changeset pr to 755 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#758): trigger draft-PR auto-close on pull_request_target (#760) Bare `pull_request` hands fork PRs a read-only GITHUB_TOKEN, so the close/comment API calls 403 and a first-time/external contributor's draft PR survives — bypassing the auto-close for exactly the population the job targets. Switch to `pull_request_target`, which runs in the base-repo context with a write-capable token even for fork PRs. Safe because the job never checks out or executes PR-supplied code; it only reads event metadata and calls the GitHub API. The minimal `permissions: pull-requests: write` block still constrains the token. Add a regression guard in tests/workflow-maintainer-skip.test.cjs asserting the workflow triggers on pull_request_target and not bare pull_request. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * docs(#58): add ADR for Runtime Install Policy Module boundary (#762) Record the Runtime Install Policy Module decision and ownership boundary: install policy projects a pure, typed install plan by composing artifact placements (ADR-3660) and command text (ADR-0009) plus per-runtime config intentions, with no filesystem IO; runtime adapters consume the plan and execute concrete file mutations and format-specific config rendering. Explicitly records what stays outside the policy module (TOML/JSON/Markdown serialization, merge semantics, filesystem effects). Adds the ADR index row in docs/adr/README.md and a glossary entry in CONTEXT.md. Leads the installer-refactor chain (#58 -> #60 -> #56). Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#759): non-destructive CHANGELOG preview in the rc release job (#763) The rc action publishes a release candidate to @next for testing but never surfaces the curated CHANGELOG section for the version under test — render only runs destructively at finalize (#715), so there was no safe way to preview the upcoming notes during the RC window. Add a --preview mode to scripts/changeset/cli.cjs cmdRender: it renders the dated release section to stdout via the existing renderChangelog/ serializeChangelog path (with priorChangelog: null, so only the new section is emitted), reuses the shared injectEmptyPlaceholder helper for zero-fragment releases, and returns WITHOUT writing CHANGELOG.md or deleting any .changeset fragment. Wire a "Preview CHANGELOG" step into the rc job that renders to a file (standalone command, so a malformed fragment fails the step) and cats it to the job summary and log. Closes #759 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#761): add scheduled base-context sweep to close SHA-branch-evading draft PRs (#765) close-draft-prs.yml (on pull_request_target after #760) cannot close fork draft PRs whose head branch name looks like a Git SHA — GitHub never dispatches pull_request_target for such branches, and a pull_request run from a fork gets a read-only token. So a draft PR on a SHA-named fork branch evades the auto-close. Add close-draft-prs-sweep.yml: a schedule (every 6h) + workflow_dispatch sweep running in base-repo context with pull-requests: write that paginates open PRs, filters to non-OWNER/MEMBER/COLLABORATOR drafts, and closes + comments them with the identical policy/message as the event-driven workflow. Re-fetches each candidate before mutating (TOCTOU guard), closes before commenting so enforcement is never gated on the explanatory comment, and core.setFailed on partial failures. The per-PR workflow remains the fast path; this is the safety net for the documented residual bypass. Extends tests/workflow-maintainer-skip.test.cjs with structural guards locking the triggers, write permission, maintainer carve-out, pagination, and message. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix discord release changelog announcements * test(#339): regression guard for gsd-sdk refs in runtime surfaces (#691) * test(#339): add regression guard for gsd-sdk refs in runtime surfaces Lock in the already-clean runtime surface so a retired `gsd-sdk`/`GSD_SDK` reference cannot creep back into a shipped prompt or hook. Scans gsd-core/workflows, gsd-core/references, commands/gsd, agents, and hooks (excluding the gitignored dist/ build artifact). Complements gsd-tools-path-refs.test.cjs, which only catches the `gsd-sdk query` binary form; this catches any runtime reference. A second test guards against an empty sweep so a future dir rename can't silently turn the guard into a no-op. Intentionally does NOT touch bin/install.js (live stale-package-detection mechanics per #339 triage) or CI/lint scripts (legitimate stale detection). Refs #339 * test(#339): split file content on /\r?\n/ for Windows CRLF parity The windows-test-parity-guard lint requires test files that readFileSync + split to use /\r?\n/, not '\n', so CRLF files don't leave a trailing \r. New test files are not in the PR #3649 allowlist. * test(#339): cover .sh/.json runtime files in workflows surface Address #691 review: the gsd-core/workflows surface scanned only .md, silently skipping two deployed runtime files — _runtime-launcher.snippet.sh (synced into every hook) and discuss-phase/templates/checkpoint.json. Add .sh/.json so the guard covers all 290 deployed runtime files (was 288/290), not just the .md subset. * test(#339): cover templates/contexts surfaces + per-ext empty-sweep guard Address PR #691 review (trek-e): - Add gsd-core/templates and gsd-core/contexts to RUNTIME_SURFACES — both are deep-copied by the installer and runtime-loaded via @~/.claude/gsd-core/templates/*.md anchors, so a reintroduced gsd-sdk ref there would have slipped past the guard. (major) - Reword the bin/install.js exclusion rationale: it has zero gsd-sdk refs today (subsystem removed in #515, shim retired in #522); the real reason it is excluded is that it is installer code, not a deployed prompt/hook surface. (minor) - Make the empty-sweep guard assert coverage per configured extension, not per surface — .md files alone kept gsd-core/workflows green even if .sh/.json were dropped, silently un-covering _runtime-launcher.snippet.sh and discuss-phase/templates/*.json. (low) --------- Co-authored-by: Tom Boucher <trekkie@nomorestars.com> * refactor(#60): make runtime config adapter registry explicit (#795) * refactor(#60): make runtime config adapter registry explicit Replace scattered inline `runtime === '...'` config-mutation branching in bin/install.js with an explicit, typed adapter registry. The new src/runtime-config-adapter-registry.cts maps each of the 15 supported runtimes to a config intent { installSurface, writesSharedSettings, finishPermissionWriter }; install()/finishInstall() dispatch by resolved intent instead of runtime-name checks (cursor/windsurf/trae collapse to one profile-marker-only branch). Behavior-preserving: the same config files are written for the same runtimes (opencode still writes both settings.json and its permissions; kilo writes only its permissions; codex minimal-mode and opencode GSD_TEST_MODE guards unchanged). Unknown runtimes fail loudly via TypeError, with an Object.hasOwn barrier so prototype-chain keys (__proto__/constructor) also throw rather than returning a bogus intent. Leads the installer-refactor chain (#58 -> #60 -> #56), building on ADR-58. Closes #60 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#60): add changeset for runtime config adapter registry Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs(#60): register Runtime Config Adapter Registry in CONTEXT.md glossary Per docs/contributor-standards.md, every new Module/seam must get a `### <Name>` entry under the domain glossary. Adds the entry for the runtime-config-adapter-registry seam introduced in this PR (interface, policy boundary, source file, ADR-58 / #60 cross-references). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#764): skip cross-platform test matrix for docs-only and inert-CI PRs (#798) test.yml had no paths filter and the ci-test-scope classifier treated docs/ and every .github/workflows/* as code_changed, so documentation edits and product-irrelevant automation tweaks still spun up the full Linux/Windows/macOS matrix. Narrow the heavy matrix to changes that can actually affect the product or the test pipeline. - ci-test-scope.cjs: drop docs/ from code_changed (docs-only -> full skip; the required-tests fan-in still reports green). Add src/ to code_changed (it was missing -> a source-only PR previously skipped all tests). Add INERT_WORKFLOWS allowlist + isInertCi() + an "inert CI" rule, and a product_changed output that gates the heavy test/coverage jobs. Fail-safe: any workflow not on the inert allowlist defaults to the full matrix. A module-load assertion throws if a PROTECTED_WORKFLOWS entry (test/install-smoke/mutation/security-scan/release) is ever added to the inert set, so a weakening edit fails CI loudly. - test.yml: keep the static 3-lane matrix (so the H1 shell-policy linter can still statically verify the Windows lane), gate test/coverage on product_changed, add a lightweight ubuntu-only test-inert job, and branch the required-tests fan-in on product_changed. - docs-required.yml: run docs-parity-live-registry (gated on docs/ changes) so pure-docs PRs still catch live-registry drift without the matrix. - tests: cover docs-only, inert-only, src/, pipeline, unknown-workflow fail-safe, mixed escalation, the code_changed=false -> no-lanes invariant, and protected- workflow tamper-evidence. Closes #764 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#766): distribute gsd-core as a native Claude Code plugin (#797) * feat(#766): distribute gsd-core as a native Claude Code plugin Add an additive .claude-plugin/plugin.json manifest plus hooks/hooks.json so gsd-core can be installed as a first-class Claude Code plugin (marketplace or zero-friction @skills-dir), with /gsd-core: namespaced commands and lifecycle management — alongside the unchanged npm/file-copy installer. - .claude-plugin/plugin.json: validated with 'claude plugin validate --strict' - hooks/hooks.json: mirrors the installer's always-on Claude hook wiring via ${CLAUDE_PLUGIN_ROOT} - package.json: ship .claude-plugin in the npm tarball - tests/issue-766-plugin-manifest.test.cjs: manifest + always-on-hook-contract drift guards - docs: install-on-your-runtime.md + FEATURES.md Closes #766 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs(#766): add ADR-766 + glossary entry for Claude Code Plugin Manifest Module Record the plugin manifest as the Seam projecting gsd-core's artifact surfaces onto the Claude Code plugin contract (sibling of the Runtime Artifact Layout Module, ADR-3660), with the defined kind->field mapping and the always-on hook projection rule. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * refactor(#56): retire legacy runtime directory helpers into runtime-homes projection (#802) * refactor(#56): retire legacy runtime directory helpers into runtime-homes projection Consolidate per-runtime global config-dir resolution onto the single canonical projection runtime-homes:getGlobalConfigDir. Extend it with the explicitDir override (CLI --config-dir) and the opencode/kilo OPENCODE_CONFIG/KILO_CONFIG file-path precedence the installer helpers had, making it byte-for-behavior equivalent to the old getGlobalDir across all 15 install runtimes. Delete bin/install.js's getGlobalDir/getOpencodeGlobalDir/getKiloGlobalDir (and the orphaned local expandTilde), repoint all 9 call-sites, and remove getGlobalDir from module.exports (net -242 lines in the installer). Migrate the 5 test importers to the canonical projection; harden default/XDG assertions against ambient *_CONFIG env vars. getAgentsDir now respects OPENCODE_CONFIG/KILO_CONFIG consistently with the installer (intentional convergence). Update CONTEXT.md Installer Module entry. Completes the installer-refactor chain #58 -> #60 -> #56. Closes #56 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#56): add changeset for runtime directory helper retirement Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#786): elevate GitHub Copilot installer — lifecycle hook + AGENTS.md (#804) * feat(#786): elevate Copilot installer with lifecycle hook + AGENTS.md Emit a self-contained sessionStart hook config (.github/hooks/gsd-session.json local, ~/.copilot/hooks/gsd-session.json global) and write AGENTS.md at the repo root (Copilot CLI reads it as primary instructions) alongside copilot-instructions.md. The hook is an inline `command` hook (no separate hook script), so it cannot dangle. Uninstall removes both and preserves user content. Verified against GitHub Copilot CLI primary docs: hooks-configuration (camelCase events, version+hooks shape, inline bash/powershell command hooks) and add-custom-instructions (AGENTS.md read at repo root as primary instructions). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#786): set changeset pr number to 804 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#783): resolve Kilo global skills base to ~/.kilo/skills (#806) * fix(#783): resolve Kilo global skills base to ~/.kilo/skills getGlobalSkillsBase('kilo') returned ~/.config/kilo/skills (the XDG config dir), but Kilo Code discovers global skills from ~/.kilo/skills/ (the .kilo dir in HOME), independent of the kilo.jsonc config dir. Add a HOME-relative special case so the resolver matches Kilo's actual discovery path. The config dir (~/.config/kilo) and the installer's command/ path are correct and unchanged. This corrects the path used by doctor/status and agent-skills-block resolution; the installer writes commands (not skills) for Kilo, so no files were being written to the wrong location. Closes #783 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#783): set changeset pr to 806 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#785): write .cursor/commands/ Cursor 1.6 slash-command surface (#805) * feat(#785): write .cursor/commands/ as Cursor 1.6 slash-command surface Cursor 1.6 (released 2025-09-12) introduced plain-markdown slash commands in `.cursor/commands/<name>.md` — no frontmatter, invocable via `/` in the Agent input. GSD previously emitted only `~/.cursor/skills/` for Cursor. This PR wires a second artifact kind for `cursor` in `runtime-artifact-layout.cts`: `convertedCommandsKind('commands', 'gsd-', 'convertClaudeCommandToCursorCommand', configDir)`. The new kind applies the same `convertClaudeToCursorMarkdown` transforms (tool renames, brand substitution, slash-command normalisation) and then strips YAML frontmatter so the output is plain prose. Skills output is unchanged. `stageCommandsForRuntimeFlat` in `install-profiles.cts` stages each source `.md` as a flat `<stem>.md` in a temp dir; the existing `_copyStaged` commands path then prefixes and copies to `<configDir>/commands/`. `.cursor/mcp.json` is explicitly OUT OF SCOPE: GSD ships no MCP server; the `mcpServers` schema cannot be usefully populated by the installer. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor(#785): address review nit --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(#787): elevate Cline — .clinerules/ dir form, PreToolUse hook, AGENTS.md (#803) * feat(#787): elevate Cline — .clinerules/ dir form, PreToolUse hook, AGENTS.md Migrate the installer's Cline output from a single-file .clinerules to the .clinerules/ directory form (.clinerules/gsd.md), which is the prerequisite for Cline's v3.36 hooks (a path cannot be both a file and a directory). Add a .clinerules/hooks/PreToolUse lifecycle hook implementing Cline's JSON stdin -> {cancel,errorMessage,contextModification} protocol; it guards .planning/ artifacts and fails open. On global installs, merge GSD instructions into the cross-tool ~/.agents/AGENTS.md target (marker-delimited, merge-safe). A legacy single-file .clinerules is migrated in place; --uninstall removes the new artifacts and strips the AGENTS.md GSD block. Also fixes the uninstall targetDir for Cline local installs (it pointed at ./.cline instead of the project root) and re-runs writeManifest after the Cline artifacts are written so they are hash-tracked. Self-contained: implemented independently of the #782 Cline skills work. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#787): address review findings - Scope PreToolUse hook path-walk to PATH_KEY fields only (eliminates false positive when doc body content mentions .planning/) - Use lstatSync + isSymbolicLink() for migration guard so GSD never writes through a user's symlinked .clinerules into an external directory - Add regression tests for both cases Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore(#787): set changeset pr: 803 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#812): honor COPILOT_HOME in Copilot global config-dir resolution (#814) * fix(#812): honor COPILOT_HOME in Copilot global config-dir resolution getGlobalConfigDir('copilot') resolved the global config directory using only --config-dir > COPILOT_CONFIG_DIR > ~/.copilot, ignoring the COPILOT_HOME env var. Per GitHub's Copilot CLI docs, COPILOT_HOME overrides the default ~/.copilot location (and user-level hooks are read from $COPILOT_HOME/hooks/), so a global --copilot install wrote all artifacts (skills, agents, copilot-instructions.md, the gsd-session.json hook) to ~/.copilot even when the user relocated their Copilot home, making them undiscoverable by Copilot CLI. Mirror the codex/CODEX_HOME branch: precedence is now --config-dir > COPILOT_CONFIG_DIR > COPILOT_HOME > ~/.copilot. Uninstall uses the same resolver, so it stays symmetric. Also: document COPILOT_HOME in the installer --help notes, the USER-GUIDE env-var table, and the installer-migrations Copilot row; and clear COPILOT_HOME in the two default-path test suites so they stay hermetic now that the resolver honors it. Closes #812 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#812): add changeset for PR #814 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#788): expand Qwen Code hook-event coverage (#807) * feat(#788): expand Qwen Code hook-event coverage to 4 new events Register SubagentStop, Stop, PreCompact (gsd-context-monitor.js) and UserPromptSubmit (gsd-prompt-guard.js) in the Qwen Code installer. Guard is isQwen-only — Claude Code and all other runtimes are unchanged. Uninstall loop extended to include the 4 new event names. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#788): reconcile to 3 Qwen-only events — defer UserPromptSubmit gsd-prompt-guard exits unless tool_name is Write|Edit (PreToolUse payload shape); UserPromptSubmit carries raw user-prompt text with no tool_name field, so wiring it would be a silent no-op. Deferred to a follow-on issue. Artifacts made consistent: - bin/install.js: drop UserPromptSubmit registration block; uninstall loop drops UPS from event list - .changeset/788-qwen-hook-events.md: corrected to 3 events + rationale - docs/how-to/install-on-your-runtime.md: remove UPS row from hook table - tests/enh-788-qwen-hook-events.test.cjs: assert UPS NOT registered; fix idempotency suite to persist settings between installs; drop UPS-specific assertions Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore(#788): update changeset PR number to #807 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test(#788): prune stale install-bucket allowlist entry for enh-788 test --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> * enhancement(#782): emit gsd skills to ~/.cline/skills for Cline >= v3.48 (#809) Cline added a global skills system (~/.cline/skills/<name>/SKILL.md) in v3.48.0, but gsd treated Cline as rules-only and emitted zero skills (getGlobalSkillsBase('cline')=null, empty artifact kinds). This makes gsd emit skills for Cline at global scope, alongside the existing .clinerules. - runtime-homes: getGlobalSkillsBase('cline') -> ~/.cline/skills (was null) - runtime-artifact-layout: cline emits a skills kind for GLOBAL scope only (local stays .clinerules-only), mirroring claude's scope dispatch - install.js: convertClaudeCommandToClineSkill emits name+description-only SKILL.md frontmatter (Cline/agentskills.io spec; no Claude-specific allowed-tools/argument-hint/agent), hyphen-normalized + .cline/-rewritten body; global cline routed through the skills path while .clinerules is still written; _applyRuntimeRewrites cline case handles custom CLINE_CONFIG_DIR; convertClaudeToCliineMarkdown also rewrites bare ~/.claude and CLAUDE_CONFIG_DIR - docs: install-on-your-runtime.md documents Cline global skills vs local rules - tests: converter (name+description-only), global emission, skills+.clinerules coexistence, scope-aware layout, custom-dir paths, idempotency Closes #782 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#790): emit Augment slash commands (~/.augment/commands/) (#808) Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> * enh(#784): emit native skills for OpenCode + Kilo runtimes (#810) * feat(#784): emit native skills for OpenCode + Kilo runtimes OpenCode and Kilo share a config schema and both discover on-demand skills from skills/<name>/SKILL.md. The installer previously emitted only flat commands (command/) and file-based agents (agents/) for these runtimes. Add a shared OpenCode-family skill writer that stages each GSD command as a spec-compliant SKILL.md (name matching the directory, description 1-1024 chars), wired through the runtime artifact layout so uninstall cleans skills/ automatically. Skills respect the active install profile. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#784): correct skill body paths + preserve user dev-preferences Address adversarial-review findings: - Add opencode/kilo cases to _applyRuntimeRewrites so staged SKILL.md bodies are re-pointed from the converter's hardcoded default config dir to the actual install target (fixes --local / --config-dir installs; commands/agents already did this by applying pathPrefix pre-conversion). - Preserve user-owned skills/gsd-dev-preferences across reinstall in installOpencodeFamilySkills (snapshot+restore around the gsd-* prune), matching installRuntimeArtifacts. - Export installOpencodeFamilySkills and add regression tests. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#784): guarantee command/skill body parity, fix kilo-alt double-rewrite Follow-up adversarial-review found the post-conversion path rewrite could double-rewrite custom Kilo dirs (kilo -> kilo-alt -> kilo-alt-alt) because the kilo pathPrefix is a $HOME (non-absolute) superset of the hardcoded default base. Restructure so OpenCode/Kilo skills mirror copyFlattenedCommands exactly: stage raw commands, apply pathPrefix BEFORE conversion via a new shared applyOpencodeFamilyPathPrefix() helper (now used by both the command and skill writers), then convert. This guarantees byte-for-byte command/ skill body parity for global, --local, and --config-dir installs and removes the prefix-overlap hazard. Drop the fragile _applyRuntimeRewrites opencode/ kilo case. Strengthen the path regression test. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * refactor(#784): derive opencode/kilo skills from the same staged command set Pass the installer's _stageSkills() output directly to installOpencodeFamilySkills instead of re-staging via the layout, so the command/ and skills/ surfaces always cover the identical profile-resolved set — including the --minimal/--core-only alias path, which stages differently from a plain --profile=core. Verified: minimal install now emits 8 commands and 8 skills. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#784): set changeset PR number to 810 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#784): fully escape backslashes in test helper (CodeQL js/incomplete-string-escaping) Replace the dot-only escape `replace(/[.]/g, '\\.')` with a complete regex-escape pattern `replace(/[\\.*+?^${}()|[\]]/g, '\\$&')` so all regex metacharacters (including backslash itself) in `defaultBase` are safely escaped before interpolation into `new RegExp(...)`. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#813): apply per-runtime skill path rewrites in applySurface (#817) * fix(#813): apply per-runtime skill path rewrites in applySurface applySurface() re-staged skill artifacts but, unlike installRuntimeArtifacts(), never applied the per-runtime path rewrites. So /gsd:surface (profile/enable/disable/reset) overwrote installed SKILL.md bodies with the converter's default ~/.claude paths instead of the install target (pathPrefix), silently regressing skill path references for every skillsKind runtime until the next reinstall. applySurface now mirrors installRuntimeArtifacts: for kind.kind === 'skills' it derives pathPrefix the same way and applies applyRuntimeContentRewritesInPlace on the staged dir before syncing. - bin/install.js: export applyRuntimeContentRewritesInPlace - runtime-artifact-layout.cts: carry resolved scope on Layout; export getInstallExports; type computePathPrefix/applyRuntimeContentRewritesInPlace on InstallExports - surface.cts: lazily derive pathPrefix (only when a skills kind exists) and apply the rewrite via the shared getInstallExports accessor — single source of truth with install, only skills kinds rewritten (matches install) - tests: regression test parameterized over cursor + codex asserting post-applySurface bodies carry the install pathPrefix, not ~/.claude - CONTEXT.md: glossary updated for the applySurface rewrite parity + scope seam Closes #813 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#813): add changeset fragment for PR #817 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#813): normalize configDir prefix to forward slashes for Windows CI The #813 regression assertion compared skill bodies against a raw ${configDir}/ prefix, but production derives pathPrefix via path.resolve(configDir).replace(/\\/g, '/'). On Windows, mkdtempSync returns backslash paths while the rewritten body uses forward slashes, so the assertion would fail Windows-only (not covered by local gsd-test). Normalize the expected prefix the same way production does. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#816): mirror install command-prefix handling in _syncGsdDir (#822) * fix(#816): mirror install command-prefix handling in _syncGsdDir applySurface() via _syncGsdDir handled command artifacts differently from a fresh install. For flat command dirs (cursor/augment/opencode/kilo) install's _copyStaged adds kind.prefix (gsd-<stem>.md) and _removeGsdEntries prunes prefix-scoped, but _syncGsdDir copied staged files verbatim (unprefixed) and pruned by exact name. So every /gsd:surface toggle wrote wrong filenames, orphaned the installed gsd-*.md, and deleted user-authored command files. _syncGsdDir's commands/agents branch now mirrors install: - flat command dirs get the gsd- prefix on copy; namespaced dirs (commands/gsd) and agents keep staged names, using install's namespacedByDir rule - prune is prefix-scoped so user files in shared flat dirs are preserved; namespaced commands/gsd stays membership-pruned so superseded commands are still removed on profile shrink The naming rule is intentionally re-implemented (not via require('bin/install.js') to avoid its module-load banner side-effect); a strict parity test asserts applySurface and installRuntimeArtifacts produce identical command filenames for opencode/kilo/cursor/augment/gemini, guarding against drift. Closes #816 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#816): add changeset fragment for PR #822 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * chore(#771): convert agent color: hex/magenta values to documented named colors (#823) * chore(#771): convert agent color: hex/magenta values to documented named colors Claude Code's sub-agent `color:` field documents only 8 named colors (red, blue, green, yellow, purple, orange, pink, cyan). Twelve agent files used hex values and two used the undocumented `magenta`; convert each to the nearest documented named color so the intended per-agent TUI color differentiation is spec-compliant. - agents/*.md: 14 color values hex/magenta -> nearest named color - scripts/research-profiles.cjs: update the 3 generated research-agent profiles (source of truth) so gen-research-agents stays in sync - docs/AGENTS.md: update documented colors; add missing Color rows for gsd-nyquist-auditor, gsd-project-researcher, gsd-phase-researcher - tests/agent-frontmatter.test.cjs: add regression guard asserting every agent color: is in the documented named-color set Closes #771 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#771): add changeset Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#773): add --ephemeral and --dangerously-bypass-hook-trust to automated codex exec wrappers (#824) * feat(#773): add --ephemeral and --dangerously-bypass-hook-trust to automated codex exec invocations Automated codex exec calls in the review workflow now carry --ephemeral (no session-state accumulation across CI runs) and --dangerously-bypass-hook-trust (skip hook-trust prompts for hooks whose provenance gsd-core already controls). Both flags were verified present in the installed codex CLI (codex exec --help). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#773): correct changeset pr: reference to #824 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#775): ship a gemini-extension.json extension package (#818) Add a Gemini CLI extension package so users can install, update, and remove GSD through Gemini's own extension lifecycle and have it appear in `gemini extensions list`: gemini extensions install https://github.com/open-gsd/gsd-core gemini extensions update gsd-core gemini extensions uninstall gsd-core gemini extensions link /path/to/gsd-core # dev This mirrors the additive Claude Code plugin manifest (#766): a thin, version-stamped manifest enforced by an in-repo drift test. The extension ships the context-file payload (GEMINI.md), loaded into every Gemini session; slash-command/agent/hook TOML projection into the extension is a documented follow-up. The manual `npx gsd-core --gemini` installer (which provides the /gsd:* commands) is unchanged — purely additive, no breaking change. - gemini-extension.json: name=binName, version tracks package.json, description, contextFileName=GEMINI.md (minimal; no mcpServers — gsd ships no MCP server) - GEMINI.md: Gemini-session context payload - package.json: add both artifacts to files[] so they publish - CONTEXT.md: add "Gemini Extension Package" glossary entry - docs: USER-GUIDE + install-on-your-runtime how-to - tests/issue-775-gemini-extension.test.cjs: manifest validity, version parity with package.json, contextFileName existence, files[] publication Closes #775 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#768): pre-populate settings.json permissions.allow/deny for Claude Code (#819) * feat(#768): pre-populate settings.json permissions.allow/deny for Claude Code Adds mergeClaudePermissions() to bin/install.js which non-destructively appends GSD's known-safe tool-call patterns to permissions.allow and defense-in-depth credential-file patterns to permissions.deny during Claude Code installs. Merge is idempotent (no duplicates on reinstall) and additive (existing user entries preserved). Uninstall removes only the exact GSD-owned entries. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore: update changeset pr number to 819 --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#774): emit service_tier/model_verbosity in Codex agent TOML + agents/openai.yaml skill chip (#828) * feat(#774): emit service_tier/model_verbosity in Codex agent TOML + agents/openai.yaml skill chip - Add service_tier = "flex" and model_verbosity = "low" to the Codex ConfigProfile TOML for light-tier agents (gsd-research-synthesizer, gsd-codebase-mapper, gsd-plan-checker, and 8 others identified via AGENT_DEFAULT_TIERS). Field names/values verified against Codex schema (profile_toml.rs / config_types.rs Verbosity enum). Non-light agents are unaffected. - Add generateCodexSkillMetadataYaml() and writeCodexSkillMetadataFiles(): after installRuntimeArtifacts, iterate every gsd-* skill directory, read the short-description already emitted in the SKILL.md frontmatter by convertClaudeCommandToCodexSkill, and write agents/openai.yaml with interface.display_name and interface.short_description for the Codex TUI skill picker chip. - yamlQuote (JSON.stringify) handles all YAML-unsafe chars. - User-owned gsd-dev-preferences dir is never overwritten. - Errors per-skill are swallowed so a bad SKILL.md can't abort install. - agents/openai.yaml is covered by the snapshot/rollback system and manifest hash (writeManifest hashes skill dirs recursively). - Uninstall symmetry: _removeGsdEntries removes whole gsd-* dirs. - 21 new tests in codex-config.test.cjs covering service_tier/verbosity TOML emission, YAML generation (round-trip via js-yaml), and writeCodexSkillMetadataFiles including an e2e integration test. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#774): correct docs-lint coverage — proper changeset format + USER-GUIDE entry Rewrite the changeset fragment from old @opengsd/gsd-core:patch format to the required type:/pr: schema so the docs-lint parser can consume it. Add a new "Codex skill picker and agent scheduling (#774)" section to docs/USER-GUIDE.md describing the flex-tier scheduling and /skills TUI chip enrichments — both are user-visible and belong in docs rather than behind a docs-exempt marker. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#769): adopt context:fork + effort on heavy workflow skills (#820) * feat(#769): emit context:fork + effort: frontmatter on heavy workflow skills Add `context: fork` and `effort: xhigh` to the three heaviest workflow commands (plan-phase, execute-phase, autonomous) and `effort: low` to the two quick-status commands (progress, stats). On Claude Code, `context: fork` runs the skill in an isolated subagent context window so the main session's context budget is protected. `effort: xhigh` / `effort: low` signal the appropriate token-budget tier to the runtime. Both fields are silently ignored by runtimes that do not recognise them (Gemini, Codex, Cursor, etc.) — no behaviour change outside Claude Code. Update convertClaudeCommandToClaudeSkill in bin/install.js to preserve `context:` and `effort:` when rewriting source command files to SKILL.md for a Claude global install. Add install-suite tests to assert the fields are present in both source commands and the installed SKILL.md output. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#769): tighten regex assertions + add execute/plan-phase effort coverage Fix low-severity adversarial finding: tighten test regex patterns from `\s*` to `[ \t]*` so they cannot match across newlines (CRLF parity). Add missing effort: xhigh assertions for gsd-execute-phase and gsd-plan-phase SKILL.md install output to complete the black-box coverage gap. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#772): adopt stable Codex hook events + commandWindows for Windows parity (#827) * feat(#772): adopt stable Codex hook events + commandWindows for Windows parity Register three new stable Codex hook events (SubagentStart, Stop, PostToolUse) wired to gsd-context-monitor.js so Codex installs get the same context-headroom tracking at subagent and session boundaries that Claude/Qwen already have. Add commandWindows field to the SessionStart hook entry on Windows so Codex uses the .cmd shim directly (Git Bash/MSYS cannot POSIX-exec node.exe). commandWindows is only emitted on win32; POSIX is unchanged. Refactor reconcileCodexHooksJsonSessionStart into a generic reconcileCodexHooksJsonEvent so any event name can be reconciled with the same dedup/preserve-user-entries logic. Add gsd-context-monitor.js and .cmd to MANAGED_HOOK_COMMAND_BASENAMES _BY_SURFACE so idempotent re-runs de-duplicate entries correctly. 30 new tests covering: export surface, event registration for each of the three events, commandWindows parity (POSIX vs win32), idempotency, uninstall, and user-entry preservation. Closes #772 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#772): windows path normalization + docs-lint - Normalize scriptPath backslashes to forward slashes in ensureCodexHooksJsonEvent and ensureCodexHooksJsonSessionStart so that isManagedHookCommand can match stored commands against configDir on Windows CI runners. path.resolve returns backslash paths on Windows, but when platform is not 'win32' (e.g. platform:'linux' in tests), projectManagedHookCommand skips normalization — producing a mismatch that breaks idempotency deduplication (the same hook entry appended twice on re-register). Forward-slash paths are always valid in both Node.js and Codex, so the normalization is safe for all platforms. - Fix changeset pr: 0 → 827 to resolve fail_malformed_fragment. - Add Codex hook coverage table to docs/how-to/install-on-your-runtime.md documenting the SubagentStart/Stop/PostToolUse events + commandWindows Windows-parity field added by this enhancement. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#778): cross-runtime command enrichment (Gemini {{args}}/!{}, Qwen priority) (#825) * feat(#778): cross-runtime command enrichment (Gemini {{args}}/!{}, Qwen priority) Enrich the installer's per-runtime command/skill generators with native, verified, additive fields: - Gemini CLI: map Claude's $ARGUMENTS -> Gemini's {{args}} in generated TOML commands so typed arguments interpolate; inject live .planning/STATE.md into /gsd:progress via a fixed, injection-safe !{cat .planning/STATE.md 2>/dev/null} shell block (no interpolated input). - Qwen Code: emit the optional numeric `priority` field on main-loop skills so the most-used workflows sort first in the /skills list (higher = earlier per the Qwen skills spec; the issue's inverse numbering was corrected). OpenCode per-command model/agent/subtask/variant enrichment was evaluated and intentionally not implemented: `model` reintroduces the #1156 ProviderModelNotFoundError regression for non-Anthropic providers (the converter deliberately strips model:), `subtask`/`agent` change execution semantics for GSD's interactive commands, and `variant` is not in the OpenCode command schema. Schemas verified against primary docs (Gemini custom-commands, Qwen skills, OpenCode commands/skills). Adds tests/enh-778-* and how-to + USER-GUIDE docs. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#778): set changeset PR number to 825 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#789): elevate CodeBuddy — slash commands (#830) * feat(#789): elevate CodeBuddy — emit slash commands (+ document subagent/MCP scope) Emit a CodeBuddy slash-command surface so GSD workflows appear in the '/' menu, reaching parity with other elevated runtimes. - Add convertClaudeCommandToCodebuddyCommand and register a commands/ artifact kind for the codebuddy runtime (commands/gsd-<name>.md), consistent with the Cursor (#785) and Augment (#790) commands surfaces. - Mark emitted skills user-invocable:false so the commands surface is the sole '/' entry point (no duplicate /gsd-* entries); skills stay model-invocable. CodeBuddy's SKILL.md supports this field. - Normalize $HOME/.codebuddy (bare + slash) path forms in runtime rewrites so --config-dir/local installs don't leak the default home. - Report installed commands/ count on install; uninstall prunes gsd-* commands while preserving user-owned commands. Scope: subagents (~/.codebuddy/agents/) are already emitted by the generic agents block (unchanged); no mcp.json is written (gsd ships no MCP server, and CodeBuddy's mcp.json registers only external servers). Closes #789 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#789): set changeset pr number to 830 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#776): Gemini hook events (BeforeAgent/AfterAgent/BeforeModel) + hooksConfig.enabled check (#829) * feat(#776): Gemini hook events (BeforeAgent/AfterAgent/BeforeModel) + hooksConfig.enabled check Register three new Gemini-CLI hook events on install: - BeforeAgent: fires before agent planning; wired to gsd-context-monitor - AfterAgent: fires after final response generation; wired to gsd-context-monitor - BeforeModel: fires before each LLM call (per-turn); wired to gsd-context-monitor All three reuse gsd-context-monitor.js (no new hook files). Uninstall cleanup loop extended to remove the new events. Non-array guard added for robustness against malformed settings. Also detect hooksConfig.enabled:false in Gemini settings and emit a clear warning — without this check, all registered hooks silently do nothing. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore: update changeset pr: 829 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs(#776): document Gemini hook events Add hook coverage table to the Gemini CLI section of install-on-your-runtime.md, covering the three new events (BeforeAgent/AfterAgent/BeforeModel wired to gsd-context-monitor) plus a callout for the hooksConfig.enabled:false silent failure mode detected by the installer. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#777): register Cursor-native hooks (.cursor/hooks.json) for session-start/post-tool parity (#831) * feat(#777): register Cursor-native hooks (.cursor/hooks.json) for session-start/post-tool parity - Add gsd-cursor-session-start.js: injects STATE.md presence reminder (or new-project nudge) into Cursor sessions via the sessionStart hook event - Add gsd-cursor-post-tool.js: emits an additional_context nudge when write-class tool calls touch .planning/ files (postToolUse hook event) - Add 'cursor-hooks-json' installSurface to runtime-config-adapter-registry; writeCursorHooksJson/reconcileCursorHooksJson write the canonical { version: 1, hooks: { sessionStart, postToolUse } } JSON shape with idempotent reconciliation that preserves user-owned hook entries - Hook scripts are copied with /gsd:→gsd- rewrite so installed files contain no colon-form slash-command refs (bug-376 invariant) - 20 new tests in tests/cursor-hooks.test.cjs cover all reconciler paths, entry helpers, removal, runtime adapter surface, and hook script behavior - Update CONTEXT.md, ARCHITECTURE.md, installer-migrations.md, and 000-first-time-baseline.cts to include Cursor hooks.json surface Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#777): build hooks/dist on demand in bug-376 test for scoped/windows CI hooks/dist is gitignored and only produced by `npm run build:hooks`. The CI scoped (ubuntu-latest/node-22) and windows (windows-latest/node-24) test jobs do NOT run build:hooks before executing tests, so bug-376's prerequisite suite was failing with "hooks/dist not found" on both legs. Add ensureHooksDist() helper (mirrors bug-3357 pattern) that builds hooks/dist on demand in the before() hooks of prerequisite and Suite 3. Also add ensureHooksDist() call to Suite 3's before() so the snapshot step is also hermetic. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * docs(#832): add how-to guide for minimal install / skill profiles (#835) Add docs/how-to/install-minimal-and-add-skills.md covering the --minimal / --core-only / --profile=core install, the core/standard/full profiles, and growing the surface live via /gsd:surface or on reinstall. Register it in the docs/README.md How-to guides index. Closes #832 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#815): add /gsd-update --next to install the @next RC channel (#839) Adds an opt-in --next (alias --rc) flag to /gsd-update targeting the @next RC dist-tag (ADR #660), with a {latest,next} allowlist enforced at three layers, channel-aware version check + banner, and byte-for-byte unchanged default @latest behavior. Closes #815 * fix(#837): three-dot diff in ci-test-scope so docs-only PRs skip the heavy matrix (#841) CI test-scope detection diffed changed files with a two-dot `git diff --name-only base head`, where base is the moving tip of `next`. A PR branch cut from a slightly older `next` surfaced every product file `next` had gained since the merge-base, flipping product_changed/full_matrix and running the full Windows/macOS matrix + coverage on docs-only PRs. Switch to a three-dot `git diff --name-only base...head` (vs the merge-base), matching GitHub's PR "Files changed" semantics. Add a regression test that builds a stale-base topology, plus a guard test pinning `fetch-depth: 0` on the `changes` job (required for the merge-base to be locally available). Closes #837 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#836): no-LLM duplicate-issue detection + challenge + 1-day auto-close (#843) * feat(#836): no-LLM duplicate-issue detection + challenge + 1-day auto-close Adds a deterministic (no-LLM) duplicate-issue governance lifecycle: - scripts/issue-dedupe.cjs: pure, unit-tested module (tokenize, Sørensen–Dice title similarity, scoreCandidates, renderChallengeComment, shouldClose) with fail-safe destructive-action guards. - duplicate-check.yml (issues:opened): scores new-issue title against open issues, posts a challenge comment + applies the pending `possible-duplicate` label on a clear match. - duplicate-sweep.yml (daily cron): closes possible-duplicate issues whose challenge comment is >24h old with no human reply and no 👎 veto; honors exempt labels; re-checks the label immediately before close (TOCTOU guard); strips the label on close to avoid reopen loops. - remove-duplicate-label.yml (issue_comment:created): clears the label and applies needs-maintainer-review when any human responds. - bug_report.yml / docs_issue.yml: add the required "I searched existing issues" preflight checkbox so all five forms force a pre-search attestation. - docs/agents/triage-labels.md: document the label + lifecycle. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#836): add changeset fragment for duplicate-issue detection Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * feat(#770): register Claude Code lifecycle hooks (SubagentStop/Stop/PreCompact/FileChanged) (#821) * feat(#770): register Claude Code lifecycle hooks (SubagentStop/Stop/PreCompact/FileChanged) Wire three new context-tracking events (SubagentStop, Stop, PreCompact) to gsd-context-monitor so context-headroom warnings surface at model-stop and subagent-finalisation moments — not just on PostToolUse. Add a new FileChanged hook (gsd-config-reload.js) that hot-reloads .planning/config.json context mid-session when the user edits it, injecting a config summary as hookSpecificOutput.additionalContext. Updates plugin manifest hooks.json, managed-hooks-registry, installer-migration-report allowlist, and shell-command-projection cleanup tables. Tests: 21 new assertions in enh-770-claude-hook-events.test.cjs; enh-788 and issue-766 test suites updated. Closes #770 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs(#770): document newly-registered Claude Code lifecycle hooks Add a Hook coverage table to the Claude Code npm installer section of docs/how-to/install-on-your-runtime.md describing SubagentStop, Stop, PreCompact, and the new FileChanged (gsd-config-reload.js) hook that hot-reloads .planning/config.json mid-session. Also fixes the changeset frontmatter (adds type: Added + pr: 821) so docs-lint can consume the fragment. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#770): add gsd-config-reload.js to INVENTORY.md and regenerate manifest The feat commit added hooks/gsd-config-reload.js but did not bump the Hooks count in docs/INVENTORY.md (14→15) or add the new row, and did not regenerate docs/INVENTORY-MANIFEST.json. Both inventory-counts and inventory-manifest-sync tests failed across the full CI matrix. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#770): make lifecycle-hook tests deterministic on scoped runner Replace the shared hooks/dist/ ensemble setup (ensureHooksDist / teardownHooksDist) in the Claude hook tests with per-test isolation: pre-populate each test's own tmpDir/.claude/hooks/ with stub files and pass installerMigrations:[] to install() so the first-time-baseline migration does not remove the stubs before the copy step can run. Root cause: hooks/dist/ is gitignored and absent on a fresh npm ci. ensureHooksDist() created it and teardownHooksDist() deleted it, but with --test-concurrency=4 both test files ran concurrently as separate Node.js worker processes sharing the same filesystem. One file's afterEach teardown deleted hooks/dist/ while the other file's install() was copying from it, producing an ENOENT (reproduced 2/10 runs locally). The additional issue: even with pre-placed stubs surviving the copy race, the 000-first-time-baseline migration classified hooks/gsd-*.js as bundled-gsd-hook artifacts, auto-removed them, and the copy step never re-ran (hooks/dist/ absent) — leaving contextMonitorFile missing and all hook registrations silently skipped (the 'got: []' symptom). Fix: pre-populate targetDir/hooks/ per-test (isolated temp dir) AND pass installerMigrations:[] so the baseline scan is skipped. The Qwen suites already used this pattern correctly; the Claude suites are aligned to it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#770): ship gsd-config-reload.js by adding it to build-hooks HOOKS_TO_COPY The #770 feature added hooks/gsd-config-reload.js and registered it in MANAGED_HOOKS, the installer, INVENTORY, and the test EXPECTED_ALL_HOOKS list — but never added it to scripts/build-hooks.js HOOKS_TO_COPY. As a result the hook was never copied into hooks/dist/ during the build, so: - the hook would never ship to users (real production bug — the FileChanged config-reload feature was dead-on-arrival), and - install-minimal-hooks.test.cjs #1755 ("all expected hooks are copied from hooks/dist/ to target", ".js hooks are executable after copy", "manifest contains .js hook entries") failed on any environment with a clean checkout (no pre-existing hooks/dist/): coverage, full test macos-22/macos-24, test ubuntu-24. The failures were masked locally only by a stale hooks/dist/ left from a prior build (build-hooks copies into dist without clearing it). On CI's fresh `npm ci` there is no dist, so the omission surfaced. Fix: add 'gsd-config-reload.js' to HOOKS_TO_COPY so build-hooks stages it into hooks/dist/ alongside the other JS hooks. Verified by removing hooks/dist/ and rerunning the full suite green (0 fail). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#770): make config prototype-pollution beforeEach deterministic on scoped runner Root cause: the #663 and alert-#26 prototype-pollution describe blocks seeded .planning/config.json in beforeEach via a bare runGsdTools('config-ensure-section') whose result was discarded. That command runs in a spawned gsd-tools child; on the scoped CI lane (--test-concurrency=4, config.test.cjs scheduled alongside the heavy install/tarball suites that #770 pulled into the targeted set) the child can be transiently killed under resource pressure (non-zero exit, empty stderr — an OS-level kill, not an app error). The swallowed failure left config.json absent, so the first subtest's readConfig() threw ENOENT opening <tmp>/.planning/config.json. Only 1 of 4 subtests failed, confirming a per-invocation transient, not a deterministic miss; the full suite schedules files differently so config.test.cjs did not collide with those heavy neighbors → passed there. Fix: add ensureConfigReady(tmpDir) which retries config-ensure-section on ANY failure or missing file and throws a clear diagnostic if it still cannot create config.json, then use it in both prototype-pollution beforeEach blocks. Setup is now deterministic under load; the #663/alert-#26 security assertions are unchanged. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * fix(#844): sync runtime manifest versions on npm version bump (#845) * fix(#844): sync runtime manifest versions on npm version bump The release workflow bumps package.json via `npm version` but never stamped the runtime-integration manifests that must track it (.claude-plugin/plugin.json #766, gemini-extension.json #775), so the first RC/finalize whose version diverged from the -dev stream failed the test suite before tagging/publishing. Add scripts/sync-manifest-versions.cjs (single VERSIONED_MANIFESTS registry) wired to a `version` npm lifecycle hook that stamps + stages the manifests on every `npm version` — covering all four release bump sites and local bumps with no workflow edits. A regression guard test fails if any repo JSON whose version matches package.json is not registered, forcing future version-bearing manifests into the sync. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs(#844): add changeset for manifest version sync fix Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> * chore: bump to 1.4.0-rc.2 * chore: finalize v1.4.0 * chore: promote CHANGELOG for v1.4.0 --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: Colin <colin@solvely.net> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Joe <44273333+jslitzkerttcu@users.noreply.github.com> Co-authored-by: Solvely-Colin <211764741+Solvely-Colin@users.noreply.github.com>
This commit is contained in:
@@ -192,8 +192,6 @@ function extractFrontmatterField(stateContent, fieldName) {
|
||||
|
||||
// Capture stdout from cmdPhaseComplete (it calls output() which writes to stdout)
|
||||
function capturePhaseComplete(cwd, phaseNum) {
|
||||
const { execFileSync } = require('child_process');
|
||||
const TOOLS = path.join(__dirname, '..', 'gsd-core', 'bin', 'gsd-tools.cjs');
|
||||
// We invoke gsd-tools directly for the full CJS path, but with GSD_DISABLE_SDK_BRIDGE=1
|
||||
// to force the CJS implementation. Since no env var disables bridge, we call cmdPhaseComplete
|
||||
// directly and redirect output capture.
|
||||
|
||||
@@ -232,6 +232,29 @@ describe('AGENT: required frontmatter fields', () => {
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Color Value Validation ──────────────────────────────────────────────────
|
||||
|
||||
const VALID_AGENT_COLORS = new Set(['red', 'blue', 'green', 'yellow', 'purple', 'orange', 'pink', 'cyan']);
|
||||
|
||||
describe('COLOR: color frontmatter must be a documented named color', () => {
|
||||
for (const agent of ALL_AGENTS) {
|
||||
test(`${agent} color: is a documented named color`, () => {
|
||||
const content = fs.readFileSync(path.join(AGENTS_DIR, agent + '.md'), 'utf-8');
|
||||
const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
||||
const frontmatter = fmMatch ? fmMatch[1] : '';
|
||||
const colorMatch = frontmatter.match(/^color:\s*(.+)$/m);
|
||||
assert.ok(colorMatch, `${agent} missing color: field in frontmatter`);
|
||||
const rawValue = colorMatch[1].trim();
|
||||
// Strip surrounding quotes (single or double) before validating
|
||||
const colorValue = rawValue.replace(/^["']|["']$/g, '');
|
||||
assert.ok(
|
||||
VALID_AGENT_COLORS.has(colorValue),
|
||||
`${agent} has invalid color: "${colorValue}" — must be one of: ${[...VALID_AGENT_COLORS].join(', ')}`
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ─── CLAUDE.md Compliance ───────────────────────────────────────────────────
|
||||
|
||||
describe('CLAUDEMD: CLAUDE.md compliance enforcement', () => {
|
||||
|
||||
@@ -25,7 +25,7 @@ const EXPECTED_AGENTS = Object.keys(MODEL_PROFILES);
|
||||
* We use --cwd to point at the project, and GSD_INSTALL_DIR env to override
|
||||
* the agents directory location for testing.
|
||||
*/
|
||||
function createAgentsDir(configDir, agentNames = []) {
|
||||
function _createAgentsDir(configDir, agentNames = []) {
|
||||
const agentsDir = path.join(configDir, AGENTS_DIR_NAME);
|
||||
fs.mkdirSync(agentsDir, { recursive: true });
|
||||
for (const name of agentNames) {
|
||||
|
||||
@@ -12,9 +12,52 @@
|
||||
|
||||
const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { spawnSync } = require('child_process');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
|
||||
const { runGsdTools, createTempProject, cleanup, TOOLS_PATH } = require('./helpers.cjs');
|
||||
const TEST_ENV_BASE = {
|
||||
GSD_SESSION_KEY: '',
|
||||
CODEX_THREAD_ID: '',
|
||||
CLAUDE_SESSION_ID: '',
|
||||
CLAUDE_CODE_SSE_PORT: '',
|
||||
OPENCODE_SESSION_ID: '',
|
||||
GEMINI_SESSION_ID: '',
|
||||
CURSOR_SESSION_ID: '',
|
||||
WINDSURF_SESSION_ID: '',
|
||||
TERM_SESSION_ID: '',
|
||||
WT_SESSION: '',
|
||||
TMUX_PANE: '',
|
||||
ZELLIJ_SESSION_NAME: '',
|
||||
TTY: '',
|
||||
SSH_TTY: '',
|
||||
};
|
||||
|
||||
/**
|
||||
* Run gsd-tools and capture BOTH stdout and stderr on success.
|
||||
* Returns { success, stdout, stderr }.
|
||||
*/
|
||||
function runGsdToolsWithStderr(args, cwd, env) {
|
||||
const childEnv = { ...process.env, ...TEST_ENV_BASE, ...(env || {}) };
|
||||
try {
|
||||
const result = spawnSync(process.execPath, [TOOLS_PATH, ...args], {
|
||||
cwd,
|
||||
encoding: 'utf-8',
|
||||
env: childEnv,
|
||||
});
|
||||
return {
|
||||
success: result.status === 0,
|
||||
stdout: (result.stdout || '').trim(),
|
||||
stderr: (result.stderr || '').trim(),
|
||||
exitCode: result.status,
|
||||
};
|
||||
} catch (err) {
|
||||
return { success: false, stdout: '', stderr: String(err), exitCode: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
const { loadTrustedGlobalRoots, validatePath } = require('../gsd-core/bin/lib/security.cjs');
|
||||
|
||||
// ─── helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -343,3 +386,390 @@ describe('agent-skills global: prefix', () => {
|
||||
assert.strictEqual(r.ir.block, '', 'block must be empty for empty global: prefix');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── loadTrustedGlobalRoots unit tests (#52) ──────────────────────────────────
|
||||
|
||||
describe('loadTrustedGlobalRoots', () => {
|
||||
test('returns [] for undefined config', () => {
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots(undefined), []);
|
||||
});
|
||||
|
||||
test('returns [] for null config', () => {
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots(null), []);
|
||||
});
|
||||
|
||||
test('returns [] when agent_skills_security is absent', () => {
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots({}), []);
|
||||
});
|
||||
|
||||
test('returns [] when trusted_global_roots is absent', () => {
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots({ agent_skills_security: {} }), []);
|
||||
});
|
||||
|
||||
test('returns [] when trusted_global_roots is not an array', () => {
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots({ agent_skills_security: { trusted_global_roots: '/some/path' } }), []);
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots({ agent_skills_security: { trusted_global_roots: 42 } }), []);
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots({ agent_skills_security: { trusted_global_roots: true } }), []);
|
||||
});
|
||||
|
||||
test('drops non-string entries from the array', () => {
|
||||
// Use a real temp dir so realpathSync succeeds; non-strings are still dropped
|
||||
const realDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-tgr-ns-'));
|
||||
try {
|
||||
const realPath = fs.realpathSync(realDir);
|
||||
const config = { agent_skills_security: { trusted_global_roots: [42, null, realDir, true] } };
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots(config), [realPath]);
|
||||
} finally {
|
||||
cleanup(realDir);
|
||||
}
|
||||
});
|
||||
|
||||
test('drops project-relative (non-absolute) entries', () => {
|
||||
const config = { agent_skills_security: { trusted_global_roots: ['foo/bar', 'relative/path'] } };
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots(config), []);
|
||||
});
|
||||
|
||||
test('keeps absolute paths — real dirs are kept and canonicalized', () => {
|
||||
// Non-existent dirs are dropped; use real temp dirs and compare against realpaths
|
||||
const dir1 = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-tgr-d1-'));
|
||||
const dir2 = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-tgr-d2-'));
|
||||
try {
|
||||
const real1 = fs.realpathSync(dir1);
|
||||
const real2 = fs.realpathSync(dir2);
|
||||
const config = { agent_skills_security: { trusted_global_roots: [dir1, dir2] } };
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots(config), [real1, real2]);
|
||||
} finally {
|
||||
cleanup(dir1);
|
||||
cleanup(dir2);
|
||||
}
|
||||
});
|
||||
|
||||
test('expands leading ~/ to os.homedir() — kept only if the dir exists', () => {
|
||||
// Create a real subdir under os.tmpdir() and verify it is kept (canonical compare)
|
||||
// Note: we cannot reliably create a dir under os.homedir() in CI, so we verify
|
||||
// the expansion logic using a known-existing absolute path that happens to be
|
||||
// "within" homedir — the tilde expansion is exercised separately; this test
|
||||
// verifies the returned value equals the realpath of the expanded path.
|
||||
const subdir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-tgr-tilde-'));
|
||||
try {
|
||||
const realSub = fs.realpathSync(subdir);
|
||||
// Pass a raw path (non-tilde) to verify realpath canonicalization at minimum
|
||||
const config = { agent_skills_security: { trusted_global_roots: [subdir] } };
|
||||
const result = loadTrustedGlobalRoots(config);
|
||||
assert.deepStrictEqual(result, [realSub], 'result must equal realpath of existing dir');
|
||||
} finally {
|
||||
cleanup(subdir);
|
||||
}
|
||||
});
|
||||
|
||||
test('non-existent absolute root is dropped (returns [])', () => {
|
||||
const config = { agent_skills_security: { trusted_global_roots: ['/nonexistent-gsd-root-12345xyz'] } };
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots(config), [], 'non-existent root must be dropped');
|
||||
});
|
||||
|
||||
test('trusted root that is a symlink is canonicalized to the link target', () => {
|
||||
const realTarget = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-tgr-symtgt-'));
|
||||
const symlinkPath = path.join(os.tmpdir(), `gsd-tgr-symlink-${Date.now()}`);
|
||||
let symlinkCreated = false;
|
||||
try {
|
||||
try {
|
||||
fs.symlinkSync(realTarget, symlinkPath);
|
||||
symlinkCreated = true;
|
||||
} catch (err) {
|
||||
if (err.code === 'EPERM' || err.code === 'ENOSYS') {
|
||||
// symlinks not supported on this platform — skip
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
const realResolved = fs.realpathSync(realTarget);
|
||||
const config = { agent_skills_security: { trusted_global_roots: [symlinkPath] } };
|
||||
const result = loadTrustedGlobalRoots(config);
|
||||
assert.deepStrictEqual(result, [realResolved], 'symlink root must be canonicalized to the link target');
|
||||
} finally {
|
||||
cleanup(realTarget);
|
||||
if (symlinkCreated) {
|
||||
try { fs.unlinkSync(symlinkPath); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('de-duplicates entries by canonical path', () => {
|
||||
// Both entries point to the same real dir — after canonicalization, only one is kept
|
||||
const realDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-tgr-dedup-'));
|
||||
try {
|
||||
const realPath = fs.realpathSync(realDir);
|
||||
const config = { agent_skills_security: { trusted_global_roots: [realDir, realDir, realPath] } };
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots(config), [realPath]);
|
||||
} finally {
|
||||
cleanup(realDir);
|
||||
}
|
||||
});
|
||||
|
||||
test('expands ~/ before absolute check — non-existent ~/x is dropped after expansion', () => {
|
||||
// ~/x becomes an absolute path after expansion, but if ~/x does not exist it is
|
||||
// dropped by the realpathSync guard (non-existent root is not trustworthy).
|
||||
const expandedX = path.join(os.homedir(), 'x-gsd-nonexistent-12345');
|
||||
// Ensure it really doesn't exist
|
||||
if (fs.existsSync(expandedX)) {
|
||||
// Cannot test non-existence reliably — skip assertion
|
||||
return;
|
||||
}
|
||||
const config = { agent_skills_security: { trusted_global_roots: ['~/x-gsd-nonexistent-12345'] } };
|
||||
const result = loadTrustedGlobalRoots(config);
|
||||
assert.deepStrictEqual(result, [], 'non-existent ~/x must be dropped after expansion');
|
||||
});
|
||||
|
||||
test('expands bare ~ to os.homedir()', () => {
|
||||
// Bare ~ (exactly) must expand to homedir — mirrors runtime-homes.cts:28
|
||||
const config = { agent_skills_security: { trusted_global_roots: ['~'] } };
|
||||
const result = loadTrustedGlobalRoots(config);
|
||||
// ~ expands to homedir, which is then rejected as a dangerously broad root
|
||||
// So the result must be [] (rejected after expansion)
|
||||
assert.deepStrictEqual(result, [], 'bare ~ expands to homedir and is then rejected as too broad');
|
||||
});
|
||||
|
||||
test('rejects filesystem root /', () => {
|
||||
const config = { agent_skills_security: { trusted_global_roots: ['/'] } };
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots(config), [], 'filesystem root must be rejected');
|
||||
});
|
||||
|
||||
test('rejects os.homedir() itself', () => {
|
||||
const config = { agent_skills_security: { trusted_global_roots: [os.homedir()] } };
|
||||
assert.deepStrictEqual(loadTrustedGlobalRoots(config), [], 'homedir itself must be rejected as too broad');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── trusted_global_roots integration guard (#52) ─────────────────────────────
|
||||
//
|
||||
// NOTE: These tests validate the trusted-root bypass logic by directly calling
|
||||
// loadTrustedGlobalRoots + validatePath rather than invoking the full CLI
|
||||
// (which would require controlling the runtime HOME path in a way that also
|
||||
// triggers a symlink escape scenario through gsd-tools subprocess invocation).
|
||||
// Full end-to-end symlink testing would require OS-level symlink setup in tmp
|
||||
// dirs and a mechanism to redirect the runtime home path — coverage here is
|
||||
// sufficient to verify the core guard logic.
|
||||
|
||||
describe('trusted_global_roots guard logic', () => {
|
||||
let tmpDir;
|
||||
let externalDir;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-52-trusted-'));
|
||||
externalDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-52-external-'));
|
||||
// Create a skill file in externalDir
|
||||
fs.writeFileSync(path.join(externalDir, 'SKILL.md'), '# External\n');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
cleanup(externalDir);
|
||||
});
|
||||
|
||||
test('validatePath rejects skill outside globalSkillsBase (baseline — no trusted roots)', () => {
|
||||
const skillMd = path.join(externalDir, 'SKILL.md');
|
||||
const result = validatePath(skillMd, tmpDir, { allowAbsolute: true });
|
||||
assert.ok(!result.safe, 'skill outside base must be rejected by validatePath');
|
||||
});
|
||||
|
||||
test('with trusted root matching real target dir — validatePath accepts', () => {
|
||||
// Simulate the trusted-root fallback: skill is outside base but inside trusted root
|
||||
const skillMd = path.join(externalDir, 'SKILL.md');
|
||||
const baseCheck = validatePath(skillMd, tmpDir, { allowAbsolute: true });
|
||||
assert.ok(!baseCheck.safe, 'base check must fail (prerequisite)');
|
||||
|
||||
// Trusted root fallback: check against externalDir
|
||||
const config = { agent_skills_security: { trusted_global_roots: [externalDir] } };
|
||||
const trustedRoots = loadTrustedGlobalRoots(config);
|
||||
const acceptedViaTrustedRoot = trustedRoots.some((root) => {
|
||||
const rootCheck = validatePath(skillMd, root, { allowAbsolute: true });
|
||||
return rootCheck.safe;
|
||||
});
|
||||
assert.ok(acceptedViaTrustedRoot, 'skill must be accepted when within a trusted root');
|
||||
});
|
||||
|
||||
test('with unrelated trusted root — skill still rejected', () => {
|
||||
const skillMd = path.join(externalDir, 'SKILL.md');
|
||||
const unrelatedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-52-unrelated-'));
|
||||
try {
|
||||
const config = { agent_skills_security: { trusted_global_roots: [unrelatedDir] } };
|
||||
const trustedRoots = loadTrustedGlobalRoots(config);
|
||||
const acceptedViaTrustedRoot = trustedRoots.some((root) => {
|
||||
const rootCheck = validatePath(skillMd, root, { allowAbsolute: true });
|
||||
return rootCheck.safe;
|
||||
});
|
||||
assert.ok(!acceptedViaTrustedRoot, 'skill must still be rejected when trusted root is unrelated');
|
||||
} finally {
|
||||
cleanup(unrelatedDir);
|
||||
}
|
||||
});
|
||||
|
||||
test('with empty trusted_global_roots array — skill still rejected (byte-identical to today)', () => {
|
||||
const skillMd = path.join(externalDir, 'SKILL.md');
|
||||
const config = { agent_skills_security: { trusted_global_roots: [] } };
|
||||
const trustedRoots = loadTrustedGlobalRoots(config);
|
||||
assert.strictEqual(trustedRoots.length, 0, 'no roots loaded');
|
||||
const acceptedViaTrustedRoot = trustedRoots.some((root) => {
|
||||
const rootCheck = validatePath(skillMd, root, { allowAbsolute: true });
|
||||
return rootCheck.safe;
|
||||
});
|
||||
assert.ok(!acceptedViaTrustedRoot, 'skill must be rejected when trusted roots is empty');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── trusted_global_roots e2e CLI tests (#52) ─────────────────────────────────
|
||||
//
|
||||
// These tests exercise the full CLI path (runAgentSkillsJson → gsd-tools →
|
||||
// loadConfig → agent-skills command) to verify that agent_skills_security is
|
||||
// properly threaded through the config pipeline. Symlinks are created so a
|
||||
// global: skill's realpath escapes the ~/.claude/skills/ base, requiring a
|
||||
// trusted root to be accepted.
|
||||
|
||||
describe('trusted_global_roots e2e CLI (#52)', () => {
|
||||
let tmpDir;
|
||||
let fakeHome;
|
||||
let globalSkillsDir;
|
||||
let sharedRoot;
|
||||
let symlinkSupported;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempProject();
|
||||
fakeHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-52-e2e-home-'));
|
||||
globalSkillsDir = path.join(fakeHome, '.claude', 'skills');
|
||||
fs.mkdirSync(globalSkillsDir, { recursive: true });
|
||||
sharedRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-52-e2e-shared-'));
|
||||
|
||||
// Create the shared skill directory OUTSIDE fakeHome
|
||||
const sharedSkillDir = path.join(sharedRoot, 'shared-skill');
|
||||
fs.mkdirSync(sharedSkillDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(sharedSkillDir, 'SKILL.md'), '# Shared Skill\nContent from shared root.\n');
|
||||
|
||||
// Attempt to create a symlink inside globalSkillsDir pointing to the shared skill
|
||||
symlinkSupported = true;
|
||||
try {
|
||||
fs.symlinkSync(sharedSkillDir, path.join(globalSkillsDir, 'shared-skill'));
|
||||
} catch (err) {
|
||||
if (err.code === 'EPERM' || err.code === 'ENOSYS') {
|
||||
symlinkSupported = false;
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
cleanup(fakeHome);
|
||||
cleanup(sharedRoot);
|
||||
});
|
||||
|
||||
test('REGRESSION: symlinked-escape skill with NO agent_skills_security in config → block is empty', (t) => {
|
||||
if (!symlinkSupported) {
|
||||
t.skip('symlinks not supported on this platform');
|
||||
return;
|
||||
}
|
||||
// No agent_skills_security in config — symlink escape must be blocked
|
||||
writeConfig(tmpDir, {
|
||||
runtime: 'claude',
|
||||
agent_skills: { 'gsd-executor': ['global:shared-skill'] },
|
||||
});
|
||||
|
||||
const r = runAgentSkillsJson(
|
||||
['agent-skills', 'gsd-executor'], tmpDir, { HOME: fakeHome, USERPROFILE: fakeHome }
|
||||
);
|
||||
assert.ok(r.success, `Command failed: ${r.error}`);
|
||||
assert.strictEqual(r.ir.block, '', 'block must be empty when symlink escapes base and no trusted root configured');
|
||||
});
|
||||
|
||||
test('FEATURE: symlink escape with matching trusted_global_roots → block includes skill', (t) => {
|
||||
if (!symlinkSupported) {
|
||||
t.skip('symlinks not supported on this platform');
|
||||
return;
|
||||
}
|
||||
// Configure the sharedRoot as a trusted global root
|
||||
writeConfig(tmpDir, {
|
||||
runtime: 'claude',
|
||||
agent_skills: { 'gsd-executor': ['global:shared-skill'] },
|
||||
agent_skills_security: { trusted_global_roots: [sharedRoot] },
|
||||
});
|
||||
|
||||
const r = runAgentSkillsJson(
|
||||
['agent-skills', 'gsd-executor'], tmpDir, { HOME: fakeHome, USERPROFILE: fakeHome }
|
||||
);
|
||||
assert.ok(r.success, `Command failed: ${r.error}`);
|
||||
assert.ok(r.ir.block.includes('<agent_skills>'), `block must contain <agent_skills> tag, got: ${r.ir.block}`);
|
||||
assert.ok(r.ir.block.includes('shared-skill/SKILL.md'), `block must include the shared skill, got: ${r.ir.block}`);
|
||||
assert.ok(r.ir.skills_count >= 1, 'skills_count must be at least 1');
|
||||
});
|
||||
|
||||
test('FEATURE NOTE: accepted-via-trusted-root emits NOTE on stderr', (t) => {
|
||||
if (!symlinkSupported) {
|
||||
t.skip('symlinks not supported on this platform');
|
||||
return;
|
||||
}
|
||||
// Capture stderr using spawnSync (runGsdTools only captures stderr on failure)
|
||||
writeConfig(tmpDir, {
|
||||
runtime: 'claude',
|
||||
agent_skills: { 'gsd-executor': ['global:shared-skill'] },
|
||||
agent_skills_security: { trusted_global_roots: [sharedRoot] },
|
||||
});
|
||||
|
||||
const r = runGsdToolsWithStderr(
|
||||
['agent-skills', '--json', 'gsd-executor'],
|
||||
tmpDir,
|
||||
{ HOME: fakeHome, USERPROFILE: fakeHome }
|
||||
);
|
||||
assert.ok(r.success, `Command failed (exit ${r.exitCode}): ${r.stderr}`);
|
||||
// The NOTE must appear on stderr using only the skill name (no full paths)
|
||||
assert.ok(
|
||||
r.stderr.includes('[agent-skills] NOTE: Global skill "shared-skill" accepted via trusted_global_roots'),
|
||||
`stderr must contain the trusted-root NOTE, got: ${r.stderr}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('NEGATIVE: symlink escape with unrelated trusted root (existing dir) → block is empty', (t) => {
|
||||
if (!symlinkSupported) {
|
||||
t.skip('symlinks not supported on this platform');
|
||||
return;
|
||||
}
|
||||
// The unrelated dir MUST exist so it isn't dropped for the wrong reason (non-existence).
|
||||
// Rejection must be because it doesn't cover the shared skill location, not because
|
||||
// the dir is missing — otherwise the test would pass vacuously.
|
||||
const unrelatedRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-52-e2e-unrelated-'));
|
||||
// Verify the dir actually exists so the trusted root is loaded (not silently dropped)
|
||||
assert.ok(fs.existsSync(unrelatedRoot), 'unrelated root must exist so it enters the trusted roots list');
|
||||
try {
|
||||
writeConfig(tmpDir, {
|
||||
runtime: 'claude',
|
||||
agent_skills: { 'gsd-executor': ['global:shared-skill'] },
|
||||
agent_skills_security: { trusted_global_roots: [unrelatedRoot] },
|
||||
});
|
||||
|
||||
const r = runAgentSkillsJson(
|
||||
['agent-skills', 'gsd-executor'], tmpDir, { HOME: fakeHome, USERPROFILE: fakeHome }
|
||||
);
|
||||
assert.ok(r.success, `Command failed: ${r.error}`);
|
||||
assert.strictEqual(r.ir.block, '', 'block must be empty when trusted root does not cover the shared skill location');
|
||||
} finally {
|
||||
cleanup(unrelatedRoot);
|
||||
}
|
||||
});
|
||||
|
||||
test('HARDENING: trusted_global_roots: ["/"] → block is empty (broad root rejected)', (t) => {
|
||||
if (!symlinkSupported) {
|
||||
t.skip('symlinks not supported on this platform');
|
||||
return;
|
||||
}
|
||||
writeConfig(tmpDir, {
|
||||
runtime: 'claude',
|
||||
agent_skills: { 'gsd-executor': ['global:shared-skill'] },
|
||||
agent_skills_security: { trusted_global_roots: ['/'] },
|
||||
});
|
||||
|
||||
const r = runAgentSkillsJson(
|
||||
['agent-skills', 'gsd-executor'], tmpDir, { HOME: fakeHome, USERPROFILE: fakeHome }
|
||||
);
|
||||
assert.ok(r.success, `Command failed: ${r.error}`);
|
||||
assert.strictEqual(r.ir.block, '', 'block must be empty when "/" is the trusted root (rejected as too broad)');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// IS what the runtime loads. Testing text content tests the deployed contract.
|
||||
// Per CONTRIBUTING.md exception matrix.
|
||||
|
||||
const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const { test, describe } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* for phases with frontend indicators.
|
||||
*/
|
||||
|
||||
const { describe, it, test, beforeEach } = require('node:test');
|
||||
const { describe, test, beforeEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
@@ -24,7 +24,7 @@ const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const { createTempProject, cleanup, runGsdTools, captureConsole } = require('./helpers.cjs');
|
||||
const { createTempProject, cleanup, captureConsole } = require('./helpers.cjs');
|
||||
const { getMilestonePhaseFilter } = require('../gsd-core/bin/lib/core.cjs');
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -25,7 +25,7 @@ const path = require('node:path');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
|
||||
// The helpers under test.
|
||||
const { runNpm, isolatedNpmEnv, cleanup } = require('./helpers.cjs');
|
||||
const { isolatedNpmEnv, cleanup } = require('./helpers.cjs');
|
||||
|
||||
// Resolve a filesystem path to its canonical (symlink-free) form even if the
|
||||
// leaf does not exist yet (e.g. ~/.npm before npm has written its cache).
|
||||
|
||||
@@ -26,7 +26,7 @@ const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
const { spawnSync } = require('node:child_process');
|
||||
const { cleanup } = require('./helpers.cjs');
|
||||
const { cleanup, delay } = require('./helpers.cjs');
|
||||
|
||||
const HOOK_PATH = path.resolve(__dirname, '..', 'hooks', 'gsd-context-monitor.js');
|
||||
const GSD_TOOLS = path.resolve(__dirname, '..', 'gsd-core', 'bin', 'gsd-tools.cjs');
|
||||
@@ -34,7 +34,7 @@ const GSD_TOOLS = path.resolve(__dirname, '..', 'gsd-core', 'bin', 'gsd-tools.cj
|
||||
// Windows can hold a transient handle on the temp dir after a spawnSync child
|
||||
// exits (AV scanner / handle-release lag), so cleanup()'s internal rmSync retry
|
||||
// (~5s) occasionally still throws EBUSY/EPERM/ENOTEMPTY under CI load. Restore a
|
||||
// bounded outer retry with async backoff (NOT Atomics.wait — lint no-magic-sleep).
|
||||
// bounded outer retry with async backoff via the shared delay() helper.
|
||||
// Re-adds the guard removed in #482. Refs #490.
|
||||
async function cleanupWithRetry(dir, attempts = 8) {
|
||||
for (let i = 0; i < attempts; i += 1) {
|
||||
@@ -42,7 +42,7 @@ async function cleanupWithRetry(dir, attempts = 8) {
|
||||
catch (err) {
|
||||
const transient = err && (err.code === 'EBUSY' || err.code === 'EPERM' || err.code === 'ENOTEMPTY');
|
||||
if (!transient || i === attempts - 1) throw err;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100 * (i + 1)));
|
||||
await delay(100 * (i + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +87,6 @@ describe('bug-211: launcher ~/.claude home fallback', () => {
|
||||
// in the same directory as gsd-tools, create a dedicated shim dir with a
|
||||
// symlink to node only (no gsd-tools there).
|
||||
const nodeBin = execFileSync('which', ['node'], { encoding: 'utf8' }).trim();
|
||||
const nodeBinDir = path.dirname(nodeBin);
|
||||
const systemPaths = (process.env.PATH || '/usr/bin:/bin')
|
||||
.split(path.delimiter)
|
||||
.filter((p) => {
|
||||
|
||||
@@ -45,7 +45,7 @@ const os = require('os');
|
||||
const { execFileSync } = require('child_process');
|
||||
|
||||
const HOOKS_DIR = path.join(__dirname, '..', 'hooks');
|
||||
const CHECK_UPDATE_FILE = path.join(HOOKS_DIR, 'gsd-check-update.js');
|
||||
const _CHECK_UPDATE_FILE = path.join(HOOKS_DIR, 'gsd-check-update.js');
|
||||
const WORKER_FILE = path.join(HOOKS_DIR, 'gsd-check-update-worker.js');
|
||||
const INSTALL_SCRIPT = path.join(__dirname, '..', 'bin', 'install.js');
|
||||
const BUILD_SCRIPT = path.join(__dirname, '..', 'scripts', 'build-hooks.js');
|
||||
@@ -142,11 +142,11 @@ describe('bug #2136 part 2: stale-hook detector handles bash comment syntax', ()
|
||||
// "(?:\/\/|#)" directly in source.
|
||||
const hasBashAlternative =
|
||||
src.includes('(?:\\/\\/|#)') || // escaped form (old template-literal style)
|
||||
src.includes('(?:\/\/|#)'); // direct form in plain JS worker
|
||||
src.includes('(?://|#)'); // direct form in plain JS worker
|
||||
assert.ok(
|
||||
hasBashAlternative,
|
||||
'gsd-check-update-worker.js version regex must include an alternative for bash "#" comments. ' +
|
||||
'Expected to find (?:\\/\\/|#) or (?:\/\/|#) in the source. ' +
|
||||
'Expected to find (?:\\/\\/|#) or (?://|#) in the source. ' +
|
||||
'The original "//" only regex causes bash hooks to always report hookVersion: "unknown"'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -17,7 +17,6 @@ const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
|
||||
const isWindows = process.platform === 'win32';
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ describe('update.md — no bare ~.claude path references (#2470)', () => {
|
||||
assert.strictEqual(
|
||||
matches,
|
||||
null,
|
||||
`update.md must not contain bare ~/\.claude (without trailing slash) — installer scanner flags these as unresolved path refs: ${JSON.stringify(matches)}`
|
||||
`update.md must not contain bare ~/.claude (without trailing slash) — installer scanner flags these as unresolved path refs: ${JSON.stringify(matches)}`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const path = require('node:path');
|
||||
const { createTempProject, cleanup, runGsdTools } = require('./helpers.cjs');
|
||||
|
||||
const { VALID_CONFIG_KEYS, isValidConfigKey } = require('../gsd-core/bin/lib/config-schema.cjs');
|
||||
|
||||
@@ -49,14 +49,6 @@ const COMMANDS_DIR = path.join(ROOT, 'commands', 'gsd');
|
||||
//
|
||||
// Expand this list only if a new runtime-emitter module is introduced AND the
|
||||
// bug-3584 test is updated to cover it.
|
||||
const RUNTIME_EMITTER_EXCLUDES = new Set([
|
||||
// Primary runtime-slash emitter (bug-3584 canonical contract):
|
||||
path.join(ROOT, 'gsd-core', 'bin', 'lib', 'runtime-slash.cjs'),
|
||||
// phase-lifecycle-policy.ts emits runtime-persisted slash references (bug-3584):
|
||||
path.join(ROOT, 'gsd-core', 'bin', 'lib', 'phase-lifecycle-policy.ts'),
|
||||
// Generated CJS files match the TS source's emitted form — never hand-edited:
|
||||
// (matched below by .generated.cjs extension — see collectFiles exclusion)
|
||||
]);
|
||||
|
||||
const SEARCH_DIRS = [
|
||||
// NOTE: gsd-core/bin/lib is intentionally EXCLUDED from SEARCH_DIRS.
|
||||
|
||||
@@ -40,8 +40,6 @@ const {
|
||||
install,
|
||||
validateCodexConfigSchema,
|
||||
hasUserNamespacedAotHooks,
|
||||
stripGsdFromCodexConfig,
|
||||
installCodexConfig,
|
||||
parseTomlToObject,
|
||||
} = require('../bin/install.js');
|
||||
|
||||
@@ -222,7 +220,7 @@ describe('#2760 defect 3 — Hooks AoT preservation across install/uninstall/rei
|
||||
|
||||
runCodexInstall(codexHome);
|
||||
const content = readCodexConfig(codexHome);
|
||||
const parsed = parseTomlToObject(content);
|
||||
parseTomlToObject(content);
|
||||
|
||||
const hooksJsonCommands = readHooksSessionStartCommands(codexHome);
|
||||
const gsdHandlers = hooksJsonCommands.filter((cmd) => /gsd-check-update/.test(cmd));
|
||||
@@ -233,7 +231,7 @@ describe('#2760 defect 3 — Hooks AoT preservation across install/uninstall/rei
|
||||
writeCodexConfig(codexHome, '');
|
||||
runCodexInstall(codexHome);
|
||||
runCodexInstall(codexHome); // second install
|
||||
const content = readCodexConfig(codexHome);
|
||||
readCodexConfig(codexHome);
|
||||
|
||||
const hooksJsonCommands = readHooksSessionStartCommands(codexHome);
|
||||
const gsdHandlers = hooksJsonCommands.filter((cmd) => /gsd-check-update/.test(cmd));
|
||||
|
||||
@@ -26,12 +26,8 @@ const { describe, test, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
|
||||
const {
|
||||
readGsdRuntimeProfileResolver,
|
||||
readGsdEffectiveModelOverrides,
|
||||
convertClaudeToOpencodeFrontmatter,
|
||||
install,
|
||||
} = require('../bin/install.js');
|
||||
|
||||
|
||||
@@ -126,19 +126,21 @@ describe('bug-2801: ingest-docs.md workflow calls gsd-tools not gsd-sdk', () =>
|
||||
);
|
||||
});
|
||||
|
||||
test('ingest-docs.md init step uses canonical node-path gsd-tools.cjs invocation', () => {
|
||||
test('ingest-docs.md init step uses the gsd_run launcher (#637)', () => {
|
||||
const content = fs.readFileSync(WORKFLOW_FILE, 'utf-8');
|
||||
// Parse fenced bash blocks structurally — do not match raw markdown text.
|
||||
const codeBlockRe = /```bash\r?\n([\s\S]*?)```/g;
|
||||
const bashLines = [...content.matchAll(codeBlockRe)]
|
||||
.flatMap((m) => m[1].split('\n'))
|
||||
.filter((l) => !/^\s*#/.test(l));
|
||||
// Per #2851 the only valid form is the absolute-path node invocation; the
|
||||
// legacy bare `gsd-tools` is the bug being fixed and must not be accepted.
|
||||
// #637 routes ingest-docs through the resolved `gsd_run` launcher instead of
|
||||
// the hardcoded `node "$HOME/.../gsd-tools.cjs"` path (which misses global
|
||||
// installs). The legacy bare `gsd-tools` form remains the bug and is still
|
||||
// rejected by bug-2851's repo-wide guard.
|
||||
const initLine = bashLines.find((l) =>
|
||||
/\bnode\s+["']?\$HOME\/\.claude\/gsd-core\/bin\/gsd-tools\.cjs["']?\s+init\s+ingest-docs\b/.test(l)
|
||||
/\bgsd_run\s+init\s+ingest-docs\b/.test(l)
|
||||
);
|
||||
assert.ok(initLine, 'workflow must invoke init ingest-docs via canonical node-path gsd-tools.cjs');
|
||||
assert.ok(initLine, 'workflow must invoke init ingest-docs via the gsd_run launcher (#637)');
|
||||
});
|
||||
|
||||
test('cmdInitIngestDocs is exported from init.cjs', () => {
|
||||
|
||||
@@ -34,7 +34,7 @@ const path = require('node:path');
|
||||
const { cleanup, createTempDir } = require('./helpers.cjs');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const { convertClaudeCommandToClaudeSkill, installRuntimeArtifacts, uninstallRuntimeArtifacts, skillFrontmatterName } =
|
||||
const { convertClaudeCommandToClaudeSkill, installRuntimeArtifacts, skillFrontmatterName } =
|
||||
require(path.join(ROOT, 'bin', 'install.js'));
|
||||
|
||||
const {
|
||||
|
||||
@@ -125,7 +125,7 @@ describe('bug-2839: /gsd-code-review-fix cleanup is transactional', () => {
|
||||
// (`rm -f .../.review-fix-recovery-pending.json`) or a shell-variable form
|
||||
// referring to the previously-declared `sentinel` variable
|
||||
// (`rm -f "$sentinel"` / `rm -f "${sentinel}"`).
|
||||
const escapedName = SENTINEL_NAME.replace(/\./g, '\\.');
|
||||
const escapedName = SENTINEL_NAME.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const sentinelRemovalRe = new RegExp(
|
||||
`(rm\\s+(?:-f\\s+)?[^\\n]*(?:${escapedName}|\\$\\{?sentinel\\}?)|unlink[^\\n]*(?:${escapedName}|\\$\\{?sentinel\\}?))`
|
||||
);
|
||||
|
||||
@@ -39,6 +39,7 @@ function captureFinishInstallOutput(runtime, isGlobal) {
|
||||
console.log = original;
|
||||
}
|
||||
// Strip ANSI color escapes so message-content assertions don't couple to colors.
|
||||
// eslint-disable-next-line no-control-regex -- \x1b (ESC) is the required leading byte of ANSI SGR color sequences; matching it is the purpose of stripping ANSI codes from captured CLI/console output
|
||||
return lines.join('\n').replace(/\x1B\[[0-9;]*m/g, '');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
'use strict';
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
const { test, describe, before, after } = require('node:test');
|
||||
const { test, describe } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const path = require('node:path');
|
||||
const cp = require('node:child_process');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const { checkLatestVersion, CHECK_REASON, PACKAGE_NAME } = require(
|
||||
@@ -94,3 +93,62 @@ describe('Bug #2992: error paths', () => {
|
||||
assert.deepEqual(r, { ok: true, version: '1.40.0-rc.1', reason: CHECK_REASON.OK });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Issue #815: --next dist-tag support', () => {
|
||||
const { buildViewArgs, resolveTag, ALLOWED_TAGS } = require(
|
||||
path.join(ROOT, 'gsd-core', 'bin', 'check-latest-version.cjs'),
|
||||
);
|
||||
|
||||
test('ALLOWED_TAGS is the sanctioned channel allowlist (latest, next)', () => {
|
||||
assert.deepEqual([...ALLOWED_TAGS].sort(), ['latest', 'next']);
|
||||
});
|
||||
|
||||
test('buildViewArgs() defaults to the bare latest spec (byte-for-byte unchanged)', () => {
|
||||
assert.deepEqual(buildViewArgs(), ['view', '@opengsd/gsd-core', 'version']);
|
||||
assert.deepEqual(buildViewArgs('latest'), ['view', '@opengsd/gsd-core', 'version']);
|
||||
});
|
||||
|
||||
test('buildViewArgs("next") targets the @next dist-tag', () => {
|
||||
assert.deepEqual(buildViewArgs('next'), ['view', '@opengsd/gsd-core@next', 'version']);
|
||||
});
|
||||
|
||||
test('resolveTag defaults to latest when no --tag flag', () => {
|
||||
assert.equal(resolveTag(['--json']), 'latest');
|
||||
});
|
||||
|
||||
test('resolveTag reads --tag next', () => {
|
||||
assert.equal(resolveTag(['--json', '--tag', 'next']), 'next');
|
||||
});
|
||||
|
||||
test('resolveTag rejects an unknown tag (typo guard)', () => {
|
||||
assert.throws(() => resolveTag(['--tag', 'nightly']), /invalid --tag 'nightly'/);
|
||||
});
|
||||
|
||||
test('resolveTag rejects --tag with no value', () => {
|
||||
assert.throws(() => resolveTag(['--tag']), /invalid --tag ''/);
|
||||
});
|
||||
|
||||
test('checkLatestVersion accepts an RC under the next tag', () => {
|
||||
const r = checkLatestVersion({ tag: 'next', spawn: () => ({ status: 0, stdout: '1.4.0-rc.1\n', stderr: '' }) });
|
||||
assert.deepEqual(r, { ok: true, version: '1.4.0-rc.1', reason: CHECK_REASON.OK });
|
||||
});
|
||||
|
||||
test('buildViewArgs rejects a tag outside the allowlist (exported-API guard)', () => {
|
||||
assert.throws(() => buildViewArgs('nightly'), /invalid dist-tag 'nightly'/);
|
||||
});
|
||||
|
||||
test('checkLatestVersion rejects an out-of-allowlist tag even with an injected spawn', () => {
|
||||
assert.throws(
|
||||
() => checkLatestVersion({ tag: 'nightly', spawn: () => ({ status: 0, stdout: '9.9.9\n', stderr: '' }) }),
|
||||
/invalid dist-tag 'nightly'/,
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveTag handles the --tag=next equals form', () => {
|
||||
assert.equal(resolveTag(['--json', '--tag=next']), 'next');
|
||||
});
|
||||
|
||||
test('resolveTag rejects an unknown --tag=value equals form (no silent fallback)', () => {
|
||||
assert.throws(() => resolveTag(['--tag=nightly']), /invalid --tag 'nightly'/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,7 +28,6 @@ const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
const { install } = require('../bin/install.js');
|
||||
|
||||
@@ -27,7 +27,6 @@ const {
|
||||
getGlobalConfigDir,
|
||||
getGlobalSkillsBase,
|
||||
getGlobalSkillDir,
|
||||
getGlobalSkillDisplayPath,
|
||||
} = require(path.join(ROOT, 'gsd-core', 'bin', 'lib', 'runtime-homes.cjs'));
|
||||
|
||||
// Helper: run fn with an env var temporarily set
|
||||
@@ -64,9 +63,10 @@ describe('bug #3126: runtime-homes getGlobalConfigDir — defaults', () => {
|
||||
test(`${runtime} default configDir`, () => {
|
||||
// Clear all env vars for this runtime
|
||||
const envKeys = ['CLAUDE_CONFIG_DIR','CURSOR_CONFIG_DIR','GEMINI_CONFIG_DIR',
|
||||
'CODEX_HOME','COPILOT_CONFIG_DIR','ANTIGRAVITY_CONFIG_DIR','WINDSURF_CONFIG_DIR',
|
||||
'CODEX_HOME','COPILOT_CONFIG_DIR','COPILOT_HOME','ANTIGRAVITY_CONFIG_DIR','WINDSURF_CONFIG_DIR',
|
||||
'AUGMENT_CONFIG_DIR','TRAE_CONFIG_DIR','QWEN_CONFIG_DIR','HERMES_HOME',
|
||||
'CODEBUDDY_CONFIG_DIR','CLINE_CONFIG_DIR','OPENCODE_CONFIG_DIR','KILO_CONFIG_DIR',
|
||||
'CODEBUDDY_CONFIG_DIR','CLINE_CONFIG_DIR','OPENCODE_CONFIG_DIR','OPENCODE_CONFIG',
|
||||
'KILO_CONFIG_DIR','KILO_CONFIG',
|
||||
'XDG_CONFIG_HOME'];
|
||||
const saved = {};
|
||||
for (const k of envKeys) { saved[k] = process.env[k]; delete process.env[k]; }
|
||||
@@ -106,15 +106,19 @@ describe('bug #3126: runtime-homes env-var overrides', () => {
|
||||
});
|
||||
test('opencode uses XDG_CONFIG_HOME when OPENCODE_CONFIG_DIR absent', () => {
|
||||
withEnv('OPENCODE_CONFIG_DIR', undefined, () => {
|
||||
withEnv('XDG_CONFIG_HOME', '/xdg', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('opencode'), path.join('/xdg', 'opencode'));
|
||||
withEnv('OPENCODE_CONFIG', undefined, () => {
|
||||
withEnv('XDG_CONFIG_HOME', '/xdg', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('opencode'), path.join('/xdg', 'opencode'));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
test('kilo uses XDG_CONFIG_HOME when KILO_CONFIG_DIR absent', () => {
|
||||
withEnv('KILO_CONFIG_DIR', undefined, () => {
|
||||
withEnv('XDG_CONFIG_HOME', '/xdg', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('kilo'), path.join('/xdg', 'kilo'));
|
||||
withEnv('KILO_CONFIG', undefined, () => {
|
||||
withEnv('XDG_CONFIG_HOME', '/xdg', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('kilo'), path.join('/xdg', 'kilo'));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -160,8 +164,13 @@ describe('bug #3126: runtime-homes getGlobalSkillsBase', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
test('cline: returns null (rules-based, no skills directory)', () => {
|
||||
assert.strictEqual(getGlobalSkillsBase('cline'), null);
|
||||
test('cline: returns ~/.cline/skills (skills-capable since v3.48.0 — #782)', () => {
|
||||
withEnv('CLINE_CONFIG_DIR', undefined, () => {
|
||||
assert.strictEqual(
|
||||
getGlobalSkillsBase('cline'),
|
||||
path.join(os.homedir(), '.cline', 'skills'),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -182,8 +191,117 @@ describe('bug #3126: runtime-homes getGlobalSkillDir', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
test('cline: returns null', () => {
|
||||
assert.strictEqual(getGlobalSkillDir('cline', 'gsd-executor'), null);
|
||||
test('cline: returns ~/.cline/skills/gsd-executor (skills-capable since v3.48.0 — #782)', () => {
|
||||
withEnv('CLINE_CONFIG_DIR', undefined, () => {
|
||||
assert.strictEqual(
|
||||
getGlobalSkillDir('cline', 'gsd-executor'),
|
||||
path.join(os.homedir(), '.cline', 'skills', 'gsd-executor'),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getGlobalConfigDir — explicitDir override and opencode/kilo file-path precedence', () => {
|
||||
// ── explicitDir override ──────────────────────────────────────────────────
|
||||
test('explicitDir absolute path is returned as-is (claude)', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('claude', '/tmp/x'), '/tmp/x');
|
||||
});
|
||||
|
||||
test('explicitDir with tilde is expanded (opencode)', () => {
|
||||
assert.strictEqual(
|
||||
getGlobalConfigDir('opencode', '~/foo'),
|
||||
path.join(os.homedir(), 'foo'),
|
||||
);
|
||||
});
|
||||
|
||||
test('explicitDir wins even when OPENCODE_CONFIG_DIR is also set', () => {
|
||||
withEnv('OPENCODE_CONFIG_DIR', '/should/not/win', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('opencode', '/explicit/wins'), '/explicit/wins');
|
||||
});
|
||||
});
|
||||
|
||||
// ── opencode: OPENCODE_CONFIG file-path step ──────────────────────────────
|
||||
test('opencode: OPENCODE_CONFIG → path.dirname(expandTilde(value))', () => {
|
||||
withEnv('OPENCODE_CONFIG_DIR', undefined, () => {
|
||||
withEnv('XDG_CONFIG_HOME', undefined, () => {
|
||||
withEnv('OPENCODE_CONFIG', '/home/u/cfg/opencode.json', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('opencode'), '/home/u/cfg');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('opencode: OPENCODE_CONFIG_DIR takes precedence over OPENCODE_CONFIG', () => {
|
||||
withEnv('OPENCODE_CONFIG_DIR', '/dir/wins', () => {
|
||||
withEnv('OPENCODE_CONFIG', '/file/loses.json', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('opencode'), '/dir/wins');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('opencode: OPENCODE_CONFIG takes precedence over XDG_CONFIG_HOME', () => {
|
||||
withEnv('OPENCODE_CONFIG_DIR', undefined, () => {
|
||||
withEnv('OPENCODE_CONFIG', '/cfg/opencode.json', () => {
|
||||
withEnv('XDG_CONFIG_HOME', '/xdg/should/lose', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('opencode'), '/cfg');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('opencode: default ~/.config/opencode when no env vars set', () => {
|
||||
withEnv('OPENCODE_CONFIG_DIR', undefined, () => {
|
||||
withEnv('OPENCODE_CONFIG', undefined, () => {
|
||||
withEnv('XDG_CONFIG_HOME', undefined, () => {
|
||||
assert.strictEqual(
|
||||
getGlobalConfigDir('opencode'),
|
||||
path.join(os.homedir(), '.config', 'opencode'),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ── kilo: KILO_CONFIG file-path step ─────────────────────────────────────
|
||||
test('kilo: KILO_CONFIG → path.dirname(expandTilde(value))', () => {
|
||||
withEnv('KILO_CONFIG_DIR', undefined, () => {
|
||||
withEnv('XDG_CONFIG_HOME', undefined, () => {
|
||||
withEnv('KILO_CONFIG', '/home/u/cfg/kilo.json', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('kilo'), '/home/u/cfg');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('kilo: KILO_CONFIG_DIR takes precedence over KILO_CONFIG', () => {
|
||||
withEnv('KILO_CONFIG_DIR', '/dir/wins', () => {
|
||||
withEnv('KILO_CONFIG', '/file/loses.json', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('kilo'), '/dir/wins');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('kilo: KILO_CONFIG takes precedence over XDG_CONFIG_HOME', () => {
|
||||
withEnv('KILO_CONFIG_DIR', undefined, () => {
|
||||
withEnv('KILO_CONFIG', '/cfg/kilo.json', () => {
|
||||
withEnv('XDG_CONFIG_HOME', '/xdg/should/lose', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('kilo'), '/cfg');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('kilo: default ~/.config/kilo when no env vars set', () => {
|
||||
withEnv('KILO_CONFIG_DIR', undefined, () => {
|
||||
withEnv('KILO_CONFIG', undefined, () => {
|
||||
withEnv('XDG_CONFIG_HOME', undefined, () => {
|
||||
assert.strictEqual(
|
||||
getGlobalConfigDir('kilo'),
|
||||
path.join(os.homedir(), '.config', 'kilo'),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
const { describe, 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 ROOT = path.join(__dirname, '..');
|
||||
@@ -33,14 +32,6 @@ const planScanLib = path.join(ROOT, 'gsd-core', 'bin', 'lib', 'plan-scan.cjs');
|
||||
// The simplest correct seam: inspect the source for the regex pattern and
|
||||
// validate with a synthetic directory that the manager path returns correct counts.
|
||||
|
||||
// Build a temporary phase directory with the slug layout
|
||||
function makeTempPhase(files) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3128-'));
|
||||
for (const f of files) {
|
||||
fs.writeFileSync(path.join(dir, f), `# ${f}\n`);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
// Import countPhasePlansAndSummaries by monkey-patching: we inline the
|
||||
// fixed filter logic and verify it matches the file on disk.
|
||||
|
||||
@@ -4,18 +4,20 @@
|
||||
// Regression guard for bug #3130.
|
||||
//
|
||||
// Two failure modes were observed with the pre-fix npx invocation form:
|
||||
// 1. Cache-stale: bare `npx -y @opengsd/gsd-core@latest` hits npx's local
|
||||
// cache and may pull an older version instead of @latest.
|
||||
// 1. Cache-stale: bare `npx -y @opengsd/gsd-core@<tag>` hits npx's local
|
||||
// cache and may pull an older version instead of the target tag.
|
||||
// 2. Token-routing: Bash-tool wrappers misroute the `@` token in
|
||||
// `@opengsd/gsd-core@latest`, causing npm to error with
|
||||
// "Unknown command: @opengsd/gsd-core@latest".
|
||||
// `@opengsd/gsd-core@<tag>`, causing npm to error with
|
||||
// "Unknown command: @opengsd/gsd-core@<tag>".
|
||||
//
|
||||
// The robust form is:
|
||||
// npx -y --package=@opengsd/gsd-core@latest -- gsd-core $ARGS
|
||||
// npx -y --package=@opengsd/gsd-core@"$TAG" -- gsd-core $ARGS
|
||||
//
|
||||
// `--package=` forces a fresh registry fetch, bypassing the npx cache.
|
||||
// `--` clearly delineates npx flags from the run-command, preventing
|
||||
// Bash-tool @-token misrouting.
|
||||
// `$TAG` is a shell variable (latest by default, next under --next/--rc),
|
||||
// set by the parse_update_channel step (#815).
|
||||
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
@@ -28,9 +30,9 @@ const UPDATE_WF = path.join(ROOT, 'gsd-core', 'workflows', 'update.md');
|
||||
const src = fs.readFileSync(UPDATE_WF, 'utf8');
|
||||
|
||||
test('bug #3130: update.md contains no bare npx invocations (cache-stale form)', () => {
|
||||
// Any occurrence of `npx -y @opengsd/gsd-core@latest` without `--package=`
|
||||
// Any occurrence of `npx -y @opengsd/gsd-core@<something>` without `--package=`
|
||||
// is the stale form that triggers the two failure modes.
|
||||
const stale = (src.match(/npx -y @opengsd\/gsd-core@latest[^\n]*/g) || []);
|
||||
const stale = (src.match(/npx -y @opengsd\/gsd-core@\S+[^\n]*/g) || []);
|
||||
assert.deepEqual(
|
||||
stale,
|
||||
[],
|
||||
@@ -40,7 +42,8 @@ test('bug #3130: update.md contains no bare npx invocations (cache-stale form)',
|
||||
|
||||
test('bug #3130: update.md has >=3 robust npx invocations (--package= + -- separator)', () => {
|
||||
// Three sibling invocations: local, global, and unknown/fallback.
|
||||
const robust = (src.match(/npx -y --package=@opengsd\/gsd-core@latest -- gsd-core/g) || []);
|
||||
// The tag is now a $TAG variable (latest by default, next under --next/--rc).
|
||||
const robust = (src.match(/npx -y --package=@opengsd\/gsd-core@\S+ -- gsd-core/g) || []);
|
||||
assert.ok(
|
||||
robust.length >= 3,
|
||||
`Expected >=3 robust npx invocations in update.md, found ${robust.length}`,
|
||||
|
||||
@@ -25,7 +25,6 @@ const path = require('node:path');
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const WORKFLOW = path.join(ROOT, 'gsd-core', 'workflows', 'add-backlog.md');
|
||||
const COMMANDS_DIR = path.join(ROOT, 'commands', 'gsd');
|
||||
const WORKFLOWS_DIR = path.join(ROOT, 'gsd-core', 'workflows');
|
||||
|
||||
// ─── #3135: add-backlog workflow ─────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@ describe('#3242 Bug A: body-only state.update preserves curated progress frontma
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('state.update "Last Activity" does not overwrite progress.completed_plans', (t) => {
|
||||
test('state.update "Last Activity" does not overwrite progress.completed_plans', (_t) => {
|
||||
const statePath = path.join(tmpDir, '.planning', 'STATE.md');
|
||||
fs.writeFileSync(statePath, buildStateWithCuratedProgress({
|
||||
completedPlans: 22,
|
||||
@@ -220,7 +220,7 @@ describe('#3242 Bug B: progress.percent reflects phase fraction when ROADMAP dec
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('12 declared phases / 6 realized / 6/6 plans done → percent is 50, not 100', (t) => {
|
||||
test('12 declared phases / 6 realized / 6/6 plans done → percent is 50, not 100', (_t) => {
|
||||
const statePath = path.join(tmpDir, '.planning', 'STATE.md');
|
||||
|
||||
// Body: 6 realized phases visible to disk scan.
|
||||
@@ -273,7 +273,7 @@ describe('#3242 Bug B: progress.percent reflects phase fraction when ROADMAP dec
|
||||
);
|
||||
});
|
||||
|
||||
test('all phases realized: percent equals plan fraction (no artificial cap)', (t) => {
|
||||
test('all phases realized: percent equals plan fraction (no artificial cap)', (_t) => {
|
||||
const statePath = path.join(tmpDir, '.planning', 'STATE.md');
|
||||
|
||||
fs.writeFileSync(statePath, [
|
||||
|
||||
@@ -26,7 +26,6 @@ const os = require('os');
|
||||
const { execFileSync } = require('child_process');
|
||||
|
||||
const { validateCodexConfigSchema, install } = require('../bin/install.js');
|
||||
const installModule = require('../bin/install.js');
|
||||
const { cleanup } = require('./helpers.cjs');
|
||||
|
||||
if (previousGsdTestMode === undefined) {
|
||||
|
||||
@@ -29,7 +29,6 @@ const { describe, test, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
|
||||
const REPO_ROOT = path.join(__dirname, '..');
|
||||
const MODEL_CATALOG_CJS = path.join(REPO_ROOT, 'gsd-core', 'bin', 'lib', 'model-catalog.cjs');
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
* "no warning" pattern from #2687).
|
||||
*/
|
||||
|
||||
const { describe, test, afterEach, before } = require('node:test');
|
||||
const { describe, test, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
const { describe, test, beforeEach, afterEach } = require('node:test');
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
@@ -25,7 +25,6 @@ const { describe, test, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
|
||||
const {
|
||||
runInstallerMigrations,
|
||||
@@ -36,10 +35,6 @@ const {
|
||||
} = require('../gsd-core/bin/lib/installer-migration-report.cjs');
|
||||
const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
function sha256(content) {
|
||||
return crypto.createHash('sha256').update(content).digest('hex');
|
||||
}
|
||||
|
||||
function writeFile(root, relPath, content) {
|
||||
const fullPath = path.join(root, relPath);
|
||||
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
||||
|
||||
@@ -11,7 +11,6 @@ process.env.GSD_TEST_MODE = '1';
|
||||
const { describe, test, beforeEach, afterEach } = 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 REPO_ROOT = path.join(__dirname, '..');
|
||||
|
||||
@@ -38,7 +38,6 @@ const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
|
||||
const { install, getCodexSkillAdapterHeader } = require('../bin/install.js');
|
||||
const { parseFrontmatter, createTempDir, cleanup } = require('./helpers.cjs');
|
||||
@@ -54,6 +53,7 @@ const COMMANDS_DIR = path.join(ROOT, 'commands', 'gsd');
|
||||
|
||||
// Strip ANSI color codes so log assertions don't depend on TTY detection.
|
||||
function stripAnsi(s) {
|
||||
// eslint-disable-next-line no-control-regex -- \x1b (ESC) is the required leading byte of ANSI SGR color sequences; matching it is the purpose of stripping ANSI codes from captured CLI/console output
|
||||
return s.replace(/\x1b\[[0-9;]*m/g, '');
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,6 @@ const { describe, test, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
|
||||
const {
|
||||
runInstallerMigrations,
|
||||
|
||||
@@ -84,7 +84,7 @@ function createFixtureWithUserGsdDir() {
|
||||
|
||||
describe('bug-3659: applySurface prunes ~/.claude/skills/gsd-*/ on cluster disable', () => {
|
||||
test('(a) disabled cluster gsd-* dirs are removed from skills dir', (t) => {
|
||||
const { configDir, skillsDir, gsdExplore, gsdHelp } = createFixture();
|
||||
const { configDir, gsdExplore, gsdHelp } = createFixture();
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
// Surface state at configDir (= ~/.claude), NOT at skillsDir (= ~/.claude/skills).
|
||||
@@ -116,7 +116,7 @@ describe('bug-3659: applySurface prunes ~/.claude/skills/gsd-*/ on cluster disab
|
||||
});
|
||||
|
||||
test('(b) gsd-* dirs in retained clusters are preserved', (t) => {
|
||||
const { configDir, skillsDir, gsdHelp } = createFixture();
|
||||
const { configDir, gsdHelp } = createFixture();
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
// Disable a cluster that does NOT include help (core_loop has help)
|
||||
@@ -138,7 +138,7 @@ describe('bug-3659: applySurface prunes ~/.claude/skills/gsd-*/ on cluster disab
|
||||
});
|
||||
|
||||
test('(c) non-gsd user dirs are untouched', (t) => {
|
||||
const { configDir, skillsDir, userSkill } = createFixture();
|
||||
const { configDir, userSkill } = createFixture();
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
writeSurface(configDir, {
|
||||
@@ -163,7 +163,7 @@ describe('bug-3659: applySurface prunes ~/.claude/skills/gsd-*/ on cluster disab
|
||||
});
|
||||
|
||||
test('(d) idempotence: running applySurface twice produces identical on-disk state', (t) => {
|
||||
const { configDir, skillsDir, gsdExplore, gsdHelp, userSkill } = createFixture();
|
||||
const { configDir, skillsDir, gsdExplore, userSkill } = createFixture();
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
writeSurface(configDir, {
|
||||
@@ -212,7 +212,7 @@ describe('bug-3659: applySurface prunes ~/.claude/skills/gsd-*/ on cluster disab
|
||||
// 2. gsd-help/ — GSD-owned, disabled cluster → REMOVED
|
||||
// 3. my-custom-skill/ — user-owned, no gsd- prefix → PRESERVED
|
||||
// 4. gsd-mything/ — prefix match but NOT in manifest → PRESERVED (Finding 1 fix)
|
||||
const { configDir, skillsDir, gsdExplore, gsdHelp, userSkill, userGsdDir } =
|
||||
const { configDir, gsdExplore, gsdHelp, userSkill, userGsdDir } =
|
||||
createFixtureWithUserGsdDir();
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ const { cleanup } = require('./helpers.cjs');
|
||||
const REPO_ROOT = path.resolve(__dirname, '..');
|
||||
const INSTALL_PATH = path.join(REPO_ROOT, 'bin', 'install.js');
|
||||
|
||||
const install = require(INSTALL_PATH);
|
||||
require(INSTALL_PATH);
|
||||
const { readCmdNames } = require(path.join(REPO_ROOT, 'scripts', 'fix-slash-commands.cjs'));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -400,7 +400,6 @@ describe('bug #3683 — workflow/reference colon-namespace leak (Claude local in
|
||||
describe('G — negative: staged gemini workflows preserve colon-namespace refs', () => {
|
||||
let tmpDir;
|
||||
const cmdNames = readCmdNames();
|
||||
const rosterRegex = buildRosterRegex(cmdNames);
|
||||
|
||||
before(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3683-gem-'));
|
||||
|
||||
@@ -83,7 +83,7 @@ describe('bug #3691 — Bug 1: Plans-block detection with inline summary', () =>
|
||||
let tmpDir;
|
||||
afterEach(() => cleanup(tmpDir));
|
||||
|
||||
test('Plans: N plans (inline count after colon) is detected as a Plans-block', (t) => {
|
||||
test('Plans: N plans (inline count after colon) is detected as a Plans-block', (_t) => {
|
||||
// Pre-fix: `Plans:\s*\n` requires bare newline — fails for "Plans: 2 plans\n"
|
||||
// Post-fix: `Plans:[^\n]*\n` accepts any text after the colon
|
||||
const roadmap = [
|
||||
@@ -117,7 +117,7 @@ describe('bug #3691 — Bug 1: Plans-block detection with inline summary', () =>
|
||||
assert.ok(written.includes('Wave'), 'wave annotation must appear in ROADMAP.md');
|
||||
});
|
||||
|
||||
test('Plans: N plans across N waves (longer inline text) is detected', (t) => {
|
||||
test('Plans: N plans across N waves (longer inline text) is detected', (_t) => {
|
||||
const roadmap = [
|
||||
'# Roadmap',
|
||||
'',
|
||||
@@ -144,7 +144,7 @@ describe('bug #3691 — Bug 1: Plans-block detection with inline summary', () =>
|
||||
'Plans-block with "N plans across N waves" inline text must be detected');
|
||||
});
|
||||
|
||||
test('**Plans:** (bold markdown wrapper) is detected as a Plans-block', (t) => {
|
||||
test('**Plans:** (bold markdown wrapper) is detected as a Plans-block', (_t) => {
|
||||
// Bold wrapper: `**Plans:** 3 plans across 2 waves`
|
||||
const roadmap = [
|
||||
'# Roadmap',
|
||||
@@ -170,7 +170,7 @@ describe('bug #3691 — Bug 1: Plans-block detection with inline summary', () =>
|
||||
'**Plans:** bold-wrapped header must be detected as a Plans-block');
|
||||
});
|
||||
|
||||
test('bare Plans: (no inline text, legacy format) still works after fix', (t) => {
|
||||
test('bare Plans: (no inline text, legacy format) still works after fix', (_t) => {
|
||||
// Regression guard: the fix must not break the working case
|
||||
const roadmap = [
|
||||
'# Roadmap',
|
||||
@@ -205,7 +205,7 @@ describe('bug #3691 — Bug 3: decimal plan IDs (e.g. 02.3-01-PLAN.md) parse cor
|
||||
let tmpDir;
|
||||
afterEach(() => cleanup(tmpDir));
|
||||
|
||||
test('decimal plan ID 02.3-01 is captured fully and matched to the correct wave', (t) => {
|
||||
test('decimal plan ID 02.3-01 is captured fully and matched to the correct wave', (_t) => {
|
||||
// Pre-fix: `[\w-]+?` stops at `.` → captures `02` only → planData.find misses → wave = 1 for all
|
||||
// Post-fix: `[\w.-]+?` captures `02.3-01` → planData.find resolves → correct wave written
|
||||
const roadmap = [
|
||||
@@ -238,7 +238,7 @@ describe('bug #3691 — Bug 3: decimal plan IDs (e.g. 02.3-01-PLAN.md) parse cor
|
||||
assert.ok(/Wave 2/.test(written), 'Wave 2 header must appear in output');
|
||||
});
|
||||
|
||||
test('combined fixture: decimal phase + bold Plans: header (both bugs together)', (t) => {
|
||||
test('combined fixture: decimal phase + bold Plans: header (both bugs together)', (_t) => {
|
||||
// Exercises Bug 1 (bold **Plans:** header) AND Bug 3 (decimal IDs) simultaneously.
|
||||
// This is the exact ROADMAP fragment from the issue report.
|
||||
const roadmap = [
|
||||
@@ -280,7 +280,7 @@ describe('review fix F3 — leading-dot plan ID is rejected (defensive guard)',
|
||||
let tmpDir;
|
||||
afterEach(() => cleanup(tmpDir));
|
||||
|
||||
test('checklist line with leading-dot plan ID is skipped and does not silently default to wave 1', (t) => {
|
||||
test('checklist line with leading-dot plan ID is skipped and does not silently default to wave 1', (_t) => {
|
||||
// Guards: `.invalid-PLAN.md` would be captured as `.invalid` by the `[\w.-]+?` regex
|
||||
// (since `.` is now included), which starts with a dot — an invalid ID.
|
||||
// Without the guard, planData.find() misses it and wave defaults to 1, silently
|
||||
@@ -327,7 +327,7 @@ describe('review fix F4 — adversarial test gaps', () => {
|
||||
let tmpDir;
|
||||
afterEach(() => cleanup(tmpDir));
|
||||
|
||||
test('001.10-PLAN.md multi-decimal leading-zero ID is captured fully and wave-assigned correctly', (t) => {
|
||||
test('001.10-PLAN.md multi-decimal leading-zero ID is captured fully and wave-assigned correctly', (_t) => {
|
||||
// Guards regression of Bug 3: `[\w-]+?` would stop at the first `.` and
|
||||
// capture `001` instead of `001.10`, which never matches any planData entry.
|
||||
// Post-fix `[\w.-]+?` must capture `001.10` in full.
|
||||
@@ -357,7 +357,7 @@ describe('review fix F4 — adversarial test gaps', () => {
|
||||
'wave 2 dependency must be resolved from full 001.10-02 ID (not truncated to 001)');
|
||||
});
|
||||
|
||||
test('**Plans:** (bold, no trailing text) is matched and checklist is processed', (t) => {
|
||||
test('**Plans:** (bold, no trailing text) is matched and checklist is processed', (_t) => {
|
||||
// Guards the bare-bold variant: `**Plans:**` with nothing after the colon.
|
||||
// The `[^\n]*` quantifier accepts zero chars so this should already work,
|
||||
// but this test would fail if `\*{0,2}Plans\*{0,2}` regressed to require no stars.
|
||||
|
||||
@@ -16,7 +16,6 @@ const { cleanup } = require('./helpers.cjs');
|
||||
|
||||
const {
|
||||
executeWorktreeWaveCleanupPlan,
|
||||
planWorktreeWaveCleanup,
|
||||
reapOrphanWorktrees,
|
||||
} = require('../gsd-core/bin/lib/worktree-safety.cjs');
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ const assert = require('node:assert/strict');
|
||||
const path = require('path');
|
||||
|
||||
const {
|
||||
PROFILES,
|
||||
resolveProfile,
|
||||
loadSkillsManifest,
|
||||
} = require('../gsd-core/bin/lib/install-profiles.cjs');
|
||||
|
||||
@@ -21,20 +21,10 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
|
||||
|
||||
const REPO_ROOT = path.join(__dirname, '..');
|
||||
|
||||
describe('bug #3739 — gap-analysis padded-prefix CONTEXT.md', () => {
|
||||
let tmpDir;
|
||||
let phaseDir;
|
||||
|
||||
function writeRequirements(ids) {
|
||||
const lines = ids.map((id, i) => `- [ ] **${id}** Requirement ${i + 1}`);
|
||||
fs.writeFileSync(
|
||||
path.join(tmpDir, '.planning', 'REQUIREMENTS.md'),
|
||||
`# Requirements\n\n${lines.join('\n')}\n`
|
||||
);
|
||||
}
|
||||
|
||||
function writeContextAs(filename, decisions) {
|
||||
const dLines = decisions.map(d => `- **${d.id}:** ${d.text}`).join('\n');
|
||||
fs.writeFileSync(
|
||||
|
||||
@@ -32,7 +32,20 @@ const { cleanup } = require('./helpers.cjs');
|
||||
const REPO_ROOT = path.resolve(__dirname, '..');
|
||||
const INSTALL_PATH = path.join(REPO_ROOT, 'bin', 'install.js');
|
||||
const HOOKS_DIST_DIR = path.join(REPO_ROOT, 'hooks', 'dist');
|
||||
const HOOKS_SRC_DIR = path.join(REPO_ROOT, 'hooks');
|
||||
const BUILD_HOOKS_SCRIPT = path.join(REPO_ROOT, 'scripts', 'build-hooks.js');
|
||||
|
||||
/**
|
||||
* Ensure hooks/dist is populated before any suite that reads it.
|
||||
* hooks/dist/ is gitignored and only produced by `npm run build:hooks`.
|
||||
* In CI the scoped/windows test jobs do NOT run build:hooks before running
|
||||
* tests, so the first test that needs hooks/dist would fail. This mirrors
|
||||
* the pattern used in bug-3357-codex-legacy-hooks-json-migration.test.cjs.
|
||||
*/
|
||||
function ensureHooksDist() {
|
||||
if (!fs.existsSync(HOOKS_DIST_DIR) || fs.readdirSync(HOOKS_DIST_DIR).filter(f => f.endsWith('.js')).length === 0) {
|
||||
execFileSync(process.execPath, [BUILD_HOOKS_SCRIPT], { stdio: 'pipe' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
@@ -93,6 +106,12 @@ function colonRefs(content) {
|
||||
// Prerequisite: hooks/dist must exist (built by `npm run build:hooks`)
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('bug #376 — prerequisite: hooks/dist is present', () => {
|
||||
before(() => {
|
||||
// hooks/dist is gitignored; build it on demand so this test is
|
||||
// deterministic in CI scoped/windows jobs that don't pre-run build:hooks.
|
||||
ensureHooksDist();
|
||||
});
|
||||
|
||||
test('hooks/dist directory exists (run npm run build:hooks if missing)', () => {
|
||||
assert.ok(
|
||||
fs.existsSync(HOOKS_DIST_DIR),
|
||||
@@ -190,11 +209,13 @@ describe('bug #376 — Suite 1: Claude install rewrites /gsd: → /gsd- in hook
|
||||
// ---------------------------------------------------------------------------
|
||||
// Suite 2 — Cursor install regression: /gsd: → /gsd- still works (pre-existing)
|
||||
//
|
||||
// Note: Cursor does NOT install hooks/dist files (Cursor skips the hooks
|
||||
// install step entirely — see install.js gate around line 8829). The Cursor
|
||||
// /gsd: rewrite applies in `copyWithPathReplacement` to JS files under the
|
||||
// agent/skill tree (.cursor/gsd-core/*.js etc). We verify that Cursor's
|
||||
// installed .js files under .cursor/ have no /gsd: colon refs.
|
||||
// Note: Cursor installs its own hooks (gsd-cursor-session-start.js and
|
||||
// gsd-cursor-post-tool.js) via the cursor-hooks-json installSurface (issue #777).
|
||||
// It does NOT install the bundled Claude-style hooks/dist files (no gsd-session-state.sh
|
||||
// etc.). The Cursor /gsd: rewrite applies in `copyWithPathReplacement` to JS files
|
||||
// under the agent/skill tree (.cursor/gsd-core/*.js etc). We verify that Cursor's
|
||||
// installed .js files under .cursor/ have no /gsd: colon refs, and that the hooks/
|
||||
// directory contains only the Cursor-specific managed hooks.
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('bug #376 — Suite 2: Cursor install still rewrites /gsd: → /gsd- (regression)', () => {
|
||||
let tmpDir;
|
||||
@@ -243,15 +264,32 @@ describe('bug #376 — Suite 2: Cursor install still rewrites /gsd: → /gsd- (r
|
||||
);
|
||||
});
|
||||
|
||||
test('2c: Cursor install does not install a hooks/ directory (hooks are cursor-skipped)', () => {
|
||||
// Cursor intentionally skips the hooks/dist copy step — verify this contract
|
||||
// is still honored so we know the regression only concerns hook .js files
|
||||
// for runtimes that DO install hooks (claude, qwen, hermes etc.).
|
||||
test('2c: Cursor install creates a hooks/ directory with only Cursor-specific managed hooks', () => {
|
||||
// Since issue #777, Cursor installs gsd-cursor-session-start.js and
|
||||
// gsd-cursor-post-tool.js into <configDir>/hooks/. These are Cursor-native
|
||||
// hooks — NOT the bundled Claude-style hooks (no gsd-session-state.sh etc.).
|
||||
// Verify: hooks/ exists AND does NOT contain any Claude-bundled hooks.
|
||||
const hooksDir = path.join(tmpDir, '.cursor', 'hooks');
|
||||
assert.strictEqual(
|
||||
assert.ok(
|
||||
fs.existsSync(hooksDir),
|
||||
false,
|
||||
'Cursor install must NOT create a hooks/ directory — Cursor skips the hooks install step',
|
||||
'Cursor install must create a hooks/ directory for its managed hook scripts (#777)',
|
||||
);
|
||||
const CLAUDE_BUNDLED_HOOKS = ['gsd-session-state.sh', 'gsd-context-monitor.js', 'gsd-statusline.js'];
|
||||
for (const hook of CLAUDE_BUNDLED_HOOKS) {
|
||||
assert.strictEqual(
|
||||
fs.existsSync(path.join(hooksDir, hook)),
|
||||
false,
|
||||
`Cursor hooks/ must NOT contain Claude-bundled hook ${hook} — only Cursor-native hooks are installed`,
|
||||
);
|
||||
}
|
||||
// The two Cursor-specific managed hooks must be present.
|
||||
assert.ok(
|
||||
fs.existsSync(path.join(hooksDir, 'gsd-cursor-session-start.js')),
|
||||
'gsd-cursor-session-start.js must be installed in .cursor/hooks/ (#777)',
|
||||
);
|
||||
assert.ok(
|
||||
fs.existsSync(path.join(hooksDir, 'gsd-cursor-post-tool.js')),
|
||||
'gsd-cursor-post-tool.js must be installed in .cursor/hooks/ (#777)',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -263,6 +301,9 @@ describe('bug #376 — Suite 3: hooks/ source files are unchanged by install', (
|
||||
let snapshotBefore;
|
||||
|
||||
before(() => {
|
||||
// Ensure hooks/dist is built before snapshotting; it may be absent in CI
|
||||
// scoped/windows jobs that don't pre-run build:hooks (#777 fix).
|
||||
ensureHooksDist();
|
||||
// Snapshot hooks/dist JS files before any install in this suite
|
||||
snapshotBefore = {};
|
||||
if (fs.existsSync(HOOKS_DIST_DIR)) {
|
||||
|
||||
@@ -184,7 +184,6 @@ describe('bug #3784: settings.md model profile UI exposes all 5 profiles', () =>
|
||||
// commit bd53925f fixed a duplicate '{' introduced by 35fc1d21 when the model-profile
|
||||
// AskUserQuestion was split into Q1+Q2. This test guards against a recurrence.
|
||||
let depth = 0;
|
||||
const maxDepth = 0;
|
||||
for (const ch of presentBlock) {
|
||||
if (ch === '{') { depth++; }
|
||||
if (ch === '}') { depth--; }
|
||||
|
||||
133
tests/bug-3810-no-gsd-sdk-runtime-refs.test.cjs
Normal file
133
tests/bug-3810-no-gsd-sdk-runtime-refs.test.cjs
Normal file
@@ -0,0 +1,133 @@
|
||||
// allow-test-rule: source-text-is-the-product
|
||||
// Runtime prompt/hook files are deployed verbatim — their text IS what the
|
||||
// runtime loads and executes. Asserting that text carries no retired `gsd-sdk`
|
||||
// reference tests the deployed contract, which no behavioral seam can observe
|
||||
// (there is no runtime API that enumerates "did any shipped prompt name the
|
||||
// removed SDK binary").
|
||||
|
||||
/**
|
||||
* Regression guard: no `gsd-sdk` references in runtime-facing surfaces (#339).
|
||||
*
|
||||
* The `@opengsd/gsd-sdk` package and its `gsd-sdk` binary were retired (ADR 0174,
|
||||
* #191). The bulk runtime cleanup is already done — this test locks it in so a
|
||||
* `gsd-sdk` / `GSD_SDK` reference cannot creep back into a shipped prompt or hook
|
||||
* and re-introduce drift between the documented surface and the supported
|
||||
* `gsd-tools` binary.
|
||||
*
|
||||
* Scope: runtime surfaces only — the prompts and hooks the installer ships into
|
||||
* a user's runtime config dir. Explicitly NOT covered here:
|
||||
* - `bin/install.js` — installer code, not a runtime-deployed prompt/hook
|
||||
* surface. (It carries zero `gsd-sdk` references today; the SDK-shim
|
||||
* verification subsystem was removed in #515 and the shim retired in #522.)
|
||||
* - `gsd-core/bin/` — executable library code, not deployed prompt text; it
|
||||
* may legitimately reference the SDK retirement in comments.
|
||||
* - `tests/`, `docs/`, `.changeset/`, CI/lint scripts — legitimately reference
|
||||
* the SDK retirement as history or detect its stale artifacts.
|
||||
*
|
||||
* Complements `tests/gsd-tools-path-refs.test.cjs`, which only catches the
|
||||
* `gsd-sdk query` binary-invocation form; this catches ANY runtime reference.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const REPO_ROOT = path.join(__dirname, '..');
|
||||
|
||||
// Runtime surfaces the installer ships. Each entry is { dir, exts } — dir is
|
||||
// repo-relative, exts is the set of file extensions whose text is deployed.
|
||||
const RUNTIME_SURFACES = [
|
||||
// .md prompts plus the non-.md runtime artifacts this dir also ships:
|
||||
// _runtime-launcher.snippet.sh (the canonical launcher synced into every hook
|
||||
// by scripts/sync-runtime-launcher.cjs) and discuss-phase/templates/*.json
|
||||
// (loaded at runtime by discuss-phase.md). Scanning only .md left these two
|
||||
// deployed files uncovered. (#691 review)
|
||||
{ dir: path.join('gsd-core', 'workflows'), exts: ['.md', '.sh', '.json'] },
|
||||
{ dir: path.join('gsd-core', 'references'), exts: ['.md'] },
|
||||
// Prompt surfaces the installer deep-copies and the runtime loads via
|
||||
// `@~/.claude/gsd-core/templates/*.md` anchors in workflows/commands; the
|
||||
// lone config.json under templates/ ships too. (#691 review)
|
||||
{ dir: path.join('gsd-core', 'templates'), exts: ['.md', '.json'] },
|
||||
{ dir: path.join('gsd-core', 'contexts'), exts: ['.md'] },
|
||||
{ dir: path.join('commands', 'gsd'), exts: ['.md'] },
|
||||
{ dir: 'agents', exts: ['.md'] },
|
||||
// Hooks ship as executable text (.js/.cjs/.sh). `hooks/dist/` is a gitignored
|
||||
// build artifact regenerated from these sources, so scanning the sources is
|
||||
// sufficient and avoids asserting against generated copies.
|
||||
{ dir: 'hooks', exts: ['.js', '.cjs', '.sh'], skipDirs: ['dist'] },
|
||||
];
|
||||
|
||||
// Matches every casing/separator variant of the retired SDK token:
|
||||
// gsd-sdk, gsd_sdk, GSD-SDK, GSD_SDK, etc.
|
||||
const SDK_REF = /gsd[-_]sdk/i;
|
||||
|
||||
/**
|
||||
* Recursively collect files under `absDir` whose extension is in `exts`,
|
||||
* skipping any directory name listed in `skipDirs`.
|
||||
*/
|
||||
function collectFiles(absDir, exts, skipDirs) {
|
||||
if (!fs.existsSync(absDir)) return [];
|
||||
const out = [];
|
||||
for (const entry of fs.readdirSync(absDir, { withFileTypes: true })) {
|
||||
if (entry.isDirectory()) {
|
||||
if (skipDirs.includes(entry.name)) continue;
|
||||
out.push(...collectFiles(path.join(absDir, entry.name), exts, skipDirs));
|
||||
} else if (entry.isFile() && exts.includes(path.extname(entry.name))) {
|
||||
out.push(path.join(absDir, entry.name));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function rel(file) {
|
||||
return path.relative(REPO_ROOT, file).split(path.sep).join('/');
|
||||
}
|
||||
|
||||
describe('#339 no gsd-sdk references in runtime surfaces', () => {
|
||||
test('shipped prompts and hooks carry no retired gsd-sdk reference', () => {
|
||||
const violations = [];
|
||||
|
||||
for (const { dir, exts, skipDirs = [] } of RUNTIME_SURFACES) {
|
||||
const files = collectFiles(path.join(REPO_ROOT, dir), exts, skipDirs);
|
||||
for (const file of files) {
|
||||
const lines = fs.readFileSync(file, 'utf-8').split(/\r?\n/);
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (SDK_REF.test(lines[i])) {
|
||||
violations.push(`${rel(file)}:${i + 1}: ${lines[i].trim()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert.strictEqual(
|
||||
violations.length,
|
||||
0,
|
||||
'Runtime surfaces must not reference the retired gsd-sdk binary/package — ' +
|
||||
'use gsd-tools instead.\nViolations:\n' + violations.join('\n')
|
||||
);
|
||||
});
|
||||
|
||||
test('at least one file per configured extension is scanned (guards against an empty sweep)', () => {
|
||||
// A path typo, directory rename, or stale extension could silently make
|
||||
// collectFiles() return [] for part of a surface, turning the guard above
|
||||
// into a no-op that always passes. Checking per-surface isn't enough: for
|
||||
// gsd-core/workflows the .md files alone keep a per-surface count > 0, so
|
||||
// dropping .sh/.json would stop covering _runtime-launcher.snippet.sh and
|
||||
// discuss-phase/templates/*.json while the test stayed green. Assert each
|
||||
// configured extension actually resolves to scanned files. (#691 review)
|
||||
for (const { dir, exts, skipDirs = [] } of RUNTIME_SURFACES) {
|
||||
for (const ext of exts) {
|
||||
const count = collectFiles(path.join(REPO_ROOT, dir), [ext], skipDirs).length;
|
||||
assert.ok(
|
||||
count > 0,
|
||||
`Runtime surface "${dir}" resolved to 0 "${ext}" files — the path may ` +
|
||||
'have moved or the extension is stale; update RUNTIME_SURFACES so the ' +
|
||||
'guard keeps covering it.'
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,7 @@
|
||||
* the clock seam (in-process, using makeFakeClock — no subprocess needed).
|
||||
*/
|
||||
|
||||
const { describe, it, test, before, after } = require('node:test');
|
||||
const { describe, test, before, after } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
@@ -4,9 +4,8 @@ process.env.GSD_TEST_MODE = "1";
|
||||
|
||||
const { describe, test, beforeEach, afterEach } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const path = require("path");
|
||||
const { createTempProject, cleanup } = require("./helpers.cjs");
|
||||
const { resolveEffortInternal, CONFIG_DEFAULTS } = require("../gsd-core/bin/lib/core.cjs");
|
||||
const { resolveEffortInternal } = require("../gsd-core/bin/lib/core.cjs");
|
||||
const { CONFIG_DEFAULTS: CANONICAL_CONFIG_DEFAULTS } = require("../gsd-core/bin/lib/configuration.cjs");
|
||||
|
||||
describe("#492 manifest effort fallback", () => {
|
||||
|
||||
@@ -30,7 +30,6 @@ const { execFileSync } = require('node:child_process');
|
||||
|
||||
const {
|
||||
install,
|
||||
writeManifest,
|
||||
convertClaudeCommandToCodexSkill,
|
||||
} = require('../bin/install.js');
|
||||
const { createTempDir, cleanup, captureConsole } = require('./helpers.cjs');
|
||||
|
||||
@@ -41,8 +41,9 @@ const GRAPHIFY_MD = path.join(__dirname, '..', 'commands', 'gsd', 'graphify.md')
|
||||
*/
|
||||
function extractStep3Block() {
|
||||
const content = fs.readFileSync(GRAPHIFY_MD, 'utf-8');
|
||||
// Capture from the `graphify update .` line through the next closing ``` fence.
|
||||
const match = content.match(/```bash\r?\n(graphify update \.[^\0]*?)```/);
|
||||
// Capture the full body of the ```bash fence that CONTAINS `graphify update .`
|
||||
// (including any leading preamble line), without crossing into other fences.
|
||||
const match = content.match(/```bash\r?\n((?:(?!```)[\s\S])*?graphify update \.(?:(?!```)[\s\S])*?)\r?\n```/);
|
||||
return match ? match[1].trim() : null;
|
||||
}
|
||||
|
||||
|
||||
67
tests/bug-637-workflow-no-hardcoded-home-tool.test.cjs
Normal file
67
tests/bug-637-workflow-no-hardcoded-home-tool.test.cjs
Normal file
@@ -0,0 +1,67 @@
|
||||
// allow-test-rule: source-text-is-the-product
|
||||
// Workflow .md text IS what the runtime loads and the agent executes, so
|
||||
// asserting on its shell invocations tests the deployed contract directly.
|
||||
//
|
||||
// Repo-wide regression guard for #637 (generalizes the plan-phase-only guard
|
||||
// from #621): NO workflow .md may invoke gsd-tools via a hardcoded
|
||||
// `node "$HOME/.../gsd-tools.cjs"` path. On a global/shim-only install with no
|
||||
// project-local runtime, that path can miss a working install, so the step
|
||||
// reports the tool "not found" instead of resolving it. Every invocation must
|
||||
// go through the `gsd_run` launcher (defined once per file in the canonical
|
||||
// preamble, which resolves RUNTIME_DIR → .claude → PATH → $HOME in order).
|
||||
//
|
||||
// The parity test (runtime-launcher-parity) guards the retired $GSD_SDK and
|
||||
// bare /gsd-tools tokens but NOT this hardcoded-node form — which is exactly
|
||||
// how it survived across plan-phase.md (#621) and three more files (#637).
|
||||
|
||||
'use strict';
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const WORKFLOWS_DIR = path.join(__dirname, '..', 'gsd-core', 'workflows');
|
||||
|
||||
// Hardcoded direct invocation form. Distinct from the canonical preamble, which
|
||||
// references $HOME only inside a `[ -f "$HOME/..." ]` probe / `GSD_TOOLS=`
|
||||
// assignment and always invokes `node "$GSD_TOOLS"` — never `node "$HOME/..."`.
|
||||
const HARDCODED_HOME_INVOCATION = /node\s+"\$HOME\/[^"]*gsd-tools\.cjs"/;
|
||||
|
||||
function collectWorkflowMarkdown(dir) {
|
||||
const out = [];
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
out.push(...collectWorkflowMarkdown(full));
|
||||
} else if (entry.isFile() && entry.name.endsWith('.md')) {
|
||||
out.push(full);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('bug #637: no workflow .md hardcodes a $HOME gsd-tools invocation', () => {
|
||||
test('every gsd-core/workflows/**/*.md resolves gsd-tools via gsd_run, not a hardcoded $HOME path', () => {
|
||||
const files = collectWorkflowMarkdown(WORKFLOWS_DIR);
|
||||
assert.ok(files.length > 0, 'expected workflow markdown files to exist');
|
||||
|
||||
const offenders = [];
|
||||
for (const file of files) {
|
||||
const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
|
||||
lines.forEach((line, i) => {
|
||||
if (HARDCODED_HOME_INVOCATION.test(line)) {
|
||||
offenders.push(`${path.relative(WORKFLOWS_DIR, file)}:${i + 1}: ${line.trim()}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
assert.deepStrictEqual(
|
||||
offenders,
|
||||
[],
|
||||
'Workflow files must invoke gsd-tools via the resolved `gsd_run` launcher, ' +
|
||||
'not a hardcoded `node "$HOME/.../gsd-tools.cjs"` path. Offenders:\n' +
|
||||
offenders.join('\n'),
|
||||
);
|
||||
});
|
||||
});
|
||||
155
tests/bug-663-redos-roadmap-phase-parsing.test.cjs
Normal file
155
tests/bug-663-redos-roadmap-phase-parsing.test.cjs
Normal file
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Regression test for the ReDoS fixes in buildRoadmapPhaseVariants() and
|
||||
* buildNotStartedPhaseVariants() (src/validate.cts, fix #663).
|
||||
*
|
||||
* The old patterns used nested quantifiers that caused catastrophic
|
||||
* backtracking on crafted input:
|
||||
* old: [\w][\w.-]*(?:-[\w.-]+)* ← ambiguous alternation → exponential
|
||||
* new: [\w][\w.-]* ← single quantifier → linear
|
||||
*
|
||||
* The same nested-quantifier shape was fixed identically in src/verify.cts,
|
||||
* src/commands.cts, and src/phase.cts.
|
||||
*
|
||||
* Part A: behavior preservation — the collapsed regex still matches the same
|
||||
* phase identifiers as before on normal roadmap content.
|
||||
* Part B: ReDoS adversarial fixtures — calls buildRoadmapPhaseVariants /
|
||||
* buildNotStartedPhaseVariants with pathological input (a malformed heading
|
||||
* or checklist line that has NO terminating colon). The adversarial input
|
||||
* would cause catastrophic backtracking under the OLD nested-quantifier
|
||||
* pattern; the fix makes backtracking linear. We assert on the STRUCTURED
|
||||
* RESULT (the returned Set is empty — no match — because the colon is
|
||||
* absent) rather than on elapsed time, in compliance with the
|
||||
* local/no-elapsed-assertion ESLint rule. A { timeout: 5000 } backstop is
|
||||
* retained so the test fails fast if a future regression reintroduces a
|
||||
* slow pattern.
|
||||
*
|
||||
* Requirements: TEST-663-B
|
||||
*/
|
||||
|
||||
const { test, describe } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const {
|
||||
buildRoadmapPhaseVariants,
|
||||
buildNotStartedPhaseVariants,
|
||||
} = require('../gsd-core/bin/lib/validate.cjs');
|
||||
|
||||
// ─── Part A: behavior preservation ───────────────────────────────────────────
|
||||
|
||||
describe('buildRoadmapPhaseVariants — behavior preservation (#663)', () => {
|
||||
test('matches plain numeric heading (Phase 1:)', () => {
|
||||
const content = [
|
||||
'# Roadmap',
|
||||
'## Phase 1: Foo',
|
||||
].join('\n');
|
||||
|
||||
const { roadmapPhases } = buildRoadmapPhaseVariants(content);
|
||||
assert.ok(roadmapPhases.has('1'), 'roadmapPhases should contain "1"');
|
||||
});
|
||||
|
||||
test('matches milestone-prefixed heading (Phase 2-01:)', () => {
|
||||
const content = [
|
||||
'# Roadmap',
|
||||
'### Phase 2-01: Bar',
|
||||
].join('\n');
|
||||
|
||||
const { roadmapPhases } = buildRoadmapPhaseVariants(content);
|
||||
assert.ok(roadmapPhases.has('2-01'), 'roadmapPhases should contain "2-01"');
|
||||
});
|
||||
|
||||
test('matches bracket-prefixed heading ([GSD] Phase 3.2:)', () => {
|
||||
const content = [
|
||||
'# Roadmap',
|
||||
'### [GSD] Phase 3.2: Baz',
|
||||
].join('\n');
|
||||
|
||||
const { roadmapPhases } = buildRoadmapPhaseVariants(content);
|
||||
assert.ok(roadmapPhases.has('3.2'), 'roadmapPhases should contain "3.2"');
|
||||
});
|
||||
|
||||
test('collects all phase identifiers from mixed-format roadmap', () => {
|
||||
const content = [
|
||||
'# Roadmap',
|
||||
'## Phase 1: Alpha',
|
||||
'### Phase 2-01: Beta',
|
||||
'### [GSD] Phase 3.2: Gamma',
|
||||
].join('\n');
|
||||
|
||||
const { roadmapPhases } = buildRoadmapPhaseVariants(content);
|
||||
assert.ok(roadmapPhases.has('1'), 'should have phase 1');
|
||||
assert.ok(roadmapPhases.has('2-01'), 'should have phase 2-01');
|
||||
assert.ok(roadmapPhases.has('3.2'), 'should have phase 3.2');
|
||||
});
|
||||
|
||||
test('populates roadmapPhaseVariants with padding-normalized forms', () => {
|
||||
const content = [
|
||||
'# Roadmap',
|
||||
'### Phase 2-01: Beta',
|
||||
].join('\n');
|
||||
|
||||
const { roadmapPhaseVariants } = buildRoadmapPhaseVariants(content);
|
||||
// phaseVariants() adds both padded and unpadded forms
|
||||
assert.ok(roadmapPhaseVariants.has('2-01') || roadmapPhaseVariants.has('02-01'),
|
||||
'roadmapPhaseVariants should contain at least one padding form of 2-01');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildNotStartedPhaseVariants — behavior preservation (#663)', () => {
|
||||
test('matches unchecked checklist item (- [ ] Phase 4-01:)', () => {
|
||||
const content = [
|
||||
'# Roadmap',
|
||||
'- [ ] Phase 4-01: Qux',
|
||||
].join('\n');
|
||||
|
||||
const notStarted = buildNotStartedPhaseVariants(content);
|
||||
// phaseVariants() expands 4-01 into multiple forms; at minimum the raw form is present.
|
||||
assert.ok(notStarted.has('4-01') || notStarted.has('04-01'),
|
||||
'notStarted should contain a variant of 4-01');
|
||||
});
|
||||
|
||||
test('does not pick up checked items', () => {
|
||||
const content = [
|
||||
'# Roadmap',
|
||||
'- [x] Phase 5: Done',
|
||||
].join('\n');
|
||||
|
||||
const notStarted = buildNotStartedPhaseVariants(content);
|
||||
assert.strictEqual(notStarted.has('5'), false, 'completed phase should not be in notStarted');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Part B: ReDoS adversarial fixtures ──────────────────────────────────────
|
||||
|
||||
describe('buildRoadmapPhaseVariants — ReDoS adversarial fixture (#663)', () => {
|
||||
// Pathological input: a heading line where the phase-id segment consists of
|
||||
// many consecutive "-a" chunks with NO terminating colon. Under the old
|
||||
// nested-quantifier pattern ([\w.-]*(?:-[\w.-]+)*\s*:) the engine must
|
||||
// explore exponentially many ways to partition the "-a" repetitions before
|
||||
// concluding there is no match. The fixed single-quantifier pattern
|
||||
// ([\w.-]*\s*:) backtracks linearly. We assert that the malformed heading
|
||||
// yields NO match (empty roadmapPhases Set) — the correct behavior when the
|
||||
// terminating colon is absent. The { timeout: 5000 } backstop catches any
|
||||
// regression that re-introduces a slow pattern.
|
||||
test('malformed heading without colon yields no phase match (adversarial input)', { timeout: 5000 }, () => {
|
||||
const pathological = '## Phase a' + '-a'.repeat(32) + ' ';
|
||||
const { roadmapPhases } = buildRoadmapPhaseVariants(pathological);
|
||||
assert.strictEqual(roadmapPhases.size, 0,
|
||||
'a heading with no terminating colon should not match any phase');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildNotStartedPhaseVariants — ReDoS adversarial fixture (#663)', () => {
|
||||
// Same analysis: the old uncheckedPattern used the same nested quantifier.
|
||||
// A checklist-style line with many "-a" segments and no colon triggers the
|
||||
// same catastrophic backtracking. Assert the correct structured result:
|
||||
// the malformed line yields an empty notStarted Set.
|
||||
test('malformed unchecked-item without terminator yields no phase match (adversarial input)', { timeout: 5000 }, () => {
|
||||
// No trailing colon or whitespace: the regex terminator [:\s*] cannot match,
|
||||
// so the engine must backtrack through all '-a' repetitions and conclude no
|
||||
// match. Under the old nested-quantifier pattern this was exponential;
|
||||
// under the fixed linear pattern it returns immediately with an empty Set.
|
||||
const pathological = '- [ ] Phase a' + '-a'.repeat(32);
|
||||
const notStarted = buildNotStartedPhaseVariants(pathological);
|
||||
assert.strictEqual(notStarted.size, 0,
|
||||
'an unchecked-item line with no terminating colon or space should not match any phase');
|
||||
});
|
||||
});
|
||||
99
tests/bug-685-windowshide-spawn.test.cjs
Normal file
99
tests/bug-685-windowshide-spawn.test.cjs
Normal file
@@ -0,0 +1,99 @@
|
||||
// allow-test-rule: source-text-is-the-product
|
||||
// These spawn/exec sites cannot be behaviourally tested for windowsHide
|
||||
// off-Windows; the source text is the runtime contract (issue #685). Without
|
||||
// windowsHide:true a detached or shell:true child allocates a visible console
|
||||
// window on Windows (the "gsd-core" flash).
|
||||
'use strict';
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const read = (p) => fs.readFileSync(path.join(root, p), 'utf-8');
|
||||
|
||||
// Slice the exact body of one spawn site so the assertion binds that site,
|
||||
// not merely "windowsHide appears somewhere in the file".
|
||||
function regionBetween(src, startAnchor, endAnchor) {
|
||||
const i = src.indexOf(startAnchor);
|
||||
assert.notEqual(i, -1, `start anchor not found: ${startAnchor}`);
|
||||
const j = src.indexOf(endAnchor, i);
|
||||
assert.notEqual(j, -1, `end anchor not found after start: ${endAnchor}`);
|
||||
return src.slice(i, j);
|
||||
}
|
||||
|
||||
describe('bug #685: Windows spawns must set windowsHide:true (no console-window flash)', () => {
|
||||
test('gsd-context-monitor record-session spawn sets windowsHide', () => {
|
||||
const region = regionBetween(read('hooks/gsd-context-monitor.js'), "'record-session'", '.unref()');
|
||||
assert.match(region, /windowsHide:\s*true/, 'record-session spawn must set windowsHide: true');
|
||||
});
|
||||
|
||||
const cts = () => read('src/shell-command-projection.cts');
|
||||
const helpers = [
|
||||
['execGit', 'export function execGit', "_spawnResult(result, 'git')"],
|
||||
['execNpm', 'export function execNpm', "_spawnResult(result, 'npm')"],
|
||||
['execTool', 'export function execTool', '_spawnResult(result, program)'],
|
||||
];
|
||||
for (const [name, start, end] of helpers) {
|
||||
test(`shell-command-projection ${name} spawnSync sets windowsHide`, () => {
|
||||
const region = regionBetween(cts(), start, end);
|
||||
assert.match(region, /windowsHide:\s*true/, `${name} spawnSync must set windowsHide: true`);
|
||||
});
|
||||
}
|
||||
|
||||
test('gsd-worktree-path-guard SPAWNOPT sets windowsHide', () => {
|
||||
const region = regionBetween(read('hooks/gsd-worktree-path-guard.js'), 'const SPAWNOPT', '};');
|
||||
assert.match(region, /windowsHide:\s*true/, 'gsd-worktree-path-guard SPAWNOPT must set windowsHide: true');
|
||||
});
|
||||
|
||||
test('gsd-workflow-guard currentBranch spawnSync sets windowsHide', () => {
|
||||
const region = regionBetween(read('hooks/gsd-workflow-guard.js'), "spawnSync('git', ['branch'", '});');
|
||||
assert.match(region, /windowsHide:\s*true/, 'gsd-workflow-guard git-branch spawn must set windowsHide: true');
|
||||
});
|
||||
|
||||
test('check-command-router recentCommitMessages execFileSync sets windowsHide', () => {
|
||||
const region = regionBetween(read('src/check-command-router.cts'), "execFileSync('git', ['log'", '});');
|
||||
assert.match(region, /windowsHide:\s*true/, 'check-command-router git-log execFileSync must set windowsHide: true');
|
||||
});
|
||||
|
||||
test('roadmap-upgrade execSync git calls all set windowsHide', () => {
|
||||
const src = read('src/roadmap-upgrade.cts');
|
||||
const calls = src.match(/execSync\([^)]*\)/g) || [];
|
||||
assert.ok(calls.length >= 4, 'expected the roadmap-upgrade git execSync calls to be present');
|
||||
const missing = calls.filter((c) => !/windowsHide:\s*true/.test(c));
|
||||
assert.deepEqual(missing, [], `execSync without windowsHide:\n${missing.join('\n')}`);
|
||||
});
|
||||
|
||||
test('gsd-check-update spawn retains windowsHide (precedent guard)', () => {
|
||||
assert.match(read('hooks/gsd-check-update.js'), /windowsHide:\s*true/,
|
||||
'gsd-check-update.js must keep windowsHide: true');
|
||||
});
|
||||
|
||||
// Durable invariant: ANY external-binary process spawn in the runtime source
|
||||
// (hooks + src) must set windowsHide — catches future additions, not just the
|
||||
// sites known today. Handles the `{ ...CONST }` spread indirection.
|
||||
test('completeness: no external-binary spawn in runtime source omits windowsHide', () => {
|
||||
const listDir = (dir, re) =>
|
||||
fs.readdirSync(path.join(root, dir)).filter((f) => re.test(f)).map((f) => `${dir}/${f}`);
|
||||
const files = [...listDir('hooks', /\.js$/), ...listDir('src', /\.cts$/)];
|
||||
const callRe = /(?:execSync|execFileSync|spawnSync|spawn)\s*\(\s*(?:`|'|")?(?:git|npm|gh)\b|spawn\s*\(\s*process\.execPath/g;
|
||||
const offenders = [];
|
||||
for (const rel of files) {
|
||||
const src = read(rel);
|
||||
let m;
|
||||
while ((m = callRe.exec(src)) !== null) {
|
||||
const win = src.slice(m.index, m.index + 400);
|
||||
let ok = /windowsHide:\s*true/.test(win);
|
||||
if (!ok) {
|
||||
const spread = win.match(/\{\s*\.\.\.(\w+)/); // e.g. { ...SPAWNOPT, cwd }
|
||||
if (spread) {
|
||||
ok = new RegExp(`(?:const|let|var)\\s+${spread[1]}\\s*=\\s*\\{[^}]*windowsHide:\\s*true`).test(src);
|
||||
}
|
||||
}
|
||||
if (!ok) offenders.push(`${rel}: ...${src.slice(m.index, m.index + 48).replace(/\s+/g, ' ')}`);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(offenders, [], `external-binary spawns missing windowsHide:\n${offenders.join('\n')}`);
|
||||
});
|
||||
});
|
||||
45
tests/bug-687-agy-timeout.test.cjs
Normal file
45
tests/bug-687-agy-timeout.test.cjs
Normal file
@@ -0,0 +1,45 @@
|
||||
// allow-test-rule: source-text-is-the-product
|
||||
// review.md is a workflow file whose deployed text IS the runtime contract; the
|
||||
// agy -p invocation cannot be run in CI, so we assert on its content (issue #687).
|
||||
'use strict';
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const reviewPath = path.resolve(__dirname, '..', 'gsd-core', 'workflows', 'review.md');
|
||||
const read = () => fs.readFileSync(reviewPath, 'utf-8');
|
||||
|
||||
describe('bug #687: agy print mode must be bounded via its native --print-timeout', () => {
|
||||
test('invokes agy with its own --print-timeout flag (not an external killer)', () => {
|
||||
assert.match(read(), /agy --print-timeout \d+s? -p "\$\(cat/,
|
||||
'review.md must cap agy through `agy --print-timeout <N> -p …` (the tool\'s own mechanism)');
|
||||
});
|
||||
|
||||
test('discards partial output on non-zero exit so the fallback fires', () => {
|
||||
const c = read();
|
||||
assert.match(c, /_AGY_RC.*-ne 0/, 'review.md must check the agy exit code');
|
||||
assert.match(c, /: > \/tmp\/gsd-review-antigravity-/,
|
||||
'review.md must truncate the output file when agy timed out / failed');
|
||||
});
|
||||
|
||||
test('agy is bounded only by its own --print-timeout, not an external process killer', () => {
|
||||
const c = read();
|
||||
// Print-mode reviewers invoke the tool directly; agy must self-terminate via
|
||||
// --print-timeout, never via an external SIGKILL/timeout binary wrapped around it.
|
||||
assert.doesNotMatch(c, /-s KILL/, 'must not SIGKILL agy from the outside');
|
||||
// Any external timeout binary wrapping agy — `timeout 300s agy …`,
|
||||
// `gtimeout 300 agy …`, `timeout -s KILL 300 agy …`. The lookbehind keeps
|
||||
// agy's own `--print-timeout` flag from tripping it.
|
||||
assert.doesNotMatch(c, /(?<!print-)\bg?timeout[ \t]+[^\n]*\bagy\b/,
|
||||
'must not wrap agy in an external timeout binary — use its --print-timeout flag');
|
||||
assert.doesNotMatch(c, /kill -9 "\$_AGY/, 'must not use a kill -9 watchdog on agy');
|
||||
});
|
||||
|
||||
test('no unguarded bare "agy -p" invocation remains at line start', () => {
|
||||
// A bare `agy -p "$(cat …)"` with no cap was the original hang.
|
||||
assert.doesNotMatch(read(), /^agy -p "\$\(cat/m,
|
||||
'review.md must not invoke agy -p without --print-timeout');
|
||||
});
|
||||
});
|
||||
418
tests/bug-704-codex-launcher-path-corruption.test.cjs
Normal file
418
tests/bug-704-codex-launcher-path-corruption.test.cjs
Normal file
@@ -0,0 +1,418 @@
|
||||
// allow-test-rule: source-text-is-the-product
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Regression test for issue #704:
|
||||
* "v1.3.1 global install ships literal $gsd-core launcher paths in workflows"
|
||||
*
|
||||
* ROOT CAUSE: `convertSlashCommandsToCodexSkillMentions` had a regex
|
||||
* /(?<![a-zA-Z0-9./])\/gsd-([a-z0-9-]+)/
|
||||
* The lookbehind did NOT include `}`, so shell variable expressions like
|
||||
* `${_GSD_RUNTIME_ROOT}/gsd-core/bin/...`
|
||||
* had their `/gsd-core` matched (the char before `/` was `}`, not in the
|
||||
* exclusion set), converting it to `$gsd-core` and breaking all Codex
|
||||
* workflow launcher paths.
|
||||
*
|
||||
* FIX: Add `}` to the lookbehind set so `${VAR}/gsd-core/` is excluded.
|
||||
*/
|
||||
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const {
|
||||
convertClaudeCommandToCodexSkill,
|
||||
convertSlashCommandsToCodexSkillMentions,
|
||||
} = require('../bin/install.js');
|
||||
|
||||
// The canonical launcher snippet path that was being corrupted
|
||||
const RUNTIME_ROOT_PATH = '${_GSD_RUNTIME_ROOT}/gsd-core/bin/${_GSD_SHIM_NAME}';
|
||||
// The exact bad token reported in issue #704
|
||||
const BAD_TOKEN = '$gsd-core';
|
||||
|
||||
describe('#704 — Codex global install launcher path corruption', () => {
|
||||
test('convertClaudeCommandToCodexSkill does not corrupt ${VAR}/gsd-core/ or $(cmd)/gsd-* paths', () => {
|
||||
// Minimal fixture with the launcher snippet and command-substitution patterns
|
||||
// that were being corrupted (#704).
|
||||
const input = [
|
||||
'---',
|
||||
'description: Test skill',
|
||||
'---',
|
||||
'',
|
||||
'```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 "$HOME/.claude/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then',
|
||||
' GSD_TOOLS="$HOME/.claude/gsd-core/bin/${_GSD_SHIM_NAME}"',
|
||||
' gsd_run() { node "$GSD_TOOLS" "$@"; }',
|
||||
'fi',
|
||||
'# Command-substitution path form (reapply-patches pattern)',
|
||||
'candidate="$(expand_home "$KILO_CONFIG_DIR")/gsd-local-patches"',
|
||||
'```',
|
||||
].join('\n');
|
||||
|
||||
const output = convertClaudeCommandToCodexSkill(input, 'gsd-test-704');
|
||||
|
||||
// Shell-context corruption patterns from issue #704:
|
||||
// - `}$gsd-*` from shell variable expressions `${VAR}/gsd-*`
|
||||
// - `)$gsd-*` from command-substitution paths `$(cmd)/gsd-*`
|
||||
const shellCorruptionPatterns = [
|
||||
{ pattern: '}' + BAD_TOKEN, description: 'shell-variable }$gsd-core' },
|
||||
{ pattern: ')$gsd-local', description: 'command-substitution )$gsd-local-patches' },
|
||||
];
|
||||
for (const { pattern, description } of shellCorruptionPatterns) {
|
||||
assert.ok(
|
||||
!output.includes(pattern),
|
||||
`Codex skill conversion must not produce "${pattern}" (${description}). ` +
|
||||
`Offending fragment: ${
|
||||
output.includes(pattern)
|
||||
? output.substring(output.indexOf(pattern) - 50, output.indexOf(pattern) + 80)
|
||||
: '(not found)'
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
// The correct path forms must be preserved — the canonical launcher path
|
||||
// (RUNTIME_ROOT_PATH) must survive Codex conversion intact.
|
||||
assert.ok(
|
||||
output.includes(RUNTIME_ROOT_PATH),
|
||||
`Expected canonical launcher path "${RUNTIME_ROOT_PATH}" to appear in the converted output. ` +
|
||||
`Got:\n${output.substring(0, 500)}`,
|
||||
);
|
||||
assert.ok(
|
||||
output.includes(')/gsd-local-patches'),
|
||||
`Expected ")/gsd-local-patches" to appear in the converted output. ` +
|
||||
`Got:\n${output.substring(0, 500)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('convertClaudeCommandToCodexSkill preserves all shell path forms (}, ) closers)', () => {
|
||||
// All these paths appear after a shell-closing character (} or )) and must
|
||||
// NOT be converted to $gsd-* by the Codex slash-command converter.
|
||||
const shellPaths = [
|
||||
// Shell variable expression forms (} closer)
|
||||
{ path: '"${_GSD_RUNTIME_ROOT}/gsd-core/bin/${_GSD_SHIM_NAME}"', corruptedForm: '}$gsd-core' },
|
||||
{ path: '"${_GSD_RUNTIME_ROOT}/.claude/gsd-core/bin/${_GSD_SHIM_NAME}"', corruptedForm: '}$gsd-core' },
|
||||
{ path: '"$HOME/.claude/gsd-core/bin/${_GSD_SHIM_NAME}"', corruptedForm: '}$gsd-core' },
|
||||
// Command-substitution forms () closer) — reapply-patches pattern
|
||||
{ path: 'candidate="$(expand_home "$KILO_CONFIG_DIR")/gsd-local-patches"', corruptedForm: ')$gsd-local' },
|
||||
{ path: 'candidate="$(dirname "$(expand_home "$OPENCODE_CONFIG")")/gsd-local-patches"', corruptedForm: ')$gsd-local' },
|
||||
];
|
||||
|
||||
for (const { path: p, corruptedForm } of shellPaths) {
|
||||
const input = `---\ndescription: Test\n---\n\n\`\`\`bash\n${p}\n\`\`\``;
|
||||
const output = convertClaudeCommandToCodexSkill(input, 'gsd-test-704-paths');
|
||||
assert.ok(
|
||||
!output.includes(corruptedForm),
|
||||
`Path "${p}" was corrupted to contain "${corruptedForm}" after Codex conversion.\n` +
|
||||
`Got:\n${output}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('convertClaudeCommandToCodexSkill still converts legitimate /gsd-<cmd> slash mentions', () => {
|
||||
// Slash-command mentions (not preceded by }) should still be converted
|
||||
const input = [
|
||||
'---',
|
||||
'description: Test',
|
||||
'---',
|
||||
'',
|
||||
'Use /gsd-discuss-phase to start a discussion.',
|
||||
'Or use /gsd-plan-phase for planning.',
|
||||
'Also: /gsd:capture --backlog adds items.',
|
||||
].join('\n');
|
||||
|
||||
const output = convertClaudeCommandToCodexSkill(input, 'gsd-test-704-cmds');
|
||||
|
||||
assert.ok(
|
||||
output.includes('$gsd-discuss-phase'),
|
||||
'Expected /gsd-discuss-phase to be converted to $gsd-discuss-phase',
|
||||
);
|
||||
assert.ok(
|
||||
output.includes('$gsd-plan-phase'),
|
||||
'Expected /gsd-plan-phase to be converted to $gsd-plan-phase',
|
||||
);
|
||||
assert.ok(
|
||||
output.includes('$gsd-capture'),
|
||||
'Expected /gsd:capture to be converted to $gsd-capture',
|
||||
);
|
||||
});
|
||||
|
||||
test('actual shipped workflow files: shell-variable launcher paths contain no $gsd-core', () => {
|
||||
// Walk gsd-core/workflows/ and assert that no file produces $gsd-core
|
||||
// inside a shell variable expansion context after Codex conversion.
|
||||
//
|
||||
// NOTE: The backtick-wrapped prose-path case (`/gsd-core/workflows/update.md`)
|
||||
// was a pre-existing gap with the #704 lookbehind fix and is now addressed by
|
||||
// the positive-boundary regex introduced in #712. That case is covered by the
|
||||
// "#712" describe block below.
|
||||
//
|
||||
// We probe for the specific shell-context pattern from the issue report:
|
||||
// BAD: ${_GSD_RUNTIME_ROOT}$gsd-core/bin/
|
||||
// GOOD: ${_GSD_RUNTIME_ROOT}/gsd-core/bin/
|
||||
const workflowsDir = path.join(__dirname, '..', 'gsd-core', 'workflows');
|
||||
if (!fs.existsSync(workflowsDir)) {
|
||||
// If the directory doesn't exist, skip gracefully (non-standard layout)
|
||||
return;
|
||||
}
|
||||
|
||||
const files = fs.readdirSync(workflowsDir)
|
||||
.filter((f) => f.endsWith('.md'))
|
||||
.map((f) => path.join(workflowsDir, f));
|
||||
|
||||
assert.ok(files.length > 0, 'Expected at least one workflow .md file');
|
||||
|
||||
// Shell-context corruption patterns from issue #704:
|
||||
// - `}$gsd-*`: closing brace from `${VAR}/gsd-*` shell variable expressions
|
||||
// - `)$gsd-*`: closing paren from `$(cmd)/gsd-*` command substitutions
|
||||
const SHELL_CORRUPTION_RE = /[})](\$gsd-[a-z])/;
|
||||
|
||||
const offending = [];
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf8');
|
||||
const skillName = `gsd-${path.basename(file, '.md')}`;
|
||||
const converted = convertClaudeCommandToCodexSkill(content, skillName);
|
||||
const match = converted.match(SHELL_CORRUPTION_RE);
|
||||
if (match) {
|
||||
const idx = converted.indexOf(match[0]);
|
||||
offending.push({
|
||||
file: path.relative(workflowsDir, file),
|
||||
context: converted.substring(Math.max(0, idx - 40), idx + 80),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
assert.deepStrictEqual(
|
||||
offending,
|
||||
[],
|
||||
`Found shell-context path corruption ([})]$gsd-*) in Codex-converted workflow files (#704):\n` +
|
||||
offending.map((o) => ` ${o.file}: ...${o.context}...`).join('\n'),
|
||||
);
|
||||
});
|
||||
|
||||
test('commands/gsd/*.md: shell-variable launcher paths contain no $gsd-core', () => {
|
||||
// Walk commands/gsd/ and assert that no command file produces the shell-context
|
||||
// }$gsd-core corruption — since commands also go through
|
||||
// convertClaudeCommandToCodexSkill when installed globally for Codex.
|
||||
const commandsDir = path.join(__dirname, '..', 'commands', 'gsd');
|
||||
if (!fs.existsSync(commandsDir)) return;
|
||||
|
||||
const files = fs.readdirSync(commandsDir)
|
||||
.filter((f) => f.endsWith('.md'))
|
||||
.map((f) => path.join(commandsDir, f));
|
||||
|
||||
assert.ok(files.length > 0, 'Expected at least one command .md file');
|
||||
|
||||
const SHELL_CORRUPTION_RE = /[})](\$gsd-[a-z])/;
|
||||
|
||||
const offending = [];
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf8');
|
||||
const skillName = `gsd-${path.basename(file, '.md')}`;
|
||||
const converted = convertClaudeCommandToCodexSkill(content, skillName);
|
||||
const match = converted.match(SHELL_CORRUPTION_RE);
|
||||
if (match) {
|
||||
const idx = converted.indexOf(match[0]);
|
||||
offending.push({
|
||||
file: path.relative(commandsDir, file),
|
||||
context: converted.substring(Math.max(0, idx - 40), idx + 80),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
assert.deepStrictEqual(
|
||||
offending,
|
||||
[],
|
||||
`Found shell-context path corruption ([})]$gsd-*) in Codex-converted command files (#704):\n` +
|
||||
offending.map((o) => ` ${o.file}: ...${o.context}...`).join('\n'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#712: positive-boundary slash-command conversion', () => {
|
||||
// Tests call convertSlashCommandsToCodexSkillMentions directly so the regex
|
||||
// is exercised in isolation — no frontmatter wrapping, no ADAPTER_CLOSE
|
||||
// stripping, no .claude→.codex rewrite masking the result.
|
||||
|
||||
// ── MUST-NOT-CONVERT (negative) cases ─────────────────────────────────────
|
||||
// These inputs must be returned UNCHANGED — no $gsd-* substitution.
|
||||
|
||||
test('backtick-wrapped path: `/gsd-core/workflows/update.md` is NOT converted (THE new fix)', () => {
|
||||
const input = 'See `/gsd-core/workflows/update.md` for details.';
|
||||
const result = convertSlashCommandsToCodexSkillMentions(input);
|
||||
assert.strictEqual(
|
||||
result,
|
||||
input,
|
||||
`Expected backtick-wrapped path to be unchanged. Got: ${result}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('backtick-wrapped path deeper: `/gsd-pi/bin/foo.cjs` is NOT converted', () => {
|
||||
const input = 'Run `/gsd-pi/bin/foo.cjs` directly.';
|
||||
const result = convertSlashCommandsToCodexSkillMentions(input);
|
||||
assert.strictEqual(
|
||||
result,
|
||||
input,
|
||||
`Expected deep backtick-wrapped path to be unchanged. Got: ${result}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('shell var expansion: ${_GSD_RUNTIME_ROOT}/gsd-core/bin/x is NOT converted (regression guard)', () => {
|
||||
const input = 'PATH="${_GSD_RUNTIME_ROOT}/gsd-core/bin/x"';
|
||||
const result = convertSlashCommandsToCodexSkillMentions(input);
|
||||
assert.ok(
|
||||
!result.includes('$gsd-core'),
|
||||
`Expected no $gsd-core substitution in shell var path. Got: ${result}`,
|
||||
);
|
||||
assert.ok(
|
||||
result.includes('/gsd-core/bin/x'),
|
||||
`Expected original path to be preserved. Got: ${result}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('command substitution: $(expand_home ~/.claude)/gsd-local-patches is NOT converted (regression guard)', () => {
|
||||
const input = 'candidate="$(expand_home ~/.claude)/gsd-local-patches"';
|
||||
const result = convertSlashCommandsToCodexSkillMentions(input);
|
||||
assert.ok(
|
||||
!result.includes(')$gsd-local'),
|
||||
`Expected no )$gsd-local substitution. Got: ${result}`,
|
||||
);
|
||||
assert.ok(
|
||||
result.includes(')/gsd-local-patches'),
|
||||
`Expected original path to be preserved. Got: ${result}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('plain path segment: bin/gsd-tools.cjs is NOT converted', () => {
|
||||
const input = 'node bin/gsd-tools.cjs --help';
|
||||
const result = convertSlashCommandsToCodexSkillMentions(input);
|
||||
assert.strictEqual(
|
||||
result,
|
||||
input,
|
||||
`Expected plain path segment to be unchanged. Got: ${result}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('plain path segment: .claude/gsd-core/agents — /gsd-core portion is NOT slash-command converted', () => {
|
||||
// Tests the regex in isolation: the .claude→.codex path rewrite that happens
|
||||
// inside convertClaudeToCodexMarkdown does NOT run here. We assert directly
|
||||
// that the slash-command regex leaves /gsd-core after the slash intact —
|
||||
// i.e. the `e` in `/gsd-core` is NOT treated as a command boundary.
|
||||
const input = 'Look in .claude/gsd-core/agents for the agent files.';
|
||||
const result = convertSlashCommandsToCodexSkillMentions(input);
|
||||
assert.ok(
|
||||
!result.includes('$gsd-core'),
|
||||
`Expected no $gsd-core substitution in .claude/gsd-core path. Got: ${result}`,
|
||||
);
|
||||
assert.ok(
|
||||
result.includes('/gsd-core/agents'),
|
||||
`Expected /gsd-core/agents to remain as a path segment. Got: ${result}`,
|
||||
);
|
||||
});
|
||||
|
||||
// ── MUST-CONVERT (positive) cases ─────────────────────────────────────────
|
||||
// These inputs contain legitimate /gsd-<cmd> mentions that MUST be converted.
|
||||
|
||||
test('space-preceded prose: Use /gsd-discuss-phase to start. → $gsd-discuss-phase', () => {
|
||||
const input = 'Use /gsd-discuss-phase to start.';
|
||||
const result = convertSlashCommandsToCodexSkillMentions(input);
|
||||
assert.ok(
|
||||
result.includes('$gsd-discuss-phase'),
|
||||
`Expected /gsd-discuss-phase to be converted. Got: ${result}`,
|
||||
);
|
||||
assert.ok(
|
||||
!result.includes('/gsd-discuss-phase'),
|
||||
`Expected original /gsd-discuss-phase to be replaced. Got: ${result}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('backtick-WRAPPED MENTION (single segment): Run `/gsd-execute-phase` now → `$gsd-execute-phase`', () => {
|
||||
// A backtick-wrapped COMMAND (single segment, no path continuation) MUST
|
||||
// still be converted — this guards against a naive whitespace-only fix.
|
||||
const input = 'Run `/gsd-execute-phase` now.';
|
||||
const result = convertSlashCommandsToCodexSkillMentions(input);
|
||||
assert.ok(
|
||||
result.includes('`$gsd-execute-phase`'),
|
||||
`Expected backtick-wrapped command to be converted to \`$gsd-execute-phase\`. Got: ${result}`,
|
||||
);
|
||||
assert.ok(
|
||||
!result.includes('`/gsd-execute-phase`'),
|
||||
`Expected original \`/gsd-execute-phase\` to be replaced. Got: ${result}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('parenthetical/backtick list like CONTEXT.md:59: (`/gsd-plan-phase`, `/gsd-progress`) → converted', () => {
|
||||
const input = 'Available commands: (`/gsd-plan-phase`, `/gsd-progress`) — pick one.';
|
||||
const result = convertSlashCommandsToCodexSkillMentions(input);
|
||||
assert.ok(
|
||||
result.includes('`$gsd-plan-phase`'),
|
||||
`Expected /gsd-plan-phase to be converted. Got: ${result}`,
|
||||
);
|
||||
assert.ok(
|
||||
result.includes('`$gsd-progress`'),
|
||||
`Expected /gsd-progress to be converted. Got: ${result}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('start-of-string: /gsd-manager runs → $gsd-manager runs (exercises the ^ branch of lookbehind)', () => {
|
||||
// This case is IMPOSSIBLE to test through the frontmatter-wrapping pipeline
|
||||
// (the body always has preceding chars). Direct call exercises the ^ branch.
|
||||
const input = '/gsd-manager runs the pipeline.';
|
||||
const result = convertSlashCommandsToCodexSkillMentions(input);
|
||||
assert.ok(
|
||||
result.includes('$gsd-manager'),
|
||||
`Expected /gsd-manager to be converted. Got: ${result}`,
|
||||
);
|
||||
assert.ok(
|
||||
!result.includes('/gsd-manager'),
|
||||
`Expected original /gsd-manager to be replaced. Got: ${result}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('double-quote wrapped: "/gsd-resume" → "$gsd-resume"', () => {
|
||||
const input = 'Call "/gsd-resume" to continue.';
|
||||
const result = convertSlashCommandsToCodexSkillMentions(input);
|
||||
assert.ok(
|
||||
result.includes('"$gsd-resume"'),
|
||||
`Expected "/gsd-resume" to be converted to "$gsd-resume". Got: ${result}`,
|
||||
);
|
||||
assert.ok(
|
||||
!result.includes('"/gsd-resume"'),
|
||||
`Expected original "/gsd-resume" to be replaced. Got: ${result}`,
|
||||
);
|
||||
});
|
||||
|
||||
// ── End-to-end: headline #712 bug through the real install pipeline ────────
|
||||
|
||||
test('end-to-end: backtick-wrapped path `/gsd-core/workflows/update.md` survives full Codex install pipeline', () => {
|
||||
// Uses convertClaudeCommandToCodexSkill (same pattern as #704 tests above)
|
||||
// to prove the real install path does not corrupt prose references to repo paths.
|
||||
const input = [
|
||||
'---',
|
||||
'description: Test',
|
||||
'---',
|
||||
'',
|
||||
'See `/gsd-core/workflows/update.md` for the update workflow.',
|
||||
].join('\n');
|
||||
|
||||
const output = convertClaudeCommandToCodexSkill(input, 'gsd-test-712-e2e');
|
||||
|
||||
assert.ok(
|
||||
!output.includes('$gsd-core'),
|
||||
`Expected no $gsd-core in converted output. Got:\n${output}`,
|
||||
);
|
||||
assert.ok(
|
||||
output.includes('/gsd-core/workflows/update.md'),
|
||||
`Expected backtick-wrapped path to survive conversion. Got:\n${output}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
275
tests/bug-730-milestone-phase-details-scope.test.cjs
Normal file
275
tests/bug-730-milestone-phase-details-scope.test.cjs
Normal file
@@ -0,0 +1,275 @@
|
||||
/**
|
||||
* Regression test for bug #730: phase details defined under a milestone-scoped
|
||||
* "## Milestone vX.Y — … (Phase Details)" section are invisible to phase
|
||||
* resolution (getRoadmapPhaseInternal / init phase-op) when the flat shared
|
||||
* "## Phase Details" section for an earlier milestone sits between the shared
|
||||
* ## Phases checklist and the per-milestone Phase Details section.
|
||||
*
|
||||
* The bug manifests ONLY before any .planning/phases/ directory exists because
|
||||
* findPhaseInternal masks it once the dir is created. RED step — tests 1 and 3
|
||||
* are expected to fail against current code.
|
||||
*/
|
||||
|
||||
const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const { runGsdTools, cleanup } = require('./helpers.cjs');
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared fixture content
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const STATE_CONTENT = `---
|
||||
milestone: v1.1
|
||||
---
|
||||
`;
|
||||
|
||||
const ROADMAP_CONTENT = `# Roadmap: Example
|
||||
|
||||
## Phases
|
||||
|
||||
- [x] **Phase 1: Setup** — initial scaffold
|
||||
|
||||
### Milestone v1.1 — Second milestone (added 2026-01-01)
|
||||
|
||||
- [ ] **Phase 2: Feature** — the new thing
|
||||
|
||||
## Phase Details
|
||||
|
||||
### Phase 1: Setup
|
||||
**Goal:** scaffold the app.
|
||||
|
||||
## Milestone v1.1 — Second milestone (Phase Details)
|
||||
|
||||
### Phase 2: Feature
|
||||
**Goal:** build the new thing.
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helper: create a bare project with .planning/ but NO .planning/phases/ dir
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function createBareProject() {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-test-730-'));
|
||||
fs.mkdirSync(path.join(tmpDir, '.planning'), { recursive: true });
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Suite
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('bug #730 — milestone (Phase Details) section scope resolution', () => {
|
||||
let dir;
|
||||
|
||||
beforeEach(() => {
|
||||
dir = createBareProject();
|
||||
fs.writeFileSync(path.join(dir, '.planning', 'STATE.md'), STATE_CONTENT, 'utf-8');
|
||||
fs.writeFileSync(path.join(dir, '.planning', 'ROADMAP.md'), ROADMAP_CONTENT, 'utf-8');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(dir);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Test 1 (AC1): init phase-op resolves phase defined only under its
|
||||
// per-milestone "(Phase Details)" section
|
||||
// -------------------------------------------------------------------------
|
||||
test('init phase-op resolves a current-milestone phase defined only under its (Phase Details) section', () => {
|
||||
const r = runGsdTools('init phase-op 2', dir);
|
||||
assert.ok(r.success, `init phase-op 2 failed: ${r.error}`);
|
||||
|
||||
const out = JSON.parse(r.output);
|
||||
assert.strictEqual(out.phase_found, true, `phase_found should be true; got phase_found=${out.phase_found}, expected_phase_dir=${out.expected_phase_dir}`);
|
||||
assert.strictEqual(out.phase_name, 'Feature', `phase_name should be 'Feature'; got '${out.phase_name}'`);
|
||||
assert.strictEqual(out.padded_phase, '02', `padded_phase should be '02'; got '${out.padded_phase}'`);
|
||||
assert.strictEqual(out.expected_phase_dir, '.planning/phases/02-feature', `expected_phase_dir should be '.planning/phases/02-feature'; got '${out.expected_phase_dir}'`);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Test 2 (AC4): first-milestone phase still resolves via the flat
|
||||
// "## Phase Details" section — no regression
|
||||
// -------------------------------------------------------------------------
|
||||
test('init phase-op still resolves a first-milestone phase (no regression on flat Phase Details)', () => {
|
||||
const r = runGsdTools('init phase-op 1', dir);
|
||||
assert.ok(r.success, `init phase-op 1 failed: ${r.error}`);
|
||||
|
||||
const out = JSON.parse(r.output);
|
||||
assert.strictEqual(out.phase_found, true, `phase_found should be true for phase 1; got ${out.phase_found}`);
|
||||
assert.strictEqual(out.phase_name, 'Setup', `phase_name should be 'Setup'; got '${out.phase_name}'`);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Test 3 (AC5): getRoadmapPhaseInternal resolves the current-milestone phase
|
||||
// directly before any phases/ dir exists
|
||||
// -------------------------------------------------------------------------
|
||||
test('getRoadmapPhaseInternal resolves the current-milestone phase directly before any dir exists', () => {
|
||||
const core = require('../gsd-core/bin/lib/core.cjs');
|
||||
|
||||
const res = core.getRoadmapPhaseInternal(dir, '2');
|
||||
assert.ok(res !== null && res !== undefined, `getRoadmapPhaseInternal returned null/undefined for phase 2`);
|
||||
assert.strictEqual(res.found, true, `res.found should be true; got ${JSON.stringify(res)}`);
|
||||
assert.strictEqual(res.phase_name, 'Feature', `res.phase_name should be 'Feature'; got '${res.phase_name}'`);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Test 4 (AC3): validate health raises W006 for a current-milestone phase
|
||||
// defined under (Phase Details) with no directory on disk.
|
||||
//
|
||||
// Before the fix, extractCurrentMilestone's slice stopped before the
|
||||
// "## Milestone v1.1 — … (Phase Details)" section, so phase 2's
|
||||
// "### Phase 2: Feature" header was invisible and W006 was never raised.
|
||||
// After the fix the slice includes that section and W006 is emitted.
|
||||
//
|
||||
// This test uses its OWN local fixture (separate tmpdir) so it does not
|
||||
// disturb the shared beforeEach/afterEach fixture used by tests 1–3.
|
||||
// -------------------------------------------------------------------------
|
||||
test('validate health raises W006 for a started current-milestone phase defined under (Phase Details) with no directory', () => {
|
||||
const localDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-test-730-t4-'));
|
||||
try {
|
||||
const planning = path.join(localDir, '.planning');
|
||||
fs.mkdirSync(planning, { recursive: true });
|
||||
|
||||
// STATE.md — milestone: v1.1
|
||||
fs.writeFileSync(
|
||||
path.join(planning, 'STATE.md'),
|
||||
`---\nmilestone: v1.1\n---\n`,
|
||||
'utf-8',
|
||||
);
|
||||
|
||||
// ROADMAP.md — phase 2 is [x] (started/complete) so the not-started
|
||||
// guard does NOT suppress W006. Phase 2's details live exclusively in
|
||||
// the per-milestone "(Phase Details)" section (the blind-spot pre-fix).
|
||||
fs.writeFileSync(
|
||||
path.join(planning, 'ROADMAP.md'),
|
||||
`# Roadmap: Example\n\n## Phases\n\n- [x] **Phase 1: Setup** — initial scaffold\n\n### Milestone v1.1 — Second milestone (added 2026-01-01)\n\n- [x] **Phase 2: Feature** — the new thing\n\n## Phase Details\n\n### Phase 1: Setup\n**Goal:** scaffold the app.\n\n## Milestone v1.1 — Second milestone (Phase Details)\n\n### Phase 2: Feature\n**Goal:** build the new thing.\n`,
|
||||
'utf-8',
|
||||
);
|
||||
|
||||
// Create the phase 1 directory so phase 1 does NOT trigger W006.
|
||||
// Phase 2 has NO directory — that's the missing-dir condition under test.
|
||||
fs.mkdirSync(path.join(planning, 'phases', '01-setup'), { recursive: true });
|
||||
|
||||
const result = runGsdTools(['validate', 'health'], localDir);
|
||||
const payload = JSON.parse(result.output);
|
||||
const warnings = payload.warnings || [];
|
||||
|
||||
// Find a W006 entry whose message references phase 2 (by number or name).
|
||||
const w006ForPhase2 = warnings.find(
|
||||
(w) =>
|
||||
w.code === 'W006' &&
|
||||
(/\b2\b/.test(w.message) || /\b02\b/.test(w.message) || /Feature/i.test(w.message)),
|
||||
);
|
||||
|
||||
assert.ok(
|
||||
w006ForPhase2 != null,
|
||||
`Expected a W006 warning referencing phase 2 (Feature) — phase 2 is started ([x]) and has no directory on disk, ` +
|
||||
`but its ### Phase 2: header lives in the Milestone v1.1 (Phase Details) section which was invisible before the fix. ` +
|
||||
`Got warnings: ${JSON.stringify(warnings)}`,
|
||||
);
|
||||
} finally {
|
||||
cleanup(localDir);
|
||||
}
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Test 5: three-milestone roadmap, current = latest (v1.2)
|
||||
// -------------------------------------------------------------------------
|
||||
test('init phase-op resolves the latest milestone phase in a 3-milestone roadmap', () => {
|
||||
const localDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-test-730-t5-'));
|
||||
try {
|
||||
const planning = path.join(localDir, '.planning');
|
||||
fs.mkdirSync(planning, { recursive: true });
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(planning, 'STATE.md'),
|
||||
`---\nmilestone: v1.2\n---\n`,
|
||||
'utf-8',
|
||||
);
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(planning, 'ROADMAP.md'),
|
||||
`# Roadmap: Example\n\n## Phases\n\n- [x] **Phase 1: Setup** — done\n\n### Milestone v1.1 — Second (added 2026-01-01)\n\n- [x] **Phase 2: Feature** — done\n\n### Milestone v1.2 — Third (added 2026-02-01)\n\n- [ ] **Phase 3: Polish** — current\n\n## Phase Details\n\n### Phase 1: Setup\n**Goal:** scaffold.\n\n## Milestone v1.1 — Second (Phase Details)\n\n### Phase 2: Feature\n**Goal:** build.\n\n## Milestone v1.2 — Third (Phase Details)\n\n### Phase 3: Polish\n**Goal:** refine.\n`,
|
||||
'utf-8',
|
||||
);
|
||||
|
||||
const r = runGsdTools('init phase-op 3', localDir);
|
||||
assert.ok(r.success, `init phase-op 3 failed: ${r.error}`);
|
||||
|
||||
const out = JSON.parse(r.output);
|
||||
assert.strictEqual(out.phase_found, true, `phase_found should be true; got phase_found=${out.phase_found}`);
|
||||
assert.strictEqual(out.phase_name, 'Polish', `phase_name should be 'Polish'; got '${out.phase_name}'`);
|
||||
assert.strictEqual(out.padded_phase, '03', `padded_phase should be '03'; got '${out.padded_phase}'`);
|
||||
assert.strictEqual(out.expected_phase_dir, '.planning/phases/03-polish', `expected_phase_dir should be '.planning/phases/03-polish'; got '${out.expected_phase_dir}'`);
|
||||
} finally {
|
||||
cleanup(localDir);
|
||||
}
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Test 6: sub-milestone sharing a version prefix — closed sibling must NOT
|
||||
// cross-pollinate into the active milestone's Phase Details lookup (#730)
|
||||
// -------------------------------------------------------------------------
|
||||
test('init phase-op anchors Phase Details to the selected sub-milestone, not a closed same-prefix sibling', () => {
|
||||
const localDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-test-730-t6-'));
|
||||
try {
|
||||
const planning = path.join(localDir, '.planning');
|
||||
fs.mkdirSync(planning, { recursive: true });
|
||||
|
||||
// STATE.md — milestone: v3.0 (matches v3.0-B active slice)
|
||||
fs.writeFileSync(
|
||||
path.join(planning, 'STATE.md'),
|
||||
`---\nmilestone: v3.0\n---\n`,
|
||||
'utf-8',
|
||||
);
|
||||
|
||||
// ROADMAP.md — v3.0-A is SHIPPED (closed), v3.0-B is active.
|
||||
// The Phase Details for v3.0-A comes FIRST — without version-boundary
|
||||
// anchoring the old code would grab it (first non-closed (Phase Details)
|
||||
// heading outside the window), returning phase_name='Alpha' instead of 'Beta'.
|
||||
fs.writeFileSync(
|
||||
path.join(planning, 'ROADMAP.md'),
|
||||
[
|
||||
'# Roadmap: Example',
|
||||
'',
|
||||
'## Phases',
|
||||
'',
|
||||
'### Milestone v3.0-A — First slice (added 2026-01-01) ✅ SHIPPED',
|
||||
'',
|
||||
'- [x] **Phase 1: Alpha** — done',
|
||||
'',
|
||||
'### Milestone v3.0-B — Second slice (added 2026-02-01)',
|
||||
'',
|
||||
'- [ ] **Phase 2: Beta** — current',
|
||||
'',
|
||||
'## Phase Details',
|
||||
'',
|
||||
'## Milestone v3.0-A — First slice (Phase Details)',
|
||||
'',
|
||||
'### Phase 1: Alpha',
|
||||
'**Goal:** alpha goal.',
|
||||
'',
|
||||
'## Milestone v3.0-B — Second slice (Phase Details)',
|
||||
'',
|
||||
'### Phase 2: Beta',
|
||||
'**Goal:** beta goal.',
|
||||
'',
|
||||
].join('\n'),
|
||||
'utf-8',
|
||||
);
|
||||
|
||||
const r = runGsdTools('init phase-op 2', localDir);
|
||||
assert.ok(r.success, `init phase-op 2 failed: ${r.error}`);
|
||||
|
||||
const out = JSON.parse(r.output);
|
||||
assert.strictEqual(out.phase_found, true, `phase_found should be true; got phase_found=${out.phase_found}, output=${JSON.stringify(out)}`);
|
||||
assert.strictEqual(out.phase_name, 'Beta', `phase_name should be 'Beta' (v3.0-B section), not '${out.phase_name}' (would indicate v3.0-A cross-pollination)`);
|
||||
assert.strictEqual(out.expected_phase_dir, '.planning/phases/02-beta', `expected_phase_dir should be '.planning/phases/02-beta'; got '${out.expected_phase_dir}'`);
|
||||
} finally {
|
||||
cleanup(localDir);
|
||||
}
|
||||
});
|
||||
});
|
||||
647
tests/bug-782-cline-skills-emission.test.cjs
Normal file
647
tests/bug-782-cline-skills-emission.test.cjs
Normal file
@@ -0,0 +1,647 @@
|
||||
'use strict';
|
||||
/**
|
||||
* Regression tests for bug #782 — Cline skills emission.
|
||||
*
|
||||
* gsd now emits skills to ~/.cline/skills/<name>/SKILL.md for Cline >= v3.48.
|
||||
* Skills discovery: https://docs.cline.bot/customization/skills
|
||||
*
|
||||
* (a) Converter unit test: convertClaudeCommandToClineSkill
|
||||
* (b) Integration test: installRuntimeArtifacts for cline writes SKILL.md files
|
||||
* (c) .clinerules/gsd.md still written by the install path (#787 dir form)
|
||||
* (d) Idempotency: running install twice leaves skills + .clinerules/ intact
|
||||
* (e) Full install() global: both skills AND .clinerules/gsd.md are written
|
||||
*/
|
||||
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { createTempDir, cleanup, captureConsole } = require('./helpers.cjs');
|
||||
|
||||
const {
|
||||
convertClaudeCommandToClineSkill,
|
||||
convertClaudeToCliineMarkdown,
|
||||
installRuntimeArtifacts,
|
||||
install,
|
||||
_applyRuntimeRewrites,
|
||||
} = require('../bin/install.js');
|
||||
|
||||
const {
|
||||
resolveRuntimeArtifactLayout,
|
||||
} = require('../gsd-core/bin/lib/runtime-artifact-layout.cjs');
|
||||
|
||||
const {
|
||||
loadSkillsManifest,
|
||||
resolveProfile,
|
||||
} = require('../gsd-core/bin/lib/install-profiles.cjs');
|
||||
|
||||
const REAL_COMMANDS_DIR = path.join(__dirname, '..', 'commands', 'gsd');
|
||||
const MANIFEST = loadSkillsManifest(REAL_COMMANDS_DIR);
|
||||
const RESOLVED_CORE = resolveProfile({ modes: ['core'], manifest: MANIFEST });
|
||||
|
||||
// ─── (a) Converter unit test ─────────────────────────────────────────────────
|
||||
|
||||
const SAMPLE_COMMAND = `---
|
||||
name: gsd:execute-phase
|
||||
description: Execute all tasks in the current phase using Cline tools.
|
||||
allowed-tools:
|
||||
- Read
|
||||
- Write
|
||||
- Bash
|
||||
---
|
||||
|
||||
## Objective
|
||||
|
||||
Run all tasks in the current phase.
|
||||
|
||||
See ~/.claude/skills/gsd-help/SKILL.md for reference.
|
||||
Use \`/gsd-help\` or Claude Code for details.
|
||||
`;
|
||||
|
||||
// A command that exercises all three Claude-specific frontmatter fields that
|
||||
// must NOT leak into the emitted Cline SKILL.md.
|
||||
const RICH_COMMAND = `---
|
||||
name: gsd:validate-phase
|
||||
description: Retroactively audit and fill Nyquist validation gaps for a completed phase
|
||||
argument-hint: "[phase number]"
|
||||
agent: researcher
|
||||
allowed-tools:
|
||||
- Read
|
||||
- Write
|
||||
- Edit
|
||||
- Bash
|
||||
- Glob
|
||||
- Grep
|
||||
- Agent
|
||||
- AskUserQuestion
|
||||
---
|
||||
|
||||
## Objective
|
||||
|
||||
Audit Nyquist validation coverage. See ~/.claude/skills/gsd-help/SKILL.md for reference.
|
||||
Use Claude Code for details.
|
||||
`;
|
||||
|
||||
/**
|
||||
* Extract frontmatter block (between --- delimiters) from output.
|
||||
* Returns the raw text between the first --- and the closing ---.
|
||||
* Uses \r?\n to handle both LF and CRLF line endings (Windows parity).
|
||||
*/
|
||||
function parseFrontmatter(text) {
|
||||
const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
|
||||
describe('convertClaudeCommandToClineSkill — unit', () => {
|
||||
test('emits frontmatter with name: gsd-<stem>', () => {
|
||||
const result = convertClaudeCommandToClineSkill(SAMPLE_COMMAND, 'gsd-execute-phase');
|
||||
const nameMatch = result.match(/^name:\s*(.+)$/m);
|
||||
assert.ok(nameMatch, 'frontmatter must contain name field');
|
||||
assert.ok(nameMatch[1].includes('gsd-execute-phase'), 'name must start with gsd-execute-phase');
|
||||
});
|
||||
|
||||
test('emits non-empty description in frontmatter', () => {
|
||||
const result = convertClaudeCommandToClineSkill(SAMPLE_COMMAND, 'gsd-execute-phase');
|
||||
const descMatch = result.match(/^description:\s*(.+)$/m);
|
||||
assert.ok(descMatch, 'frontmatter must contain description field');
|
||||
assert.ok(descMatch[1].trim().length > 0, 'description must not be empty');
|
||||
});
|
||||
|
||||
test('body uses .cline/ paths not .claude/', () => {
|
||||
const result = convertClaudeCommandToClineSkill(SAMPLE_COMMAND, 'gsd-execute-phase');
|
||||
// The body reference to ~/.claude/ should be rewritten to ~/.cline/
|
||||
assert.ok(!result.includes('~/.claude/skills'), 'body must not contain ~/.claude/skills');
|
||||
assert.ok(result.includes('.cline/skills'), 'body must contain .cline/skills');
|
||||
});
|
||||
|
||||
test('body replaces "Claude Code" with "Cline"', () => {
|
||||
const result = convertClaudeCommandToClineSkill(SAMPLE_COMMAND, 'gsd-execute-phase');
|
||||
assert.ok(!result.includes('Claude Code'), 'Claude Code must be replaced with Cline');
|
||||
assert.ok(result.includes('Cline'), 'result must contain Cline branding');
|
||||
});
|
||||
|
||||
test('no stray .claude/ paths in frontmatter or body', () => {
|
||||
const result = convertClaudeCommandToClineSkill(SAMPLE_COMMAND, 'gsd-execute-phase');
|
||||
// Should not contain .claude/ anywhere (except inside CLAUDE.md→.clinerules rewrites
|
||||
// but those are already handled by convertClaudeToCliineMarkdown)
|
||||
assert.ok(!result.includes('/.claude/'), 'no /.claude/ paths in output');
|
||||
});
|
||||
|
||||
// ── Fix 1 (code-review): frontmatter must be ONLY name + description ──────
|
||||
|
||||
test('frontmatter emits ONLY name and description — no allowed-tools (SAMPLE_COMMAND)', () => {
|
||||
const result = convertClaudeCommandToClineSkill(SAMPLE_COMMAND, 'gsd-execute-phase');
|
||||
const fm = parseFrontmatter(result);
|
||||
assert.ok(fm !== null, 'result must have YAML frontmatter');
|
||||
assert.ok(!fm.includes('allowed-tools'), 'frontmatter must NOT contain allowed-tools');
|
||||
assert.ok(!fm.includes('argument-hint'), 'frontmatter must NOT contain argument-hint');
|
||||
assert.ok(!fm.includes('agent:'), 'frontmatter must NOT contain agent:');
|
||||
});
|
||||
|
||||
test('frontmatter emits ONLY name and description — no allowed-tools/argument-hint/agent (RICH_COMMAND)', () => {
|
||||
const result = convertClaudeCommandToClineSkill(RICH_COMMAND, 'gsd-validate-phase');
|
||||
const fm = parseFrontmatter(result);
|
||||
assert.ok(fm !== null, 'result must have YAML frontmatter');
|
||||
assert.ok(!fm.includes('allowed-tools'), 'frontmatter must NOT contain allowed-tools');
|
||||
assert.ok(!fm.includes('argument-hint'), 'frontmatter must NOT contain argument-hint');
|
||||
assert.ok(!fm.includes('agent:'), 'frontmatter must NOT contain agent:');
|
||||
});
|
||||
|
||||
test('name == gsd-validate-phase for RICH_COMMAND', () => {
|
||||
const result = convertClaudeCommandToClineSkill(RICH_COMMAND, 'gsd-validate-phase');
|
||||
const nameMatch = result.match(/^name:\s*(.+)$/m);
|
||||
assert.ok(nameMatch, 'must have name field');
|
||||
// yamlIdentifier may quote the value; strip surrounding quotes for comparison
|
||||
const nameVal = nameMatch[1].replace(/^['"]|['"]$/g, '').trim();
|
||||
assert.strictEqual(nameVal, 'gsd-validate-phase', `name must be gsd-validate-phase, got: ${nameVal}`);
|
||||
});
|
||||
|
||||
test('description is non-empty and <= 1024 chars for RICH_COMMAND', () => {
|
||||
const result = convertClaudeCommandToClineSkill(RICH_COMMAND, 'gsd-validate-phase');
|
||||
const descMatch = result.match(/^description:\s*(.+)$/m);
|
||||
assert.ok(descMatch, 'must have description field');
|
||||
const desc = descMatch[1].replace(/^['"]|['"]$/g, '').trim();
|
||||
assert.ok(desc.length > 0, 'description must be non-empty');
|
||||
assert.ok(desc.length <= 1024, `description must be <= 1024 chars, got ${desc.length}`);
|
||||
});
|
||||
|
||||
test('description truncated to <=1024 chars when source description is very long', () => {
|
||||
const longDesc = 'A'.repeat(2000);
|
||||
const longDescCommand = `---\nname: gsd:test\ndescription: ${longDesc}\n---\n\nBody text.\n`;
|
||||
const result = convertClaudeCommandToClineSkill(longDescCommand, 'gsd-test');
|
||||
const descMatch = result.match(/^description:\s*'?(.*?)'?$/m);
|
||||
assert.ok(descMatch, 'must have description field');
|
||||
// The raw description value (unquoted) should be <=1024 chars
|
||||
// The result string after the --- block will have the quoted form; check raw length
|
||||
// by checking the whole result doesn't have the full 2000-char string
|
||||
assert.ok(!result.includes('A'.repeat(1025)), 'description must be truncated to 1024 chars');
|
||||
});
|
||||
|
||||
test('returns content unchanged when source has no frontmatter', () => {
|
||||
const noFm = 'Just a body, no frontmatter here.\n';
|
||||
const result = convertClaudeCommandToClineSkill(noFm, 'gsd-test');
|
||||
assert.strictEqual(result, noFm, 'content without frontmatter must be returned unchanged');
|
||||
});
|
||||
|
||||
test('RICH_COMMAND body uses .cline/ paths and Cline branding', () => {
|
||||
const result = convertClaudeCommandToClineSkill(RICH_COMMAND, 'gsd-validate-phase');
|
||||
assert.ok(!result.includes('~/.claude/'), 'body must not contain ~/.claude/');
|
||||
assert.ok(result.includes('.cline/'), 'body must contain .cline/ paths');
|
||||
assert.ok(!result.includes('Claude Code'), 'body must not contain "Claude Code"');
|
||||
assert.ok(result.includes('Cline'), 'body must reference Cline');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── (b) + (c) + (d) Integration tests ────────────────────────────────────────
|
||||
|
||||
describe('installRuntimeArtifacts — cline skills emission', () => {
|
||||
test('cline global: writes gsd-prefixed skill dirs under skills/', (t) => {
|
||||
const configDir = createTempDir('gsd-cline-skills-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('cline', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
const layout = resolveRuntimeArtifactLayout('cline', configDir, 'global');
|
||||
const skillsKind = layout.kinds.find(k => k.kind === 'skills');
|
||||
assert.ok(skillsKind, 'cline must have a skills kind after #782');
|
||||
|
||||
const skillsDir = path.join(configDir, skillsKind.destSubpath);
|
||||
assert.ok(fs.existsSync(skillsDir), 'skills/ directory must be created');
|
||||
|
||||
const helpSkillDir = path.join(skillsDir, `${skillsKind.prefix}help`);
|
||||
assert.ok(
|
||||
fs.existsSync(path.join(helpSkillDir, 'SKILL.md')),
|
||||
`gsd-help/SKILL.md must exist under ${skillsKind.destSubpath}/`
|
||||
);
|
||||
});
|
||||
|
||||
test('cline global: SKILL.md has valid cline frontmatter (name + description)', (t) => {
|
||||
const configDir = createTempDir('gsd-cline-fm-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('cline', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
const skillsDir = path.join(configDir, 'skills');
|
||||
const helpSkill = path.join(skillsDir, 'gsd-help', 'SKILL.md');
|
||||
assert.ok(fs.existsSync(helpSkill), 'gsd-help/SKILL.md must exist');
|
||||
|
||||
const content = fs.readFileSync(helpSkill, 'utf8');
|
||||
// Must have YAML frontmatter
|
||||
assert.ok(content.startsWith('---'), 'SKILL.md must start with YAML frontmatter');
|
||||
assert.ok(content.includes('name:'), 'frontmatter must have name field');
|
||||
assert.ok(content.includes('description:'), 'frontmatter must have description field');
|
||||
// name must be gsd-help
|
||||
const nameMatch = content.match(/^name:\s*(.+)$/m);
|
||||
assert.ok(nameMatch, 'must have name field');
|
||||
assert.ok(nameMatch[1].includes('gsd-help'), `name must include gsd-help, got: ${nameMatch[1]}`);
|
||||
});
|
||||
|
||||
test('cline global: SKILL.md uses .cline/ paths not .claude/', (t) => {
|
||||
const configDir = createTempDir('gsd-cline-paths-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('cline', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
const skillsDir = path.join(configDir, 'skills');
|
||||
// Check all installed skill files for stray .claude/ references
|
||||
const skills = fs.readdirSync(skillsDir).filter(n => n.startsWith('gsd-'));
|
||||
assert.ok(skills.length > 0, 'at least one gsd- skill must be installed');
|
||||
|
||||
for (const skillName of skills) {
|
||||
const skillFile = path.join(skillsDir, skillName, 'SKILL.md');
|
||||
if (!fs.existsSync(skillFile)) continue;
|
||||
const content = fs.readFileSync(skillFile, 'utf8');
|
||||
assert.ok(
|
||||
!content.includes('~/.claude/'),
|
||||
`${skillName}/SKILL.md must not contain ~/.claude/ — found stray path`
|
||||
);
|
||||
assert.ok(
|
||||
!content.includes('/.claude/'),
|
||||
`${skillName}/SKILL.md must not contain /.claude/ — found stray path`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('cline global: skill count matches resolved profile', (t) => {
|
||||
const configDir = createTempDir('gsd-cline-count-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('cline', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
const skillsDir = path.join(configDir, 'skills');
|
||||
const count = fs.readdirSync(skillsDir)
|
||||
.filter(n => n.startsWith('gsd-') && fs.statSync(path.join(skillsDir, n)).isDirectory())
|
||||
.length;
|
||||
|
||||
if (RESOLVED_CORE.skills !== '*') {
|
||||
assert.strictEqual(count, RESOLVED_CORE.skills.size,
|
||||
`installed skill count (${count}) must match profile size (${RESOLVED_CORE.skills.size})`);
|
||||
} else {
|
||||
assert.ok(count > 0, 'must install at least 1 skill');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('installRuntimeArtifacts — cline idempotency', () => {
|
||||
test('cline: running install twice leaves skills intact (idempotency)', (t) => {
|
||||
const configDir = createTempDir('gsd-cline-idempotent-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
// First install
|
||||
installRuntimeArtifacts('cline', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
const skillsDir = path.join(configDir, 'skills');
|
||||
const countAfterFirst = fs.readdirSync(skillsDir)
|
||||
.filter(n => n.startsWith('gsd-') && fs.statSync(path.join(skillsDir, n)).isDirectory())
|
||||
.length;
|
||||
|
||||
// Second install (upgrade over existing)
|
||||
installRuntimeArtifacts('cline', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
const countAfterSecond = fs.readdirSync(skillsDir)
|
||||
.filter(n => n.startsWith('gsd-') && fs.statSync(path.join(skillsDir, n)).isDirectory())
|
||||
.length;
|
||||
|
||||
assert.strictEqual(countAfterFirst, countAfterSecond,
|
||||
`skill count must be stable across installs: first=${countAfterFirst} second=${countAfterSecond}`);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── (e) Full install() global — coexistence regression ───────────────────────
|
||||
//
|
||||
// Issue #782 explicitly requires that a global Cline install writes BOTH:
|
||||
// - skills/<gsd-*>/SKILL.md (skills for Cline >= v3.48)
|
||||
// - .clinerules/gsd.md (rules dir form introduced by #787)
|
||||
//
|
||||
// installRuntimeArtifacts() tests cover skills in isolation; this test exercises
|
||||
// the FULL install() code path to ensure neither artifact is silently dropped.
|
||||
|
||||
describe('install() global cline — coexistence: skills AND .clinerules', () => {
|
||||
let tmpGlobalDir;
|
||||
let originalClineConfigDir;
|
||||
|
||||
beforeEach(() => {
|
||||
originalClineConfigDir = process.env.CLINE_CONFIG_DIR;
|
||||
tmpGlobalDir = createTempDir('gsd-cline-global-');
|
||||
// Redirect CLINE_CONFIG_DIR to the temp dir so install() never touches ~/.cline
|
||||
process.env.CLINE_CONFIG_DIR = tmpGlobalDir;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalClineConfigDir !== undefined) {
|
||||
process.env.CLINE_CONFIG_DIR = originalClineConfigDir;
|
||||
} else {
|
||||
delete process.env.CLINE_CONFIG_DIR;
|
||||
}
|
||||
cleanup(tmpGlobalDir);
|
||||
});
|
||||
|
||||
test('global cline install writes at least one gsd-* SKILL.md under skills/', () => {
|
||||
captureConsole(() => install(true, 'cline'));
|
||||
|
||||
const skillsDir = path.join(tmpGlobalDir, 'skills');
|
||||
assert.ok(
|
||||
fs.existsSync(skillsDir),
|
||||
`skills/ directory must exist under ${tmpGlobalDir} after global cline install`
|
||||
);
|
||||
|
||||
// gsd-help is present in every profile (core, standard, full)
|
||||
const helpSkillFile = path.join(skillsDir, 'gsd-help', 'SKILL.md');
|
||||
assert.ok(
|
||||
fs.existsSync(helpSkillFile),
|
||||
`skills/gsd-help/SKILL.md must exist under ${tmpGlobalDir} — skills emission broken for global cline`
|
||||
);
|
||||
});
|
||||
|
||||
test('global cline install writes .clinerules/gsd.md to the global config dir', () => {
|
||||
captureConsole(() => install(true, 'cline'));
|
||||
|
||||
// For a global Cline install, targetDir = getGlobalDir('cline') = CLINE_CONFIG_DIR.
|
||||
// The cline-rules surface (#787) writes the .clinerules/ DIRECTORY form:
|
||||
// .clinerules/gsd.md (rule file)
|
||||
// .clinerules/hooks/PreToolUse (lifecycle hook)
|
||||
const clinerulesMd = path.join(tmpGlobalDir, '.clinerules', 'gsd.md');
|
||||
assert.ok(
|
||||
fs.existsSync(clinerulesMd),
|
||||
`.clinerules/gsd.md must exist at ${clinerulesMd} — coexistence with skills broken for global cline (#782+#787)`
|
||||
);
|
||||
});
|
||||
|
||||
test('global cline .clinerules/gsd.md contains GSD instructions', () => {
|
||||
captureConsole(() => install(true, 'cline'));
|
||||
|
||||
// #787 dir form: rule content lives in .clinerules/gsd.md, not a flat .clinerules file
|
||||
const clinerulesMd = path.join(tmpGlobalDir, '.clinerules', 'gsd.md');
|
||||
assert.ok(fs.existsSync(clinerulesMd), '.clinerules/gsd.md must exist');
|
||||
const content = fs.readFileSync(clinerulesMd, 'utf8');
|
||||
assert.ok(
|
||||
content.includes('GSD') || content.includes('gsd'),
|
||||
'.clinerules/gsd.md must reference GSD'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Fix 3 regression: converter rewrites bare ~/.claude and CLAUDE_CONFIG_DIR ──
|
||||
//
|
||||
// convertClaudeToCliineMarkdown must also handle bare ~/.claude (no trailing
|
||||
// slash) and the CLAUDE_CONFIG_DIR env-var name. surface.md contains these;
|
||||
// the emitted Cline SKILL.md must contain no such stale Claude refs.
|
||||
|
||||
describe('convertClaudeToCliineMarkdown — bare ~/.claude and CLAUDE_CONFIG_DIR (Fix 3)', () => {
|
||||
const surfacePath = path.join(__dirname, '..', 'commands', 'gsd', 'surface.md');
|
||||
|
||||
test('no bare ~/.claude in converted surface.md', () => {
|
||||
const raw = fs.readFileSync(surfacePath, 'utf8');
|
||||
const result = convertClaudeToCliineMarkdown(raw);
|
||||
// ~/.claude followed by a word-boundary (not a /) must be gone
|
||||
assert.ok(
|
||||
!/~\/\.claude\b/.test(result),
|
||||
'converted surface.md must not contain bare ~/.claude'
|
||||
);
|
||||
});
|
||||
|
||||
test('no CLAUDE_CONFIG_DIR in converted surface.md', () => {
|
||||
const raw = fs.readFileSync(surfacePath, 'utf8');
|
||||
const result = convertClaudeToCliineMarkdown(raw);
|
||||
assert.ok(
|
||||
!result.includes('CLAUDE_CONFIG_DIR'),
|
||||
'converted surface.md must not contain CLAUDE_CONFIG_DIR'
|
||||
);
|
||||
});
|
||||
|
||||
test('CLAUDE_CONFIG_DIR rewritten to CLINE_CONFIG_DIR', () => {
|
||||
const input = 'Use CLAUDE_CONFIG_DIR or $HOME/.claude to configure';
|
||||
const result = convertClaudeToCliineMarkdown(input);
|
||||
assert.ok(result.includes('CLINE_CONFIG_DIR'), 'CLAUDE_CONFIG_DIR must become CLINE_CONFIG_DIR');
|
||||
assert.ok(!result.includes('CLAUDE_CONFIG_DIR'), 'CLAUDE_CONFIG_DIR must be gone');
|
||||
});
|
||||
|
||||
test('bare ~/.claude rewritten to ~/.cline', () => {
|
||||
const input = 'Config dir: (~/.claude), skills at ~/.claude/skills';
|
||||
const result = convertClaudeToCliineMarkdown(input);
|
||||
assert.ok(!result.includes('~/.claude'), 'bare ~/.claude must be rewritten');
|
||||
assert.ok(result.includes('~/.cline'), 'must rewrite to ~/.cline');
|
||||
});
|
||||
|
||||
test('installRuntimeArtifacts cline global: gsd-surface SKILL.md has no bare ~/.claude or CLAUDE_CONFIG_DIR', (t) => {
|
||||
const configDir = createTempDir('gsd-cline-surface-fix3-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
const MANIFEST_FULL = require('../gsd-core/bin/lib/install-profiles.cjs').loadSkillsManifest(
|
||||
path.join(__dirname, '..', 'commands', 'gsd')
|
||||
);
|
||||
const RESOLVED_FULL = require('../gsd-core/bin/lib/install-profiles.cjs').resolveProfile({
|
||||
modes: ['full'], manifest: MANIFEST_FULL,
|
||||
});
|
||||
|
||||
installRuntimeArtifacts('cline', configDir, 'global', RESOLVED_FULL);
|
||||
|
||||
const surfaceSkill = path.join(configDir, 'skills', 'gsd-surface', 'SKILL.md');
|
||||
assert.ok(fs.existsSync(surfaceSkill), 'gsd-surface/SKILL.md must exist for full profile');
|
||||
|
||||
const content = fs.readFileSync(surfaceSkill, 'utf8');
|
||||
assert.ok(
|
||||
!/~\/\.claude\b/.test(content),
|
||||
'gsd-surface SKILL.md must not contain bare ~/.claude (Fix 3)'
|
||||
);
|
||||
assert.ok(
|
||||
!content.includes('CLAUDE_CONFIG_DIR'),
|
||||
'gsd-surface SKILL.md must not contain CLAUDE_CONFIG_DIR (Fix 3)'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Fix 1 regression: custom CLINE_CONFIG_DIR → embedded paths use custom dir ──
|
||||
//
|
||||
// _applyRuntimeRewrites for cline must rewrite ~/.cline/ → pathPrefix.
|
||||
// For default global installs, pathPrefix = "$HOME/.cline/" (unchanged).
|
||||
// For custom installs (CLINE_CONFIG_DIR=/custom), pathPrefix = "/custom/" and
|
||||
// all embedded ~/.cline/ refs in SKILL.md must become /custom/...
|
||||
|
||||
describe('_applyRuntimeRewrites — cline custom-dir embedded path (Fix 1)', () => {
|
||||
test('default pathPrefix ($HOME/.cline/) leaves ~/.cline refs as $HOME/.cline', () => {
|
||||
const content = 'See ~/.cline/skills/gsd-help/SKILL.md for reference.\nBare: ~/.cline\n';
|
||||
const result = _applyRuntimeRewrites(content, 'cline', '$HOME/.cline/');
|
||||
assert.ok(result.includes('$HOME/.cline/'), 'default prefix must map ~/.cline/ to $HOME/.cline/');
|
||||
assert.ok(!result.includes('~/.cline'), 'no tilde form should remain after rewrite');
|
||||
});
|
||||
|
||||
test('custom pathPrefix rewrites ~/.cline/ → custom path in SKILL.md body', () => {
|
||||
const content = 'See ~/.cline/skills/gsd-help/SKILL.md for reference.\nBare: ~/.cline\n';
|
||||
const result = _applyRuntimeRewrites(content, 'cline', '/custom/cline-dir/');
|
||||
assert.ok(result.includes('/custom/cline-dir/'), 'custom prefix must appear in output');
|
||||
assert.ok(!result.includes('~/.cline'), 'no tilde cline form should remain after custom rewrite');
|
||||
});
|
||||
|
||||
test('custom pathPrefix rewrites residual ~/.claude/ safety net', () => {
|
||||
const content = 'Residual: ~/.claude/skills\n';
|
||||
const result = _applyRuntimeRewrites(content, 'cline', '/custom/cline-dir/');
|
||||
assert.ok(result.includes('/custom/cline-dir/'), 'safety-net ~/.claude/ also rewritten to custom prefix');
|
||||
assert.ok(!result.includes('~/.claude/'), 'no ~/.claude/ should remain');
|
||||
});
|
||||
|
||||
test('installRuntimeArtifacts cline with CLINE_CONFIG_DIR custom: SKILL.md embeds custom path', (t) => {
|
||||
const configDir = createTempDir('gsd-cline-custom-dir-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
const MANIFEST_FULL = require('../gsd-core/bin/lib/install-profiles.cjs').loadSkillsManifest(
|
||||
path.join(__dirname, '..', 'commands', 'gsd')
|
||||
);
|
||||
const RESOLVED_FULL = require('../gsd-core/bin/lib/install-profiles.cjs').resolveProfile({
|
||||
modes: ['full'], manifest: MANIFEST_FULL,
|
||||
});
|
||||
|
||||
installRuntimeArtifacts('cline', configDir, 'global', RESOLVED_FULL);
|
||||
|
||||
// gsd-surface SKILL.md references config paths; with a custom configDir
|
||||
// (not under $HOME), pathPrefix will be the absolute custom path.
|
||||
const surfaceSkill = path.join(configDir, 'skills', 'gsd-surface', 'SKILL.md');
|
||||
assert.ok(fs.existsSync(surfaceSkill), 'gsd-surface/SKILL.md must exist');
|
||||
|
||||
const content = fs.readFileSync(surfaceSkill, 'utf8');
|
||||
// With a custom dir (path under /tmp, not ~/.cline), the output must NOT
|
||||
// contain ~/.cline/ or $HOME/.cline/ — it must embed the actual configDir path.
|
||||
assert.ok(
|
||||
!content.includes('~/.cline/'),
|
||||
`gsd-surface SKILL.md must not contain ~/.cline/ when configDir=${configDir} (Fix 1)`
|
||||
);
|
||||
// The custom path must appear somewhere in the file
|
||||
// (configDir is a /tmp/... path so pathPrefix = configDir+'/').
|
||||
// Production normalizes backslashes to forward slashes via
|
||||
// path.resolve(configDir).replace(/\\/g, '/'), so compare against that
|
||||
// form — otherwise this assertion fails on Windows where mkdtempSync
|
||||
// returns a backslash path (e.g. C:\Users\...) but the emitted content
|
||||
// already has forward slashes (C:/Users/...).
|
||||
const expectedPath = path.resolve(configDir).replace(/\\/g, '/');
|
||||
assert.ok(
|
||||
content.includes(expectedPath),
|
||||
`gsd-surface SKILL.md must embed custom configDir path ${expectedPath} (Fix 1)`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Fix 4 regression: description truncation is code-point-aware ────────────
|
||||
//
|
||||
// Naive UTF-16 slicing (`str.slice(0, 1021)`) can split a surrogate pair when
|
||||
// the cut falls between the high and low surrogate of a multibyte character
|
||||
// (e.g. emoji U+1F600, which is encoded as two UTF-16 code units). The fix
|
||||
// uses Array.from() to split by code point, guaranteeing that the truncated
|
||||
// value never contains a lone surrogate.
|
||||
|
||||
describe('convertClaudeCommandToClineSkill — code-point-aware truncation (Fix 4)', () => {
|
||||
/**
|
||||
* Build a frontmatter+body command string whose description is:
|
||||
* - exactly `prefixLen` ASCII chars
|
||||
* - followed by `emojiCount` repetitions of '😀' (U+1F600, 2 UTF-16 units)
|
||||
* - total UTF-16 length is prefixLen + emojiCount * 2
|
||||
*/
|
||||
function makeEmojiCommand(prefixLen, emojiCount) {
|
||||
const desc = 'A'.repeat(prefixLen) + '😀'.repeat(emojiCount);
|
||||
return `---\nname: gsd:emoji-test\ndescription: ${desc}\n---\n\nBody.\n`;
|
||||
}
|
||||
|
||||
test('emitted description is <= 1024 code points when source overflows', () => {
|
||||
// 1020 ASCII chars + 4 emoji = 1020 + 8 UTF-16 units = 1028 UTF-16 units > 1024.
|
||||
// Code-point count = 1020 + 4 = 1024 — exactly at the boundary BEFORE adding '...'.
|
||||
// After truncation to 1021 code points + '...' → 1024 code points total.
|
||||
const cmd = makeEmojiCommand(1020, 10); // 1030 code points → must truncate
|
||||
const result = convertClaudeCommandToClineSkill(cmd, 'gsd-emoji-test');
|
||||
|
||||
// Extract raw description value (strip surrounding YAML quotes if present)
|
||||
const descMatch = result.match(/^description:\s*(.+)$/m);
|
||||
assert.ok(descMatch, 'emitted SKILL.md must have a description field');
|
||||
const rawDesc = descMatch[1].trim().replace(/^['"]|['"]$/g, '');
|
||||
|
||||
const codePoints = Array.from(rawDesc);
|
||||
assert.ok(
|
||||
codePoints.length <= 1024,
|
||||
`emitted description must be <= 1024 code points, got ${codePoints.length}`
|
||||
);
|
||||
});
|
||||
|
||||
test('emitted description ends with "..." when truncated', () => {
|
||||
const cmd = makeEmojiCommand(1020, 10); // 1030 code points → must truncate
|
||||
const result = convertClaudeCommandToClineSkill(cmd, 'gsd-emoji-test');
|
||||
|
||||
const descMatch = result.match(/^description:\s*(.+)$/m);
|
||||
assert.ok(descMatch, 'emitted SKILL.md must have a description field');
|
||||
const rawDesc = descMatch[1].trim().replace(/^['"]|['"]$/g, '');
|
||||
|
||||
assert.ok(rawDesc.endsWith('...'), `truncated description must end with "...", got: ${rawDesc.slice(-10)}`);
|
||||
});
|
||||
|
||||
test('emitted description has no lone surrogate (no split emoji)', () => {
|
||||
// Place emojis exactly at positions 1021–1025 (code points) so that a naive
|
||||
// UTF-16 slice at 1021 code units would cut inside the second emoji's surrogate pair.
|
||||
// 1019 ASCII chars + 6 emoji = 1025 code points (>1024, triggers truncation).
|
||||
// UTF-16 length = 1019 + 12 = 1031. Naive slice(0,1021) yields 1019 ASCII +
|
||||
// the HIGH surrogate of emoji[0] — a lone surrogate.
|
||||
const cmd = makeEmojiCommand(1019, 6);
|
||||
const result = convertClaudeCommandToClineSkill(cmd, 'gsd-emoji-test');
|
||||
|
||||
const descMatch = result.match(/^description:\s*(.+)$/m);
|
||||
assert.ok(descMatch, 'emitted SKILL.md must have a description field');
|
||||
const rawDesc = descMatch[1].trim().replace(/^['"]|['"]$/g, '');
|
||||
|
||||
// Verify no lone surrogate: every char's code point must be outside [0xD800, 0xDFFF].
|
||||
const hasLoneSurrogate = [...rawDesc].some(c => {
|
||||
const cp = c.codePointAt(0);
|
||||
return cp >= 0xD800 && cp <= 0xDFFF;
|
||||
});
|
||||
assert.ok(!hasLoneSurrogate, 'emitted description must not contain a lone surrogate');
|
||||
|
||||
// Also round-trip through Buffer to confirm the string is valid UTF-8 encodable.
|
||||
assert.doesNotThrow(
|
||||
() => Buffer.from(rawDesc, 'utf8').toString('utf8'),
|
||||
'emitted description must round-trip through Buffer without error'
|
||||
);
|
||||
});
|
||||
|
||||
test('short description (<= 1024 code points) is not truncated', () => {
|
||||
// 10 ASCII + 5 emoji = 15 code points — well under the limit.
|
||||
const cmd = makeEmojiCommand(10, 5);
|
||||
const result = convertClaudeCommandToClineSkill(cmd, 'gsd-emoji-test');
|
||||
|
||||
const descMatch = result.match(/^description:\s*(.+)$/m);
|
||||
assert.ok(descMatch, 'emitted SKILL.md must have a description field');
|
||||
const rawDesc = descMatch[1].trim().replace(/^['"]|['"]$/g, '');
|
||||
|
||||
assert.ok(!rawDesc.endsWith('...'), 'short description must NOT be truncated with "..."');
|
||||
// Must contain the original emoji characters intact
|
||||
assert.ok(rawDesc.includes('😀'), 'short description must preserve emoji characters');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Fix 2 regression: cline local scope emits no skills ─────────────────────
|
||||
//
|
||||
// resolveRuntimeArtifactLayout('cline', dir, 'local') must return 0 kinds.
|
||||
// installRuntimeArtifacts('cline', dir, 'local') must not write any skills.
|
||||
|
||||
describe('resolveRuntimeArtifactLayout — cline scope-aware (Fix 2)', () => {
|
||||
test('cline local: kinds.length === 0 (no skills for local scope)', () => {
|
||||
const { resolveRuntimeArtifactLayout } = require('../gsd-core/bin/lib/runtime-artifact-layout.cjs');
|
||||
const layout = resolveRuntimeArtifactLayout('cline', '/tmp/x', 'local');
|
||||
assert.strictEqual(layout.kinds.length, 0, 'cline local must have 0 kinds');
|
||||
});
|
||||
|
||||
test('cline global: kinds.length === 1 (skills kind)', () => {
|
||||
const { resolveRuntimeArtifactLayout } = require('../gsd-core/bin/lib/runtime-artifact-layout.cjs');
|
||||
const layout = resolveRuntimeArtifactLayout('cline', '/tmp/x', 'global');
|
||||
assert.strictEqual(layout.kinds.length, 1, 'cline global must have 1 skills kind');
|
||||
assert.strictEqual(layout.kinds[0].kind, 'skills');
|
||||
});
|
||||
|
||||
test('installRuntimeArtifacts cline local: no skills/ dir created', (t) => {
|
||||
const configDir = createTempDir('gsd-cline-local-noskills-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
assert.doesNotThrow(() => installRuntimeArtifacts('cline', configDir, 'local', RESOLVED_CORE));
|
||||
const skillsDir = path.join(configDir, 'skills');
|
||||
assert.ok(
|
||||
!fs.existsSync(skillsDir),
|
||||
`skills/ must NOT be created for cline local install (Fix 2), but found ${skillsDir}`
|
||||
);
|
||||
});
|
||||
});
|
||||
105
tests/bug-783-kilo-global-skills-base.test.cjs
Normal file
105
tests/bug-783-kilo-global-skills-base.test.cjs
Normal file
@@ -0,0 +1,105 @@
|
||||
'use strict';
|
||||
// Regression guard for bug #783.
|
||||
//
|
||||
// getGlobalSkillsBase('kilo') was returning ~/.config/kilo/skills (the XDG
|
||||
// config dir) instead of ~/.kilo/skills — where Kilo Code actually discovers
|
||||
// global skills per its docs:
|
||||
// https://kilo.ai/docs/customize/skills
|
||||
// "Global skills are located in the `.kilo` directory within your Home
|
||||
// directory: ~/.kilo/skills/"
|
||||
//
|
||||
// The fix adds a special case in getGlobalSkillsBase() that resolves kilo's
|
||||
// skills dir from HOME (not from the XDG config dir). The config dir at
|
||||
// ~/.config/kilo is still CORRECT for commands (command/) and must stay
|
||||
// unchanged — this test verifies both roles are separate.
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const {
|
||||
getGlobalConfigDir,
|
||||
getGlobalSkillsBase,
|
||||
} = require(path.join(ROOT, 'gsd-core', 'bin', 'lib', 'runtime-homes.cjs'));
|
||||
|
||||
// Helper: temporarily override env vars for a test, restoring them afterwards.
|
||||
function withEnv(overrides, fn) {
|
||||
const saved = {};
|
||||
for (const [key, value] of Object.entries(overrides)) {
|
||||
saved[key] = process.env[key];
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
try {
|
||||
return fn();
|
||||
} finally {
|
||||
for (const [key] of Object.entries(overrides)) {
|
||||
if (saved[key] === undefined) delete process.env[key];
|
||||
else process.env[key] = saved[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clear all kilo-relevant env vars so tests are hermetic.
|
||||
const kiloEnvClears = {
|
||||
KILO_CONFIG_DIR: undefined,
|
||||
XDG_CONFIG_HOME: undefined,
|
||||
};
|
||||
|
||||
describe('bug #783: kilo global skills dir is ~/.kilo/skills, not ~/.config/kilo/skills', () => {
|
||||
test('getGlobalSkillsBase("kilo") resolves to ~/.kilo/skills', () => {
|
||||
withEnv(kiloEnvClears, () => {
|
||||
assert.strictEqual(
|
||||
getGlobalSkillsBase('kilo'),
|
||||
path.join(os.homedir(), '.kilo', 'skills'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('getGlobalConfigDir("kilo") still resolves to ~/.config/kilo (config dir unchanged)', () => {
|
||||
withEnv(kiloEnvClears, () => {
|
||||
assert.strictEqual(
|
||||
getGlobalConfigDir('kilo'),
|
||||
path.join(os.homedir(), '.config', 'kilo'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('kilo skills dir and config dir are decoupled (not equal, not nested)', () => {
|
||||
withEnv(kiloEnvClears, () => {
|
||||
const skillsBase = getGlobalSkillsBase('kilo');
|
||||
const configDir = getGlobalConfigDir('kilo');
|
||||
|
||||
assert.notStrictEqual(skillsBase, configDir, 'skills dir must differ from config dir');
|
||||
assert.ok(
|
||||
!skillsBase.startsWith(configDir + path.sep),
|
||||
`skills dir (${skillsBase}) must not be nested under config dir (${configDir})`,
|
||||
);
|
||||
assert.ok(
|
||||
!configDir.startsWith(skillsBase + path.sep),
|
||||
`config dir (${configDir}) must not be nested under skills dir (${skillsBase})`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('getGlobalSkillsBase("kilo") is NOT affected by KILO_CONFIG_DIR override', () => {
|
||||
// Skills always live in ~/.kilo/skills regardless of XDG/config-dir overrides.
|
||||
withEnv({ KILO_CONFIG_DIR: '/tmp/custom-kilo-config', XDG_CONFIG_HOME: undefined }, () => {
|
||||
assert.strictEqual(
|
||||
getGlobalSkillsBase('kilo'),
|
||||
path.join(os.homedir(), '.kilo', 'skills'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('getGlobalSkillsBase("kilo") is NOT affected by XDG_CONFIG_HOME override', () => {
|
||||
withEnv({ KILO_CONFIG_DIR: undefined, XDG_CONFIG_HOME: '/tmp/custom-xdg' }, () => {
|
||||
assert.strictEqual(
|
||||
getGlobalSkillsBase('kilo'),
|
||||
path.join(os.homedir(), '.kilo', 'skills'),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
const { test, describe, before, after } = require('node:test');
|
||||
const { test, describe, before, after, beforeEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
@@ -36,6 +36,11 @@ function runRender(args = []) {
|
||||
};
|
||||
}
|
||||
|
||||
function runRenderRaw(args = []) {
|
||||
const r = cp.spawnSync(process.execPath, [SCRIPT, 'render', '--repo', tmp, ...args], { encoding: 'utf8' });
|
||||
return { status: r.status, stdout: r.stdout || '', stderr: r.stderr || '' };
|
||||
}
|
||||
|
||||
before(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-changeset-')); });
|
||||
after(() => { cleanup(tmp); });
|
||||
|
||||
@@ -93,7 +98,7 @@ function runExtract(args = [], changelogText = null) {
|
||||
}
|
||||
|
||||
describe('changeset cli extract: version-range changelog extraction (#3496)', () => {
|
||||
test('exits 2 with no output when no versions fall in range', (t) => {
|
||||
test('exits 2 with no output when no versions fall in range', (_t) => {
|
||||
const r = runExtract(['--from', '1.5.15', '--to', '1.5.15', '--json'], EXTRACT_CHANGELOG);
|
||||
assert.equal(r.status, 2, `expected exit 2 for empty range, stderr=${r.stderr}`);
|
||||
// F11: assert JSON structure is present and releases is empty array
|
||||
@@ -101,7 +106,7 @@ describe('changeset cli extract: version-range changelog extraction (#3496)', ()
|
||||
assert.strictEqual(r.json.releases.length, 0, 'releases must be empty array on exit 2');
|
||||
});
|
||||
|
||||
test('extracts versions strictly after from and up to and including to', (t) => {
|
||||
test('extracts versions strictly after from and up to and including to', (_t) => {
|
||||
const r = runExtract(['--from', '1.5.13', '--to', '1.5.15', '--json'], EXTRACT_CHANGELOG);
|
||||
assert.equal(r.status, 0, `stderr=${r.stderr}`);
|
||||
assert.ok(r.json, 'stdout must be valid JSON');
|
||||
@@ -112,7 +117,7 @@ describe('changeset cli extract: version-range changelog extraction (#3496)', ()
|
||||
assert.ok(!versions.includes('1.5.10'), '1.5.10 must NOT be in range (below from)');
|
||||
});
|
||||
|
||||
test('accepts v-prefixed version arguments', (t) => {
|
||||
test('accepts v-prefixed version arguments', (_t) => {
|
||||
const r = runExtract(['--from', 'v1.5.13', '--to', 'v1.5.15', '--json'], EXTRACT_CHANGELOG);
|
||||
assert.equal(r.status, 0, `stderr=${r.stderr}`);
|
||||
assert.ok(r.json, 'stdout must be valid JSON');
|
||||
@@ -122,7 +127,7 @@ describe('changeset cli extract: version-range changelog extraction (#3496)', ()
|
||||
assert.ok(!versions.includes('1.5.13'));
|
||||
});
|
||||
|
||||
test('captures multi-line bullets in extracted range', (t) => {
|
||||
test('captures multi-line bullets in extracted range', (_t) => {
|
||||
const r = runExtract(['--from', '1.5.13', '--to', '1.5.14', '--json'], EXTRACT_CHANGELOG);
|
||||
assert.equal(r.status, 0, `stderr=${r.stderr}`);
|
||||
const release = r.json.releases.find((rel) => rel.version === '1.5.14');
|
||||
@@ -132,7 +137,7 @@ describe('changeset cli extract: version-range changelog extraction (#3496)', ()
|
||||
assert.ok(prs.includes(102), 'multi-line bullet pr=102 must be captured');
|
||||
});
|
||||
|
||||
test('emits markdown text (non-JSON) when --json is not passed', (t) => {
|
||||
test('emits markdown text (non-JSON) when --json is not passed', (_t) => {
|
||||
// Without --json the output is human-readable markdown, not JSON.
|
||||
// Assert on structural facts derivable from the text: exactly the two
|
||||
// matched releases appear as ## headers, using parseChangelog so we
|
||||
@@ -149,13 +154,13 @@ describe('changeset cli extract: version-range changelog extraction (#3496)', ()
|
||||
assert.ok(!versions.includes('1.5.13'), '1.5.13 must not appear in output (excluded by --from)');
|
||||
});
|
||||
|
||||
test('missing --from or --to emits usage and exits non-zero', (t) => {
|
||||
test('missing --from or --to emits usage and exits non-zero', (_t) => {
|
||||
const r = runExtract(['--from', '1.0.0'], EXTRACT_CHANGELOG);
|
||||
assert.notEqual(r.status, 0);
|
||||
assert.ok(r.stderr.length > 0 || r.stdout.length > 0, 'must emit usage text');
|
||||
});
|
||||
|
||||
test('rejects malformed --from semver (non-numeric component) with exit 1', (t) => {
|
||||
test('rejects malformed --from semver (non-numeric component) with exit 1', (_t) => {
|
||||
const r = runExtract(['--from', '1.41.x', '--to', '1.5.15', '--json'], EXTRACT_CHANGELOG);
|
||||
assert.equal(r.status, 1, `expected exit 1 for malformed --from, stderr=${r.stderr}`);
|
||||
assert.ok(r.json, 'stdout must be valid JSON on error');
|
||||
@@ -163,7 +168,7 @@ describe('changeset cli extract: version-range changelog extraction (#3496)', ()
|
||||
assert.ok(r.json.error.includes('--from'), 'error must mention --from');
|
||||
});
|
||||
|
||||
test('rejects malformed --to semver (alphabetic) with exit 1', (t) => {
|
||||
test('rejects malformed --to semver (alphabetic) with exit 1', (_t) => {
|
||||
const r = runExtract(['--from', '1.5.13', '--to', 'foo', '--json'], EXTRACT_CHANGELOG);
|
||||
assert.equal(r.status, 1, `expected exit 1 for malformed --to, stderr=${r.stderr}`);
|
||||
assert.ok(r.json, 'stdout must be valid JSON on error');
|
||||
@@ -171,7 +176,7 @@ describe('changeset cli extract: version-range changelog extraction (#3496)', ()
|
||||
assert.ok(r.json.error.includes('--to'), 'error must mention --to');
|
||||
});
|
||||
|
||||
test('preserves bullets without PR trailer in extracted output', (t) => {
|
||||
test('preserves bullets without PR trailer in extracted output', (_t) => {
|
||||
// Fixture with one no-PR bullet and one PR bullet.
|
||||
const CHANGELOG_NO_PR = [
|
||||
'# Changelog',
|
||||
@@ -196,7 +201,7 @@ describe('changeset cli extract: version-range changelog extraction (#3496)', ()
|
||||
});
|
||||
|
||||
// F2: pre-release entries must be excluded from range queries
|
||||
test('F2: pre-release entry 1.0.0-rc.1 is excluded from range --from 0.9.9 --to 1.0.0', (t) => {
|
||||
test('F2: pre-release entry 1.0.0-rc.1 is excluded from range --from 0.9.9 --to 1.0.0', (_t) => {
|
||||
const CHANGELOG_WITH_PRERELEASE = [
|
||||
'# Changelog',
|
||||
'',
|
||||
@@ -228,7 +233,7 @@ describe('changeset cli extract: version-range changelog extraction (#3496)', ()
|
||||
});
|
||||
|
||||
// F3: linked-header format ## [1.42.1](url) - date must parse date correctly
|
||||
test('F3: linked-header ## [1.42.1](url) - date parses date correctly', (t) => {
|
||||
test('F3: linked-header ## [1.42.1](url) - date parses date correctly', (_t) => {
|
||||
const CHANGELOG_LINKED = [
|
||||
'# Changelog',
|
||||
'',
|
||||
@@ -255,7 +260,7 @@ describe('changeset cli extract: version-range changelog extraction (#3496)', ()
|
||||
});
|
||||
|
||||
// F4: nested bullets must remain as separate bullets, not fold into parent
|
||||
test('F4: nested bullets are not folded into parent bullet', (t) => {
|
||||
test('F4: nested bullets are not folded into parent bullet', (_t) => {
|
||||
const CHANGELOG_NESTED = [
|
||||
'# Changelog',
|
||||
'',
|
||||
@@ -283,7 +288,7 @@ describe('changeset cli extract: version-range changelog extraction (#3496)', ()
|
||||
});
|
||||
|
||||
// F5+F6: 4-part headers and v-prefix in-file headers
|
||||
test('F5+F6: 4-part version in CHANGELOG is skipped, v-prefixed version parses without v', (t) => {
|
||||
test('F5+F6: 4-part version in CHANGELOG is skipped, v-prefixed version parses without v', (_t) => {
|
||||
const CHANGELOG_EDGE = [
|
||||
'# Changelog',
|
||||
'',
|
||||
@@ -324,7 +329,7 @@ describe('changeset cli extract: version-range changelog extraction (#3496)', ()
|
||||
// F1: workflows/update.md must reference the extract subcommand invocation.
|
||||
// allow-test-rule: reads a product workflow .md file (not CJS source) to verify
|
||||
// the user-facing instruction was wired; there is no behavioural runtime to invoke.
|
||||
test('F1: workflows/update.md contains concrete extract subcommand invocation', (t) => {
|
||||
test('F1: workflows/update.md contains concrete extract subcommand invocation', (_t) => {
|
||||
const workflowPath = path.join(ROOT, 'gsd-core', 'workflows', 'update.md');
|
||||
const workflowText = fs.readFileSync(workflowPath, 'utf8');
|
||||
// The invocation is: node "$GSD_DIR/gsd-core/scripts/changeset/cli.cjs" extract
|
||||
@@ -382,3 +387,653 @@ describe('changeset cli render: file-I/O wrapper (#2975)', () => {
|
||||
assert.deepEqual(remaining.filter((f) => f.endsWith('.md')), []);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GROUP A — #690 regression guard (real repo CHANGELOG.md)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('changeset cli #690 regression: CHANGELOG.md has 1.3.0 and 1.3.1 entries', () => {
|
||||
const CHANGELOG_PATH = path.join(ROOT, 'CHANGELOG.md');
|
||||
|
||||
test('CHANGELOG.md has dated 1.3.0 and 1.3.1 release headings (regression #690)', () => {
|
||||
const text = fs.readFileSync(CHANGELOG_PATH, 'utf8');
|
||||
const { releases } = parseChangelog(text);
|
||||
const stableReleases = releases.filter((r) => r.version !== 'Unreleased');
|
||||
|
||||
const v130 = stableReleases.find((r) => r.version === '1.3.0');
|
||||
assert.ok(v130, 'CHANGELOG.md must contain a release entry for version 1.3.0');
|
||||
assert.ok(v130.date !== null && v130.date !== '', '1.3.0 entry must have a non-null, non-empty date');
|
||||
|
||||
const v131 = stableReleases.find((r) => r.version === '1.3.1');
|
||||
assert.ok(v131, 'CHANGELOG.md must contain a release entry for version 1.3.1');
|
||||
assert.ok(v131.date !== null && v131.date !== '', '1.3.1 entry must have a non-null, non-empty date');
|
||||
});
|
||||
|
||||
test('extract 1.2.0->1.3.1 against repo CHANGELOG returns both 1.3.x releases (regression #690)', () => {
|
||||
const r = cp.spawnSync(
|
||||
process.execPath,
|
||||
[SCRIPT, 'extract', '--from', '1.2.0', '--to', '1.3.1', '--changelog', CHANGELOG_PATH, '--json'],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
const json = (() => { try { return JSON.parse(r.stdout); } catch { return null; } })();
|
||||
assert.equal(r.status, 0, `expected exit 0 but got ${r.status}; stderr=${r.stderr}; stdout=${r.stdout}`);
|
||||
assert.ok(json, 'stdout must be valid JSON');
|
||||
const versions = (json.releases || []).map((rel) => rel.version);
|
||||
assert.ok(versions.includes('1.3.0'), `releases array must include 1.3.0; got: ${JSON.stringify(versions)}`);
|
||||
assert.ok(versions.includes('1.3.1'), `releases array must include 1.3.1; got: ${JSON.stringify(versions)}`);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GROUP B — unit tests for the (not-yet-implemented) `verify` subcommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function runVerify(args, changelogText) {
|
||||
const changelogFile = path.join(tmp, 'CHANGELOG-verify-test.md');
|
||||
fs.writeFileSync(changelogFile, changelogText);
|
||||
const r = cp.spawnSync(
|
||||
process.execPath,
|
||||
[SCRIPT, 'verify', '--changelog', changelogFile, ...args],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
return {
|
||||
status: r.status,
|
||||
stdout: r.stdout || '',
|
||||
stderr: r.stderr || '',
|
||||
};
|
||||
}
|
||||
|
||||
describe('changeset cli verify subcommand (not yet implemented — TDD red step)', () => {
|
||||
// Fixture: inline-URL heading form ## [1.3.1](url) - 2026-06-04
|
||||
const FIXTURE_URL_HEADING = [
|
||||
'# Changelog',
|
||||
'',
|
||||
'## [1.3.1](https://www.npmjs.com/package/@opengsd/gsd-core/v/1.3.1) - 2026-06-04',
|
||||
'',
|
||||
'### Fixed',
|
||||
'',
|
||||
'- Some fix. (#42)',
|
||||
'',
|
||||
'## [1.2.0] - 2026-05-31',
|
||||
'',
|
||||
'### Added',
|
||||
'',
|
||||
'- Some feature. (#10)',
|
||||
].join('\n');
|
||||
|
||||
// Fixture: plain dated heading ## [1.3.1] - 2026-06-04
|
||||
const FIXTURE_PLAIN_HEADING = [
|
||||
'# Changelog',
|
||||
'',
|
||||
'## [1.3.1] - 2026-06-04',
|
||||
'',
|
||||
'### Fixed',
|
||||
'',
|
||||
'- Some fix. (#42)',
|
||||
'',
|
||||
'## [1.2.0] - 2026-05-31',
|
||||
'',
|
||||
'### Added',
|
||||
'',
|
||||
'- Some feature. (#10)',
|
||||
].join('\n');
|
||||
|
||||
// Fixture: version absent (only Unreleased + 1.2.0)
|
||||
const FIXTURE_NO_131 = [
|
||||
'# Changelog',
|
||||
'',
|
||||
'## [Unreleased]',
|
||||
'',
|
||||
'## [1.2.0] - 2026-05-31',
|
||||
'',
|
||||
'### Added',
|
||||
'',
|
||||
'- Some feature. (#10)',
|
||||
].join('\n');
|
||||
|
||||
// Fixture: heading present but NO date
|
||||
const FIXTURE_NO_DATE = [
|
||||
'# Changelog',
|
||||
'',
|
||||
'## [1.3.1]',
|
||||
'',
|
||||
'### Fixed',
|
||||
'',
|
||||
'- Some fix. (#42)',
|
||||
].join('\n');
|
||||
|
||||
test('verify --version 1.3.1 exits 0 when inline-URL dated heading is present', () => {
|
||||
const r = runVerify(['--version', '1.3.1'], FIXTURE_URL_HEADING);
|
||||
assert.equal(r.status, 0, `expected exit 0; stderr=${r.stderr}`);
|
||||
});
|
||||
|
||||
test('verify --version 1.3.1 exits 0 when plain dated heading is present', () => {
|
||||
const r = runVerify(['--version', '1.3.1'], FIXTURE_PLAIN_HEADING);
|
||||
assert.equal(r.status, 0, `expected exit 0; stderr=${r.stderr}`);
|
||||
});
|
||||
|
||||
test('verify --version 1.3.1 exits 1 when version heading is absent', () => {
|
||||
const r = runVerify(['--version', '1.3.1'], FIXTURE_NO_131);
|
||||
assert.equal(r.status, 1, `expected exit 1; stderr=${r.stderr}`);
|
||||
});
|
||||
|
||||
test('verify --version 1.3.1 exits 1 when heading has no date', () => {
|
||||
const r = runVerify(['--version', '1.3.1'], FIXTURE_NO_DATE);
|
||||
assert.equal(r.status, 1, `expected exit 1; stderr=${r.stderr}`);
|
||||
});
|
||||
|
||||
test('verify --version 1.3.1 with no match emits non-empty stderr/message', () => {
|
||||
const r = runVerify(['--version', '1.3.1'], FIXTURE_NO_131);
|
||||
assert.ok(
|
||||
(r.stderr && r.stderr.trim().length > 0) || (r.stdout && r.stdout.trim().length > 0),
|
||||
'must emit a non-empty error message to stderr or stdout when version not found',
|
||||
);
|
||||
});
|
||||
|
||||
test('verify --version 1.3.x exits 1 for invalid semver', () => {
|
||||
// Use any non-empty fixture; the version check should fail before reading the file.
|
||||
const r = runVerify(['--version', '1.3.x'], FIXTURE_PLAIN_HEADING);
|
||||
assert.equal(r.status, 1, `expected exit 1 for invalid semver 1.3.x; stderr=${r.stderr}`);
|
||||
});
|
||||
|
||||
test('verify --version v1.3.1 (v-prefixed) exits 0 when dated heading present', () => {
|
||||
// The leading `v` must be stripped, matching extract's behavior.
|
||||
const FIXTURE_DATED = [
|
||||
'# Changelog',
|
||||
'',
|
||||
'## [1.3.1] - 2026-06-04',
|
||||
'',
|
||||
'### Fixed',
|
||||
'',
|
||||
'- Some fix. (#42)',
|
||||
].join('\n');
|
||||
const r = runVerify(['--version', 'v1.3.1'], FIXTURE_DATED);
|
||||
assert.equal(r.status, 0, `expected exit 0 for v-prefixed version; stderr=${r.stderr}`);
|
||||
});
|
||||
|
||||
test('verify --version 1.3.1 --json exits 0 and emits ok/version/date JSON fields', () => {
|
||||
const FIXTURE_DATED = [
|
||||
'# Changelog',
|
||||
'',
|
||||
'## [1.3.1] - 2026-06-04',
|
||||
'',
|
||||
'### Fixed',
|
||||
'',
|
||||
'- Some fix. (#42)',
|
||||
].join('\n');
|
||||
const changelogFile = path.join(tmp, 'CHANGELOG-verify-test.md');
|
||||
fs.writeFileSync(changelogFile, FIXTURE_DATED);
|
||||
const r = cp.spawnSync(
|
||||
process.execPath,
|
||||
[SCRIPT, 'verify', '--version', '1.3.1', '--json', '--changelog', changelogFile],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
assert.equal(r.status, 0, `expected exit 0; stderr=${r.stderr}`);
|
||||
const json = (() => { try { return JSON.parse(r.stdout); } catch { return null; } })();
|
||||
assert.ok(json, 'stdout must be valid JSON');
|
||||
assert.strictEqual(json.ok, true, 'json.ok must be true');
|
||||
assert.strictEqual(json.version, '1.3.1', 'json.version must equal "1.3.1"');
|
||||
assert.ok(json.date && json.date.length > 0, 'json.date must be non-empty');
|
||||
});
|
||||
|
||||
test('verify --version 1.3.1-rc.1 (pre-release) exits 1', () => {
|
||||
// Non-stable-triplet semver is rejected by the verify subcommand.
|
||||
const r = runVerify(['--version', '1.3.1-rc.1'], FIXTURE_PLAIN_HEADING);
|
||||
assert.equal(r.status, 1, `expected exit 1 for pre-release version; stderr=${r.stderr}`);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GROUP C — render --allow-empty
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('changeset cli render --allow-empty', () => {
|
||||
// Helper: run render for a specific test-local tmp directory.
|
||||
function runRenderIn(dir, args = []) {
|
||||
const r = cp.spawnSync(
|
||||
process.execPath,
|
||||
[SCRIPT, 'render', '--repo', dir, ...args, '--json'],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
return {
|
||||
status: r.status,
|
||||
report: r.stdout && r.stdout.length ? JSON.parse(r.stdout) : null,
|
||||
stderr: r.stderr || '',
|
||||
};
|
||||
}
|
||||
|
||||
function runVerifyIn(dir, version) {
|
||||
const changelogPath = path.join(dir, 'CHANGELOG.md');
|
||||
const r = cp.spawnSync(
|
||||
process.execPath,
|
||||
[SCRIPT, 'verify', '--version', version, '--changelog', changelogPath],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
return { status: r.status, stdout: r.stdout || '', stderr: r.stderr || '' };
|
||||
}
|
||||
|
||||
// Test 1: --allow-empty with zero fragments writes a dated heading +
|
||||
// placeholder, and subsequent verify exits 0.
|
||||
test('--allow-empty with zero fragments writes dated heading + placeholder; verify exits 0', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-ae-'));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, '.changeset'), { recursive: true });
|
||||
// Only a README — no fragment files.
|
||||
fs.writeFileSync(
|
||||
path.join(dir, '.changeset', 'README.md'),
|
||||
'# Changesets\n\nThis folder holds changeset fragments.\n',
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'CHANGELOG.md'),
|
||||
'# Changelog\n\n## [Unreleased]\n',
|
||||
);
|
||||
|
||||
const r = runRenderIn(dir, ['--version', '9.9.9', '--date', '2026-06-05', '--allow-empty']);
|
||||
assert.equal(r.status, 0, `render exited non-zero; stderr=${r.stderr}`);
|
||||
assert.equal(r.report.consumed, 0, 'consumed must be 0 for empty run');
|
||||
assert.equal(r.report.failures.length, 0, 'no failures expected');
|
||||
assert.strictEqual(r.report.written, true, 'report.written must be true');
|
||||
|
||||
// The CHANGELOG must now contain a dated heading for 9.9.9.
|
||||
const text = fs.readFileSync(path.join(dir, 'CHANGELOG.md'), 'utf8');
|
||||
const parsed = parseChangelog(text);
|
||||
const rel = parsed.releases.find((r) => r.version === '9.9.9');
|
||||
assert.ok(rel, 'release 9.9.9 must appear in CHANGELOG after --allow-empty render');
|
||||
assert.equal(rel.date, '2026-06-05', 'release date must be 2026-06-05');
|
||||
|
||||
// The placeholder line must be present in the raw text.
|
||||
assert.ok(
|
||||
text.includes('_No notable changes._'),
|
||||
'CHANGELOG must contain _No notable changes._ placeholder',
|
||||
);
|
||||
|
||||
// verify must exit 0 for this version.
|
||||
const vr = runVerifyIn(dir, '9.9.9');
|
||||
assert.equal(vr.status, 0, `verify must exit 0 after --allow-empty render; stderr=${vr.stderr}`);
|
||||
} finally {
|
||||
cleanup(dir);
|
||||
}
|
||||
});
|
||||
|
||||
// Test 2: render WITHOUT --allow-empty and zero fragments early-exits —
|
||||
// CHANGELOG is not created / not modified. Regression lock.
|
||||
test('render without --allow-empty and zero fragments does NOT write CHANGELOG', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-ae-'));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, '.changeset'), { recursive: true });
|
||||
// No fragment files, only README.
|
||||
fs.writeFileSync(
|
||||
path.join(dir, '.changeset', 'README.md'),
|
||||
'# Changesets\n',
|
||||
);
|
||||
// Write a known CHANGELOG so we can verify it is unchanged.
|
||||
const originalChangelog = '# Changelog\n\n## [Unreleased]\n';
|
||||
fs.writeFileSync(path.join(dir, 'CHANGELOG.md'), originalChangelog);
|
||||
|
||||
const r = runRenderIn(dir, ['--version', '9.9.8', '--date', '2026-06-05']);
|
||||
assert.equal(r.status, 0, `render without --allow-empty exited non-zero; stderr=${r.stderr}`);
|
||||
assert.equal(r.report.consumed, 0, 'consumed must be 0');
|
||||
assert.equal(r.report.failures.length, 0, 'no failures expected');
|
||||
// report.written must NOT be set (undefined or absent).
|
||||
assert.ok(
|
||||
r.report.written === undefined || r.report.written === null || r.report.written === false,
|
||||
'report.written must not be true in the no-op path',
|
||||
);
|
||||
|
||||
// CHANGELOG must be byte-identical to the original.
|
||||
const text = fs.readFileSync(path.join(dir, 'CHANGELOG.md'), 'utf8');
|
||||
assert.equal(text, originalChangelog, 'CHANGELOG must be unchanged when no fragments and no --allow-empty');
|
||||
} finally {
|
||||
cleanup(dir);
|
||||
}
|
||||
});
|
||||
|
||||
// Test 3: render WITH fragments + --allow-empty behaves exactly like normal
|
||||
// render (consumes/deletes fragments, NO placeholder injected).
|
||||
test('render --allow-empty with fragments behaves like normal render (no placeholder)', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-ae-'));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, '.changeset'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(dir, '.changeset', 'fix-one.md'),
|
||||
'---\ntype: Fixed\npr: 200\n---\nFragment-driven fix.\n',
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'CHANGELOG.md'),
|
||||
'# Changelog\n\n## [Unreleased]\n',
|
||||
);
|
||||
|
||||
const r = runRenderIn(dir, ['--version', '9.9.7', '--date', '2026-06-05', '--allow-empty']);
|
||||
assert.equal(r.status, 0, `render with fragments exited non-zero; stderr=${r.stderr}`);
|
||||
assert.equal(r.report.consumed, 1, 'one fragment must be consumed');
|
||||
assert.equal(r.report.failures.length, 0, 'no failures expected');
|
||||
|
||||
const text = fs.readFileSync(path.join(dir, 'CHANGELOG.md'), 'utf8');
|
||||
// Placeholder must NOT appear when there are real fragments.
|
||||
assert.ok(
|
||||
!text.includes('_No notable changes._'),
|
||||
'placeholder must NOT appear when fragments were consumed',
|
||||
);
|
||||
// The fragment bullet must be present.
|
||||
const parsed = parseChangelog(text);
|
||||
const rel = parsed.releases.find((r) => r.version === '9.9.7');
|
||||
assert.ok(rel, 'release 9.9.7 must appear in CHANGELOG');
|
||||
assert.equal(rel.date, '2026-06-05', 'release date must be 2026-06-05');
|
||||
const prs = rel.sections.flatMap((s) => s.bullets.map((b) => b.pr));
|
||||
assert.ok(prs.includes(200), 'pr=200 bullet must be present in the release');
|
||||
|
||||
// Fragment file must be deleted.
|
||||
const remaining = fs.readdirSync(path.join(dir, '.changeset'))
|
||||
.filter((f) => f.endsWith('.md') && f !== 'README.md');
|
||||
assert.deepEqual(remaining, [], 'fragment must be deleted after consumption');
|
||||
|
||||
// verify must exit 0.
|
||||
const vr = runVerifyIn(dir, '9.9.7');
|
||||
assert.equal(vr.status, 0, `verify must exit 0 after render with fragments; stderr=${vr.stderr}`);
|
||||
} finally {
|
||||
cleanup(dir);
|
||||
}
|
||||
});
|
||||
|
||||
// Test 4 (idempotency): after a fragmentful render, a second render
|
||||
// --allow-empty for the SAME version is now a NO-OP (FIX 1 guard). It must
|
||||
// NOT add a second heading, must exit 0, and must report alreadyPromoted:true.
|
||||
test('idempotency: second --allow-empty render for same version is a no-op (no duplicate heading)', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-ae-'));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, '.changeset'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(dir, '.changeset', 'fix-two.md'),
|
||||
'---\ntype: Fixed\npr: 300\n---\nIdempotency test fix.\n',
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'CHANGELOG.md'),
|
||||
'# Changelog\n\n## [Unreleased]\n',
|
||||
);
|
||||
|
||||
// First render: with a fragment.
|
||||
const r1 = runRenderIn(dir, ['--version', '9.9.6', '--date', '2026-06-05']);
|
||||
assert.equal(r1.status, 0, `first render exited non-zero; stderr=${r1.stderr}`);
|
||||
assert.equal(r1.report.consumed, 1, 'first render must consume 1 fragment');
|
||||
|
||||
// verify after first render must succeed.
|
||||
const vr1 = runVerifyIn(dir, '9.9.6');
|
||||
assert.equal(vr1.status, 0, `verify after first render must exit 0; stderr=${vr1.stderr}`);
|
||||
|
||||
// Second render --allow-empty: zero fragments now, same version.
|
||||
// This is now a NO-OP due to the already-promoted guard (FIX 1).
|
||||
const r2 = runRenderIn(dir, ['--version', '9.9.6', '--date', '2026-06-05', '--allow-empty']);
|
||||
assert.equal(r2.status, 0, `second render exited non-zero; stderr=${r2.stderr}`);
|
||||
assert.equal(r2.report.consumed, 0, 'second render must consume 0 fragments');
|
||||
assert.strictEqual(r2.report.alreadyPromoted, true, 'second render must report alreadyPromoted:true');
|
||||
|
||||
// Exactly ONE ## [9.9.6] heading must be present — no duplicate.
|
||||
const text = fs.readFileSync(path.join(dir, 'CHANGELOG.md'), 'utf8');
|
||||
const parsed = parseChangelog(text);
|
||||
const all996 = parsed.releases.filter((r) => r.version === '9.9.6');
|
||||
assert.equal(
|
||||
all996.length, 1,
|
||||
`exactly one 9.9.6 heading must be present after two renders; found ${all996.length}`,
|
||||
);
|
||||
|
||||
// verify must still exit 0.
|
||||
const vr2 = runVerifyIn(dir, '9.9.6');
|
||||
assert.equal(vr2.status, 0, `verify after second render must still exit 0; stderr=${vr2.stderr}`);
|
||||
} finally {
|
||||
cleanup(dir);
|
||||
}
|
||||
});
|
||||
|
||||
// Test 4b (stale fragments): alreadyPromoted + fragments present → render exits
|
||||
// NON-ZERO, CHANGELOG is NOT modified, and the fragment file is NOT deleted.
|
||||
// This guards the inconsistent-state scenario identified in the adversarial review:
|
||||
// a manual/partial promotion wrote the heading but left fragments unconsumed.
|
||||
test('alreadyPromoted + fragments present: exits non-zero, CHANGELOG unchanged, fragment survives', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-ae-'));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, '.changeset'), { recursive: true });
|
||||
|
||||
// CHANGELOG already has a dated heading for 3.3.3 (out-of-band promotion).
|
||||
const originalChangelog = [
|
||||
'# Changelog',
|
||||
'',
|
||||
'## [Unreleased]',
|
||||
'',
|
||||
'## [3.3.3] - 2026-01-01',
|
||||
'',
|
||||
'### Fixed',
|
||||
'',
|
||||
'- x (#1)',
|
||||
'',
|
||||
].join('\n');
|
||||
fs.writeFileSync(path.join(dir, 'CHANGELOG.md'), originalChangelog);
|
||||
|
||||
// A fragment file is still present — unconsumed.
|
||||
const fragmentPath = path.join(dir, '.changeset', 'leftover.md');
|
||||
fs.writeFileSync(fragmentPath, '---\ntype: Fixed\npr: 9\n---\nleftover fragment\n');
|
||||
|
||||
// Run render for the same version.
|
||||
const r = runRenderIn(dir, ['--version', '3.3.3', '--date', '2026-06-05', '--allow-empty']);
|
||||
|
||||
// Must exit non-zero.
|
||||
assert.notEqual(r.status, 0, `expected non-zero exit for alreadyPromoted+fragments; got ${r.status}`);
|
||||
|
||||
// report.alreadyPromoted must be true and report.error must be present.
|
||||
assert.strictEqual(r.report.alreadyPromoted, true, 'report.alreadyPromoted must be true');
|
||||
assert.ok(typeof r.report.error === 'string' && r.report.error.length > 0, 'report.error must be a non-empty string');
|
||||
assert.ok(r.report.error.includes('3.3.3'), 'report.error must mention the version');
|
||||
|
||||
// Fragment file must still exist — render must NOT have deleted it.
|
||||
assert.ok(fs.existsSync(fragmentPath), 'leftover fragment must still exist after non-zero exit');
|
||||
|
||||
// CHANGELOG must be byte-identical to the original — render must NOT have modified it.
|
||||
const text = fs.readFileSync(path.join(dir, 'CHANGELOG.md'), 'utf8');
|
||||
assert.equal(text, originalChangelog, 'CHANGELOG must be unchanged');
|
||||
|
||||
// Exactly one ## [3.3.3] heading must be present (no duplicate added).
|
||||
const parsed = parseChangelog(text);
|
||||
const all333 = parsed.releases.filter((rel) => rel.version === '3.3.3');
|
||||
assert.equal(all333.length, 1, `exactly one 3.3.3 heading must be present; found ${all333.length}`);
|
||||
} finally {
|
||||
cleanup(dir);
|
||||
}
|
||||
});
|
||||
|
||||
// Test 5 (cold start): --allow-empty when CHANGELOG.md does NOT exist creates
|
||||
// the file with # Changelog, ## [Unreleased], and a dated release with placeholder.
|
||||
test('--allow-empty cold start (no CHANGELOG.md) creates file with expected structure', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-ae-'));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, '.changeset'), { recursive: true });
|
||||
// No CHANGELOG.md, no fragments.
|
||||
|
||||
const r = runRenderIn(dir, ['--version', '8.8.8', '--date', '2026-06-05', '--allow-empty']);
|
||||
assert.equal(r.status, 0, `render exited non-zero; stderr=${r.stderr}`);
|
||||
assert.equal(r.report.consumed, 0, 'consumed must be 0');
|
||||
assert.strictEqual(r.report.written, true, 'report.written must be true');
|
||||
|
||||
const changelogPath = path.join(dir, 'CHANGELOG.md');
|
||||
assert.ok(fs.existsSync(changelogPath), 'CHANGELOG.md must be created');
|
||||
|
||||
const text = fs.readFileSync(changelogPath, 'utf8');
|
||||
// Must contain a top-level heading.
|
||||
assert.ok(text.includes('# Changelog'), 'must contain # Changelog heading');
|
||||
// Must contain an ## [Unreleased] block.
|
||||
assert.ok(text.includes('## [Unreleased]'), 'must contain ## [Unreleased] block');
|
||||
// Must contain a dated release heading for 8.8.8.
|
||||
assert.ok(text.includes('## [8.8.8] - 2026-06-05'), 'must contain dated release heading for 8.8.8');
|
||||
// Must contain the placeholder.
|
||||
assert.ok(text.includes('_No notable changes._'), 'must contain _No notable changes._ placeholder');
|
||||
|
||||
// parseChangelog must see the release with the correct date.
|
||||
const parsed = parseChangelog(text);
|
||||
const rel = parsed.releases.find((r) => r.version === '8.8.8');
|
||||
assert.ok(rel, 'release 8.8.8 must appear in parsed CHANGELOG');
|
||||
assert.equal(rel.date, '2026-06-05', 'release date must be 2026-06-05');
|
||||
|
||||
// verify must exit 0.
|
||||
const vr = runVerifyIn(dir, '8.8.8');
|
||||
assert.equal(vr.status, 0, `verify must exit 0 after cold-start --allow-empty render; stderr=${vr.stderr}`);
|
||||
} finally {
|
||||
cleanup(dir);
|
||||
}
|
||||
});
|
||||
|
||||
// Test 6: --allow-empty (zero fragments) on a CHANGELOG that already has a
|
||||
// prior dated release PRESERVES that prior release in the output.
|
||||
test('--allow-empty preserves prior dated release below new section', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-ae-'));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, '.changeset'), { recursive: true });
|
||||
// Pre-existing CHANGELOG with a prior dated release.
|
||||
const priorChangelog = [
|
||||
'# Changelog',
|
||||
'',
|
||||
'## [Unreleased]',
|
||||
'',
|
||||
'## [1.0.0] - 2026-01-01',
|
||||
'',
|
||||
'### Fixed',
|
||||
'',
|
||||
'- Old fix. (#1)',
|
||||
'',
|
||||
].join('\n');
|
||||
fs.writeFileSync(path.join(dir, 'CHANGELOG.md'), priorChangelog);
|
||||
|
||||
const r = runRenderIn(dir, ['--version', '2.0.0', '--date', '2026-06-05', '--allow-empty']);
|
||||
assert.equal(r.status, 0, `render exited non-zero; stderr=${r.stderr}`);
|
||||
assert.equal(r.report.consumed, 0, 'consumed must be 0');
|
||||
assert.strictEqual(r.report.written, true, 'report.written must be true');
|
||||
|
||||
const text = fs.readFileSync(path.join(dir, 'CHANGELOG.md'), 'utf8');
|
||||
|
||||
// New release must appear.
|
||||
assert.ok(text.includes('## [2.0.0]'), 'new 2.0.0 heading must be present');
|
||||
assert.ok(text.includes('_No notable changes._'), 'placeholder must be present');
|
||||
|
||||
// Prior release must survive.
|
||||
assert.ok(text.includes('## [1.0.0] - 2026-01-01'), 'prior 1.0.0 heading must be preserved');
|
||||
assert.ok(text.includes('- Old fix. (#1)'), 'prior release bullet must be preserved');
|
||||
|
||||
// Parse and assert both releases are present.
|
||||
const parsed = parseChangelog(text);
|
||||
const rel200 = parsed.releases.find((r) => r.version === '2.0.0');
|
||||
assert.ok(rel200, '2.0.0 must appear in parsed CHANGELOG');
|
||||
assert.equal(rel200.date, '2026-06-05', '2.0.0 date must be 2026-06-05');
|
||||
const rel100 = parsed.releases.find((r) => r.version === '1.0.0');
|
||||
assert.ok(rel100, '1.0.0 must still appear in parsed CHANGELOG');
|
||||
assert.equal(rel100.date, '2026-01-01', '1.0.0 date must be preserved');
|
||||
assert.equal(rel100.sections[0].bullets[0].pr, 1, 'pr=1 bullet in 1.0.0 must be preserved');
|
||||
|
||||
// verify for the new version must exit 0.
|
||||
const vr = runVerifyIn(dir, '2.0.0');
|
||||
assert.equal(vr.status, 0, `verify must exit 0 after --allow-empty on existing CHANGELOG; stderr=${vr.stderr}`);
|
||||
} finally {
|
||||
cleanup(dir);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GROUP D — render --preview (#759)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('changeset cli render --preview (#759)', () => {
|
||||
// Helper: reset the shared tmp dir to a clean state for preview tests.
|
||||
function resetTmp() {
|
||||
// Remove CHANGELOG.md if present.
|
||||
const changelogPath = path.join(tmp, 'CHANGELOG.md');
|
||||
if (fs.existsSync(changelogPath)) {
|
||||
fs.unlinkSync(changelogPath);
|
||||
}
|
||||
// Remove any leftover .changeset/*.md fragments.
|
||||
const changesetDir = path.join(tmp, '.changeset');
|
||||
if (fs.existsSync(changesetDir)) {
|
||||
for (const f of fs.readdirSync(changesetDir)) {
|
||||
if (f.endsWith('.md') && f !== 'README.md') {
|
||||
fs.unlinkSync(path.join(changesetDir, f));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reset state before each preview test so a new test added to this group
|
||||
// can never inherit a CHANGELOG.md or fragments left by the previous one.
|
||||
beforeEach(resetTmp);
|
||||
|
||||
test('render --preview prints the section to stdout and mutates nothing', () => {
|
||||
writeFragment('preview-frag-one', 'Added', 900, 'preview-added-feature');
|
||||
|
||||
const fragmentPath = path.join(tmp, '.changeset', 'preview-frag-one.md');
|
||||
const r = runRenderRaw(['--version', '9.9.0', '--date', '2026-01-02', '--preview']);
|
||||
|
||||
assert.equal(r.status, 0, `expected exit 0; stderr=${r.stderr}`);
|
||||
assert.ok(r.stdout.includes('## [9.9.0]'), `stdout must contain ## [9.9.0]; got: ${r.stdout}`);
|
||||
assert.ok(r.stdout.includes('### Added'), `stdout must contain ### Added; got: ${r.stdout}`);
|
||||
assert.ok(r.stdout.includes('preview-added-feature'), `stdout must contain fragment body; got: ${r.stdout}`);
|
||||
|
||||
// CHANGELOG.md must NOT have been created.
|
||||
assert.ok(!fs.existsSync(path.join(tmp, 'CHANGELOG.md')), 'CHANGELOG.md must NOT be created by --preview');
|
||||
|
||||
// Fragment file must still exist.
|
||||
assert.ok(fs.existsSync(fragmentPath), 'fragment file must still exist after --preview');
|
||||
});
|
||||
|
||||
test('render --preview with zero fragments emits the placeholder and writes nothing', () => {
|
||||
// No fragments written — zero-fragment scenario.
|
||||
|
||||
const r = runRenderRaw(['--version', '9.9.0', '--date', '2026-01-02', '--preview']);
|
||||
|
||||
assert.equal(r.status, 0, `expected exit 0; stderr=${r.stderr}`);
|
||||
assert.ok(r.stdout.includes('## ['), `stdout must contain a release heading; got: ${r.stdout}`);
|
||||
assert.ok(r.stdout.includes('_No notable changes._'), `stdout must contain placeholder; got: ${r.stdout}`);
|
||||
|
||||
// CHANGELOG.md must NOT have been created.
|
||||
assert.ok(!fs.existsSync(path.join(tmp, 'CHANGELOG.md')), 'CHANGELOG.md must NOT be created by zero-fragment --preview');
|
||||
});
|
||||
|
||||
test('render --preview --json returns preview text in report with consumed 0', () => {
|
||||
writeFragment('preview-frag-two', 'Fixed', 901, 'preview-fixed-bug');
|
||||
|
||||
const fragmentPath = path.join(tmp, '.changeset', 'preview-frag-two.md');
|
||||
// runRender appends --json automatically.
|
||||
const r = runRender(['--version', '9.9.0', '--date', '2026-01-02', '--preview']);
|
||||
|
||||
assert.equal(r.status, 0, `expected exit 0; stderr=${r.stderr}`);
|
||||
assert.ok(r.report, 'report must be parseable JSON');
|
||||
assert.strictEqual(r.report.consumed, 0, 'consumed must be 0 for preview');
|
||||
assert.strictEqual(r.report.fragmentCount, 1, 'fragmentCount must be 1');
|
||||
assert.ok(typeof r.report.preview === 'string', 'report.preview must be a string');
|
||||
assert.ok(r.report.preview.includes('## [9.9.0]'), `report.preview must contain ## [9.9.0]; got: ${r.report.preview}`);
|
||||
|
||||
// Fragment file must still exist.
|
||||
assert.ok(fs.existsSync(fragmentPath), 'fragment file must still exist after --preview --json');
|
||||
});
|
||||
|
||||
test('render --preview with an existing CHANGELOG.md leaves it byte-identical and shows only the new section', () => {
|
||||
// Seed an existing CHANGELOG with a prior dated release.
|
||||
const changelogPath = path.join(tmp, 'CHANGELOG.md');
|
||||
const existing =
|
||||
'# Changelog\n\n## [1.0.0] - 2020-01-01\n\n### Added\n\n- old prior feature (#1)\n';
|
||||
fs.writeFileSync(changelogPath, existing);
|
||||
writeFragment('preview-frag-three', 'Added', 902, 'brand-new-thing');
|
||||
const before = fs.readFileSync(changelogPath, 'utf8');
|
||||
|
||||
const r = runRenderRaw(['--version', '9.9.0', '--date', '2026-01-02', '--preview']);
|
||||
|
||||
assert.equal(r.status, 0, `expected exit 0; stderr=${r.stderr}`);
|
||||
// Output shows the new section...
|
||||
assert.ok(r.stdout.includes('## [9.9.0]'), `stdout must contain new heading; got: ${r.stdout}`);
|
||||
assert.ok(r.stdout.includes('brand-new-thing'), `stdout must contain new fragment body; got: ${r.stdout}`);
|
||||
// ...and NOT the prior release history (preview is the new section only).
|
||||
assert.ok(!r.stdout.includes('## [1.0.0]'), `preview must NOT include prior releases; got: ${r.stdout}`);
|
||||
assert.ok(!r.stdout.includes('old prior feature'), `preview must NOT include prior bullets; got: ${r.stdout}`);
|
||||
|
||||
// Existing CHANGELOG.md must be byte-identical — preview mutates nothing.
|
||||
assert.strictEqual(
|
||||
fs.readFileSync(changelogPath, 'utf8'),
|
||||
before,
|
||||
'CHANGELOG.md must be byte-identical after --preview',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,9 +4,13 @@ const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { spawnSync } = require('child_process');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const os = require('node:os');
|
||||
const { cleanup } = require('./helpers.cjs');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const SCRIPT = path.join(ROOT, 'scripts', 'ci-test-scope.cjs');
|
||||
const WORKFLOWS_DIR = path.join(ROOT, '.github', 'workflows');
|
||||
|
||||
function scopeFor(files) {
|
||||
const r = spawnSync(process.execPath, [SCRIPT, '--files', files.join(' ')], {
|
||||
@@ -18,25 +22,124 @@ function scopeFor(files) {
|
||||
}
|
||||
|
||||
describe('ci-test-scope.cjs', () => {
|
||||
test('docs-only changes mark code_changed and select docs-parity (new correct contract)', () => {
|
||||
test('docs-only changes: code_changed is false, product_changed false (skip matrix entirely)', () => {
|
||||
const result = scopeFor(['docs/usage.md']);
|
||||
assert.strictEqual(result.code_changed, true);
|
||||
assert.strictEqual(result.code_changed, false,
|
||||
`expected code_changed=false for docs-only change, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.product_changed, false,
|
||||
`expected product_changed=false for docs-only change, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.full_matrix, false);
|
||||
// docs-parity is NOT in targeted_tests when docs-only (it runs via docs-required.yml instead)
|
||||
assert.ok(
|
||||
result.targeted_tests.some(t => t.includes('docs-parity-live-registry')),
|
||||
`expected docs-parity-live-registry in targeted_tests, got: ${JSON.stringify(result.targeted_tests)}`,
|
||||
!result.targeted_tests.some(t => t.includes('docs-parity-live-registry')),
|
||||
`docs-parity-live-registry must NOT be in targeted_tests for docs-only, got: ${JSON.stringify(result.targeted_tests)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('workflow changes request full matrix and workflow contract tests', () => {
|
||||
test('root markdown only: code_changed is false, product_changed false', () => {
|
||||
const result = scopeFor(['README.md']);
|
||||
assert.strictEqual(result.code_changed, false,
|
||||
`expected code_changed=false for root markdown, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.product_changed, false,
|
||||
`expected product_changed=false for root markdown, got: ${JSON.stringify(result)}`);
|
||||
});
|
||||
|
||||
test('pipeline workflow (test.yml) — product_changed true, full_matrix true, workflow contract tests', () => {
|
||||
const result = scopeFor(['.github/workflows/test.yml']);
|
||||
assert.strictEqual(result.code_changed, true);
|
||||
assert.strictEqual(result.product_changed, true,
|
||||
`expected product_changed=true for test.yml, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.full_matrix, true);
|
||||
assert.ok(result.targeted_tests.includes('tests/workflow-shell-pinning.test.cjs'));
|
||||
assert.ok(result.targeted_tests.includes('tests/release-tarball-smoke-workflow.test.cjs'));
|
||||
assert.ok(result.windows_tests.includes('tests/workflow-shell-pinning.test.cjs'));
|
||||
});
|
||||
|
||||
test('pipeline workflow (install-smoke.yml) — product_changed true, full_matrix true', () => {
|
||||
const result = scopeFor(['.github/workflows/install-smoke.yml']);
|
||||
assert.strictEqual(result.code_changed, true);
|
||||
assert.strictEqual(result.product_changed, true,
|
||||
`expected product_changed=true for install-smoke.yml, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.full_matrix, true);
|
||||
});
|
||||
|
||||
test('inert CI only (stale.yml) — code_changed true, product_changed false, full_matrix false', () => {
|
||||
const result = scopeFor(['.github/workflows/stale.yml']);
|
||||
assert.strictEqual(result.code_changed, true,
|
||||
`expected code_changed=true for inert CI, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.product_changed, false,
|
||||
`expected product_changed=false for inert CI, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.full_matrix, false,
|
||||
`expected full_matrix=false for inert CI, got: ${JSON.stringify(result)}`);
|
||||
assert.ok(result.targeted_tests.includes('tests/workflow-shell-pinning.test.cjs'),
|
||||
`expected workflow-shell-pinning in targeted_tests, got: ${JSON.stringify(result.targeted_tests)}`);
|
||||
assert.ok(result.targeted_tests.includes('tests/policy-lint-shallow-checkout.test.cjs'),
|
||||
`expected policy-lint-shallow-checkout in targeted_tests for inert CI, got: ${JSON.stringify(result.targeted_tests)}`);
|
||||
});
|
||||
|
||||
test('TS runtime sources (src/semver.cts) — code_changed true, product_changed true, full_matrix false, semver tests targeted', () => {
|
||||
const result = scopeFor(['src/semver.cts']);
|
||||
assert.strictEqual(result.code_changed, true,
|
||||
`expected code_changed=true for src/ change, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.product_changed, true,
|
||||
`expected product_changed=true for src/ change, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.full_matrix, false,
|
||||
`expected full_matrix=false for src/-only change (TS runtime sources rule has no fullMatrix), got: ${JSON.stringify(result)}`);
|
||||
assert.ok(result.targeted_tests.includes('tests/semver-compare.test.cjs'),
|
||||
`expected semver-compare in targeted_tests, got: ${JSON.stringify(result.targeted_tests)}`);
|
||||
});
|
||||
|
||||
test('product code (gsd-core/bin/lib/foo.cjs) — product_changed true', () => {
|
||||
const result = scopeFor(['gsd-core/bin/lib/foo.cjs']);
|
||||
assert.strictEqual(result.code_changed, true);
|
||||
assert.strictEqual(result.product_changed, true,
|
||||
`expected product_changed=true for gsd-core/ change, got: ${JSON.stringify(result)}`);
|
||||
});
|
||||
|
||||
test('unknown/new workflow defaults to pipeline (fail-safe) — product_changed true', () => {
|
||||
const result = scopeFor(['.github/workflows/brand-new-thing.yml']);
|
||||
assert.strictEqual(result.code_changed, true);
|
||||
assert.strictEqual(result.product_changed, true,
|
||||
`expected product_changed=true for unknown workflow (fail-safe), got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.full_matrix, true,
|
||||
`expected full_matrix=true for unknown workflow (fail-safe), got: ${JSON.stringify(result)}`);
|
||||
});
|
||||
|
||||
test('mixed docs + code — escalates to product_changed true', () => {
|
||||
// Use bin/gsd (installer rule, fullMatrix:true) to get a code file that reliably triggers full matrix.
|
||||
const result = scopeFor(['docs/x.md', 'bin/gsd']);
|
||||
assert.strictEqual(result.code_changed, true);
|
||||
assert.strictEqual(result.product_changed, true,
|
||||
`expected product_changed=true for docs+code, got: ${JSON.stringify(result)}`);
|
||||
});
|
||||
|
||||
test('inert CI (docs-required.yml) — includes shallow-checkout policy test, product_changed false', () => {
|
||||
const result = scopeFor(['.github/workflows/docs-required.yml']);
|
||||
assert.strictEqual(result.code_changed, true,
|
||||
`expected code_changed=true for docs-required.yml, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.product_changed, false,
|
||||
`expected product_changed=false for docs-required.yml, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.full_matrix, false,
|
||||
`expected full_matrix=false for docs-required.yml, got: ${JSON.stringify(result)}`);
|
||||
assert.ok(result.targeted_tests.includes('tests/policy-lint-shallow-checkout.test.cjs'),
|
||||
`expected policy-lint-shallow-checkout in targeted_tests for docs-required.yml, got: ${JSON.stringify(result.targeted_tests)}`);
|
||||
});
|
||||
|
||||
test('mixed docs + inert CI — code_changed true, product_changed false (inert lane)', () => {
|
||||
const result = scopeFor(['docs/x.md', '.github/workflows/stale.yml']);
|
||||
assert.strictEqual(result.code_changed, true);
|
||||
assert.strictEqual(result.product_changed, false,
|
||||
`expected product_changed=false for docs+inert, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.full_matrix, false);
|
||||
});
|
||||
|
||||
test('mixed docs + src — product_changed true', () => {
|
||||
const result = scopeFor(['docs/x.md', 'src/semver.cts']);
|
||||
assert.strictEqual(result.code_changed, true);
|
||||
assert.strictEqual(result.product_changed, true,
|
||||
`expected product_changed=true for docs+src, got: ${JSON.stringify(result)}`);
|
||||
});
|
||||
|
||||
test('command changes request command tests without full parity matrix', () => {
|
||||
const result = scopeFor(['commands/gsd/plan-phase.md']);
|
||||
assert.strictEqual(result.code_changed, true);
|
||||
@@ -54,6 +157,8 @@ describe('ci-test-scope.cjs', () => {
|
||||
test('installer-sensitive changes request full matrix and install tests', () => {
|
||||
const result = scopeFor(['bin/gsd']);
|
||||
assert.strictEqual(result.code_changed, true);
|
||||
assert.strictEqual(result.product_changed, true,
|
||||
`expected product_changed=true for bin/gsd, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.full_matrix, true);
|
||||
assert.ok(result.targeted_tests.includes('tests/install.test.cjs'));
|
||||
assert.ok(result.targeted_tests.includes('tests/release-tarball-smoke.install.test.cjs'));
|
||||
@@ -104,6 +209,74 @@ describe('ci-test-scope.cjs', () => {
|
||||
assert.deepStrictEqual(result.targeted_tests, ['unit'],
|
||||
'targeted_tests must be [\'unit\'] when code changed but no rule matched');
|
||||
});
|
||||
|
||||
test('three-dot diff: docs-only PR on a stale base ignores product commits next gained after the merge-base', () => {
|
||||
// Reproduces #837: a docs-only PR branched from a slightly older `next`.
|
||||
// After the branch point, `next` advances with a PRODUCT commit. A two-dot
|
||||
// `git diff base head` would surface that product file (flipping product_changed/
|
||||
// full_matrix true); a three-dot `git diff base...head` (vs the merge-base, which is
|
||||
// GitHub's PR semantics) must see ONLY the docs change.
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ci-scope-837-'));
|
||||
try {
|
||||
const git = (...a) => {
|
||||
const r = spawnSync('git', a, { cwd: tmp, encoding: 'utf8' });
|
||||
assert.strictEqual(r.status, 0, `git ${a.join(' ')} failed: ${r.stderr}`);
|
||||
return r.stdout.trim();
|
||||
};
|
||||
git('init', '-q');
|
||||
git('config', 'user.email', 'test@example.com');
|
||||
git('config', 'user.name', 'Test');
|
||||
git('config', 'commit.gpgsign', 'false');
|
||||
|
||||
// merge-base: a docs file + a product file (package.json)
|
||||
fs.mkdirSync(path.join(tmp, 'tests'), { recursive: true }); // existingTests() reads tests/
|
||||
fs.mkdirSync(path.join(tmp, 'docs'), { recursive: true });
|
||||
fs.writeFileSync(path.join(tmp, 'docs', 'a.md'), 'base\n');
|
||||
fs.writeFileSync(path.join(tmp, 'package.json'), '{"name":"x","version":"1.0.0"}\n');
|
||||
git('add', '-A');
|
||||
git('commit', '-qm', 'merge-base');
|
||||
const baseBranch = git('rev-parse', '--abbrev-ref', 'HEAD');
|
||||
|
||||
// PR branch (head): docs-only change
|
||||
git('checkout', '-q', '-b', 'feature');
|
||||
fs.writeFileSync(path.join(tmp, 'docs', 'a.md'), 'base\nnew docs line\n');
|
||||
git('add', '-A');
|
||||
git('commit', '-qm', 'docs: add line');
|
||||
const head = git('rev-parse', 'HEAD');
|
||||
|
||||
// base advances (next gains a PRODUCT commit after the merge-base)
|
||||
git('checkout', '-q', baseBranch);
|
||||
fs.writeFileSync(path.join(tmp, 'package.json'), '{"name":"x","version":"2.0.0"}\n');
|
||||
git('add', '-A');
|
||||
git('commit', '-qm', 'chore: bump version on next');
|
||||
const base = git('rev-parse', 'HEAD');
|
||||
|
||||
const r = spawnSync(process.execPath, [SCRIPT, '--base', base, '--head', head], {
|
||||
cwd: tmp,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
assert.strictEqual(r.status, 0, `script failed: stderr=${r.stderr}\nstdout=${r.stdout}`);
|
||||
const result = JSON.parse(r.stdout);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
result.changed_files,
|
||||
['docs/a.md'],
|
||||
`expected three-dot diff to see only the docs file, got: ${JSON.stringify(result.changed_files)}`,
|
||||
);
|
||||
assert.strictEqual(
|
||||
result.product_changed,
|
||||
false,
|
||||
`docs-only PR must not set product_changed even on a stale base, got: ${JSON.stringify(result)}`,
|
||||
);
|
||||
assert.strictEqual(
|
||||
result.full_matrix,
|
||||
false,
|
||||
`docs-only PR must not set full_matrix even on a stale base, got: ${JSON.stringify(result)}`,
|
||||
);
|
||||
} finally {
|
||||
cleanup(tmp);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('ci-test-scope superset invariant (#494)', () => {
|
||||
@@ -120,25 +293,27 @@ describe('ci-test-scope superset invariant (#494)', () => {
|
||||
`expected full_matrix=true for tests/** change, got: ${JSON.stringify(result)}`);
|
||||
});
|
||||
|
||||
// Facet B: docs/**, commands/**, agents/** → code_changed AND docs-parity selected
|
||||
test('B1: docs/adr change marks code_changed and selects docs-parity-live-registry', () => {
|
||||
// Facet B: commands/**, agents/** → code_changed AND docs-parity selected
|
||||
// docs/ is NO LONGER in this facet — docs-only PRs skip the matrix entirely.
|
||||
test('B1: docs/adr change: code_changed is false (docs skip matrix)', () => {
|
||||
const result = scopeFor(['docs/adr/22-plan-drift-guard.md']);
|
||||
assert.strictEqual(result.code_changed, true,
|
||||
`expected code_changed=true for docs/** change, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.code_changed, false,
|
||||
`expected code_changed=false for docs/** change (matrix skip), got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.product_changed, false,
|
||||
`expected product_changed=false for docs/** change, got: ${JSON.stringify(result)}`);
|
||||
// docs-parity is NOT in targeted_tests (handled by docs-required.yml)
|
||||
assert.ok(
|
||||
result.targeted_tests.some(t => t.includes('docs-parity-live-registry')),
|
||||
`expected docs-parity-live-registry in targeted_tests, got: ${JSON.stringify(result.targeted_tests)}`,
|
||||
!result.targeted_tests.some(t => t.includes('docs-parity-live-registry')),
|
||||
`docs-parity-live-registry must NOT be in targeted_tests for docs-only, got: ${JSON.stringify(result.targeted_tests)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('B2: docs locale dir change marks code_changed and selects docs-parity-live-registry', () => {
|
||||
test('B2: docs locale dir change: code_changed is false (docs skip matrix)', () => {
|
||||
const result = scopeFor(['docs/ja-JP/USAGE.md']);
|
||||
assert.strictEqual(result.code_changed, true,
|
||||
`expected code_changed=true for docs/ja-JP/** change, got: ${JSON.stringify(result)}`);
|
||||
assert.ok(
|
||||
result.targeted_tests.some(t => t.includes('docs-parity-live-registry')),
|
||||
`expected docs-parity-live-registry in targeted_tests, got: ${JSON.stringify(result.targeted_tests)}`,
|
||||
);
|
||||
assert.strictEqual(result.code_changed, false,
|
||||
`expected code_changed=false for docs/ja-JP/** change, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.product_changed, false,
|
||||
`expected product_changed=false for docs/ja-JP/** change, got: ${JSON.stringify(result)}`);
|
||||
});
|
||||
|
||||
test('B3: commands/** change selects docs-parity-live-registry', () => {
|
||||
@@ -149,3 +324,172 @@ describe('ci-test-scope superset invariant (#494)', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('INERT_WORKFLOWS allowlist integrity guard', () => {
|
||||
// Load the INERT_WORKFLOWS set from the script by spawning it and using --files
|
||||
// on a sentinel path, then separately verify the set contents via the filesystem.
|
||||
|
||||
// Known pipeline workflows that MUST NOT appear in INERT_WORKFLOWS.
|
||||
// Must stay in sync with PROTECTED_WORKFLOWS in scripts/ci-test-scope.cjs.
|
||||
const KNOWN_PIPELINE = [
|
||||
'test.yml',
|
||||
'install-smoke.yml',
|
||||
'mutation.yml',
|
||||
'security-scan.yml',
|
||||
'release.yml',
|
||||
];
|
||||
|
||||
// Canonical inert workflow list — reused by both tests below.
|
||||
const knownInert = [
|
||||
'stale.yml', 'branch-cleanup.yml', 'branch-naming.yml', 'auto-label-issues.yml',
|
||||
'auto-branch.yml', 'auto-backmerge.yml', 'close-draft-prs.yml',
|
||||
'dismiss-unauthorized-pr-approvals.yml', 'pr-gate.yml', 'pr-target-validator.yml',
|
||||
'pr-template-format.yml', 'require-issue-link.yml', 'changeset-required.yml',
|
||||
'docs-required.yml', 'discord-changelog.yml',
|
||||
];
|
||||
|
||||
test('all entries in INERT_WORKFLOWS exist under .github/workflows/', () => {
|
||||
// We derive the inert set implicitly: any .github/workflows/*.yml that produces
|
||||
// full_matrix=false when passed alone is inert. We check the known inert names
|
||||
// against the filesystem instead.
|
||||
// The canonical list is in the script — we verify each named file exists.
|
||||
for (const name of knownInert) {
|
||||
const fullPath = path.join(WORKFLOWS_DIR, name);
|
||||
assert.ok(
|
||||
fs.existsSync(fullPath),
|
||||
`INERT_WORKFLOWS entry '${name}' does not exist at ${fullPath}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('known pipeline workflows are NOT treated as inert (product_changed true, full_matrix true)', () => {
|
||||
for (const name of KNOWN_PIPELINE) {
|
||||
const result = scopeFor([`.github/workflows/${name}`]);
|
||||
assert.strictEqual(result.product_changed, true,
|
||||
`${name} must be pipeline (product_changed=true), got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.full_matrix, true,
|
||||
`${name} must be pipeline (full_matrix=true), got: ${JSON.stringify(result)}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Explicit per-workflow guard: each of the five protected workflows must route to
|
||||
// the full matrix. This documents intent and proves that PROTECTED_WORKFLOWS
|
||||
// enforcement is covered end-to-end via the spawn helper.
|
||||
test('all five PROTECTED_WORKFLOWS individually route to full matrix (tamper-evidence)', () => {
|
||||
const protected_ = [
|
||||
'test.yml',
|
||||
'install-smoke.yml',
|
||||
'mutation.yml',
|
||||
'security-scan.yml',
|
||||
'release.yml',
|
||||
];
|
||||
for (const name of protected_) {
|
||||
const result = scopeFor([`.github/workflows/${name}`]);
|
||||
assert.strictEqual(result.product_changed, true,
|
||||
`PROTECTED_WORKFLOW ${name}: expected product_changed=true, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.full_matrix, true,
|
||||
`PROTECTED_WORKFLOW ${name}: expected full_matrix=true, got: ${JSON.stringify(result)}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('every inert workflow produces code_changed=true, product_changed=false, and full_matrix=false', () => {
|
||||
for (const name of knownInert) {
|
||||
const result = scopeFor([`.github/workflows/${name}`]);
|
||||
assert.strictEqual(result.code_changed, true,
|
||||
`${name}: expected code_changed=true`);
|
||||
assert.strictEqual(result.product_changed, false,
|
||||
`${name}: expected product_changed=false`);
|
||||
assert.strictEqual(result.full_matrix, false,
|
||||
`${name}: expected full_matrix=false`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('test.yml changes job contract (#837)', () => {
|
||||
// ci-test-scope.cjs uses a three-dot `git diff base...head`, which requires the
|
||||
// merge-base commit to be locally present. The `changes` job in test.yml guarantees
|
||||
// this via `fetch-depth: 0` on its checkout step. This test pins that contract so
|
||||
// any future reduction of fetch-depth fails CI loudly (#837).
|
||||
test('changes job checkout step sets fetch-depth: 0 (required for three-dot diff merge-base)', () => {
|
||||
const workflowPath = path.join(WORKFLOWS_DIR, 'test.yml');
|
||||
const text = fs.readFileSync(workflowPath, 'utf8');
|
||||
const lines = text.split('\n');
|
||||
|
||||
// Locate the `changes:` job (two-space-indented top-level job key).
|
||||
const jobStart = lines.findIndex(l => /^ {2}changes:\s*$/.test(l));
|
||||
assert.ok(jobStart !== -1, 'Could not find ` changes:` job in test.yml');
|
||||
|
||||
// Find the next top-level job key at the same two-space indentation to bound the region.
|
||||
let jobEnd = lines.length;
|
||||
for (let i = jobStart + 1; i < lines.length; i++) {
|
||||
if (/^ {2}[A-Za-z0-9_-]+:\s*$/.test(lines[i])) {
|
||||
jobEnd = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const changesJobText = lines.slice(jobStart, jobEnd).join('\n');
|
||||
|
||||
assert.ok(
|
||||
/fetch-depth:\s*0/.test(changesJobText),
|
||||
'changes job checkout must set `fetch-depth: 0` so the three-dot `git diff base...head` ' +
|
||||
'in ci-test-scope.cjs can resolve the merge-base locally (#837). ' +
|
||||
'Reducing fetch-depth breaks the three-dot diff and causes incorrect scope detection.',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('code_changed=false implies clean output invariant', () => {
|
||||
// Fix 1: when code_changed is false, full_matrix, targeted_tests, windows_tests
|
||||
// must ALL be empty/false — even if a docs path coincidentally
|
||||
// matches a content rule via coarse substring (e.g. path.includes('install') or
|
||||
// path.includes('config')).
|
||||
|
||||
test('docs-only: code_changed=false → product_changed=false, full_matrix=false, empty targeted_tests', () => {
|
||||
const result = scopeFor(['docs/usage.md']);
|
||||
assert.strictEqual(result.code_changed, false);
|
||||
assert.strictEqual(result.product_changed, false);
|
||||
assert.strictEqual(result.full_matrix, false);
|
||||
assert.deepStrictEqual(result.targeted_tests, []);
|
||||
});
|
||||
|
||||
// docs/installer-migrations.md contains 'install' → would match the installer rule
|
||||
// via path.includes('install'). Normalization must suppress the contradictory output.
|
||||
test('docs/installer-migrations.md: code_changed=false AND product_changed=false AND full_matrix=false AND empty targeted_tests', () => {
|
||||
const result = scopeFor(['docs/installer-migrations.md']);
|
||||
assert.strictEqual(result.code_changed, false,
|
||||
`expected code_changed=false for docs/installer-migrations.md, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.product_changed, false,
|
||||
`expected product_changed=false for docs/installer-migrations.md, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.full_matrix, false,
|
||||
`expected full_matrix=false for docs/installer-migrations.md, got: ${JSON.stringify(result)}`);
|
||||
assert.deepStrictEqual(result.targeted_tests, [],
|
||||
`expected empty targeted_tests for docs/installer-migrations.md, got: ${JSON.stringify(result.targeted_tests)}`);
|
||||
});
|
||||
|
||||
// docs/how-to/configure-model-profiles.md contains 'config' → matches configuration rule.
|
||||
test('docs path matching config rule: code_changed=false → empty output (coarse-substring docs suppressed)', () => {
|
||||
const result = scopeFor(['docs/how-to/configure-model-profiles.md']);
|
||||
assert.strictEqual(result.code_changed, false,
|
||||
`expected code_changed=false, got: ${JSON.stringify(result)}`);
|
||||
assert.strictEqual(result.product_changed, false);
|
||||
assert.strictEqual(result.full_matrix, false);
|
||||
assert.deepStrictEqual(result.targeted_tests, []);
|
||||
});
|
||||
|
||||
// code_changed=true must produce >= 1 targeted_test or 'unit' fallback.
|
||||
test('code_changed=true implies non-empty targeted_tests', () => {
|
||||
for (const files of [
|
||||
['src/semver.cts'],
|
||||
['bin/gsd'],
|
||||
['.github/workflows/test.yml'],
|
||||
['.github/workflows/stale.yml'],
|
||||
]) {
|
||||
const result = scopeFor(files);
|
||||
assert.strictEqual(result.code_changed, true,
|
||||
`expected code_changed=true for ${files}, got: ${JSON.stringify(result)}`);
|
||||
assert.ok(result.targeted_tests.length >= 1,
|
||||
`expected >= 1 targeted_test for ${files}, got: ${JSON.stringify(result.targeted_tests)}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,7 +25,6 @@ const ROOT = path.join(__dirname, '..');
|
||||
const {
|
||||
convertClaudeCommandToClaudeSkill,
|
||||
writeManifest,
|
||||
install,
|
||||
installRuntimeArtifacts,
|
||||
uninstallRuntimeArtifacts,
|
||||
} = require(path.join(ROOT, 'bin', 'install.js'));
|
||||
|
||||
161
tests/cli-exit.test.cjs
Normal file
161
tests/cli-exit.test.cjs
Normal file
@@ -0,0 +1,161 @@
|
||||
'use strict';
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const { ExitError, runMain } = require('../scripts/lib/cli-exit.cjs');
|
||||
|
||||
/** Settle the runMain promise chain before asserting. */
|
||||
async function settle() {
|
||||
await new Promise((r) => setImmediate(r));
|
||||
}
|
||||
|
||||
describe('ExitError', () => {
|
||||
test('default code is 1', () => {
|
||||
const err = new ExitError();
|
||||
assert.equal(err.code, 1);
|
||||
});
|
||||
|
||||
test('name is ExitError', () => {
|
||||
const err = new ExitError();
|
||||
assert.equal(err.name, 'ExitError');
|
||||
});
|
||||
|
||||
test('instanceof Error', () => {
|
||||
assert.ok(new ExitError() instanceof Error);
|
||||
});
|
||||
|
||||
test('hasUserMessage is false when no message passed', () => {
|
||||
const err = new ExitError(1);
|
||||
assert.equal(err.hasUserMessage, false);
|
||||
});
|
||||
|
||||
test('hasUserMessage is true when message passed', () => {
|
||||
const err = new ExitError(1, 'something went wrong');
|
||||
assert.equal(err.hasUserMessage, true);
|
||||
});
|
||||
|
||||
test('custom code is preserved', () => {
|
||||
const err = new ExitError(42, 'boom');
|
||||
assert.equal(err.code, 42);
|
||||
});
|
||||
|
||||
test('message is set to user message when provided', () => {
|
||||
const err = new ExitError(2, 'user msg');
|
||||
assert.equal(err.message, 'user msg');
|
||||
});
|
||||
|
||||
test('message is synthetic when no message provided', () => {
|
||||
const err = new ExitError(3);
|
||||
assert.equal(err.message, 'process exit 3');
|
||||
});
|
||||
});
|
||||
|
||||
describe('runMain', () => {
|
||||
test('main returns a number sets process.exitCode', async () => {
|
||||
const saved = process.exitCode;
|
||||
try {
|
||||
runMain(() => 42);
|
||||
await settle();
|
||||
assert.equal(process.exitCode, 42);
|
||||
} finally {
|
||||
process.exitCode = saved || 0;
|
||||
}
|
||||
});
|
||||
|
||||
test('main returns undefined leaves process.exitCode unchanged', async () => {
|
||||
const saved = process.exitCode;
|
||||
// Set a known value before calling
|
||||
process.exitCode = 0;
|
||||
try {
|
||||
runMain(() => undefined);
|
||||
await settle();
|
||||
assert.equal(process.exitCode, 0);
|
||||
} finally {
|
||||
process.exitCode = saved || 0;
|
||||
}
|
||||
});
|
||||
|
||||
test('main throws ExitError sets process.exitCode to err.code', async () => {
|
||||
const saved = process.exitCode;
|
||||
try {
|
||||
runMain(() => { throw new ExitError(2); });
|
||||
await settle();
|
||||
assert.equal(process.exitCode, 2);
|
||||
} finally {
|
||||
process.exitCode = saved || 0;
|
||||
}
|
||||
});
|
||||
|
||||
test('main rejects async ExitError(0) sets process.exitCode to 0', async () => {
|
||||
const saved = process.exitCode;
|
||||
try {
|
||||
runMain(async () => { throw new ExitError(0); });
|
||||
await settle();
|
||||
assert.equal(process.exitCode, 0);
|
||||
} finally {
|
||||
process.exitCode = saved !== undefined ? saved : 0;
|
||||
}
|
||||
});
|
||||
|
||||
test('main throws generic Error sets process.exitCode to 1 and writes stderr', async () => {
|
||||
const saved = process.exitCode;
|
||||
const stderrChunks = [];
|
||||
const origWrite = process.stderr.write.bind(process.stderr);
|
||||
process.stderr.write = (chunk, ...args) => {
|
||||
stderrChunks.push(typeof chunk === 'string' ? chunk : chunk.toString());
|
||||
return origWrite(chunk, ...args);
|
||||
};
|
||||
try {
|
||||
runMain(() => { throw new Error('kaboom'); });
|
||||
await settle();
|
||||
assert.equal(process.exitCode, 1);
|
||||
const combined = stderrChunks.join('');
|
||||
assert.ok(combined.includes('kaboom'), `expected "kaboom" in stderr: ${combined}`);
|
||||
} finally {
|
||||
process.stderr.write = origWrite;
|
||||
process.exitCode = saved || 0;
|
||||
}
|
||||
});
|
||||
|
||||
test('ExitError with hasUserMessage and non-zero code writes to stderr', async () => {
|
||||
const saved = process.exitCode;
|
||||
const stderrChunks = [];
|
||||
const origWrite = process.stderr.write.bind(process.stderr);
|
||||
process.stderr.write = (chunk, ...args) => {
|
||||
stderrChunks.push(typeof chunk === 'string' ? chunk : chunk.toString());
|
||||
return origWrite(chunk, ...args);
|
||||
};
|
||||
try {
|
||||
runMain(() => { throw new ExitError(1, 'user-visible error'); });
|
||||
await settle();
|
||||
assert.equal(process.exitCode, 1);
|
||||
const combined = stderrChunks.join('');
|
||||
assert.ok(combined.includes('user-visible error'), `expected message in stderr: ${combined}`);
|
||||
} finally {
|
||||
process.stderr.write = origWrite;
|
||||
process.exitCode = saved || 0;
|
||||
}
|
||||
});
|
||||
|
||||
test('ExitError with hasUserMessage and code 0 does NOT write to stderr', async () => {
|
||||
const saved = process.exitCode;
|
||||
const stderrChunks = [];
|
||||
const origWrite = process.stderr.write.bind(process.stderr);
|
||||
process.stderr.write = (chunk, ...args) => {
|
||||
stderrChunks.push(typeof chunk === 'string' ? chunk : chunk.toString());
|
||||
return origWrite(chunk, ...args);
|
||||
};
|
||||
try {
|
||||
runMain(() => { throw new ExitError(0, 'silent success'); });
|
||||
await settle();
|
||||
assert.equal(process.exitCode, 0);
|
||||
const combined = stderrChunks.join('');
|
||||
assert.equal(combined.includes('silent success'), false,
|
||||
`did not expect message in stderr: ${combined}`);
|
||||
} finally {
|
||||
process.stderr.write = origWrite;
|
||||
process.exitCode = saved !== undefined ? saved : 0;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -30,20 +30,21 @@ const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
const {
|
||||
getDirName,
|
||||
getGlobalDir,
|
||||
getConfigDirFromHome,
|
||||
convertClaudeToCliineMarkdown,
|
||||
install,
|
||||
finishInstall,
|
||||
} = require('../bin/install.js');
|
||||
|
||||
const { getGlobalConfigDir } = require('../gsd-core/bin/lib/runtime-homes.cjs');
|
||||
|
||||
describe('Cline runtime directory mapping', () => {
|
||||
test('getDirName returns .cline for local installs', () => {
|
||||
assert.strictEqual(getDirName('cline'), '.cline');
|
||||
});
|
||||
|
||||
test('getGlobalDir returns ~/.cline for global installs', () => {
|
||||
assert.strictEqual(getGlobalDir('cline'), path.join(os.homedir(), '.cline'));
|
||||
test('getGlobalConfigDir returns ~/.cline for global installs', () => {
|
||||
assert.strictEqual(getGlobalConfigDir('cline'), path.join(os.homedir(), '.cline'));
|
||||
});
|
||||
|
||||
test('getConfigDirFromHome returns .cline fragment', () => {
|
||||
@@ -52,7 +53,7 @@ describe('Cline runtime directory mapping', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('getGlobalDir (Cline)', () => {
|
||||
describe('getGlobalConfigDir (Cline)', () => {
|
||||
let originalClineConfigDir;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -69,30 +70,30 @@ describe('getGlobalDir (Cline)', () => {
|
||||
|
||||
test('returns ~/.cline with no env var or explicit dir', () => {
|
||||
delete process.env.CLINE_CONFIG_DIR;
|
||||
const result = getGlobalDir('cline');
|
||||
const result = getGlobalConfigDir('cline');
|
||||
assert.strictEqual(result, path.join(os.homedir(), '.cline'));
|
||||
});
|
||||
|
||||
test('returns explicit dir when provided', () => {
|
||||
const result = getGlobalDir('cline', '/custom/cline-path');
|
||||
const result = getGlobalConfigDir('cline', '/custom/cline-path');
|
||||
assert.strictEqual(result, '/custom/cline-path');
|
||||
});
|
||||
|
||||
test('respects CLINE_CONFIG_DIR env var', () => {
|
||||
process.env.CLINE_CONFIG_DIR = '~/custom-cline';
|
||||
const result = getGlobalDir('cline');
|
||||
const result = getGlobalConfigDir('cline');
|
||||
assert.strictEqual(result, path.join(os.homedir(), 'custom-cline'));
|
||||
});
|
||||
|
||||
test('explicit dir takes priority over CLINE_CONFIG_DIR', () => {
|
||||
process.env.CLINE_CONFIG_DIR = '~/from-env';
|
||||
const result = getGlobalDir('cline', '/explicit/path');
|
||||
const result = getGlobalConfigDir('cline', '/explicit/path');
|
||||
assert.strictEqual(result, '/explicit/path');
|
||||
});
|
||||
|
||||
test('does not break other runtimes', () => {
|
||||
assert.strictEqual(getGlobalDir('claude'), path.join(os.homedir(), '.claude'));
|
||||
assert.strictEqual(getGlobalDir('codex'), path.join(os.homedir(), '.codex'));
|
||||
assert.strictEqual(getGlobalConfigDir('claude'), path.join(os.homedir(), '.claude'));
|
||||
assert.strictEqual(getGlobalConfigDir('codex'), path.join(os.homedir(), '.codex'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -141,17 +142,19 @@ describe('Cline install (local)', () => {
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('install creates .clinerules file', () => {
|
||||
test('install creates .clinerules directory with gsd.md (#787 directory form)', () => {
|
||||
install(false, 'cline');
|
||||
const clinerules = path.join(tmpDir, '.clinerules');
|
||||
assert.ok(fs.existsSync(clinerules), '.clinerules must exist after cline install');
|
||||
const clinerulesDir = path.join(tmpDir, '.clinerules');
|
||||
assert.ok(fs.existsSync(clinerulesDir), '.clinerules must exist after cline install');
|
||||
assert.ok(fs.statSync(clinerulesDir).isDirectory(), '.clinerules must be a directory (#787)');
|
||||
assert.ok(fs.existsSync(path.join(clinerulesDir, 'gsd.md')), '.clinerules/gsd.md must exist');
|
||||
});
|
||||
|
||||
test('.clinerules contains GSD instructions', () => {
|
||||
test('.clinerules/gsd.md contains GSD instructions', () => {
|
||||
install(false, 'cline');
|
||||
const clinerules = path.join(tmpDir, '.clinerules');
|
||||
const content = fs.readFileSync(clinerules, 'utf8');
|
||||
assert.ok(content.includes('GSD') || content.includes('gsd'), '.clinerules must reference GSD');
|
||||
const ruleFile = path.join(tmpDir, '.clinerules', 'gsd.md');
|
||||
const content = fs.readFileSync(ruleFile, 'utf8');
|
||||
assert.ok(content.includes('GSD') || content.includes('gsd'), '.clinerules/gsd.md must reference GSD');
|
||||
});
|
||||
|
||||
test('install creates gsd-core engine directory', () => {
|
||||
|
||||
@@ -34,12 +34,11 @@ const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
const { spawnSync } = require('node:child_process');
|
||||
|
||||
const { makeFakeClock } = require('./helpers/clock.cjs');
|
||||
const { acquireStateLock, releaseStateLock, readModifyWriteStateMd } = require('../gsd-core/bin/lib/state.cjs');
|
||||
const { withPlanningLock } = require('../gsd-core/bin/lib/planning-workspace.cjs');
|
||||
const { createTempProject, cleanup, runGsdTools, TOOLS_PATH } = require('./helpers.cjs');
|
||||
const { createTempProject, cleanup, runGsdTools } = require('./helpers.cjs');
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 1. Fake-clock proof: acquireStateLock accepts and uses the clock seam
|
||||
@@ -209,10 +208,6 @@ describe('withPlanningLock clock seam', () => {
|
||||
// Clock that advances past lockTimeout on every sleep call so the while
|
||||
// condition trips immediately after the first retry.
|
||||
let nowValue = 0;
|
||||
const clock = {
|
||||
now() { return nowValue; },
|
||||
sleep(ms) { nowValue += ms + 11000; }, // jump past lockTimeout on every sleep
|
||||
};
|
||||
|
||||
// withPlanningLock exits the while loop (timeout), deletes the lock, then
|
||||
// calls runWithHeldLock() which tries writeFileSync with { flag: 'wx' }.
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
* wired into config, templates, and the ship workflow.
|
||||
*/
|
||||
|
||||
const { describe, test, beforeEach, afterEach } = require('node:test');
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
@@ -14,7 +14,6 @@ const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
const {
|
||||
getDirName,
|
||||
getGlobalDir,
|
||||
getConfigDirFromHome,
|
||||
convertClaudeToCodebuddyMarkdown,
|
||||
convertClaudeCommandToCodebuddySkill,
|
||||
@@ -25,6 +24,8 @@ const {
|
||||
installRuntimeArtifacts,
|
||||
} = require('../bin/install.js');
|
||||
|
||||
const { getGlobalConfigDir } = require('../gsd-core/bin/lib/runtime-homes.cjs');
|
||||
|
||||
// ─── Profile resolution for installRuntimeArtifacts tests ────────────────────
|
||||
const _gsdLibDir = path.join(__dirname, '..', 'gsd-core', 'bin', 'lib');
|
||||
const { loadSkillsManifest, resolveProfile } = require(path.join(_gsdLibDir, 'install-profiles.cjs'));
|
||||
@@ -37,7 +38,7 @@ describe('CodeBuddy runtime directory mapping', () => {
|
||||
});
|
||||
|
||||
test('maps CodeBuddy to ~/.codebuddy for global installs', () => {
|
||||
assert.strictEqual(getGlobalDir('codebuddy'), path.join(os.homedir(), '.codebuddy'));
|
||||
assert.strictEqual(getGlobalConfigDir('codebuddy'), path.join(os.homedir(), '.codebuddy'));
|
||||
});
|
||||
|
||||
test('returns .codebuddy config fragments for local and global installs', () => {
|
||||
@@ -46,7 +47,7 @@ describe('CodeBuddy runtime directory mapping', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('getGlobalDir (CodeBuddy)', () => {
|
||||
describe('getGlobalConfigDir (CodeBuddy)', () => {
|
||||
let originalCodebuddyConfigDir;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -63,30 +64,30 @@ describe('getGlobalDir (CodeBuddy)', () => {
|
||||
|
||||
test('returns ~/.codebuddy with no env var or explicit dir', () => {
|
||||
delete process.env.CODEBUDDY_CONFIG_DIR;
|
||||
const result = getGlobalDir('codebuddy');
|
||||
const result = getGlobalConfigDir('codebuddy');
|
||||
assert.strictEqual(result, path.join(os.homedir(), '.codebuddy'));
|
||||
});
|
||||
|
||||
test('returns explicit dir when provided', () => {
|
||||
const result = getGlobalDir('codebuddy', '/custom/codebuddy-path');
|
||||
const result = getGlobalConfigDir('codebuddy', '/custom/codebuddy-path');
|
||||
assert.strictEqual(result, '/custom/codebuddy-path');
|
||||
});
|
||||
|
||||
test('respects CODEBUDDY_CONFIG_DIR env var', () => {
|
||||
process.env.CODEBUDDY_CONFIG_DIR = '~/custom-codebuddy';
|
||||
const result = getGlobalDir('codebuddy');
|
||||
const result = getGlobalConfigDir('codebuddy');
|
||||
assert.strictEqual(result, path.join(os.homedir(), 'custom-codebuddy'));
|
||||
});
|
||||
|
||||
test('explicit dir takes priority over CODEBUDDY_CONFIG_DIR', () => {
|
||||
process.env.CODEBUDDY_CONFIG_DIR = '~/from-env';
|
||||
const result = getGlobalDir('codebuddy', '/explicit/path');
|
||||
const result = getGlobalConfigDir('codebuddy', '/explicit/path');
|
||||
assert.strictEqual(result, '/explicit/path');
|
||||
});
|
||||
|
||||
test('does not break other runtimes', () => {
|
||||
assert.strictEqual(getGlobalDir('claude'), path.join(os.homedir(), '.claude'));
|
||||
assert.strictEqual(getGlobalDir('codex'), path.join(os.homedir(), '.codex'));
|
||||
assert.strictEqual(getGlobalConfigDir('claude'), path.join(os.homedir(), '.claude'));
|
||||
assert.strictEqual(getGlobalConfigDir('codex'), path.join(os.homedir(), '.codex'));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ const path = require('path');
|
||||
const os = require('os');
|
||||
const { execFileSync } = require('child_process');
|
||||
const { cleanup } = require('./helpers.cjs');
|
||||
const jsYaml = require('js-yaml');
|
||||
|
||||
// #2153 follow-up: ensure hooks/dist/ exists before any install integration
|
||||
// test runs. The Codex install path copies hook files from hooks/dist/, which
|
||||
@@ -44,6 +45,8 @@ const {
|
||||
convertClaudeAgentToCodexAgent,
|
||||
convertClaudeCommandToCodexSkill,
|
||||
generateCodexAgentToml,
|
||||
generateCodexSkillMetadataYaml,
|
||||
writeCodexSkillMetadataFiles,
|
||||
generateCodexConfigBlock,
|
||||
stripGsdFromCodexConfig,
|
||||
migrateCodexHooksMapFormat,
|
||||
@@ -401,6 +404,74 @@ tools: Read, Grep, Glob
|
||||
assert.ok(instrIdx !== -1, 'developer_instructions present');
|
||||
assert.ok(modelIdx < instrIdx, 'model field must appear before developer_instructions');
|
||||
});
|
||||
|
||||
// ─── #774: service_tier / model_verbosity for light-tier agents ───────────────
|
||||
|
||||
test('emits service_tier="flex" and model_verbosity="low" for light-tier agents (#774)', () => {
|
||||
// gsd-plan-checker has routingTier:"light" in model-catalog.json
|
||||
const lightAgent = `---
|
||||
name: gsd-plan-checker
|
||||
description: Checks plans quickly
|
||||
tools: Read, Grep
|
||||
---
|
||||
|
||||
<role>You check plans.</role>`;
|
||||
const result = generateCodexAgentToml('gsd-plan-checker', lightAgent);
|
||||
assert.ok(result.includes('service_tier = "flex"'), 'light-tier agent must have service_tier = "flex"');
|
||||
assert.ok(result.includes('model_verbosity = "low"'), 'light-tier agent must have model_verbosity = "low"');
|
||||
});
|
||||
|
||||
test('does not emit service_tier or model_verbosity for standard-tier agents (#774)', () => {
|
||||
// gsd-executor has routingTier:"standard" in model-catalog.json
|
||||
const result = generateCodexAgentToml('gsd-executor', sampleAgent);
|
||||
assert.ok(!result.includes('service_tier'), 'standard-tier agent must not have service_tier');
|
||||
assert.ok(!result.includes('model_verbosity'), 'standard-tier agent must not have model_verbosity');
|
||||
});
|
||||
|
||||
test('does not emit service_tier or model_verbosity for heavy-tier agents (#774)', () => {
|
||||
// gsd-planner has routingTier:"heavy" in model-catalog.json
|
||||
const heavyAgent = `---
|
||||
name: gsd-planner
|
||||
description: Creates plans
|
||||
tools: Read, Write, Edit
|
||||
---
|
||||
|
||||
<role>You plan.</role>`;
|
||||
const result = generateCodexAgentToml('gsd-planner', heavyAgent);
|
||||
assert.ok(!result.includes('service_tier'), 'heavy-tier agent must not have service_tier');
|
||||
assert.ok(!result.includes('model_verbosity'), 'heavy-tier agent must not have model_verbosity');
|
||||
});
|
||||
|
||||
test('service_tier and model_verbosity appear before developer_instructions (#774)', () => {
|
||||
const lightAgent = `---
|
||||
name: gsd-plan-checker
|
||||
description: Checks plans
|
||||
---
|
||||
|
||||
<role>You check plans.</role>`;
|
||||
const result = generateCodexAgentToml('gsd-plan-checker', lightAgent);
|
||||
const stIdx = result.indexOf('service_tier = "flex"');
|
||||
const mvIdx = result.indexOf('model_verbosity = "low"');
|
||||
const instrIdx = result.indexOf("developer_instructions = '''");
|
||||
assert.ok(stIdx !== -1, 'service_tier present');
|
||||
assert.ok(mvIdx !== -1, 'model_verbosity present');
|
||||
assert.ok(instrIdx !== -1, 'developer_instructions present');
|
||||
assert.ok(stIdx < instrIdx, 'service_tier must appear before developer_instructions');
|
||||
assert.ok(mvIdx < instrIdx, 'model_verbosity must appear before developer_instructions');
|
||||
});
|
||||
|
||||
test('emitted TOML is parseable and contains correct field values for light-tier agents (#774)', () => {
|
||||
const lightAgent = `---
|
||||
name: gsd-codebase-mapper
|
||||
description: Maps the codebase
|
||||
---
|
||||
|
||||
<role>You map the codebase.</role>`;
|
||||
const toml = generateCodexAgentToml('gsd-codebase-mapper', lightAgent);
|
||||
const parsed = parseTomlToObject(toml);
|
||||
assert.strictEqual(parsed.service_tier, 'flex', 'service_tier must parse to "flex"');
|
||||
assert.strictEqual(parsed.model_verbosity, 'low', 'model_verbosity must parse to "low"');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── CODEX_AGENT_SANDBOX mapping ────────────────────────────────────────────────
|
||||
@@ -2302,3 +2373,215 @@ describe('Codex uninstall symmetry for hook-enabled configs', () => {
|
||||
assert.strictEqual(countMatches(cleaned, /\[agents\.gsd-/g), 0, 'removes managed GSD agent sections');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── #774: generateCodexSkillMetadataYaml ────────────────────────────────────────
|
||||
|
||||
describe('generateCodexSkillMetadataYaml', () => {
|
||||
test('emits valid parseable YAML with interface section (#774)', () => {
|
||||
const yaml = generateCodexSkillMetadataYaml('gsd-plan-phase', 'Plan and structure the next development phase.');
|
||||
// Must start with interface: and be parseable YAML
|
||||
assert.ok(yaml.startsWith('interface:'), 'must start with interface: key');
|
||||
const parsed = jsYaml.load(yaml);
|
||||
assert.ok(parsed && typeof parsed === 'object', 'must be parseable YAML object');
|
||||
assert.ok(parsed.interface, 'must have interface key');
|
||||
assert.ok('display_name' in parsed.interface, 'must include display_name');
|
||||
assert.ok('short_description' in parsed.interface, 'must include short_description');
|
||||
});
|
||||
|
||||
test('strips gsd- prefix from display_name and converts hyphens to spaces (#774)', () => {
|
||||
const yaml = generateCodexSkillMetadataYaml('gsd-plan-phase', 'Plan and structure the next development phase.');
|
||||
const parsed = jsYaml.load(yaml);
|
||||
assert.strictEqual(parsed.interface.display_name, 'plan phase',
|
||||
'display_name must be "plan phase" (gsd- stripped, hyphens→spaces)');
|
||||
});
|
||||
|
||||
test('embeds the short_description text as decoded string (#774)', () => {
|
||||
const desc = 'Run GSD workflow gsd-test.';
|
||||
const yaml = generateCodexSkillMetadataYaml('gsd-test', desc);
|
||||
const parsed = jsYaml.load(yaml);
|
||||
assert.strictEqual(parsed.interface.short_description, desc,
|
||||
'short_description must round-trip through YAML correctly');
|
||||
});
|
||||
|
||||
test('escapes double-quotes in description so parsed value is correct (#774)', () => {
|
||||
const desc = 'Run "special" workflow.';
|
||||
const yaml = generateCodexSkillMetadataYaml('gsd-test', desc);
|
||||
const parsed = jsYaml.load(yaml);
|
||||
assert.strictEqual(parsed.interface.short_description, desc,
|
||||
'double-quotes in description must round-trip correctly through YAML');
|
||||
});
|
||||
|
||||
test('escapes backslashes in description so parsed value is correct (#774)', () => {
|
||||
const desc = 'Run C:\\path\\to workflow.';
|
||||
const yaml = generateCodexSkillMetadataYaml('gsd-test', desc);
|
||||
const parsed = jsYaml.load(yaml);
|
||||
assert.strictEqual(parsed.interface.short_description, desc,
|
||||
'backslashes in description must round-trip correctly through YAML');
|
||||
});
|
||||
|
||||
test('output ends with a newline (#774)', () => {
|
||||
const yaml = generateCodexSkillMetadataYaml('gsd-test', 'Test skill.');
|
||||
assert.ok(yaml.endsWith('\n'), 'output must end with a newline');
|
||||
});
|
||||
|
||||
test('works for skill without gsd- prefix (#774)', () => {
|
||||
const yaml = generateCodexSkillMetadataYaml('my-skill', 'A custom skill.');
|
||||
const parsed = jsYaml.load(yaml);
|
||||
assert.strictEqual(parsed.interface.display_name, 'my skill',
|
||||
'display_name must convert hyphens to spaces even without gsd- prefix');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── #774: writeCodexSkillMetadataFiles ─────────────────────────────────────────
|
||||
|
||||
describe('writeCodexSkillMetadataFiles', () => {
|
||||
let tmpDir;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-test-skill-meta-'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('writes agents/openai.yaml for each gsd-* skill directory (#774)', () => {
|
||||
// Set up a synthetic skills directory with two gsd-* skill dirs
|
||||
const skills = [
|
||||
{ name: 'gsd-plan-phase', desc: 'Plan and structure the next development phase.' },
|
||||
{ name: 'gsd-execute-phase', desc: 'Execute the current phase.' },
|
||||
];
|
||||
for (const { name, desc } of skills) {
|
||||
const skillDir = path.join(tmpDir, name);
|
||||
fs.mkdirSync(skillDir, { recursive: true });
|
||||
const skillMd = `---\nname: ${name}\ndescription: "${desc}"\nmetadata:\n short-description: "${desc}"\n---\n\nBody text.\n`;
|
||||
fs.writeFileSync(path.join(skillDir, 'SKILL.md'), skillMd);
|
||||
}
|
||||
|
||||
writeCodexSkillMetadataFiles(tmpDir);
|
||||
|
||||
for (const { name, desc } of skills) {
|
||||
const yamlPath = path.join(tmpDir, name, 'agents', 'openai.yaml');
|
||||
assert.ok(fs.existsSync(yamlPath), `agents/openai.yaml must exist for ${name}`);
|
||||
const content = fs.readFileSync(yamlPath, 'utf8');
|
||||
// Verify it's parseable YAML with the correct structure
|
||||
const parsed = jsYaml.load(content);
|
||||
assert.ok(parsed && parsed.interface, `${name}/agents/openai.yaml must parse to object with interface:`);
|
||||
assert.ok('display_name' in parsed.interface, `${name}/agents/openai.yaml must have display_name`);
|
||||
assert.strictEqual(parsed.interface.short_description, desc,
|
||||
`${name}/agents/openai.yaml short_description must match source description`);
|
||||
}
|
||||
});
|
||||
|
||||
test('ignores non-gsd directories (#774)', () => {
|
||||
// Non-gsd-* dir should not get agents/openai.yaml
|
||||
const nonGsdDir = path.join(tmpDir, 'custom-skill');
|
||||
fs.mkdirSync(nonGsdDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(nonGsdDir, 'SKILL.md'), '---\nname: custom\n---\nBody.\n');
|
||||
|
||||
writeCodexSkillMetadataFiles(tmpDir);
|
||||
|
||||
assert.ok(!fs.existsSync(path.join(nonGsdDir, 'agents', 'openai.yaml')),
|
||||
'non-gsd-* dirs must not get agents/openai.yaml');
|
||||
});
|
||||
|
||||
test('does not overwrite user-owned gsd-dev-preferences/agents/openai.yaml (#774)', () => {
|
||||
// gsd-dev-preferences is user-owned and must never be modified by GSD install
|
||||
const userOwnedDir = path.join(tmpDir, 'gsd-dev-preferences');
|
||||
const agentsSubdir = path.join(userOwnedDir, 'agents');
|
||||
fs.mkdirSync(agentsSubdir, { recursive: true });
|
||||
fs.writeFileSync(path.join(userOwnedDir, 'SKILL.md'), '---\nname: gsd-dev-preferences\ndescription: "User pref"\n---\nBody.\n');
|
||||
const userYaml = 'interface:\n display_name: "my preferences"\n short_description: "User-authored"\n';
|
||||
fs.writeFileSync(path.join(agentsSubdir, 'openai.yaml'), userYaml);
|
||||
|
||||
writeCodexSkillMetadataFiles(tmpDir);
|
||||
|
||||
// User-authored file must remain unchanged
|
||||
const after = fs.readFileSync(path.join(agentsSubdir, 'openai.yaml'), 'utf8');
|
||||
assert.strictEqual(after, userYaml, 'user-owned gsd-dev-preferences/agents/openai.yaml must not be overwritten');
|
||||
});
|
||||
|
||||
test('does not create agents/openai.yaml for gsd-dev-preferences if absent (#774)', () => {
|
||||
// Even if gsd-dev-preferences exists without an openai.yaml, we must not create one
|
||||
const userOwnedDir = path.join(tmpDir, 'gsd-dev-preferences');
|
||||
fs.mkdirSync(userOwnedDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(userOwnedDir, 'SKILL.md'), '---\nname: gsd-dev-preferences\n---\nBody.\n');
|
||||
|
||||
writeCodexSkillMetadataFiles(tmpDir);
|
||||
|
||||
assert.ok(!fs.existsSync(path.join(userOwnedDir, 'agents', 'openai.yaml')),
|
||||
'gsd-dev-preferences must not get agents/openai.yaml even if it was absent');
|
||||
});
|
||||
|
||||
test('is a no-op when skillsDir does not exist (#774)', () => {
|
||||
// Should not throw when the directory doesn't exist
|
||||
assert.doesNotThrow(() => {
|
||||
writeCodexSkillMetadataFiles(path.join(tmpDir, 'nonexistent'));
|
||||
}, 'must not throw when skillsDir does not exist');
|
||||
});
|
||||
|
||||
test('skips skill dirs with missing SKILL.md without throwing (#774)', () => {
|
||||
// Create a gsd-* dir with no SKILL.md — should fail open
|
||||
const emptySkillDir = path.join(tmpDir, 'gsd-empty');
|
||||
fs.mkdirSync(emptySkillDir, { recursive: true });
|
||||
|
||||
assert.doesNotThrow(() => {
|
||||
writeCodexSkillMetadataFiles(tmpDir);
|
||||
}, 'must not throw when SKILL.md is missing');
|
||||
});
|
||||
|
||||
test('display_name in agents/openai.yaml has gsd- prefix stripped (#774)', () => {
|
||||
const skillDir = path.join(tmpDir, 'gsd-plan-phase');
|
||||
fs.mkdirSync(skillDir, { recursive: true });
|
||||
const skillMd = `---\nname: gsd-plan-phase\ndescription: "Plan the phase."\nmetadata:\n short-description: "Plan the phase."\n---\n\nBody.\n`;
|
||||
fs.writeFileSync(path.join(skillDir, 'SKILL.md'), skillMd);
|
||||
|
||||
writeCodexSkillMetadataFiles(tmpDir);
|
||||
|
||||
const yamlContent = fs.readFileSync(path.join(tmpDir, 'gsd-plan-phase', 'agents', 'openai.yaml'), 'utf8');
|
||||
const parsed = jsYaml.load(yamlContent);
|
||||
assert.strictEqual(parsed.interface.display_name, 'plan phase',
|
||||
'display_name must have gsd- stripped and hyphens→spaces');
|
||||
});
|
||||
|
||||
test('correctly unescapes YAML-quoted short-description from SKILL.md (#774)', () => {
|
||||
// convertClaudeCommandToCodexSkill emits double-quoted YAML for descriptions.
|
||||
// Verify that escape sequences like \" in the YAML source round-trip to literal " in output.
|
||||
const skillDir = path.join(tmpDir, 'gsd-test-esc');
|
||||
fs.mkdirSync(skillDir, { recursive: true });
|
||||
// SKILL.md has a YAML-escaped double-quote in short-description
|
||||
const skillMd = '---\nname: gsd-test-esc\ndescription: "Normal"\nmetadata:\n short-description: "Run \\"special\\" workflow."\n---\n\nBody.\n';
|
||||
fs.writeFileSync(path.join(skillDir, 'SKILL.md'), skillMd);
|
||||
|
||||
writeCodexSkillMetadataFiles(tmpDir);
|
||||
|
||||
const yamlContent = fs.readFileSync(path.join(tmpDir, 'gsd-test-esc', 'agents', 'openai.yaml'), 'utf8');
|
||||
const parsed = jsYaml.load(yamlContent);
|
||||
assert.strictEqual(parsed.interface.short_description, 'Run "special" workflow.',
|
||||
'YAML-escaped quotes in SKILL.md must round-trip to literal quotes in agents/openai.yaml');
|
||||
});
|
||||
|
||||
test('Codex install emits agents/openai.yaml for each skill (#774)', () => {
|
||||
// Integration test: run a full Codex install and verify agents/openai.yaml is written.
|
||||
// Use runCodexInstall so CODEX_HOME is saved and restored correctly even if it was
|
||||
// already set in the environment before this test ran.
|
||||
const codexHome = path.join(tmpDir, 'codex-home');
|
||||
fs.mkdirSync(codexHome, { recursive: true });
|
||||
runCodexInstall(codexHome);
|
||||
const skillsDir = path.join(codexHome, 'skills');
|
||||
// Assert that the install actually created a skills directory
|
||||
assert.ok(fs.existsSync(skillsDir), 'Codex install must create a skills/ directory');
|
||||
const gsdSkillDirs = fs.readdirSync(skillsDir, { withFileTypes: true })
|
||||
.filter(e => e.isDirectory() && e.name.startsWith('gsd-'));
|
||||
// At least some skills should be present
|
||||
assert.ok(gsdSkillDirs.length > 0, 'install must create at least one gsd-* skill directory');
|
||||
// Each skill directory must have agents/openai.yaml with valid YAML
|
||||
for (const skillEntry of gsdSkillDirs) {
|
||||
const yamlPath = path.join(skillsDir, skillEntry.name, 'agents', 'openai.yaml');
|
||||
assert.ok(fs.existsSync(yamlPath), `${skillEntry.name}/agents/openai.yaml must exist after install`);
|
||||
const content = fs.readFileSync(yamlPath, 'utf8');
|
||||
const parsed = jsYaml.load(content);
|
||||
assert.ok(parsed && parsed.interface, `${skillEntry.name}/agents/openai.yaml must parse to object with interface:`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,7 +20,6 @@ const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
|
||||
|
||||
const { normalizeContent } = require('../gsd-core/bin/lib/shell-command-projection.cjs');
|
||||
@@ -31,13 +30,6 @@ const normalizeMd = (input) => normalizeContent('test.md', input).content;
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
function writeMinimalRoadmap(tmpDir, phases = ['1']) {
|
||||
const lines = phases.map(n => `### Phase ${n}: Phase ${n} Description`).join('\n');
|
||||
fs.writeFileSync(
|
||||
path.join(tmpDir, '.planning', 'ROADMAP.md'),
|
||||
`# Roadmap\n\n${lines}\n`
|
||||
);
|
||||
}
|
||||
|
||||
function writeMinimalStateMd(tmpDir, content) {
|
||||
const defaultContent = content || `# Session State\n\n## Current Position\n\nPhase: 1\n`;
|
||||
@@ -47,22 +39,6 @@ function writeMinimalStateMd(tmpDir, content) {
|
||||
);
|
||||
}
|
||||
|
||||
function writeMinimalProjectMd(tmpDir) {
|
||||
const sections = ['## What This Is', '## Core Value', '## Requirements'];
|
||||
const content = sections.map(s => `${s}\n\nContent here.\n`).join('\n');
|
||||
fs.writeFileSync(
|
||||
path.join(tmpDir, '.planning', 'PROJECT.md'),
|
||||
`# Project\n\n${content}`
|
||||
);
|
||||
}
|
||||
|
||||
function writeValidConfigJson(tmpDir, overrides = {}) {
|
||||
const base = { model_profile: 'balanced', commit_docs: true };
|
||||
fs.writeFileSync(
|
||||
path.join(tmpDir, '.planning', 'config.json'),
|
||||
JSON.stringify({ ...base, ...overrides }, null, 2)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a 50-phase project structure for stress testing.
|
||||
|
||||
@@ -11,7 +11,7 @@ const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
|
||||
const { runGsdTools, createTempProject, cleanup, delay } = require('./helpers.cjs');
|
||||
|
||||
// ─── helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -25,11 +25,7 @@ function writeConfig(tmpDir, obj) {
|
||||
fs.writeFileSync(configPath, JSON.stringify(obj, null, 2), 'utf-8');
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
||||
}
|
||||
|
||||
function runConfigEnsureSectionWithRetry(tmpDir, attempts = 4) {
|
||||
async function runConfigEnsureSectionWithRetry(tmpDir, attempts = 4) {
|
||||
let last;
|
||||
for (let i = 0; i < attempts; i += 1) {
|
||||
last = runGsdTools('config-ensure-section', tmpDir);
|
||||
@@ -38,11 +34,42 @@ function runConfigEnsureSectionWithRetry(tmpDir, attempts = 4) {
|
||||
const detail = `${last.error || ''}\n${last.output || ''}`;
|
||||
const transient = /(EPERM|EBUSY|EACCES|ENOTEMPTY|resource busy|used by another process|permission denied)/i.test(detail);
|
||||
if (!transient || i === attempts - 1) return last;
|
||||
sleep(150 * (i + 1));
|
||||
await delay(150 * (i + 1));
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed `.planning/config.json` for a test and guarantee it lands on disk
|
||||
* before the test body runs.
|
||||
*
|
||||
* `config-ensure-section` is invoked through a spawned `gsd-tools.cjs` child.
|
||||
* On the scoped CI lane (`--test-concurrency=4`, config.test.cjs scheduled
|
||||
* alongside the heavy install/tarball suites) that child can be transiently
|
||||
* killed under resource pressure — surfacing as a non-zero exit with empty
|
||||
* stderr (an OS-level kill, not a gsd-tools application error; see the
|
||||
* `runGsdTools` catch). A bare `runGsdTools('config-ensure-section')` in
|
||||
* `beforeEach` swallows that failure, leaving config.json absent so the first
|
||||
* subtest's `readConfig()` throws a confusing ENOENT (#770 scoped-lane flake).
|
||||
*
|
||||
* This retries on ANY failure or missing file (not just the EPERM/EBUSY class
|
||||
* `runConfigEnsureSectionWithRetry` covers) and throws a clear diagnostic if it
|
||||
* still cannot create the file, so setup is deterministic under load.
|
||||
*/
|
||||
async function ensureConfigReady(tmpDir, attempts = 5) {
|
||||
const configPath = path.join(tmpDir, '.planning', 'config.json');
|
||||
let last;
|
||||
for (let i = 0; i < attempts; i += 1) {
|
||||
last = runGsdTools('config-ensure-section', tmpDir);
|
||||
if (last.success && fs.existsSync(configPath)) return last;
|
||||
if (i < attempts - 1) await delay(150 * (i + 1));
|
||||
}
|
||||
throw new Error(
|
||||
`config-ensure-section failed to create ${configPath} after ${attempts} attempts: ` +
|
||||
`${(last && last.error) || 'unknown error'}`,
|
||||
);
|
||||
}
|
||||
|
||||
// ─── config-ensure-section ───────────────────────────────────────────────────
|
||||
|
||||
describe('config-ensure-section command', () => {
|
||||
@@ -81,13 +108,13 @@ describe('config-ensure-section command', () => {
|
||||
assert.ok('search_gitignored' in config, 'search_gitignored should exist');
|
||||
});
|
||||
|
||||
test('is idempotent — returns already_exists on second call', () => {
|
||||
const first = runConfigEnsureSectionWithRetry(tmpDir);
|
||||
test('is idempotent — returns already_exists on second call', async () => {
|
||||
const first = await runConfigEnsureSectionWithRetry(tmpDir);
|
||||
assert.ok(first.success, `First call failed: ${first.error}`);
|
||||
const firstOutput = JSON.parse(first.output);
|
||||
assert.strictEqual(firstOutput.created, true);
|
||||
|
||||
const second = runConfigEnsureSectionWithRetry(tmpDir);
|
||||
const second = await runConfigEnsureSectionWithRetry(tmpDir);
|
||||
assert.ok(second.success, `Second call failed: ${second.error}`);
|
||||
const secondOutput = JSON.parse(second.output);
|
||||
assert.strictEqual(secondOutput.created, false);
|
||||
@@ -108,6 +135,118 @@ describe('config-ensure-section command', () => {
|
||||
assert.strictEqual(config.brave_search, true);
|
||||
});
|
||||
|
||||
test('detects Tavily Search from env var', () => {
|
||||
const result = runGsdTools('config-ensure-section', tmpDir, { HOME: tmpDir, USERPROFILE: tmpDir, TAVILY_API_KEY: 'test-key' });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.tavily_search, true);
|
||||
});
|
||||
|
||||
test('tavily_search is false when env var absent and no key file', () => {
|
||||
const result = runGsdTools('config-ensure-section', tmpDir, { HOME: tmpDir, USERPROFILE: tmpDir, TAVILY_API_KEY: '' });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.tavily_search, false);
|
||||
});
|
||||
|
||||
test('detects Tavily Search from file-based key', () => {
|
||||
const gsdDir = path.join(tmpDir, '.gsd');
|
||||
fs.mkdirSync(gsdDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(gsdDir, 'tavily_api_key'), 'test-key', 'utf-8');
|
||||
|
||||
const result = runGsdTools('config-ensure-section', tmpDir, { HOME: tmpDir, USERPROFILE: tmpDir, TAVILY_API_KEY: '' });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.tavily_search, true);
|
||||
});
|
||||
|
||||
test('detects Ref Search from env var', () => {
|
||||
const result = runGsdTools('config-ensure-section', tmpDir, { HOME: tmpDir, USERPROFILE: tmpDir, REF_API_KEY: 'test-key' });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.ref_search, true);
|
||||
});
|
||||
|
||||
test('ref_search is false when env var absent and no key file', () => {
|
||||
const result = runGsdTools('config-ensure-section', tmpDir, { HOME: tmpDir, USERPROFILE: tmpDir, REF_API_KEY: '' });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.ref_search, false);
|
||||
});
|
||||
|
||||
test('detects Ref Search from file-based key', () => {
|
||||
const gsdDir = path.join(tmpDir, '.gsd');
|
||||
fs.mkdirSync(gsdDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(gsdDir, 'ref_api_key'), 'test-key', 'utf-8');
|
||||
|
||||
const result = runGsdTools('config-ensure-section', tmpDir, { HOME: tmpDir, USERPROFILE: tmpDir, REF_API_KEY: '' });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.ref_search, true);
|
||||
});
|
||||
|
||||
test('detects Perplexity from env var', () => {
|
||||
const result = runGsdTools('config-ensure-section', tmpDir, { HOME: tmpDir, USERPROFILE: tmpDir, PERPLEXITY_API_KEY: 'test-key' });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.perplexity, true);
|
||||
});
|
||||
|
||||
test('perplexity is false when env var absent and no key file', () => {
|
||||
const result = runGsdTools('config-ensure-section', tmpDir, { HOME: tmpDir, USERPROFILE: tmpDir, PERPLEXITY_API_KEY: '' });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.perplexity, false);
|
||||
});
|
||||
|
||||
test('detects Perplexity from file-based key', () => {
|
||||
const gsdDir = path.join(tmpDir, '.gsd');
|
||||
fs.mkdirSync(gsdDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(gsdDir, 'perplexity_api_key'), 'test-key', 'utf-8');
|
||||
|
||||
const result = runGsdTools('config-ensure-section', tmpDir, { HOME: tmpDir, USERPROFILE: tmpDir, PERPLEXITY_API_KEY: '' });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.perplexity, true);
|
||||
});
|
||||
|
||||
test('detects Jina from env var', () => {
|
||||
const result = runGsdTools('config-ensure-section', tmpDir, { HOME: tmpDir, USERPROFILE: tmpDir, JINA_API_KEY: 'test-key' });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.jina, true);
|
||||
});
|
||||
|
||||
test('jina is false when env var absent and no key file', () => {
|
||||
const result = runGsdTools('config-ensure-section', tmpDir, { HOME: tmpDir, USERPROFILE: tmpDir, JINA_API_KEY: '' });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.jina, false);
|
||||
});
|
||||
|
||||
test('detects Jina from file-based key', () => {
|
||||
const gsdDir = path.join(tmpDir, '.gsd');
|
||||
fs.mkdirSync(gsdDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(gsdDir, 'jina_api_key'), 'test-key', 'utf-8');
|
||||
|
||||
const result = runGsdTools('config-ensure-section', tmpDir, { HOME: tmpDir, USERPROFILE: tmpDir, JINA_API_KEY: '' });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.jina, true);
|
||||
});
|
||||
|
||||
test('merges user defaults from defaults.json', () => {
|
||||
// runGsdTools sandboxes HOME=tmpDir, so defaults.json is written there —
|
||||
// no real filesystem side effects, cleanup happens via afterEach.
|
||||
@@ -993,6 +1132,188 @@ describe('config-path command (#2282)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ─── config-set prototype-pollution guard (#663) ─────────────────────────────
|
||||
|
||||
describe('config-set prototype-pollution guard (#663)', () => {
|
||||
let tmpDir;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = createTempProject();
|
||||
// Initialise config so there is a config.json to write to. Retry + assert
|
||||
// so a transient config-ensure-section child failure under scoped-lane load
|
||||
// cannot leave config.json absent (#770).
|
||||
await ensureConfigReady(tmpDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('rejects __proto__ key segment and does not pollute Object.prototype', () => {
|
||||
const result = runGsdTools('config-set __proto__.polluted true', tmpDir);
|
||||
|
||||
assert.strictEqual(result.success, false, `Expected failure but got: ${result.output}`);
|
||||
|
||||
// No prototype pollution.
|
||||
assert.strictEqual(({}).polluted, undefined, '__proto__ pollution: {}.polluted should be undefined');
|
||||
assert.strictEqual(Object.prototype.polluted, undefined, '__proto__ pollution: Object.prototype.polluted should be undefined');
|
||||
|
||||
// Confirm .planning/config.json does not have a 'polluted' property at any level.
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(Object.prototype.hasOwnProperty.call(config, 'polluted'), false,
|
||||
'config.json root must not gain a "polluted" key');
|
||||
});
|
||||
|
||||
test('rejects constructor.prototype key and does not pollute Object.prototype', () => {
|
||||
const result = runGsdTools('config-set constructor.prototype.polluted2 true', tmpDir);
|
||||
|
||||
assert.strictEqual(result.success, false, `Expected failure but got: ${result.output}`);
|
||||
|
||||
assert.strictEqual(({}).polluted2, undefined, 'constructor chain pollution: {}.polluted2 should be undefined');
|
||||
assert.strictEqual(Object.prototype.polluted2, undefined,
|
||||
'constructor chain pollution: Object.prototype.polluted2 should be undefined');
|
||||
});
|
||||
|
||||
test('rejects bare prototype key segment', () => {
|
||||
const result = runGsdTools('config-set prototype.x true', tmpDir);
|
||||
|
||||
assert.strictEqual(result.success, false, `Expected failure but got: ${result.output}`);
|
||||
assert.strictEqual(Object.prototype.x, undefined, 'prototype.x should not leak onto Object.prototype');
|
||||
});
|
||||
|
||||
test('positive control: legitimate nested key workflow.research succeeds', () => {
|
||||
const result = runGsdTools('config-set workflow.research true', tmpDir);
|
||||
|
||||
assert.ok(result.success, `Legitimate key rejected unexpectedly: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.workflow.research, true, 'workflow.research should be written to config.json');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── config-set prototype-pollution guard via dynamic-key prefixes (alert #26) ─
|
||||
|
||||
describe('config-set prototype-pollution guard via dynamic-key prefixes (alert #26)', () => {
|
||||
let tmpDir;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = createTempProject();
|
||||
// Initialise config so there is a config.json to write to. Retry + assert
|
||||
// so a transient config-ensure-section child failure under scoped-lane load
|
||||
// cannot leave config.json absent (#770).
|
||||
await ensureConfigReady(tmpDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('agent_skills.__proto__ is blocked by setConfigValue guard (not schema gate)', () => {
|
||||
const result = runGsdTools('config-set agent_skills.__proto__ somevalue', tmpDir);
|
||||
|
||||
assert.strictEqual(result.success, false, `Expected failure but got: ${result.output}`);
|
||||
|
||||
// Must be the pollution guard, not the schema gate.
|
||||
assert.ok(
|
||||
result.error.includes('prototype pollution guard'),
|
||||
`Expected "prototype pollution guard" in error, got: ${result.error}`,
|
||||
);
|
||||
// No schema-gate message.
|
||||
assert.ok(
|
||||
!result.error.includes('Unknown config key'),
|
||||
`Should not hit schema gate, got: ${result.error}`,
|
||||
);
|
||||
|
||||
// No prototype pollution occurred.
|
||||
assert.strictEqual(({}).somevalue, undefined, 'agent_skills.__proto__: {}.somevalue should be undefined');
|
||||
assert.strictEqual(Object.prototype.hasOwnProperty.call(Object.prototype, 'somevalue'), false,
|
||||
'agent_skills.__proto__: Object.prototype should not gain "somevalue"');
|
||||
});
|
||||
|
||||
test('agent_skills.constructor is blocked by setConfigValue guard (not schema gate)', () => {
|
||||
const result = runGsdTools('config-set agent_skills.constructor somevalue', tmpDir);
|
||||
|
||||
assert.strictEqual(result.success, false, `Expected failure but got: ${result.output}`);
|
||||
|
||||
assert.ok(
|
||||
result.error.includes('prototype pollution guard'),
|
||||
`Expected "prototype pollution guard" in error, got: ${result.error}`,
|
||||
);
|
||||
assert.ok(
|
||||
!result.error.includes('Unknown config key'),
|
||||
`Should not hit schema gate, got: ${result.error}`,
|
||||
);
|
||||
|
||||
assert.strictEqual(Object.prototype.hasOwnProperty.call(Object.prototype, 'somevalue'), false,
|
||||
'agent_skills.constructor: Object.prototype should not gain "somevalue"');
|
||||
});
|
||||
|
||||
test('agent_skills.prototype is blocked by setConfigValue guard (not schema gate)', () => {
|
||||
const result = runGsdTools('config-set agent_skills.prototype somevalue', tmpDir);
|
||||
|
||||
assert.strictEqual(result.success, false, `Expected failure but got: ${result.output}`);
|
||||
|
||||
assert.ok(
|
||||
result.error.includes('prototype pollution guard'),
|
||||
`Expected "prototype pollution guard" in error, got: ${result.error}`,
|
||||
);
|
||||
assert.ok(
|
||||
!result.error.includes('Unknown config key'),
|
||||
`Should not hit schema gate, got: ${result.error}`,
|
||||
);
|
||||
|
||||
assert.strictEqual(Object.prototype.hasOwnProperty.call(Object.prototype, 'somevalue'), false,
|
||||
'agent_skills.prototype: Object.prototype should not gain "somevalue"');
|
||||
});
|
||||
|
||||
test('features.__proto__ is blocked by setConfigValue guard (not schema gate)', () => {
|
||||
const result = runGsdTools('config-set features.__proto__ somevalue', tmpDir);
|
||||
|
||||
assert.strictEqual(result.success, false, `Expected failure but got: ${result.output}`);
|
||||
|
||||
assert.ok(
|
||||
result.error.includes('prototype pollution guard'),
|
||||
`Expected "prototype pollution guard" in error, got: ${result.error}`,
|
||||
);
|
||||
assert.ok(
|
||||
!result.error.includes('Unknown config key'),
|
||||
`Should not hit schema gate, got: ${result.error}`,
|
||||
);
|
||||
|
||||
assert.strictEqual(({}).somevalue, undefined, 'features.__proto__: {}.somevalue should be undefined');
|
||||
assert.strictEqual(Object.prototype.hasOwnProperty.call(Object.prototype, 'somevalue'), false,
|
||||
'features.__proto__: Object.prototype should not gain "somevalue"');
|
||||
});
|
||||
|
||||
test('review.models.constructor is blocked by setConfigValue guard (not schema gate)', () => {
|
||||
const result = runGsdTools('config-set review.models.constructor somevalue', tmpDir);
|
||||
|
||||
assert.strictEqual(result.success, false, `Expected failure but got: ${result.output}`);
|
||||
|
||||
assert.ok(
|
||||
result.error.includes('prototype pollution guard'),
|
||||
`Expected "prototype pollution guard" in error, got: ${result.error}`,
|
||||
);
|
||||
assert.ok(
|
||||
!result.error.includes('Unknown config key'),
|
||||
`Should not hit schema gate, got: ${result.error}`,
|
||||
);
|
||||
|
||||
assert.strictEqual(Object.prototype.hasOwnProperty.call(Object.prototype, 'somevalue'), false,
|
||||
'review.models.constructor: Object.prototype should not gain "somevalue"');
|
||||
});
|
||||
|
||||
test('positive control: agent_skills.sonnet-coder with valid value succeeds', () => {
|
||||
const result = runGsdTools('config-set agent_skills.sonnet-coder true', tmpDir);
|
||||
|
||||
assert.ok(result.success, `Legitimate agent_skills key rejected unexpectedly: ${result.error}`);
|
||||
|
||||
const config = readConfig(tmpDir);
|
||||
assert.strictEqual(config.agent_skills['sonnet-coder'], true,
|
||||
'agent_skills.sonnet-coder should be written to config.json');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── plan_review.source_grounding + _authority (#22) ─────────────────────────
|
||||
|
||||
describe('plan_review.source_grounding and plan_review.source_grounding_authority (#22)', () => {
|
||||
|
||||
@@ -28,7 +28,6 @@ const { parseFrontmatter, createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
const {
|
||||
getDirName,
|
||||
getGlobalDir,
|
||||
getConfigDirFromHome,
|
||||
claudeToCopilotTools,
|
||||
convertCopilotToolName,
|
||||
@@ -39,6 +38,9 @@ const {
|
||||
GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER,
|
||||
mergeCopilotInstructions,
|
||||
stripGsdFromCopilotInstructions,
|
||||
GSD_COPILOT_HOOK_FILE,
|
||||
buildCopilotHookConfig,
|
||||
writeCopilotHookConfig,
|
||||
writeManifest,
|
||||
reportLocalPatches,
|
||||
installRuntimeArtifacts,
|
||||
@@ -48,6 +50,8 @@ const {
|
||||
buildRuntimePromptText,
|
||||
} = require('../bin/install.js');
|
||||
|
||||
const { getGlobalConfigDir } = require('../gsd-core/bin/lib/runtime-homes.cjs');
|
||||
|
||||
// ─── Profile resolution for installRuntimeArtifacts tests ────────────────────
|
||||
const _gsdLibDir = path.join(__dirname, '..', 'gsd-core', 'bin', 'lib');
|
||||
const { loadSkillsManifest, resolveProfile } = require(path.join(_gsdLibDir, 'install-profiles.cjs'));
|
||||
@@ -70,13 +74,15 @@ describe('getDirName (Copilot)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ─── getGlobalDir ───────────────────────────────────────────────────────────────
|
||||
// ─── getGlobalConfigDir ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('getGlobalDir (Copilot)', () => {
|
||||
describe('getGlobalConfigDir (Copilot)', () => {
|
||||
let originalCopilotConfigDir;
|
||||
let originalCopilotHome;
|
||||
|
||||
beforeEach(() => {
|
||||
originalCopilotConfigDir = process.env.COPILOT_CONFIG_DIR;
|
||||
originalCopilotHome = process.env.COPILOT_HOME;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -85,34 +91,68 @@ describe('getGlobalDir (Copilot)', () => {
|
||||
} else {
|
||||
delete process.env.COPILOT_CONFIG_DIR;
|
||||
}
|
||||
if (originalCopilotHome !== undefined) {
|
||||
process.env.COPILOT_HOME = originalCopilotHome;
|
||||
} else {
|
||||
delete process.env.COPILOT_HOME;
|
||||
}
|
||||
});
|
||||
|
||||
test('returns ~/.copilot with no env var or explicit dir', () => {
|
||||
delete process.env.COPILOT_CONFIG_DIR;
|
||||
const result = getGlobalDir('copilot');
|
||||
delete process.env.COPILOT_HOME;
|
||||
const result = getGlobalConfigDir('copilot');
|
||||
assert.strictEqual(result, path.join(os.homedir(), '.copilot'));
|
||||
});
|
||||
|
||||
test('returns explicit dir when provided', () => {
|
||||
const result = getGlobalDir('copilot', '/custom/path');
|
||||
const result = getGlobalConfigDir('copilot', '/custom/path');
|
||||
assert.strictEqual(result, '/custom/path');
|
||||
});
|
||||
|
||||
test('respects COPILOT_CONFIG_DIR env var', () => {
|
||||
process.env.COPILOT_CONFIG_DIR = '~/custom-copilot';
|
||||
const result = getGlobalDir('copilot');
|
||||
const result = getGlobalConfigDir('copilot');
|
||||
assert.strictEqual(result, path.join(os.homedir(), 'custom-copilot'));
|
||||
});
|
||||
|
||||
test('explicit dir takes priority over COPILOT_CONFIG_DIR', () => {
|
||||
process.env.COPILOT_CONFIG_DIR = '~/env-path';
|
||||
const result = getGlobalDir('copilot', '/explicit/path');
|
||||
const result = getGlobalConfigDir('copilot', '/explicit/path');
|
||||
assert.strictEqual(result, '/explicit/path');
|
||||
});
|
||||
|
||||
test('respects COPILOT_HOME env var', () => {
|
||||
delete process.env.COPILOT_CONFIG_DIR;
|
||||
process.env.COPILOT_HOME = '/custom/copilot-home';
|
||||
const result = getGlobalConfigDir('copilot');
|
||||
assert.strictEqual(result, '/custom/copilot-home');
|
||||
});
|
||||
|
||||
test('COPILOT_HOME supports tilde expansion', () => {
|
||||
delete process.env.COPILOT_CONFIG_DIR;
|
||||
process.env.COPILOT_HOME = '~/my-copilot';
|
||||
const result = getGlobalConfigDir('copilot');
|
||||
assert.strictEqual(result, path.join(os.homedir(), 'my-copilot'));
|
||||
});
|
||||
|
||||
test('COPILOT_CONFIG_DIR takes priority over COPILOT_HOME', () => {
|
||||
process.env.COPILOT_CONFIG_DIR = '/config-dir-path';
|
||||
process.env.COPILOT_HOME = '/home-path';
|
||||
const result = getGlobalConfigDir('copilot');
|
||||
assert.strictEqual(result, '/config-dir-path');
|
||||
});
|
||||
|
||||
test('explicit dir takes priority over COPILOT_HOME', () => {
|
||||
delete process.env.COPILOT_CONFIG_DIR;
|
||||
process.env.COPILOT_HOME = '/home-path';
|
||||
const result = getGlobalConfigDir('copilot', '/explicit/path');
|
||||
assert.strictEqual(result, '/explicit/path');
|
||||
});
|
||||
|
||||
test('does not break existing runtimes', () => {
|
||||
assert.strictEqual(getGlobalDir('claude'), path.join(os.homedir(), '.claude'));
|
||||
assert.strictEqual(getGlobalDir('codex'), path.join(os.homedir(), '.codex'));
|
||||
assert.strictEqual(getGlobalConfigDir('claude'), path.join(os.homedir(), '.claude'));
|
||||
assert.strictEqual(getGlobalConfigDir('codex'), path.join(os.homedir(), '.codex'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -272,6 +312,36 @@ describe('convertCopilotToolName', () => {
|
||||
test('mapping constant has 13 entries (12 direct + mcp handled separately)', () => {
|
||||
assert.strictEqual(Object.keys(claudeToCopilotTools).length, 12);
|
||||
});
|
||||
|
||||
// Regression: mcp__tavily/ref/jina use the same generic passthrough as exa/firecrawl (#657)
|
||||
// No explicit io.github.* registry ID is known for these providers; they lower-case passthrough.
|
||||
const genericMcpCases = [
|
||||
['mcp__exa__*', 'mcp__exa__*'],
|
||||
['mcp__firecrawl__*', 'mcp__firecrawl__*'],
|
||||
['mcp__tavily__*', 'mcp__tavily__*'],
|
||||
['mcp__ref__*', 'mcp__ref__*'],
|
||||
['mcp__jina__*', 'mcp__jina__*'],
|
||||
['mcp__exa__web_search_exa', 'mcp__exa__web_search_exa'],
|
||||
['mcp__firecrawl__scrape', 'mcp__firecrawl__scrape'],
|
||||
['mcp__tavily__search', 'mcp__tavily__search'],
|
||||
['mcp__ref__get', 'mcp__ref__get'],
|
||||
['mcp__jina__read_url', 'mcp__jina__read_url'],
|
||||
];
|
||||
|
||||
for (const [input, expected] of genericMcpCases) {
|
||||
test(`generic MCP passthrough: ${input} → ${expected}`, () => {
|
||||
assert.strictEqual(convertCopilotToolName(input), expected);
|
||||
});
|
||||
}
|
||||
|
||||
test('mcp__context7__* still gets the explicit io.github.upstash mapping (not generic passthrough)', () => {
|
||||
// Confirm the context7 special-case is NOT affected by the generic path
|
||||
assert.strictEqual(convertCopilotToolName('mcp__context7__*'), 'io.github.upstash/context7/*');
|
||||
assert.strictEqual(
|
||||
convertCopilotToolName('mcp__context7__resolve-library-id'),
|
||||
'io.github.upstash/context7/resolve-library-id'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── convertClaudeToCopilotContent ──────────────────────────────────────────────
|
||||
@@ -861,8 +931,6 @@ describe('Copilot content conversion - engine files', () => {
|
||||
// ─── Copilot instructions merge/strip ──────────────────────────────────────────
|
||||
|
||||
describe('Copilot instructions merge/strip', () => {
|
||||
let tmpDir;
|
||||
|
||||
const gsdContent = '- Follow project conventions\n- Use structured workflows';
|
||||
|
||||
function makeGsdBlock(content) {
|
||||
@@ -1011,6 +1079,112 @@ describe('Copilot instructions merge/strip', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Copilot lifecycle hooks (#786) ────────────────────────────────────────────
|
||||
|
||||
describe('Copilot lifecycle hook config (#786)', () => {
|
||||
describe('buildCopilotHookConfig', () => {
|
||||
test('emits the documented Copilot hooks-config shape', () => {
|
||||
const cfg = buildCopilotHookConfig();
|
||||
assert.strictEqual(cfg.version, 1, 'version must be 1 per Copilot hooks schema');
|
||||
assert.ok(cfg.hooks && typeof cfg.hooks === 'object', 'has hooks object');
|
||||
assert.ok(Array.isArray(cfg.hooks.sessionStart), 'sessionStart is an array (camelCase event name)');
|
||||
assert.strictEqual(cfg.hooks.sessionStart.length, 1, 'one sessionStart entry');
|
||||
});
|
||||
|
||||
test('sessionStart entry is a self-contained inline command hook', () => {
|
||||
const [entry] = buildCopilotHookConfig().hooks.sessionStart;
|
||||
assert.strictEqual(entry.type, 'command', 'type is command');
|
||||
assert.ok(typeof entry.bash === 'string' && entry.bash.length > 0, 'has inline bash body');
|
||||
assert.ok(typeof entry.powershell === 'string' && entry.powershell.length > 0, 'has inline powershell body');
|
||||
assert.strictEqual(entry.timeoutSec, 10, 'uses timeoutSec (Copilot field), not timeout');
|
||||
});
|
||||
|
||||
test('command bodies emit the Copilot sessionStart JSON envelope (additionalContext)', () => {
|
||||
// Copilot parses command-hook stdout as JSON; sessionStart schema is
|
||||
// { additionalContext?: string }. Bare text would be invalid hook output.
|
||||
const [entry] = buildCopilotHookConfig().hooks.sessionStart;
|
||||
assert.ok(entry.bash.includes('"additionalContext"'), 'bash body emits additionalContext JSON');
|
||||
assert.ok(entry.powershell.includes('"additionalContext"'), 'powershell body emits additionalContext JSON');
|
||||
});
|
||||
|
||||
test('executing the bash hook body produces valid sessionStart JSON', { skip: process.platform === 'win32' }, () => {
|
||||
const { execFileSync } = require('child_process');
|
||||
const [entry] = buildCopilotHookConfig().hooks.sessionStart;
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-hook-exec-'));
|
||||
try {
|
||||
// No .planning/STATE.md → absent branch
|
||||
const outAbsent = execFileSync('bash', ['-c', entry.bash], { cwd: tmp, encoding: 'utf8' });
|
||||
const parsedAbsent = JSON.parse(outAbsent);
|
||||
assert.ok(typeof parsedAbsent.additionalContext === 'string', 'absent branch yields additionalContext string');
|
||||
assert.ok(/gsd-new-project/.test(parsedAbsent.additionalContext), 'absent branch suggests gsd-new-project');
|
||||
|
||||
// With .planning/STATE.md → present branch
|
||||
fs.mkdirSync(path.join(tmp, '.planning'), { recursive: true });
|
||||
fs.writeFileSync(path.join(tmp, '.planning', 'STATE.md'), '# state\n');
|
||||
const outPresent = execFileSync('bash', ['-c', entry.bash], { cwd: tmp, encoding: 'utf8' });
|
||||
const parsedPresent = JSON.parse(outPresent);
|
||||
assert.ok(/STATE\.md present/.test(parsedPresent.additionalContext), 'present branch references STATE.md');
|
||||
} finally {
|
||||
cleanup(tmp);
|
||||
}
|
||||
});
|
||||
|
||||
test('hook command references no external script path (cannot dangle)', () => {
|
||||
const [entry] = buildCopilotHookConfig().hooks.sessionStart;
|
||||
// A dangling hook points at a hook SCRIPT file the installer never wrote.
|
||||
// The GSD Copilot hook is inline, so it must not reference hooks/gsd-*.js|sh.
|
||||
assert.ok(!/hooks\/gsd-[\w-]+\.(js|cjs|sh)/.test(entry.bash), 'bash body references no gsd hook script file');
|
||||
assert.ok(!/hooks\/gsd-[\w-]+\.(js|cjs|sh)/.test(entry.powershell), 'powershell body references no gsd hook script file');
|
||||
});
|
||||
|
||||
test('produces valid JSON', () => {
|
||||
const json = JSON.stringify(buildCopilotHookConfig());
|
||||
assert.doesNotThrow(() => JSON.parse(json), 'config round-trips through JSON');
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeCopilotHookConfig', () => {
|
||||
let tmpHookDir;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpHookDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-copilot-hook-'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpHookDir);
|
||||
});
|
||||
|
||||
test('writes hooks/gsd-session.json under the config dir', () => {
|
||||
const written = writeCopilotHookConfig(tmpHookDir);
|
||||
const expected = path.join(tmpHookDir, 'hooks', GSD_COPILOT_HOOK_FILE);
|
||||
assert.strictEqual(written, expected, 'returns the written path');
|
||||
assert.ok(fs.existsSync(expected), 'hook config file exists');
|
||||
const parsed = JSON.parse(fs.readFileSync(expected, 'utf8'));
|
||||
assert.strictEqual(parsed.version, 1, 'written file has version 1');
|
||||
assert.ok(Array.isArray(parsed.hooks.sessionStart), 'written file has sessionStart array');
|
||||
});
|
||||
|
||||
test('is idempotent and overwrites the managed file in place', () => {
|
||||
writeCopilotHookConfig(tmpHookDir);
|
||||
const hookPath = path.join(tmpHookDir, 'hooks', GSD_COPILOT_HOOK_FILE);
|
||||
fs.writeFileSync(hookPath, '{"stale":true}\n');
|
||||
writeCopilotHookConfig(tmpHookDir);
|
||||
const parsed = JSON.parse(fs.readFileSync(hookPath, 'utf8'));
|
||||
assert.strictEqual(parsed.stale, undefined, 'stale content replaced');
|
||||
assert.strictEqual(parsed.version, 1, 'managed content restored');
|
||||
});
|
||||
|
||||
test('preserves sibling user-authored hook files', () => {
|
||||
const hooksDir = path.join(tmpHookDir, 'hooks');
|
||||
fs.mkdirSync(hooksDir, { recursive: true });
|
||||
const userHook = path.join(hooksDir, 'my-hook.json');
|
||||
fs.writeFileSync(userHook, '{"version":1,"hooks":{}}\n');
|
||||
writeCopilotHookConfig(tmpHookDir);
|
||||
assert.ok(fs.existsSync(userHook), 'user hook file untouched');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Copilot uninstall skill removal ───────────────────────────────────────────
|
||||
|
||||
describe('Copilot uninstall skill removal', () => {
|
||||
@@ -1097,7 +1271,7 @@ describe('Copilot manifest and patches fixes', () => {
|
||||
fs.mkdirSync(skillDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(skillDir, 'SKILL.md'), '# Test Skill\n\nA test skill.');
|
||||
|
||||
const manifest = writeManifest(tmpDir, 'copilot');
|
||||
writeManifest(tmpDir, 'copilot');
|
||||
|
||||
// Check manifest file was written
|
||||
const manifestPath = path.join(tmpDir, 'gsd-file-manifest.json');
|
||||
@@ -1292,6 +1466,23 @@ describe('E2E: Copilot full install verification', () => {
|
||||
'Should contain GSD Configuration close marker');
|
||||
});
|
||||
|
||||
test('emits AGENTS.md at the repo root with GSD markers (#786)', () => {
|
||||
const agentsMdPath = path.join(tmpDir, 'AGENTS.md');
|
||||
assert.ok(fs.existsSync(agentsMdPath), 'AGENTS.md should exist at repo root for local install');
|
||||
const content = fs.readFileSync(agentsMdPath, 'utf-8');
|
||||
assert.ok(content.includes('<!-- GSD Configuration'), 'AGENTS.md has GSD open marker');
|
||||
assert.ok(content.includes('<!-- /GSD Configuration -->'), 'AGENTS.md has GSD close marker');
|
||||
});
|
||||
|
||||
test('emits a Copilot lifecycle hook config (#786)', () => {
|
||||
const hookPath = path.join(tmpDir, '.github', 'hooks', 'gsd-session.json');
|
||||
assert.ok(fs.existsSync(hookPath), '.github/hooks/gsd-session.json should exist');
|
||||
const cfg = JSON.parse(fs.readFileSync(hookPath, 'utf-8'));
|
||||
assert.strictEqual(cfg.version, 1, 'hook config has version 1');
|
||||
assert.ok(Array.isArray(cfg.hooks.sessionStart), 'hook config has sessionStart array');
|
||||
assert.strictEqual(cfg.hooks.sessionStart[0].type, 'command', 'sessionStart is a command hook');
|
||||
});
|
||||
|
||||
test('creates manifest with correct structure', () => {
|
||||
const manifestPath = path.join(tmpDir, '.github', 'gsd-file-manifest.json');
|
||||
assert.ok(fs.existsSync(manifestPath), 'gsd-file-manifest.json should exist');
|
||||
@@ -1400,6 +1591,16 @@ describe('E2E: Copilot uninstall verification', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('removes the Copilot lifecycle hook config (#786)', () => {
|
||||
const hookPath = path.join(tmpDir, '.github', 'hooks', 'gsd-session.json');
|
||||
assert.ok(!fs.existsSync(hookPath), 'gsd-session.json should not exist after uninstall');
|
||||
});
|
||||
|
||||
test('removes GSD-only AGENTS.md (#786)', () => {
|
||||
const agentsMdPath = path.join(tmpDir, 'AGENTS.md');
|
||||
assert.ok(!fs.existsSync(agentsMdPath), 'GSD-only AGENTS.md should be removed after uninstall');
|
||||
});
|
||||
|
||||
describe('preserves non-GSD content', () => {
|
||||
let td;
|
||||
|
||||
@@ -1434,6 +1635,90 @@ describe('E2E: Copilot uninstall verification', () => {
|
||||
assert.ok(fs.existsSync(customAgentPath),
|
||||
'Non-GSD agent file should be preserved after uninstall');
|
||||
});
|
||||
|
||||
test('preserves user-authored content in AGENTS.md on uninstall (#786)', () => {
|
||||
// After install, AGENTS.md exists with the GSD block. Prepend user content.
|
||||
const agentsMdPath = path.join(td, 'AGENTS.md');
|
||||
assert.ok(fs.existsSync(agentsMdPath), 'AGENTS.md created by install');
|
||||
const gsdBlock = fs.readFileSync(agentsMdPath, 'utf-8');
|
||||
fs.writeFileSync(agentsMdPath, '# My Project Notes\n\nKeep these.\n\n' + gsdBlock);
|
||||
// Uninstall strips only the GSD section
|
||||
runCopilotUninstall(td);
|
||||
assert.ok(fs.existsSync(agentsMdPath), 'AGENTS.md preserved (had user content)');
|
||||
const after = fs.readFileSync(agentsMdPath, 'utf-8');
|
||||
assert.ok(after.includes('# My Project Notes'), 'user content preserved');
|
||||
assert.ok(!after.includes('<!-- GSD Configuration'), 'GSD section stripped');
|
||||
});
|
||||
|
||||
test('preserves a user-authored sibling hook file on uninstall (#786)', () => {
|
||||
const userHook = path.join(td, '.github', 'hooks', 'user-hook.json');
|
||||
fs.writeFileSync(userHook, '{"version":1,"hooks":{}}\n');
|
||||
runCopilotUninstall(td);
|
||||
assert.ok(fs.existsSync(userHook), 'user-authored hook file preserved');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ─── E2E: Copilot global scope (#786) ──────────────────────────────────────────
|
||||
|
||||
function runCopilotInstallGlobal(cwd, configDir) {
|
||||
const env = { ...process.env };
|
||||
delete env.GSD_TEST_MODE;
|
||||
return execFileSync(process.execPath,
|
||||
[INSTALL_PATH, '--copilot', '--global', '--config-dir', configDir, '--no-sdk'], {
|
||||
cwd,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
env,
|
||||
});
|
||||
}
|
||||
|
||||
function runCopilotUninstallGlobal(cwd, configDir) {
|
||||
const env = { ...process.env };
|
||||
delete env.GSD_TEST_MODE;
|
||||
return execFileSync(process.execPath,
|
||||
[INSTALL_PATH, '--copilot', '--global', '--config-dir', configDir, '--uninstall', '--no-sdk'], {
|
||||
cwd,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
env,
|
||||
});
|
||||
}
|
||||
|
||||
describe('E2E: Copilot global install (#786)', () => {
|
||||
let projectDir;
|
||||
let configDir;
|
||||
|
||||
beforeEach(() => {
|
||||
projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-e2e-gproj-'));
|
||||
configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-e2e-gcfg-'));
|
||||
runCopilotInstallGlobal(projectDir, configDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(projectDir);
|
||||
cleanup(configDir);
|
||||
});
|
||||
|
||||
test('writes the lifecycle hook config under the global config dir', () => {
|
||||
const hookPath = path.join(configDir, 'hooks', 'gsd-session.json');
|
||||
assert.ok(fs.existsSync(hookPath), 'global hook config should exist under config dir');
|
||||
const cfg = JSON.parse(fs.readFileSync(hookPath, 'utf-8'));
|
||||
assert.strictEqual(cfg.version, 1, 'hook config version is 1');
|
||||
assert.ok(Array.isArray(cfg.hooks.sessionStart), 'has sessionStart array');
|
||||
});
|
||||
|
||||
test('does NOT emit AGENTS.md for global scope (no repo-root home)', () => {
|
||||
assert.ok(!fs.existsSync(path.join(projectDir, 'AGENTS.md')),
|
||||
'global install must not write AGENTS.md into the working directory');
|
||||
assert.ok(!fs.existsSync(path.join(configDir, 'AGENTS.md')),
|
||||
'global install must not write AGENTS.md into the config directory');
|
||||
});
|
||||
|
||||
test('global uninstall removes the lifecycle hook config', () => {
|
||||
runCopilotUninstallGlobal(projectDir, configDir);
|
||||
const hookPath = path.join(configDir, 'hooks', 'gsd-session.json');
|
||||
assert.ok(!fs.existsSync(hookPath), 'global hook config removed after uninstall');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -22,9 +22,7 @@ const {
|
||||
resolveModelInternal,
|
||||
escapeRegex,
|
||||
generateSlugInternal,
|
||||
normalizePhaseName,
|
||||
reapStaleTempFiles,
|
||||
comparePhaseNum,
|
||||
pathExistsInternal,
|
||||
getMilestoneInfo,
|
||||
getMilestonePhaseFilter,
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
* Ensures Cursor frontmatter names are emitted as plain identifiers
|
||||
* (without surrounding quotes), so Cursor does not treat quotes as
|
||||
* literal parts of skill/subagent names.
|
||||
*
|
||||
* Also covers convertClaudeCommandToCursorCommand (#785 — Cursor 1.6
|
||||
* slash commands via .cursor/commands/).
|
||||
*/
|
||||
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
@@ -14,6 +17,7 @@ const assert = require('node:assert/strict');
|
||||
const {
|
||||
convertClaudeCommandToCursorSkill,
|
||||
convertClaudeAgentToCursorAgent,
|
||||
convertClaudeCommandToCursorCommand,
|
||||
} = require('../bin/install.js');
|
||||
|
||||
describe('convertClaudeCommandToCursorSkill', () => {
|
||||
@@ -79,3 +83,71 @@ Planner body
|
||||
assert.ok(!result.includes('name: "gsd-planner"'), 'quoted agent name is not emitted');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── convertClaudeCommandToCursorCommand (#785) ───────────────────────────────
|
||||
|
||||
describe('convertClaudeCommandToCursorCommand (#785 — Cursor 1.6 .cursor/commands/)', () => {
|
||||
test('strips YAML frontmatter — output is plain markdown', () => {
|
||||
const input = `---
|
||||
name: help
|
||||
description: Show help for GSD commands
|
||||
---
|
||||
|
||||
# GSD Help
|
||||
|
||||
Use \`/gsd-help\` to see available commands.
|
||||
`;
|
||||
|
||||
const result = convertClaudeCommandToCursorCommand(input);
|
||||
assert.ok(!result.startsWith('---'), 'cursor commands must not have YAML frontmatter');
|
||||
assert.ok(!result.includes('name: help'), 'name field must be stripped');
|
||||
assert.ok(!result.includes('description:'), 'description field must be stripped');
|
||||
assert.ok(result.includes('GSD Help'), 'body content must be preserved');
|
||||
});
|
||||
|
||||
test('applies convertClaudeToCursorMarkdown transforms (Bash → Shell, Claude Code → Cursor)', () => {
|
||||
const input = `---
|
||||
name: quick
|
||||
description: Quick task
|
||||
---
|
||||
|
||||
Use Bash( to run commands.
|
||||
This runs in Claude Code.
|
||||
`;
|
||||
|
||||
const result = convertClaudeCommandToCursorCommand(input);
|
||||
assert.ok(result.includes('Shell('), 'Bash( should be renamed to Shell(');
|
||||
assert.ok(!result.includes('Claude Code'), 'Claude Code brand reference should be replaced');
|
||||
assert.ok(result.includes('Cursor'), 'should reference Cursor instead');
|
||||
});
|
||||
|
||||
test('normalizes gsd: colon slash commands to gsd- hyphen form', () => {
|
||||
const input = `---
|
||||
name: plan-phase
|
||||
description: Plan a phase
|
||||
---
|
||||
|
||||
Next step: /gsd:execute-phase 17
|
||||
`;
|
||||
|
||||
const result = convertClaudeCommandToCursorCommand(input);
|
||||
assert.ok(result.includes('/gsd-execute-phase 17'), 'colon form should become hyphen form');
|
||||
assert.ok(!result.includes('/gsd:execute-phase'), 'colon form should be removed');
|
||||
});
|
||||
|
||||
test('handles input with no frontmatter gracefully', () => {
|
||||
const input = `# No Frontmatter Command
|
||||
|
||||
Some body content.
|
||||
`;
|
||||
|
||||
const result = convertClaudeCommandToCursorCommand(input);
|
||||
assert.ok(!result.startsWith('---'), 'output must not start with ---');
|
||||
assert.ok(result.includes('No Frontmatter Command'), 'body should be preserved');
|
||||
});
|
||||
|
||||
test('is exported from install.js', () => {
|
||||
assert.strictEqual(typeof convertClaudeCommandToCursorCommand, 'function',
|
||||
'convertClaudeCommandToCursorCommand must be exported from install.js');
|
||||
});
|
||||
});
|
||||
|
||||
462
tests/cursor-hooks.test.cjs
Normal file
462
tests/cursor-hooks.test.cjs
Normal file
@@ -0,0 +1,462 @@
|
||||
/**
|
||||
* Tests for Cursor hooks.json lifecycle hook registration (issue #777).
|
||||
*
|
||||
* Cursor v2.4+ supports a hooks.json system with events including sessionStart
|
||||
* and postToolUse. GSD registers two managed command hooks so Cursor users get
|
||||
* baseline parity with Claude Code and Gemini.
|
||||
*
|
||||
* Test plan:
|
||||
* T1 reconcileCursorHooksJson — creates new hooks.json with both events
|
||||
* T2 reconcileCursorHooksJson — idempotent (re-run writes same content)
|
||||
* T3 reconcileCursorHooksJson — preserves user-owned entries in sessionStart
|
||||
* T4 reconcileCursorHooksJson — preserves user-owned entries in postToolUse
|
||||
* T5 reconcileCursorHooksJson — remove-only (managedEntries=null) strips managed, keeps user
|
||||
* T6 reconcileCursorHooksJson — handles nested { version, hooks: {...} } shape
|
||||
* T7 reconcileCursorHooksJson — handles flat (no version) shape
|
||||
* T8 reconcileCursorHooksJson — corrupted JSON throws descriptive error
|
||||
* T9 isManagedCursorHookEntry — returns true for GSD-marked entries
|
||||
* T10 isManagedCursorHookEntry — returns false for user entries
|
||||
* T11 buildCursorHookEntry — emits correct shape with marker
|
||||
* T12 removeCursorHooksJson — removes hooks.json when it becomes empty
|
||||
* T13 removeCursorHooksJson — preserves file when user entries remain
|
||||
* T14 runtime-config-adapter — cursor now has 'cursor-hooks-json' surface
|
||||
* T15 INSTALL_SURFACES — 'cursor-hooks-json' in the valid surfaces list
|
||||
* T16 Hook scripts exist in hooks/
|
||||
* T17 Hook script content — sessionStart script emits JSON with additional_context
|
||||
* T18 Hook script content — postToolUse script emits JSON {} for non-write tools
|
||||
* T19 GSD_CURSOR_HOOK_MARKER constant is exported
|
||||
* T20 GSD_CURSOR_SESSION_HOOK_SCRIPT / GSD_CURSOR_POST_TOOL_HOOK_SCRIPT constants
|
||||
*/
|
||||
|
||||
// allow-test-rule: source-text-is-the-product
|
||||
// Hook script text IS what Cursor loads. Testing script content tests the deployed contract.
|
||||
|
||||
'use strict';
|
||||
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
const { test, describe } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
const {
|
||||
reconcileCursorHooksJson,
|
||||
isManagedCursorHookEntry,
|
||||
buildCursorHookEntry,
|
||||
removeCursorHooksJson,
|
||||
GSD_CURSOR_HOOK_MARKER,
|
||||
GSD_CURSOR_SESSION_HOOK_SCRIPT,
|
||||
GSD_CURSOR_POST_TOOL_HOOK_SCRIPT,
|
||||
} = require('../bin/install.js');
|
||||
|
||||
const {
|
||||
resolveRuntimeConfigIntent,
|
||||
INSTALL_SURFACES,
|
||||
} = require('../gsd-core/bin/lib/runtime-config-adapter-registry.cjs');
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makeHooksJson(obj) {
|
||||
return JSON.stringify(obj, null, 2) + '\n';
|
||||
}
|
||||
|
||||
function readHooksJson(dir) {
|
||||
const p = path.join(dir, 'hooks.json');
|
||||
if (!fs.existsSync(p)) return null;
|
||||
return JSON.parse(fs.readFileSync(p, 'utf8'));
|
||||
}
|
||||
|
||||
function managedEntry(command) {
|
||||
return { type: 'command', command, [GSD_CURSOR_HOOK_MARKER]: true };
|
||||
}
|
||||
|
||||
function userEntry(command) {
|
||||
return { type: 'command', command };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T1: Creates new hooks.json with both events
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('reconcileCursorHooksJson', () => {
|
||||
test('T1: creates new hooks.json with sessionStart and postToolUse', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
const hooksJsonPath = path.join(dir, 'hooks.json');
|
||||
const result = reconcileCursorHooksJson(hooksJsonPath, {
|
||||
sessionStart: managedEntry('/node /path/gsd-cursor-session-start.js'),
|
||||
postToolUse: managedEntry('/node /path/gsd-cursor-post-tool.js'),
|
||||
});
|
||||
|
||||
assert.equal(result.wrote, true);
|
||||
assert.equal(result.changed, true);
|
||||
|
||||
const parsed = readHooksJson(dir);
|
||||
assert.ok(parsed, 'hooks.json must exist');
|
||||
|
||||
// Cursor requires the canonical nested { "version": 1, "hooks": { ... } } shape.
|
||||
assert.equal(parsed.version, 1, 'hooks.json must have version: 1');
|
||||
assert.ok(parsed.hooks && typeof parsed.hooks === 'object', 'hooks.json must have top-level hooks object');
|
||||
const hookTable = parsed.hooks;
|
||||
assert.ok(Array.isArray(hookTable.sessionStart), 'sessionStart must be an array');
|
||||
assert.ok(Array.isArray(hookTable.postToolUse), 'postToolUse must be an array');
|
||||
assert.equal(hookTable.sessionStart.length, 1);
|
||||
assert.equal(hookTable.postToolUse.length, 1);
|
||||
assert.equal(hookTable.sessionStart[0][GSD_CURSOR_HOOK_MARKER], true);
|
||||
assert.equal(hookTable.postToolUse[0][GSD_CURSOR_HOOK_MARKER], true);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T2: Idempotent
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T2: idempotent — second run produces same content (no write)', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
const hooksJsonPath = path.join(dir, 'hooks.json');
|
||||
const entries = {
|
||||
sessionStart: managedEntry('/node /gsd-cursor-session-start.js'),
|
||||
postToolUse: managedEntry('/node /gsd-cursor-post-tool.js'),
|
||||
};
|
||||
|
||||
reconcileCursorHooksJson(hooksJsonPath, entries);
|
||||
const result2 = reconcileCursorHooksJson(hooksJsonPath, entries);
|
||||
|
||||
assert.equal(result2.wrote, false, 'second run must not write (idempotent)');
|
||||
assert.equal(result2.changed, false, 'content must not change on second run');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T3: Preserves user-owned entries in sessionStart
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T3: preserves user-owned entries in sessionStart', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
const hooksJsonPath = path.join(dir, 'hooks.json');
|
||||
// Pre-populate with user-owned entry.
|
||||
fs.writeFileSync(hooksJsonPath, makeHooksJson({
|
||||
version: 1,
|
||||
hooks: {
|
||||
sessionStart: [userEntry('/my-team/hook.sh')],
|
||||
},
|
||||
}));
|
||||
|
||||
reconcileCursorHooksJson(hooksJsonPath, {
|
||||
sessionStart: managedEntry('/node /gsd-cursor-session-start.js'),
|
||||
postToolUse: managedEntry('/node /gsd-cursor-post-tool.js'),
|
||||
});
|
||||
|
||||
const parsed = readHooksJson(dir);
|
||||
const hookTable = parsed.hooks && typeof parsed.hooks === 'object' ? parsed.hooks : parsed;
|
||||
assert.ok(Array.isArray(hookTable.sessionStart));
|
||||
// Both user and GSD entries must survive.
|
||||
assert.equal(hookTable.sessionStart.length, 2, 'user + GSD entry must coexist');
|
||||
const userStays = hookTable.sessionStart.some((e) => e.command === '/my-team/hook.sh');
|
||||
const gsdAdded = hookTable.sessionStart.some((e) => e[GSD_CURSOR_HOOK_MARKER]);
|
||||
assert.ok(userStays, 'user-owned entry must be preserved');
|
||||
assert.ok(gsdAdded, 'GSD managed entry must be present');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T4: Preserves user-owned entries in postToolUse
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T4: preserves user-owned entries in postToolUse', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
const hooksJsonPath = path.join(dir, 'hooks.json');
|
||||
fs.writeFileSync(hooksJsonPath, makeHooksJson({
|
||||
hooks: {
|
||||
postToolUse: [userEntry('/user/post-tool.sh')],
|
||||
},
|
||||
}));
|
||||
|
||||
reconcileCursorHooksJson(hooksJsonPath, {
|
||||
sessionStart: managedEntry('/node /gsd-cursor-session-start.js'),
|
||||
postToolUse: managedEntry('/node /gsd-cursor-post-tool.js'),
|
||||
});
|
||||
|
||||
const parsed = readHooksJson(dir);
|
||||
const hookTable = parsed.hooks && typeof parsed.hooks === 'object' ? parsed.hooks : parsed;
|
||||
assert.ok(Array.isArray(hookTable.postToolUse));
|
||||
assert.equal(hookTable.postToolUse.length, 2);
|
||||
assert.ok(hookTable.postToolUse.some((e) => e.command === '/user/post-tool.sh'));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T5: Remove-only (managedEntries=null) strips managed, keeps user entries
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T5: remove-only (null managedEntries) strips GSD entries, preserves user', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
const hooksJsonPath = path.join(dir, 'hooks.json');
|
||||
fs.writeFileSync(hooksJsonPath, makeHooksJson({
|
||||
version: 1,
|
||||
hooks: {
|
||||
sessionStart: [
|
||||
userEntry('/user/session.sh'),
|
||||
managedEntry('/node /gsd-cursor-session-start.js'),
|
||||
],
|
||||
postToolUse: [
|
||||
managedEntry('/node /gsd-cursor-post-tool.js'),
|
||||
],
|
||||
},
|
||||
}));
|
||||
|
||||
reconcileCursorHooksJson(hooksJsonPath, null);
|
||||
|
||||
const parsed = readHooksJson(dir);
|
||||
const hookTable = parsed.hooks && typeof parsed.hooks === 'object' ? parsed.hooks : parsed;
|
||||
// sessionStart user entry survives; postToolUse key should be absent.
|
||||
assert.ok(Array.isArray(hookTable.sessionStart), 'sessionStart must remain (user entry)');
|
||||
assert.equal(hookTable.sessionStart.length, 1, 'only user entry remains');
|
||||
assert.equal(hookTable.sessionStart[0].command, '/user/session.sh');
|
||||
assert.equal(hookTable.postToolUse, undefined, 'postToolUse key must be removed (was GSD-only)');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T6: Handles nested { version, hooks: {...} } shape
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T6: handles nested { version, hooks } shape', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
const hooksJsonPath = path.join(dir, 'hooks.json');
|
||||
fs.writeFileSync(hooksJsonPath, makeHooksJson({ version: 1, hooks: {} }));
|
||||
|
||||
reconcileCursorHooksJson(hooksJsonPath, {
|
||||
sessionStart: managedEntry('/node /gsd-cursor-session-start.js'),
|
||||
});
|
||||
|
||||
const parsed = readHooksJson(dir);
|
||||
assert.ok(parsed.hooks, 'top-level hooks key must be preserved');
|
||||
assert.equal(parsed.version, 1, 'version must be preserved');
|
||||
assert.ok(Array.isArray(parsed.hooks.sessionStart));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T7: Handles flat (no version) shape
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T7: handles flat shape (no wrapper object)', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
const hooksJsonPath = path.join(dir, 'hooks.json');
|
||||
fs.writeFileSync(hooksJsonPath, makeHooksJson({ sessionStart: [] }));
|
||||
|
||||
reconcileCursorHooksJson(hooksJsonPath, {
|
||||
sessionStart: managedEntry('/node /gsd-cursor-session-start.js'),
|
||||
});
|
||||
|
||||
const parsed = readHooksJson(dir);
|
||||
// Flat input is migrated to nested canonical shape: { version: 1, hooks: { ... } }.
|
||||
assert.equal(parsed.version, 1, 'migrated flat shape must get version: 1');
|
||||
assert.ok(parsed.hooks && typeof parsed.hooks === 'object', 'migrated shape must have hooks object');
|
||||
assert.ok(Array.isArray(parsed.hooks.sessionStart), 'sessionStart must be in hooks object after migration');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T8: Corrupted JSON throws descriptive error
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T8: throws descriptive error for corrupted hooks.json', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
const hooksJsonPath = path.join(dir, 'hooks.json');
|
||||
fs.writeFileSync(hooksJsonPath, '{ not valid json }');
|
||||
|
||||
assert.throws(
|
||||
() => reconcileCursorHooksJson(hooksJsonPath, { sessionStart: managedEntry('/cmd') }),
|
||||
(err) => {
|
||||
assert.match(err.message, /Cursor hooks\.json parse failed/i);
|
||||
return true;
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T9-T11: Entry helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('isManagedCursorHookEntry / buildCursorHookEntry', () => {
|
||||
test('T9: isManagedCursorHookEntry returns true for GSD-marked entry', () => {
|
||||
const entry = { type: 'command', command: '/x', [GSD_CURSOR_HOOK_MARKER]: true };
|
||||
assert.equal(isManagedCursorHookEntry(entry), true);
|
||||
});
|
||||
|
||||
test('T10: isManagedCursorHookEntry returns false for user-owned entry', () => {
|
||||
const entry = { type: 'command', command: '/user/hook.sh' };
|
||||
assert.equal(isManagedCursorHookEntry(entry), false);
|
||||
assert.equal(isManagedCursorHookEntry(null), false);
|
||||
assert.equal(isManagedCursorHookEntry({}), false);
|
||||
});
|
||||
|
||||
test('T11: buildCursorHookEntry emits correct shape', () => {
|
||||
const entry = buildCursorHookEntry('/usr/local/bin/node /path/to/hook.js');
|
||||
assert.equal(entry.type, 'command');
|
||||
assert.equal(entry[GSD_CURSOR_HOOK_MARKER], true);
|
||||
assert.ok(typeof entry.command === 'string');
|
||||
// Forward slashes only.
|
||||
assert.ok(!entry.command.includes('\\'), 'command must use forward slashes');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T12-T13: removeCursorHooksJson
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('removeCursorHooksJson', () => {
|
||||
test('T12: removes hooks.json when it becomes empty after GSD removal', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
const hooksJsonPath = path.join(dir, 'hooks.json');
|
||||
// GSD-only file.
|
||||
fs.writeFileSync(hooksJsonPath, makeHooksJson({
|
||||
version: 1,
|
||||
hooks: {
|
||||
sessionStart: [managedEntry('/node /gsd-cursor-session-start.js')],
|
||||
postToolUse: [managedEntry('/node /gsd-cursor-post-tool.js')],
|
||||
},
|
||||
}));
|
||||
|
||||
const result = removeCursorHooksJson(dir);
|
||||
assert.equal(result.changed, true);
|
||||
// File should be removed (was GSD-only).
|
||||
assert.equal(fs.existsSync(hooksJsonPath), false, 'empty hooks.json must be removed');
|
||||
});
|
||||
|
||||
test('T13: preserves hooks.json when user entries remain', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
const hooksJsonPath = path.join(dir, 'hooks.json');
|
||||
fs.writeFileSync(hooksJsonPath, makeHooksJson({
|
||||
version: 1,
|
||||
hooks: {
|
||||
sessionStart: [
|
||||
managedEntry('/node /gsd-cursor-session-start.js'),
|
||||
userEntry('/user/session.sh'),
|
||||
],
|
||||
},
|
||||
}));
|
||||
|
||||
removeCursorHooksJson(dir);
|
||||
|
||||
assert.ok(fs.existsSync(hooksJsonPath), 'hooks.json must remain (user entries present)');
|
||||
const parsed = readHooksJson(dir);
|
||||
const hookTable = parsed.hooks && typeof parsed.hooks === 'object' ? parsed.hooks : parsed;
|
||||
assert.equal(hookTable.sessionStart.length, 1);
|
||||
assert.equal(hookTable.sessionStart[0].command, '/user/session.sh');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T14: runtime-config-adapter — cursor now has 'cursor-hooks-json' surface
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T14: cursor runtime has installSurface cursor-hooks-json', () => {
|
||||
const intent = resolveRuntimeConfigIntent('cursor');
|
||||
assert.equal(intent.installSurface, 'cursor-hooks-json');
|
||||
assert.equal(intent.writesSharedSettings, false);
|
||||
assert.equal(intent.finishPermissionWriter, null);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T15: INSTALL_SURFACES includes 'cursor-hooks-json'
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T15: INSTALL_SURFACES includes cursor-hooks-json', () => {
|
||||
assert.ok(
|
||||
INSTALL_SURFACES.includes('cursor-hooks-json'),
|
||||
"'cursor-hooks-json' must be in INSTALL_SURFACES"
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T16: Hook script files exist in hooks/
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T16: Cursor hook script files exist in hooks/', () => {
|
||||
const hooksDir = path.join(__dirname, '..', 'hooks');
|
||||
const sessionStart = path.join(hooksDir, GSD_CURSOR_SESSION_HOOK_SCRIPT);
|
||||
const postTool = path.join(hooksDir, GSD_CURSOR_POST_TOOL_HOOK_SCRIPT);
|
||||
assert.ok(fs.existsSync(sessionStart), `${GSD_CURSOR_SESSION_HOOK_SCRIPT} must exist in hooks/`);
|
||||
assert.ok(fs.existsSync(postTool), `${GSD_CURSOR_POST_TOOL_HOOK_SCRIPT} must exist in hooks/`);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T17: sessionStart script emits JSON with additional_context on stdin close
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T17: gsd-cursor-session-start.js emits JSON with additional_context', (t, done) => {
|
||||
const hooksDir = path.join(__dirname, '..', 'hooks');
|
||||
const scriptPath = path.join(hooksDir, GSD_CURSOR_SESSION_HOOK_SCRIPT);
|
||||
const { execFile } = require('child_process');
|
||||
|
||||
const input = JSON.stringify({ session_id: 'test-123', composer_mode: 'agent' });
|
||||
const child = execFile(process.execPath, [scriptPath], {
|
||||
timeout: 10000,
|
||||
cwd: os.tmpdir(), // no .planning/ dir here — should get MSG_ABSENT
|
||||
}, (err, stdout) => {
|
||||
if (err && !stdout) { done(err); return; }
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(stdout); } catch (e) { done(new Error(`stdout not valid JSON: ${stdout}`)); return; }
|
||||
assert.ok('additional_context' in parsed, 'output must have additional_context field');
|
||||
assert.ok(typeof parsed.additional_context === 'string', 'additional_context must be a string');
|
||||
assert.ok(parsed.additional_context.length > 0, 'additional_context must not be empty');
|
||||
done();
|
||||
});
|
||||
child.stdin.write(input);
|
||||
child.stdin.end();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T18: postToolUse script emits {} for non-write tools
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T18: gsd-cursor-post-tool.js emits {} for non-write tool names', (t, done) => {
|
||||
const hooksDir = path.join(__dirname, '..', 'hooks');
|
||||
const scriptPath = path.join(hooksDir, GSD_CURSOR_POST_TOOL_HOOK_SCRIPT);
|
||||
const { execFile } = require('child_process');
|
||||
|
||||
const input = JSON.stringify({
|
||||
tool_name: 'Read',
|
||||
tool_input: { path: '/some/file.js' },
|
||||
tool_output: 'contents',
|
||||
duration: 42,
|
||||
});
|
||||
|
||||
const child = execFile(process.execPath, [scriptPath], {
|
||||
timeout: 10000,
|
||||
cwd: os.tmpdir(),
|
||||
}, (err, stdout) => {
|
||||
if (err && !stdout) { done(err); return; }
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(stdout); } catch (e) { done(new Error(`stdout not valid JSON: ${stdout}`)); return; }
|
||||
// Non-write tool → empty response (no additional_context).
|
||||
assert.ok(typeof parsed === 'object', 'output must be an object');
|
||||
// additional_context should be absent for non-write, non-planning tool.
|
||||
assert.equal(parsed.additional_context, undefined, 'no additional_context for non-write tool');
|
||||
done();
|
||||
});
|
||||
child.stdin.write(input);
|
||||
child.stdin.end();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T19: GSD_CURSOR_HOOK_MARKER is exported and is a non-empty string
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T19: GSD_CURSOR_HOOK_MARKER is exported and is a non-empty string', () => {
|
||||
assert.equal(typeof GSD_CURSOR_HOOK_MARKER, 'string');
|
||||
assert.ok(GSD_CURSOR_HOOK_MARKER.length > 0);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// T20: Script name constants are exported and correct
|
||||
// ---------------------------------------------------------------------------
|
||||
test('T20: GSD_CURSOR_SESSION_HOOK_SCRIPT and GSD_CURSOR_POST_TOOL_HOOK_SCRIPT are exported', () => {
|
||||
assert.equal(GSD_CURSOR_SESSION_HOOK_SCRIPT, 'gsd-cursor-session-start.js');
|
||||
assert.equal(GSD_CURSOR_POST_TOOL_HOOK_SCRIPT, 'gsd-cursor-post-tool.js');
|
||||
});
|
||||
@@ -29,18 +29,18 @@ describe('Cursor CLI reviewer in /gsd-review (#1960)', () => {
|
||||
|
||||
describe('review.md workflow', () => {
|
||||
const reviewPath = path.join(ROOT, 'gsd-core', 'workflows', 'review.md');
|
||||
let content;
|
||||
let _content;
|
||||
|
||||
test('review.md exists', () => {
|
||||
assert.ok(fs.existsSync(reviewPath), 'review.md should exist');
|
||||
content = fs.readFileSync(reviewPath, 'utf-8');
|
||||
_content = fs.readFileSync(reviewPath, 'utf-8');
|
||||
});
|
||||
|
||||
test('contains cursor CLI detection via command -v', () => {
|
||||
test('contains cursor CLI detection via command -v cursor-agent', () => {
|
||||
const c = fs.readFileSync(reviewPath, 'utf-8');
|
||||
assert.ok(
|
||||
c.includes('command -v cursor'),
|
||||
'review.md should detect cursor CLI via "command -v cursor"'
|
||||
c.includes('command -v cursor-agent'),
|
||||
'review.md should detect cursor CLI via "command -v cursor-agent" (not the cursor IDE launcher)'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -60,11 +60,47 @@ describe('Cursor CLI reviewer in /gsd-review (#1960)', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('contains cursor agent invocation command', () => {
|
||||
test('invocation uses cursor-agent single binary with -p flag', () => {
|
||||
const c = fs.readFileSync(reviewPath, 'utf-8');
|
||||
assert.ok(
|
||||
c.includes('cursor agent -p --mode ask --trust'),
|
||||
'review.md should invoke cursor via "cursor agent -p --mode ask --trust"'
|
||||
c.includes('cursor-agent -p'),
|
||||
'review.md should invoke cursor via "cursor-agent -p" (single binary, not two-token "cursor agent")'
|
||||
);
|
||||
});
|
||||
|
||||
test('invocation includes --output-format text', () => {
|
||||
const c = fs.readFileSync(reviewPath, 'utf-8');
|
||||
assert.ok(
|
||||
c.includes('--output-format text'),
|
||||
'review.md cursor-agent invocation should include "--output-format text"'
|
||||
);
|
||||
});
|
||||
|
||||
test('invocation passes prompt as a file-path argument (not via stdin pipe)', () => {
|
||||
const c = fs.readFileSync(reviewPath, 'utf-8');
|
||||
assert.ok(
|
||||
c.includes('Read the file at /tmp/gsd-review-prompt-'),
|
||||
'review.md cursor-agent invocation should pass prompt by referencing the file path as an argument'
|
||||
);
|
||||
});
|
||||
|
||||
test('does NOT use broken two-token "cursor agent " form', () => {
|
||||
const c = fs.readFileSync(reviewPath, 'utf-8');
|
||||
// Must not match "cursor agent " (cursor + space + agent + space)
|
||||
// The hyphenated "cursor-agent" must NOT trip this check — the regex uses a space, not a hyphen.
|
||||
assert.ok(
|
||||
!/cursor agent /.test(c),
|
||||
'review.md must NOT contain the broken two-token form "cursor agent " (use "cursor-agent" instead)'
|
||||
);
|
||||
});
|
||||
|
||||
test('does NOT pipe the prompt into a cursor command via stdin', () => {
|
||||
const c = fs.readFileSync(reviewPath, 'utf-8');
|
||||
// Must not match a pipe feeding into a cursor command (e.g. "| cursor" or "|cursor")
|
||||
// "cursor-agent" (hyphenated) must NOT trip this — the regex anchors on "cursor" not followed by "-agent"
|
||||
assert.ok(
|
||||
!/\| *cursor(?!-agent)/.test(c),
|
||||
'review.md must NOT pipe the prompt to a cursor command via stdin'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -184,7 +220,6 @@ describe('Cursor CLI reviewer in /gsd-review (#1960)', () => {
|
||||
});
|
||||
|
||||
test('mentions Cursor in the review section', () => {
|
||||
const c = fs.readFileSync(jaPath, 'utf-8');
|
||||
assert.ok(
|
||||
/Cursor/i.test(fs.readFileSync(jaPath, 'utf-8')),
|
||||
'docs/ja-JP/FEATURES.md should mention Cursor in the review section'
|
||||
@@ -218,7 +253,6 @@ describe('Cursor CLI reviewer in /gsd-review (#1960)', () => {
|
||||
});
|
||||
|
||||
test('mentions Cursor in the review section', () => {
|
||||
const c = fs.readFileSync(koPath, 'utf-8');
|
||||
assert.ok(
|
||||
/Cursor/i.test(fs.readFileSync(koPath, 'utf-8')),
|
||||
'docs/ko-KR/FEATURES.md should mention Cursor in the review section'
|
||||
|
||||
92
tests/discord-release-summary.test.cjs
Normal file
92
tests/discord-release-summary.test.cjs
Normal file
@@ -0,0 +1,92 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const { describe, test } = require('node:test');
|
||||
const {
|
||||
buildDiscordReleasePayload,
|
||||
cleanBullet,
|
||||
collectSections,
|
||||
extractInstallCommand,
|
||||
} = require('../scripts/release-notes/discord-release-summary.cjs');
|
||||
|
||||
const sampleRelease = {
|
||||
tagName: 'v1.4.0-rc.1',
|
||||
name: 'v1.4.0-rc.1',
|
||||
isPrerelease: true,
|
||||
url: 'https://github.com/open-gsd/gsd-core/releases/tag/v1.4.0-rc.1',
|
||||
body: [
|
||||
'## Install',
|
||||
'',
|
||||
'This pre-release is published to npm under the `next` dist-tag.',
|
||||
'',
|
||||
'```bash',
|
||||
'npm i @opengsd/gsd-core@1.4.0-rc.1',
|
||||
'# or',
|
||||
'npm i @opengsd/gsd-core@next',
|
||||
'```',
|
||||
'',
|
||||
'## What\'s Changed',
|
||||
'',
|
||||
'### Feature',
|
||||
'* feat(#656): Research module cache by @trek-e in https://github.com/open-gsd/gsd-core/pull/664',
|
||||
'* feat(#717): size budget on bytes by @trek-e in https://github.com/open-gsd/gsd-core/pull/719',
|
||||
'* feat(#159): auto-use existing RESEARCH.md by @trek-e in https://github.com/open-gsd/gsd-core/pull/718',
|
||||
'* feat(#703): add --granularity override by @trek-e in https://github.com/open-gsd/gsd-core/pull/750',
|
||||
'* feat(#25): scope verifier Step 7b by @trek-e in https://github.com/open-gsd/gsd-core/pull/753',
|
||||
'',
|
||||
'### Fix',
|
||||
'* fix(#663): resolve CodeQL alerts by @trek-e in https://github.com/open-gsd/gsd-core/pull/665',
|
||||
'',
|
||||
'**Full Changelog**: https://github.com/open-gsd/gsd-core/compare/v1.3.1...v1.4.0-rc.1',
|
||||
].join('\n'),
|
||||
};
|
||||
|
||||
describe('discord release summary', () => {
|
||||
test('builds a hybrid payload with a preserved full changelog URL', () => {
|
||||
const payload = buildDiscordReleasePayload({
|
||||
release: sampleRelease,
|
||||
packageName: '@opengsd/gsd-core',
|
||||
maxContent: 1850,
|
||||
});
|
||||
|
||||
assert.equal(payload.username, 'GSD Releases');
|
||||
assert.match(payload.content, /\*\*@opengsd\/gsd-core v1\.4\.0-rc\.1 pre-release is out\*\*/);
|
||||
assert.match(payload.content, /`npm i @opengsd\/gsd-core@1\.4\.0-rc\.1`/);
|
||||
assert.match(payload.content, /Full changelog: https:\/\/github\.com\/open-gsd\/gsd-core\/releases\/tag\/v1\.4\.0-rc\.1/);
|
||||
assert.doesNotMatch(payload.content, /\*\*Full Changelog\*\*:\s*$/m);
|
||||
assert.match(payload.content, /Research module cache \(#664\)/);
|
||||
assert.match(payload.content, /\.\.\.and 1 more features/);
|
||||
assert.equal(payload.embeds[0].fields[1].value, '`next`');
|
||||
});
|
||||
|
||||
test('summarizes auto-generated What Changed bullets when release notes are not yet curated', () => {
|
||||
const sections = collectSections([
|
||||
'## What\'s Changed',
|
||||
'* feat: add thing by @trek-e in https://github.com/open-gsd/gsd-core/pull/10',
|
||||
'* fix: repair thing by @trek-e in https://github.com/open-gsd/gsd-core/pull/11',
|
||||
'* docs: explain thing by @trek-e in https://github.com/open-gsd/gsd-core/pull/12',
|
||||
].join('\n'));
|
||||
|
||||
assert.deepEqual(sections.get('Feature'), ['add thing (#10)']);
|
||||
assert.deepEqual(sections.get('Fix'), ['repair thing (#11)']);
|
||||
assert.deepEqual(sections.get('Enhancement'), ['explain thing (#12)']);
|
||||
});
|
||||
|
||||
test('cleans common GitHub release-note link noise without deleting issue references', () => {
|
||||
assert.equal(
|
||||
cleanBullet('* fix: repair [#670](https://github.com/open-gsd/gsd-core/issues/670) by @trek-e in https://github.com/open-gsd/gsd-core/pull/675'),
|
||||
'repair #670 (#675)'
|
||||
);
|
||||
});
|
||||
|
||||
test('falls back to the release channel when no install block exists', () => {
|
||||
assert.equal(
|
||||
extractInstallCommand('', '@opengsd/gsd-core', { tagName: 'v1.4.0-rc.1', isPrerelease: true }),
|
||||
'npm i @opengsd/gsd-core@next'
|
||||
);
|
||||
assert.equal(
|
||||
extractInstallCommand('', '@opengsd/gsd-core', { tagName: 'v1.4.0', isPrerelease: false }),
|
||||
'npm i @opengsd/gsd-core@latest'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -181,7 +181,7 @@ describe('trace correlation — end-to-end parentTraceId propagation', () => {
|
||||
const allEvents = readJsonl(isolatedAuditPath);
|
||||
assert.equal(allEvents.length, 3, 'must have 3 events total (root + valid child + invalid child)');
|
||||
|
||||
const [root, validChild, invalidChild] = allEvents;
|
||||
const [, validChild, invalidChild] = allEvents;
|
||||
|
||||
// Valid child carries the correct parentTraceId
|
||||
assert.strictEqual(validChild.parentTraceId, rootTraceId,
|
||||
|
||||
@@ -309,10 +309,6 @@ describe('getLiveCommandTokens() — helper contract', () => {
|
||||
test('contains exactly 3 tokens per slug (slash, colon, dollar)', () => {
|
||||
const result = getLiveCommandTokens();
|
||||
// Every /gsd-slug should have a matching /gsd:slug and $gsd-slug
|
||||
let tokenCount = 0;
|
||||
for (const token of result) {
|
||||
if (token.startsWith('/gsd-')) tokenCount++;
|
||||
}
|
||||
const slashTokens = [...result].filter(t => t.startsWith('/gsd-'));
|
||||
for (const slash of slashTokens) {
|
||||
const slug = slash.slice('/gsd-'.length);
|
||||
|
||||
@@ -35,7 +35,7 @@ describe('enh-2430 Part A — plan-phase LEARNINGS.md context load', () => {
|
||||
|
||||
test('plan-phase.md LEARNINGS load is inside the 1M context-window gate', () => {
|
||||
content = content || readWorkflow('plan-phase.md');
|
||||
const windowBlock = content.match(/\$\{CONTEXT_WINDOW >= 500000[\s\S]*?\` : ''\}/);
|
||||
const windowBlock = content.match(/\$\{CONTEXT_WINDOW >= 500000[\s\S]*?` : ''\}/);
|
||||
assert.ok(windowBlock, 'CONTEXT_WINDOW gate block must exist');
|
||||
assert.ok(
|
||||
windowBlock[0].includes('LEARNINGS.md'),
|
||||
@@ -62,7 +62,7 @@ describe('enh-2430 Part A — plan-phase LEARNINGS.md context load', () => {
|
||||
|
||||
test('plan-phase.md LEARNINGS load includes Depends-on chain', () => {
|
||||
content = content || readWorkflow('plan-phase.md');
|
||||
const dependsSection = content.match(/Depends on.*?(\n.*?)+/);
|
||||
content.match(/Depends on.*?(\n.*?)+/);
|
||||
assert.ok(
|
||||
content.includes('LEARNINGS.md from any phases listed in'),
|
||||
'plan-phase.md must load LEARNINGS.md for Depends on chain phases'
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* Tests for ROADMAP wave dependency surfacing (#2447).
|
||||
*/
|
||||
|
||||
const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const { test, describe, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
317
tests/enh-769-context-fork-effort.install.test.cjs
Normal file
317
tests/enh-769-context-fork-effort.install.test.cjs
Normal file
@@ -0,0 +1,317 @@
|
||||
// allow-test-rule: integration-test-input
|
||||
// Exercises install() as a black-box by inspecting produced SKILL.md output
|
||||
// in a temp dir. Source command .md files are inputs whose installed
|
||||
// transformation is asserted — not inspected for string presence.
|
||||
|
||||
/**
|
||||
* #769 — context:fork + effort: frontmatter on heavy workflow skills.
|
||||
*
|
||||
* Verifies:
|
||||
* 1. Source commands/gsd/autonomous.md has context: fork and effort: xhigh
|
||||
* 2. Source commands/gsd/execute-phase.md has context: fork and effort: xhigh
|
||||
* 3. Source commands/gsd/plan-phase.md has context: fork and effort: xhigh
|
||||
* 4. Source commands/gsd/progress.md has effort: low
|
||||
* 5. Source commands/gsd/stats.md has effort: low
|
||||
* 6. Claude global install: SKILL.md for autonomous has context: fork and effort: xhigh
|
||||
* 7. Claude global install: SKILL.md for execute-phase has context: fork and effort: xhigh
|
||||
* 8. Claude global install: SKILL.md for plan-phase has context: fork and effort: xhigh
|
||||
* 9. Claude global install: SKILL.md for progress has effort: low
|
||||
* 10. Claude global install: SKILL.md for stats has effort: low
|
||||
* 11. convertClaudeCommandToClaudeSkill preserves context: fork field
|
||||
* 12. convertClaudeCommandToClaudeSkill preserves effort: field
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
const { describe, test, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
|
||||
const { install, convertClaudeCommandToClaudeSkill } = require('../bin/install.js');
|
||||
const { cleanup } = require('./helpers.cjs');
|
||||
|
||||
const REPO_ROOT = path.resolve(__dirname, '..');
|
||||
const SOURCE_COMMANDS_DIR = path.join(REPO_ROOT, 'commands', 'gsd');
|
||||
|
||||
// ─── helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function makeTmpDir(prefix) {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
}
|
||||
|
||||
function readFrontmatter(mdPath) {
|
||||
const content = fs.readFileSync(mdPath, 'utf8');
|
||||
if (!content.startsWith('---')) return '';
|
||||
const end = content.indexOf('---', 3);
|
||||
if (end === -1) return '';
|
||||
return content.substring(3, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a global install for Claude, redirecting its home dir to tmpHome.
|
||||
* Returns the tmpHome for inspection.
|
||||
*/
|
||||
function runClaudeGlobalInstall(claudeHome) {
|
||||
const isolatedHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-769-home-'));
|
||||
|
||||
const prevCwd = process.cwd();
|
||||
const prevClaudeConfigDir = process.env.CLAUDE_CONFIG_DIR;
|
||||
const prevHome = process.env.HOME;
|
||||
const prevUserProfile = process.env.USERPROFILE;
|
||||
const prevSkipStale = process.env.GSD_SKIP_STALE_SDK_CHECK;
|
||||
|
||||
process.env.CLAUDE_CONFIG_DIR = claudeHome;
|
||||
process.env.HOME = isolatedHome;
|
||||
process.env.USERPROFILE = isolatedHome;
|
||||
process.env.GSD_SKIP_STALE_SDK_CHECK = '1';
|
||||
process.chdir(REPO_ROOT);
|
||||
|
||||
try {
|
||||
install(true, 'claude');
|
||||
} finally {
|
||||
process.chdir(prevCwd);
|
||||
if (prevClaudeConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;
|
||||
else process.env.CLAUDE_CONFIG_DIR = prevClaudeConfigDir;
|
||||
if (prevHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = prevHome;
|
||||
if (prevUserProfile === undefined) delete process.env.USERPROFILE;
|
||||
else process.env.USERPROFILE = prevUserProfile;
|
||||
if (prevSkipStale === undefined) delete process.env.GSD_SKIP_STALE_SDK_CHECK;
|
||||
else process.env.GSD_SKIP_STALE_SDK_CHECK = prevSkipStale;
|
||||
cleanup(isolatedHome);
|
||||
}
|
||||
|
||||
return claudeHome;
|
||||
}
|
||||
|
||||
// ─── describe 1: Source command files have correct frontmatter ────────────────
|
||||
|
||||
describe('#769 source commands: heavy skills have context: fork and effort: xhigh', () => {
|
||||
test('commands/gsd/autonomous.md has context: fork', () => {
|
||||
const fm = readFrontmatter(path.join(SOURCE_COMMANDS_DIR, 'autonomous.md'));
|
||||
assert.match(fm, /^context:[ \t]*fork$/m,
|
||||
`autonomous.md frontmatter must have context: fork\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('commands/gsd/autonomous.md has effort: xhigh', () => {
|
||||
const fm = readFrontmatter(path.join(SOURCE_COMMANDS_DIR, 'autonomous.md'));
|
||||
assert.match(fm, /^effort:[ \t]*xhigh$/m,
|
||||
`autonomous.md frontmatter must have effort: xhigh\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('commands/gsd/execute-phase.md has context: fork', () => {
|
||||
const fm = readFrontmatter(path.join(SOURCE_COMMANDS_DIR, 'execute-phase.md'));
|
||||
assert.match(fm, /^context:[ \t]*fork$/m,
|
||||
`execute-phase.md frontmatter must have context: fork\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('commands/gsd/execute-phase.md has effort: xhigh', () => {
|
||||
const fm = readFrontmatter(path.join(SOURCE_COMMANDS_DIR, 'execute-phase.md'));
|
||||
assert.match(fm, /^effort:[ \t]*xhigh$/m,
|
||||
`execute-phase.md frontmatter must have effort: xhigh\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('commands/gsd/plan-phase.md has context: fork', () => {
|
||||
const fm = readFrontmatter(path.join(SOURCE_COMMANDS_DIR, 'plan-phase.md'));
|
||||
assert.match(fm, /^context:[ \t]*fork$/m,
|
||||
`plan-phase.md frontmatter must have context: fork\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('commands/gsd/plan-phase.md has effort: xhigh', () => {
|
||||
const fm = readFrontmatter(path.join(SOURCE_COMMANDS_DIR, 'plan-phase.md'));
|
||||
assert.match(fm, /^effort:[ \t]*xhigh$/m,
|
||||
`plan-phase.md frontmatter must have effort: xhigh\nActual:\n${fm}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#769 source commands: quick-status skills have effort: low', () => {
|
||||
test('commands/gsd/progress.md has effort: low', () => {
|
||||
const fm = readFrontmatter(path.join(SOURCE_COMMANDS_DIR, 'progress.md'));
|
||||
assert.match(fm, /^effort:[ \t]*low$/m,
|
||||
`progress.md frontmatter must have effort: low\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('commands/gsd/stats.md has effort: low', () => {
|
||||
const fm = readFrontmatter(path.join(SOURCE_COMMANDS_DIR, 'stats.md'));
|
||||
assert.match(fm, /^effort:[ \t]*low$/m,
|
||||
`stats.md frontmatter must have effort: low\nActual:\n${fm}`);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── describe 2: convertClaudeCommandToClaudeSkill preserves new fields ───────
|
||||
|
||||
describe('#769 convertClaudeCommandToClaudeSkill: preserves context and effort fields', () => {
|
||||
test('preserves context: fork in emitted SKILL.md frontmatter', () => {
|
||||
const input = [
|
||||
'---',
|
||||
'name: gsd:test-heavy',
|
||||
'description: Test heavy skill',
|
||||
'context: fork',
|
||||
'effort: xhigh',
|
||||
'allowed-tools:',
|
||||
' - Read',
|
||||
' - Bash',
|
||||
'---',
|
||||
'',
|
||||
'Heavy skill body.',
|
||||
].join('\n');
|
||||
|
||||
const result = convertClaudeCommandToClaudeSkill(input, 'test-heavy');
|
||||
const end = result.indexOf('---', 3);
|
||||
const fm = result.substring(3, end);
|
||||
|
||||
assert.match(fm, /^context:[ \t]*fork$/m,
|
||||
`SKILL.md frontmatter must include context: fork\nActual frontmatter:\n${fm}`);
|
||||
});
|
||||
|
||||
test('preserves effort: xhigh in emitted SKILL.md frontmatter', () => {
|
||||
const input = [
|
||||
'---',
|
||||
'name: gsd:test-heavy',
|
||||
'description: Test heavy skill',
|
||||
'context: fork',
|
||||
'effort: xhigh',
|
||||
'allowed-tools:',
|
||||
' - Read',
|
||||
' - Bash',
|
||||
'---',
|
||||
'',
|
||||
'Heavy skill body.',
|
||||
].join('\n');
|
||||
|
||||
const result = convertClaudeCommandToClaudeSkill(input, 'test-heavy');
|
||||
const end = result.indexOf('---', 3);
|
||||
const fm = result.substring(3, end);
|
||||
|
||||
assert.match(fm, /^effort:[ \t]*xhigh$/m,
|
||||
`SKILL.md frontmatter must include effort: xhigh\nActual frontmatter:\n${fm}`);
|
||||
});
|
||||
|
||||
test('preserves effort: low in emitted SKILL.md frontmatter', () => {
|
||||
const input = [
|
||||
'---',
|
||||
'name: gsd:test-light',
|
||||
'description: Test light skill',
|
||||
'effort: low',
|
||||
'allowed-tools:',
|
||||
' - Read',
|
||||
'---',
|
||||
'',
|
||||
'Light skill body.',
|
||||
].join('\n');
|
||||
|
||||
const result = convertClaudeCommandToClaudeSkill(input, 'test-light');
|
||||
const end = result.indexOf('---', 3);
|
||||
const fm = result.substring(3, end);
|
||||
|
||||
assert.match(fm, /^effort:[ \t]*low$/m,
|
||||
`SKILL.md frontmatter must include effort: low\nActual frontmatter:\n${fm}`);
|
||||
});
|
||||
|
||||
test('does NOT emit context: or effort: when absent from source', () => {
|
||||
const input = [
|
||||
'---',
|
||||
'name: gsd:test-plain',
|
||||
'description: Plain skill without context or effort',
|
||||
'allowed-tools:',
|
||||
' - Read',
|
||||
'---',
|
||||
'',
|
||||
'Plain skill body.',
|
||||
].join('\n');
|
||||
|
||||
const result = convertClaudeCommandToClaudeSkill(input, 'test-plain');
|
||||
const end = result.indexOf('---', 3);
|
||||
const fm = result.substring(3, end);
|
||||
|
||||
assert.doesNotMatch(fm, /^context:/m,
|
||||
`SKILL.md must not emit context: when absent from source\nActual:\n${fm}`);
|
||||
assert.doesNotMatch(fm, /^effort:/m,
|
||||
`SKILL.md must not emit effort: when absent from source\nActual:\n${fm}`);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── describe 3: Claude global install — SKILL.md files include new fields ────
|
||||
|
||||
describe('#769 Claude global install: SKILL.md files preserve context: fork and effort:', () => {
|
||||
let tmpDir;
|
||||
let claudeHome;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = makeTmpDir('gsd-769-claude-');
|
||||
claudeHome = path.join(tmpDir, 'claude-home');
|
||||
fs.mkdirSync(claudeHome, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('gsd-autonomous SKILL.md has context: fork after global install', () => {
|
||||
runClaudeGlobalInstall(claudeHome);
|
||||
const skillPath = path.join(claudeHome, 'skills', 'gsd-autonomous', 'SKILL.md');
|
||||
const fm = readFrontmatter(skillPath);
|
||||
assert.match(fm, /^context:[ \t]*fork$/m,
|
||||
`gsd-autonomous SKILL.md must have context: fork\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('gsd-autonomous SKILL.md has effort: xhigh after global install', () => {
|
||||
runClaudeGlobalInstall(claudeHome);
|
||||
const skillPath = path.join(claudeHome, 'skills', 'gsd-autonomous', 'SKILL.md');
|
||||
const fm = readFrontmatter(skillPath);
|
||||
assert.match(fm, /^effort:[ \t]*xhigh$/m,
|
||||
`gsd-autonomous SKILL.md must have effort: xhigh\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('gsd-execute-phase SKILL.md has context: fork after global install', () => {
|
||||
runClaudeGlobalInstall(claudeHome);
|
||||
const skillPath = path.join(claudeHome, 'skills', 'gsd-execute-phase', 'SKILL.md');
|
||||
const fm = readFrontmatter(skillPath);
|
||||
assert.match(fm, /^context:[ \t]*fork$/m,
|
||||
`gsd-execute-phase SKILL.md must have context: fork\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('gsd-execute-phase SKILL.md has effort: xhigh after global install', () => {
|
||||
runClaudeGlobalInstall(claudeHome);
|
||||
const skillPath = path.join(claudeHome, 'skills', 'gsd-execute-phase', 'SKILL.md');
|
||||
const fm = readFrontmatter(skillPath);
|
||||
assert.match(fm, /^effort:[ \t]*xhigh$/m,
|
||||
`gsd-execute-phase SKILL.md must have effort: xhigh\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('gsd-plan-phase SKILL.md has context: fork after global install', () => {
|
||||
runClaudeGlobalInstall(claudeHome);
|
||||
const skillPath = path.join(claudeHome, 'skills', 'gsd-plan-phase', 'SKILL.md');
|
||||
const fm = readFrontmatter(skillPath);
|
||||
assert.match(fm, /^context:[ \t]*fork$/m,
|
||||
`gsd-plan-phase SKILL.md must have context: fork\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('gsd-plan-phase SKILL.md has effort: xhigh after global install', () => {
|
||||
runClaudeGlobalInstall(claudeHome);
|
||||
const skillPath = path.join(claudeHome, 'skills', 'gsd-plan-phase', 'SKILL.md');
|
||||
const fm = readFrontmatter(skillPath);
|
||||
assert.match(fm, /^effort:[ \t]*xhigh$/m,
|
||||
`gsd-plan-phase SKILL.md must have effort: xhigh\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('gsd-progress SKILL.md has effort: low after global install', () => {
|
||||
runClaudeGlobalInstall(claudeHome);
|
||||
const skillPath = path.join(claudeHome, 'skills', 'gsd-progress', 'SKILL.md');
|
||||
const fm = readFrontmatter(skillPath);
|
||||
assert.match(fm, /^effort:[ \t]*low$/m,
|
||||
`gsd-progress SKILL.md must have effort: low\nActual:\n${fm}`);
|
||||
});
|
||||
|
||||
test('gsd-stats SKILL.md has effort: low after global install', () => {
|
||||
runClaudeGlobalInstall(claudeHome);
|
||||
const skillPath = path.join(claudeHome, 'skills', 'gsd-stats', 'SKILL.md');
|
||||
const fm = readFrontmatter(skillPath);
|
||||
assert.match(fm, /^effort:[ \t]*low$/m,
|
||||
`gsd-stats SKILL.md must have effort: low\nActual:\n${fm}`);
|
||||
});
|
||||
});
|
||||
379
tests/enh-770-claude-hook-events.test.cjs
Normal file
379
tests/enh-770-claude-hook-events.test.cjs
Normal file
@@ -0,0 +1,379 @@
|
||||
'use strict';
|
||||
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
/**
|
||||
* Enhancement #770: Register Claude Code lifecycle hooks (SubagentStop / Stop /
|
||||
* PreCompact / FileChanged).
|
||||
*
|
||||
* Claude Code now supports the same SubagentStop, Stop, and PreCompact events
|
||||
* that were wired for Qwen Code in #788. This suite asserts:
|
||||
*
|
||||
* 1. Claude Code installs register SubagentStop, Stop, and PreCompact, each
|
||||
* wired to gsd-context-monitor.js (same as Qwen).
|
||||
* 2. Claude Code installs register a FileChanged hook for .planning/config.json
|
||||
* wired to gsd-config-reload.js (new hook; hot-reloads gsd config).
|
||||
* 3. All four registrations are idempotent (reinstall does not duplicate).
|
||||
* 4. Uninstall removes all four event registrations.
|
||||
* 5. The gsd-config-reload.js hook script exists in hooks/ and has the
|
||||
* expected structure (reads on stdin, emits additionalContext or exits 0).
|
||||
* 6. The hooks/hooks.json plugin manifest includes the new events.
|
||||
*
|
||||
* Source: https://code.claude.com/docs/en/hooks
|
||||
*/
|
||||
|
||||
const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const { install, uninstall, validateHookFields } = require('../bin/install.js');
|
||||
const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Extract all hook commands registered under `eventName` from settings. */
|
||||
function hooksForEvent(settings, eventName) {
|
||||
if (!settings || !settings.hooks || !Array.isArray(settings.hooks[eventName])) return [];
|
||||
return settings.hooks[eventName].flatMap(entry =>
|
||||
(entry && Array.isArray(entry.hooks) ? entry.hooks : [])
|
||||
.map(h => h && h.command)
|
||||
.filter(Boolean)
|
||||
);
|
||||
}
|
||||
|
||||
/** Extract all matchers registered under `eventName` from settings. */
|
||||
function matchersForEvent(settings, eventName) {
|
||||
if (!settings || !settings.hooks || !Array.isArray(settings.hooks[eventName])) return [];
|
||||
return settings.hooks[eventName]
|
||||
.map(entry => entry && entry.matcher)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
const HOOKS_SRC = path.join(__dirname, '..', 'hooks');
|
||||
// Hooks the installer existsSync-checks before registering; must be present
|
||||
// in targetDir/hooks/ so the registration guards pass.
|
||||
const STUB_HOOKS = [
|
||||
'gsd-context-monitor.js',
|
||||
'gsd-prompt-guard.js',
|
||||
'gsd-check-update.js',
|
||||
'gsd-config-reload.js',
|
||||
];
|
||||
|
||||
/**
|
||||
* Pre-populate targetDir/hooks/ with stub hook files so the installer's
|
||||
* fs.existsSync guards pass even when hooks/dist/ is absent (e.g. CI without
|
||||
* a build step). Each test suite passes its own per-test tmpDir/.claude path
|
||||
* so stubs are isolated to that test's temp directory — no shared filesystem
|
||||
* state, no cross-test races.
|
||||
*
|
||||
* When hooks/dist/ DOES exist (local dev with npm run build:hooks), the
|
||||
* installer copies real files over these stubs during install() — that is
|
||||
* fine and correct.
|
||||
*/
|
||||
function stubHooksIntoTarget(targetDir) {
|
||||
const hooksDest = path.join(targetDir, 'hooks');
|
||||
fs.mkdirSync(hooksDest, { recursive: true });
|
||||
for (const hookFile of STUB_HOOKS) {
|
||||
const src = path.join(HOOKS_SRC, hookFile);
|
||||
const dest = path.join(hooksDest, hookFile);
|
||||
if (fs.existsSync(src)) {
|
||||
fs.copyFileSync(src, dest);
|
||||
} else {
|
||||
// Minimal stub so existsSync passes
|
||||
fs.writeFileSync(dest, '#!/usr/bin/env node\n// stub\n');
|
||||
}
|
||||
try { fs.chmodSync(dest, 0o755); } catch { /* Windows */ }
|
||||
}
|
||||
}
|
||||
|
||||
function persistSettings(settingsPath, settings) {
|
||||
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
|
||||
fs.writeFileSync(settingsPath, JSON.stringify(validateHookFields(settings), null, 2) + '\n', 'utf8');
|
||||
}
|
||||
|
||||
// ─── Suite 1: Claude — new context monitor events are registered ──────────────
|
||||
|
||||
describe('enh-770: Claude install registers SubagentStop / Stop / PreCompact context hooks', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
let settings;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-770-claude-ctx-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
stubHooksIntoTarget(path.join(tmpDir, '.claude'));
|
||||
|
||||
const result = install(false, 'claude', { installerMigrations: [] });
|
||||
settings = result && result.settings;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('install returns a settings object (not null)', () => {
|
||||
assert.ok(settings !== null && typeof settings === 'object',
|
||||
'Claude install must return a non-null settings object');
|
||||
});
|
||||
|
||||
test('SubagentStop event is registered with at least one hook', () => {
|
||||
const cmds = hooksForEvent(settings, 'SubagentStop');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Expected SubagentStop hooks; got hooks: ${JSON.stringify(settings && settings.hooks)}`);
|
||||
});
|
||||
|
||||
test('Stop event is registered with at least one hook', () => {
|
||||
const cmds = hooksForEvent(settings, 'Stop');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Expected Stop hooks; got hooks: ${JSON.stringify(settings && settings.hooks)}`);
|
||||
});
|
||||
|
||||
test('PreCompact event is registered with at least one hook', () => {
|
||||
const cmds = hooksForEvent(settings, 'PreCompact');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Expected PreCompact hooks; got hooks: ${JSON.stringify(settings && settings.hooks)}`);
|
||||
});
|
||||
|
||||
test('SubagentStop / Stop / PreCompact all use gsd-context-monitor', () => {
|
||||
for (const event of ['SubagentStop', 'Stop', 'PreCompact']) {
|
||||
const cmds = hooksForEvent(settings, event);
|
||||
assert.ok(
|
||||
cmds.some(c => c.includes('gsd-context-monitor')),
|
||||
`Event ${event} should use gsd-context-monitor; got commands: ${JSON.stringify(cmds)}`
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 2: Claude — FileChanged hook for config hot-reload ─────────────────
|
||||
|
||||
describe('enh-770: Claude install registers FileChanged hook for .planning/config.json', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
let settings;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-770-filechanged-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
stubHooksIntoTarget(path.join(tmpDir, '.claude'));
|
||||
|
||||
const result = install(false, 'claude', { installerMigrations: [] });
|
||||
settings = result && result.settings;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('FileChanged event is registered with at least one hook', () => {
|
||||
const cmds = hooksForEvent(settings, 'FileChanged');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Expected FileChanged hooks; got hooks: ${JSON.stringify(settings && settings.hooks)}`);
|
||||
});
|
||||
|
||||
test('FileChanged hook uses gsd-config-reload', () => {
|
||||
const cmds = hooksForEvent(settings, 'FileChanged');
|
||||
assert.ok(
|
||||
cmds.some(c => c.includes('gsd-config-reload')),
|
||||
`FileChanged should use gsd-config-reload; got commands: ${JSON.stringify(cmds)}`
|
||||
);
|
||||
});
|
||||
|
||||
test('FileChanged hook has a matcher targeting .planning/config.json', () => {
|
||||
const matchers = matchersForEvent(settings, 'FileChanged');
|
||||
assert.ok(
|
||||
matchers.some(m => m && m.includes('config.json')),
|
||||
`FileChanged matcher should target config.json; got matchers: ${JSON.stringify(matchers)}`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 3: Idempotency ─────────────────────────────────────────────────────
|
||||
|
||||
describe('enh-770: Claude install is idempotent for the new hook events', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-770-idem-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
stubHooksIntoTarget(path.join(tmpDir, '.claude'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('re-running after persisted first install does not duplicate context monitor hooks', () => {
|
||||
const result1 = install(false, 'claude', { installerMigrations: [] });
|
||||
persistSettings(result1.settingsPath, result1.settings);
|
||||
|
||||
process.chdir(tmpDir);
|
||||
const result2 = install(false, 'claude', { installerMigrations: [] });
|
||||
const s2 = result2.settings;
|
||||
|
||||
for (const event of ['SubagentStop', 'Stop', 'PreCompact']) {
|
||||
const cmds = hooksForEvent(s2, event);
|
||||
assert.strictEqual(cmds.length, 1,
|
||||
`Event ${event} should have exactly 1 hook after idempotent reinstall; got ${cmds.length}: ${JSON.stringify(cmds)}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('re-running after persisted first install does not duplicate FileChanged hook', () => {
|
||||
const result1 = install(false, 'claude', { installerMigrations: [] });
|
||||
persistSettings(result1.settingsPath, result1.settings);
|
||||
|
||||
process.chdir(tmpDir);
|
||||
const result2 = install(false, 'claude', { installerMigrations: [] });
|
||||
const s2 = result2.settings;
|
||||
|
||||
const cmds = hooksForEvent(s2, 'FileChanged');
|
||||
assert.strictEqual(cmds.length, 1,
|
||||
`FileChanged should have exactly 1 hook after idempotent reinstall; got ${cmds.length}: ${JSON.stringify(cmds)}`);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 4: Uninstall removes registrations ─────────────────────────────────
|
||||
|
||||
describe('enh-770: Uninstall removes new hook event entries', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-770-uninstall-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
stubHooksIntoTarget(path.join(tmpDir, '.claude'));
|
||||
|
||||
const result = install(false, 'claude', { installerMigrations: [] });
|
||||
persistSettings(result.settingsPath, result.settings);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('settings.json hook entries are removed on uninstall', () => {
|
||||
uninstall(false, 'claude', { installerMigrations: [] });
|
||||
const settingsPath = path.join(tmpDir, '.claude', 'settings.json');
|
||||
if (!fs.existsSync(settingsPath)) return; // file removed entirely is fine
|
||||
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
||||
for (const event of ['SubagentStop', 'Stop', 'PreCompact', 'FileChanged']) {
|
||||
const cmds = hooksForEvent(settings, event);
|
||||
assert.strictEqual(cmds.length, 0,
|
||||
`After uninstall, ${event} should have 0 hooks; got: ${JSON.stringify(cmds)}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 5: gsd-config-reload.js hook script exists and has correct shape ───
|
||||
|
||||
describe('enh-770: gsd-config-reload.js hook script', () => {
|
||||
const reloadScript = path.join(__dirname, '..', 'hooks', 'gsd-config-reload.js');
|
||||
|
||||
test('gsd-config-reload.js exists in hooks/', () => {
|
||||
assert.ok(fs.existsSync(reloadScript),
|
||||
`gsd-config-reload.js must exist at ${reloadScript}`);
|
||||
});
|
||||
|
||||
test('gsd-config-reload.js contains the gsd-hook-version stamp', () => {
|
||||
// allow-test-rule: runtime-contract-is-the-product — the stamp template token
|
||||
// IS the product surface that the installer must find and replace with the
|
||||
// real version at copy time; asserting its presence is required.
|
||||
const content = fs.readFileSync(reloadScript, 'utf8');
|
||||
assert.ok(
|
||||
content.includes('gsd-hook-version'),
|
||||
'gsd-config-reload.js must contain the gsd-hook-version stamp for installer stamping'
|
||||
);
|
||||
});
|
||||
|
||||
test('gsd-config-reload.js reads from stdin and emits JSON output', () => {
|
||||
// allow-test-rule: runtime-contract-is-the-product — the stdin-read and
|
||||
// JSON-emit pattern IS the hook contract; asserting its presence is required.
|
||||
const content = fs.readFileSync(reloadScript, 'utf8');
|
||||
assert.ok(
|
||||
content.includes('process.stdin') && content.includes('JSON.stringify'),
|
||||
'gsd-config-reload.js must read stdin and emit JSON output per hook protocol'
|
||||
);
|
||||
});
|
||||
|
||||
test('gsd-config-reload.js targets the FileChanged hook event', () => {
|
||||
// allow-test-rule: runtime-contract-is-the-product — the hookEventName is
|
||||
// the protocol surface; asserting its presence verifies the contract.
|
||||
const content = fs.readFileSync(reloadScript, 'utf8');
|
||||
assert.ok(
|
||||
content.includes('FileChanged'),
|
||||
'gsd-config-reload.js must reference FileChanged in its hookSpecificOutput'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 6: hooks.json plugin manifest includes new events ──────────────────
|
||||
|
||||
describe('enh-770: hooks/hooks.json plugin manifest includes new hook events', () => {
|
||||
const hooksJsonPath = path.join(__dirname, '..', 'hooks', 'hooks.json');
|
||||
|
||||
test('hooks.json exists', () => {
|
||||
assert.ok(fs.existsSync(hooksJsonPath), `hooks.json must exist at ${hooksJsonPath}`);
|
||||
});
|
||||
|
||||
test('hooks.json contains SubagentStop event', () => {
|
||||
// allow-test-rule: runtime-contract-is-the-product — hooks.json IS the
|
||||
// plugin manifest surface that Claude Code reads at plugin load time.
|
||||
const content = JSON.parse(fs.readFileSync(hooksJsonPath, 'utf8'));
|
||||
assert.ok(
|
||||
content.hooks && content.hooks.SubagentStop,
|
||||
'hooks.json must contain SubagentStop'
|
||||
);
|
||||
});
|
||||
|
||||
test('hooks.json contains Stop event', () => {
|
||||
// allow-test-rule: runtime-contract-is-the-product — hooks.json IS the
|
||||
// plugin manifest surface that Claude Code reads at plugin load time.
|
||||
const content = JSON.parse(fs.readFileSync(hooksJsonPath, 'utf8'));
|
||||
assert.ok(
|
||||
content.hooks && content.hooks.Stop,
|
||||
'hooks.json must contain Stop'
|
||||
);
|
||||
});
|
||||
|
||||
test('hooks.json contains PreCompact event', () => {
|
||||
// allow-test-rule: runtime-contract-is-the-product — hooks.json IS the
|
||||
// plugin manifest surface that Claude Code reads at plugin load time.
|
||||
const content = JSON.parse(fs.readFileSync(hooksJsonPath, 'utf8'));
|
||||
assert.ok(
|
||||
content.hooks && content.hooks.PreCompact,
|
||||
'hooks.json must contain PreCompact'
|
||||
);
|
||||
});
|
||||
|
||||
test('hooks.json contains FileChanged event', () => {
|
||||
// allow-test-rule: runtime-contract-is-the-product — hooks.json IS the
|
||||
// plugin manifest surface that Claude Code reads at plugin load time.
|
||||
const content = JSON.parse(fs.readFileSync(hooksJsonPath, 'utf8'));
|
||||
assert.ok(
|
||||
content.hooks && content.hooks.FileChanged,
|
||||
'hooks.json must contain FileChanged'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 7: managed-hooks-registry includes gsd-config-reload.js ───────────
|
||||
|
||||
describe('enh-770: managed-hooks-registry includes gsd-config-reload.js', () => {
|
||||
test('MANAGED_HOOKS array includes gsd-config-reload.js', () => {
|
||||
const { MANAGED_HOOKS } = require('../hooks/managed-hooks-registry.cjs');
|
||||
assert.ok(
|
||||
MANAGED_HOOKS.includes('gsd-config-reload.js'),
|
||||
`MANAGED_HOOKS must include gsd-config-reload.js; got: ${JSON.stringify(MANAGED_HOOKS)}`
|
||||
);
|
||||
});
|
||||
});
|
||||
411
tests/enh-772-codex-hook-events.test.cjs
Normal file
411
tests/enh-772-codex-hook-events.test.cjs
Normal file
@@ -0,0 +1,411 @@
|
||||
'use strict';
|
||||
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
/**
|
||||
* Enhancement #772: Adopt new stable Codex hook events + commandWindows for
|
||||
* Windows parity.
|
||||
*
|
||||
* Codex CLI (rust-v0.137.0) stabilised the full hook-event set. This suite
|
||||
* asserts that a Codex install:
|
||||
*
|
||||
* (a) Registers the 3 new high-value hook events in hooks.json:
|
||||
* - SubagentStart — inject context / GSD_AGENT_NAME awareness at subagent open
|
||||
* - Stop — post-session context headroom tracking
|
||||
* - PostToolUse — mirror the Claude Code PostToolUse context monitor
|
||||
*
|
||||
* (b) Emits `commandWindows` in the SessionStart hooks.json entry so that
|
||||
* Windows users get the .cmd shim path and non-Windows users get the POSIX
|
||||
* node runner command. Both fields are present in the same entry; Codex picks
|
||||
* the right one per its HookHandlerConfig schema
|
||||
* (codex-rs/config/src/hook_config.rs: commandWindows / command_windows alias).
|
||||
*
|
||||
* Note: UserPromptSubmit is NOT wired (same rationale as Qwen #788 — the
|
||||
* gsd-prompt-guard handler exits unless tool_name is Write|Edit, so it would be
|
||||
* a silent no-op for the UserPromptSubmit payload shape).
|
||||
*
|
||||
* Test strategy:
|
||||
* - Test new event registration via ensureCodexHooksJsonEvent() directly
|
||||
* (mirrors the #3426 pattern of testing ensureCodexHooksJsonSessionStart
|
||||
* directly with a stub hook file — avoids full install() migration dance).
|
||||
* - Test commandWindows via ensureCodexHooksJsonSessionStart() directly.
|
||||
* - IR-first discipline: assert on the structured result, not rendered text.
|
||||
*
|
||||
* Verified hook event schema:
|
||||
* https://github.com/openai/codex/blob/main/codex-rs/protocol/src/protocol.rs
|
||||
* https://github.com/openai/codex/blob/main/codex/codex-rs/config/src/hook_config.rs
|
||||
*/
|
||||
|
||||
const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const INSTALL = require('../bin/install.js');
|
||||
const {
|
||||
ensureCodexHooksJsonSessionStart,
|
||||
ensureCodexHooksJsonEvent,
|
||||
removeCodexHooksJsonEvent,
|
||||
reconcileCodexHooksJsonEvent,
|
||||
} = INSTALL;
|
||||
const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Extract all hook handler entries (full objects with type/command/etc.) for
|
||||
* `eventName` from a hooks.json object (flat or nested-hooks shape).
|
||||
*/
|
||||
function hooksJsonHandlersForEvent(hooksJson, eventName) {
|
||||
if (!hooksJson || typeof hooksJson !== 'object') return [];
|
||||
const table =
|
||||
hooksJson.hooks && typeof hooksJson.hooks === 'object' && !Array.isArray(hooksJson.hooks)
|
||||
? hooksJson.hooks
|
||||
: hooksJson;
|
||||
if (!Array.isArray(table[eventName])) return [];
|
||||
return table[eventName].flatMap(entry =>
|
||||
Array.isArray(entry && entry.hooks) ? entry.hooks : []
|
||||
);
|
||||
}
|
||||
|
||||
function readHooksJson(targetDir) {
|
||||
const p = path.join(targetDir, 'hooks.json');
|
||||
if (!fs.existsSync(p)) return null;
|
||||
return JSON.parse(fs.readFileSync(p, 'utf8'));
|
||||
}
|
||||
|
||||
function stubHookFile(targetDir, hookName) {
|
||||
const hooksDest = path.join(targetDir, 'hooks');
|
||||
fs.mkdirSync(hooksDest, { recursive: true });
|
||||
const dest = path.join(hooksDest, hookName);
|
||||
if (!fs.existsSync(dest)) {
|
||||
fs.writeFileSync(dest, '#!/usr/bin/env node\n// stub\n');
|
||||
try { fs.chmodSync(dest, 0o755); } catch { /* Windows */ }
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Suite 1: ensureCodexHooksJsonEvent export surface ───────────────────────
|
||||
|
||||
describe('enh-772: export surface — new functions are exported', () => {
|
||||
test('ensureCodexHooksJsonEvent is a function', () => {
|
||||
assert.strictEqual(typeof ensureCodexHooksJsonEvent, 'function',
|
||||
'ensureCodexHooksJsonEvent must be exported from bin/install.js');
|
||||
});
|
||||
|
||||
test('removeCodexHooksJsonEvent is a function', () => {
|
||||
assert.strictEqual(typeof removeCodexHooksJsonEvent, 'function',
|
||||
'removeCodexHooksJsonEvent must be exported from bin/install.js');
|
||||
});
|
||||
|
||||
test('reconcileCodexHooksJsonEvent is a function', () => {
|
||||
assert.strictEqual(typeof reconcileCodexHooksJsonEvent, 'function',
|
||||
'reconcileCodexHooksJsonEvent must be exported from bin/install.js');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 2: ensureCodexHooksJsonEvent registers new events ─────────────────
|
||||
|
||||
describe('enh-772: ensureCodexHooksJsonEvent registers SubagentStart, Stop, PostToolUse', () => {
|
||||
let tmpDir;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-772-events-');
|
||||
stubHookFile(tmpDir, 'gsd-context-monitor.js');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
for (const eventName of ['SubagentStart', 'Stop', 'PostToolUse']) {
|
||||
test(`${eventName}: ensureCodexHooksJsonEvent writes hooks.json`, () => {
|
||||
const fakeRunner = '"/usr/local/bin/node"';
|
||||
const result = ensureCodexHooksJsonEvent(tmpDir, eventName, {
|
||||
absoluteRunner: fakeRunner,
|
||||
platform: 'linux',
|
||||
});
|
||||
assert.ok(result && result.path, `result must have path for ${eventName}`);
|
||||
assert.ok(result.wrote || result.changed,
|
||||
`ensureCodexHooksJsonEvent must write or change hooks.json for ${eventName}`);
|
||||
assert.ok(fs.existsSync(path.join(tmpDir, 'hooks.json')),
|
||||
`hooks.json must exist after registering ${eventName}`);
|
||||
});
|
||||
|
||||
test(`${eventName}: hooks.json contains the event entry`, () => {
|
||||
const fakeRunner = '"/usr/local/bin/node"';
|
||||
ensureCodexHooksJsonEvent(tmpDir, eventName, {
|
||||
absoluteRunner: fakeRunner,
|
||||
platform: 'linux',
|
||||
});
|
||||
const hooksJson = readHooksJson(tmpDir);
|
||||
const handlers = hooksJsonHandlersForEvent(hooksJson, eventName);
|
||||
assert.ok(handlers.length > 0,
|
||||
`Expected ${eventName} entry in hooks.json; got: ${JSON.stringify(hooksJson)}`);
|
||||
});
|
||||
|
||||
test(`${eventName}: hook entry uses gsd-context-monitor`, () => {
|
||||
const fakeRunner = '"/usr/local/bin/node"';
|
||||
ensureCodexHooksJsonEvent(tmpDir, eventName, {
|
||||
absoluteRunner: fakeRunner,
|
||||
platform: 'linux',
|
||||
});
|
||||
const hooksJson = readHooksJson(tmpDir);
|
||||
const handlers = hooksJsonHandlersForEvent(hooksJson, eventName);
|
||||
assert.ok(
|
||||
handlers.some(h => h.command && h.command.includes('gsd-context-monitor')),
|
||||
`${eventName} hook must use gsd-context-monitor; got: ${JSON.stringify(handlers)}`
|
||||
);
|
||||
});
|
||||
|
||||
test(`${eventName}: hook entry has type: 'command'`, () => {
|
||||
const fakeRunner = '"/usr/local/bin/node"';
|
||||
ensureCodexHooksJsonEvent(tmpDir, eventName, {
|
||||
absoluteRunner: fakeRunner,
|
||||
platform: 'linux',
|
||||
});
|
||||
const hooksJson = readHooksJson(tmpDir);
|
||||
const handlers = hooksJsonHandlersForEvent(hooksJson, eventName);
|
||||
const entry = handlers.find(h => h.command && h.command.includes('gsd-context-monitor'));
|
||||
assert.strictEqual(entry && entry.type, 'command',
|
||||
`${eventName} hook entry must have type 'command'`);
|
||||
});
|
||||
|
||||
test(`${eventName}: hook entry has timeout: 10`, () => {
|
||||
const fakeRunner = '"/usr/local/bin/node"';
|
||||
ensureCodexHooksJsonEvent(tmpDir, eventName, {
|
||||
absoluteRunner: fakeRunner,
|
||||
platform: 'linux',
|
||||
});
|
||||
const hooksJson = readHooksJson(tmpDir);
|
||||
const handlers = hooksJsonHandlersForEvent(hooksJson, eventName);
|
||||
const entry = handlers.find(h => h.command && h.command.includes('gsd-context-monitor'));
|
||||
assert.strictEqual(entry && entry.timeout, 10,
|
||||
`${eventName} hook entry must have timeout 10`);
|
||||
});
|
||||
}
|
||||
|
||||
test('null absoluteRunner returns unchanged result without writing', () => {
|
||||
const result = ensureCodexHooksJsonEvent(tmpDir, 'SubagentStart', {
|
||||
absoluteRunner: null,
|
||||
platform: 'linux',
|
||||
});
|
||||
assert.strictEqual(result.changed, false,
|
||||
'null runner must return changed: false');
|
||||
assert.ok(!fs.existsSync(path.join(tmpDir, 'hooks.json')),
|
||||
'hooks.json must NOT be written when runner is null');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 3: commandWindows parity in SessionStart ──────────────────────────
|
||||
|
||||
describe('enh-772: commandWindows parity — ensureCodexHooksJsonSessionStart emits commandWindows', () => {
|
||||
let tmpDir;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-772-cmdwin-');
|
||||
stubHookFile(tmpDir, 'gsd-check-update.js');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
// commandWindows is ONLY emitted on win32 platform (where the .cmd shim is also
|
||||
// written). On POSIX platforms, commandWindows is omitted to avoid pointing Windows
|
||||
// Codex at a non-existent .cmd file (the shim is only present after a native Windows
|
||||
// install that runs buildCodexHookWindowsShimIR and atomicWriteFileSync).
|
||||
|
||||
test('POSIX platform: commandWindows is NOT emitted (shim not written on POSIX)', () => {
|
||||
const fakeRunner = '"/usr/local/bin/node"';
|
||||
const result = ensureCodexHooksJsonSessionStart(tmpDir, {
|
||||
absoluteRunner: fakeRunner,
|
||||
platform: 'linux',
|
||||
});
|
||||
assert.ok(result && result.wrote, 'must write hooks.json on linux');
|
||||
|
||||
const hooksJson = readHooksJson(tmpDir);
|
||||
const handlers = hooksJsonHandlersForEvent(hooksJson, 'SessionStart');
|
||||
assert.ok(handlers.length > 0, `Expected SessionStart handlers; got: ${JSON.stringify(hooksJson)}`);
|
||||
|
||||
const entry = handlers[0];
|
||||
assert.ok(
|
||||
entry.commandWindows === undefined,
|
||||
`commandWindows must NOT be emitted on POSIX (shim not written); got: ${JSON.stringify(entry)}`
|
||||
);
|
||||
});
|
||||
|
||||
test('POSIX platform: command references gsd-check-update.js (not .cmd)', () => {
|
||||
const fakeRunner = '"/usr/local/bin/node"';
|
||||
ensureCodexHooksJsonSessionStart(tmpDir, {
|
||||
absoluteRunner: fakeRunner,
|
||||
platform: 'linux',
|
||||
});
|
||||
const hooksJson = readHooksJson(tmpDir);
|
||||
const handlers = hooksJsonHandlersForEvent(hooksJson, 'SessionStart');
|
||||
const entry = handlers[0];
|
||||
assert.ok(
|
||||
entry.command && entry.command.includes('gsd-check-update'),
|
||||
`POSIX command must reference gsd-check-update; got: ${entry.command}`
|
||||
);
|
||||
assert.ok(
|
||||
!entry.command.endsWith('.cmd') && !entry.command.endsWith('.cmd"'),
|
||||
`POSIX command must not end with .cmd; got: ${entry.command}`
|
||||
);
|
||||
});
|
||||
|
||||
test('null absoluteRunner: no commandWindows emitted, no write', () => {
|
||||
const result = ensureCodexHooksJsonSessionStart(tmpDir, {
|
||||
absoluteRunner: null,
|
||||
platform: 'linux',
|
||||
});
|
||||
assert.strictEqual(result.changed, false, 'null runner must return changed: false');
|
||||
const hooksJson = readHooksJson(tmpDir);
|
||||
if (hooksJson) {
|
||||
const handlers = hooksJsonHandlersForEvent(hooksJson, 'SessionStart');
|
||||
for (const h of handlers) {
|
||||
assert.ok(!h.commandWindows,
|
||||
`commandWindows must not be present when runner is null; got: ${JSON.stringify(h)}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('Windows platform: SessionStart hook is written with commandWindows pointing to .cmd shim', () => {
|
||||
// On win32, both `command` and `commandWindows` use the .cmd shim path
|
||||
// (because managedCommand = shimIR.hookCommand = .cmd path, and
|
||||
// commandWindows = same .cmd path). This ensures Codex picks the .cmd
|
||||
// on Windows regardless of which field it reads.
|
||||
const fakeRunner = '"C:/Program Files/nodejs/node.exe"';
|
||||
const result = ensureCodexHooksJsonSessionStart(tmpDir, {
|
||||
absoluteRunner: fakeRunner,
|
||||
platform: 'win32',
|
||||
});
|
||||
// The shim write and hooks.json write should succeed in the tmp dir.
|
||||
if (result.wrote) {
|
||||
const hooksJson = readHooksJson(tmpDir);
|
||||
const handlers = hooksJsonHandlersForEvent(hooksJson, 'SessionStart');
|
||||
assert.ok(handlers.length > 0,
|
||||
`SessionStart must be registered on Windows path; got: ${JSON.stringify(hooksJson)}`);
|
||||
const entry = handlers[0];
|
||||
assert.ok(typeof entry.commandWindows === 'string',
|
||||
`commandWindows must be present on Windows path; got: ${JSON.stringify(entry)}`);
|
||||
// commandWindows should reference the .cmd shim
|
||||
assert.ok(
|
||||
entry.commandWindows.includes('gsd-check-update') && entry.commandWindows.includes('.cmd'),
|
||||
`commandWindows must reference gsd-check-update.cmd on win32; got: ${entry.commandWindows}`
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 4: idempotency ────────────────────────────────────────────────────
|
||||
|
||||
describe('enh-772: ensureCodexHooksJsonEvent is idempotent', () => {
|
||||
let tmpDir;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-772-idem-');
|
||||
stubHookFile(tmpDir, 'gsd-context-monitor.js');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
for (const eventName of ['SubagentStart', 'Stop', 'PostToolUse']) {
|
||||
test(`${eventName}: calling twice does not duplicate hook entries`, () => {
|
||||
const fakeRunner = '"/usr/local/bin/node"';
|
||||
const opts = { absoluteRunner: fakeRunner, platform: 'linux' };
|
||||
|
||||
ensureCodexHooksJsonEvent(tmpDir, eventName, opts);
|
||||
ensureCodexHooksJsonEvent(tmpDir, eventName, opts);
|
||||
|
||||
const hooksJson = readHooksJson(tmpDir);
|
||||
const handlers = hooksJsonHandlersForEvent(hooksJson, eventName);
|
||||
assert.strictEqual(handlers.length, 1,
|
||||
`${eventName} should have exactly 1 hook handler after idempotent re-register; got ${handlers.length}: ${JSON.stringify(handlers)}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Suite 5: removeCodexHooksJsonEvent ──────────────────────────────────────
|
||||
|
||||
describe('enh-772: removeCodexHooksJsonEvent removes managed entries', () => {
|
||||
let tmpDir;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-772-remove-');
|
||||
stubHookFile(tmpDir, 'gsd-context-monitor.js');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
for (const eventName of ['SubagentStart', 'Stop', 'PostToolUse']) {
|
||||
test(`${eventName}: removeCodexHooksJsonEvent removes the managed entry`, () => {
|
||||
const fakeRunner = '"/usr/local/bin/node"';
|
||||
ensureCodexHooksJsonEvent(tmpDir, eventName, {
|
||||
absoluteRunner: fakeRunner,
|
||||
platform: 'linux',
|
||||
});
|
||||
|
||||
// Verify it was registered
|
||||
let hooksJson = readHooksJson(tmpDir);
|
||||
let handlers = hooksJsonHandlersForEvent(hooksJson, eventName);
|
||||
assert.ok(handlers.length > 0, `${eventName} must be registered before removal`);
|
||||
|
||||
// Remove
|
||||
const result = removeCodexHooksJsonEvent(tmpDir, eventName);
|
||||
assert.ok(result.changed || result.wrote,
|
||||
`removeCodexHooksJsonEvent must change hooks.json for ${eventName}`);
|
||||
|
||||
hooksJson = readHooksJson(tmpDir);
|
||||
if (hooksJson) {
|
||||
handlers = hooksJsonHandlersForEvent(hooksJson, eventName);
|
||||
assert.strictEqual(handlers.length, 0,
|
||||
`After removal, ${eventName} should have 0 handlers; got: ${JSON.stringify(handlers)}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Suite 6: reconcileCodexHooksJsonEvent preserves user entries ─────────────
|
||||
|
||||
describe('enh-772: reconcileCodexHooksJsonEvent preserves user-owned entries', () => {
|
||||
let tmpDir;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-772-preserve-');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('user-owned SubagentStart entry is preserved when GSD entry is registered', () => {
|
||||
const hooksJsonPath = path.join(tmpDir, 'hooks.json');
|
||||
const userEntry = {
|
||||
hooks: [{ type: 'command', command: 'my-custom-hook.sh' }]
|
||||
};
|
||||
fs.writeFileSync(hooksJsonPath, JSON.stringify({
|
||||
SubagentStart: [userEntry]
|
||||
}, null, 2) + '\n');
|
||||
|
||||
reconcileCodexHooksJsonEvent(tmpDir, 'SubagentStart', {
|
||||
managedCommand: '"/usr/local/bin/node" "/home/me/.codex/hooks/gsd-context-monitor.js"',
|
||||
});
|
||||
|
||||
const hooksJson = JSON.parse(fs.readFileSync(hooksJsonPath, 'utf8'));
|
||||
const table = hooksJson.hooks || hooksJson;
|
||||
const entries = Array.isArray(table.SubagentStart) ? table.SubagentStart : [];
|
||||
// Should have 2 entries: user entry + GSD entry
|
||||
assert.ok(entries.length >= 2,
|
||||
`User entry must be preserved; got entries: ${JSON.stringify(entries)}`);
|
||||
// User entry must still be present
|
||||
const userEntryStillPresent = entries.some(e =>
|
||||
Array.isArray(e.hooks) && e.hooks.some(h => h.command === 'my-custom-hook.sh')
|
||||
);
|
||||
assert.ok(userEntryStillPresent,
|
||||
`User entry must survive GSD registration; entries: ${JSON.stringify(entries)}`);
|
||||
});
|
||||
});
|
||||
68
tests/enh-773-codex-exec-automation-flags.test.cjs
Normal file
68
tests/enh-773-codex-exec-automation-flags.test.cjs
Normal file
@@ -0,0 +1,68 @@
|
||||
'use strict';
|
||||
|
||||
// allow-test-rule: source-text-is-the-product
|
||||
// Workflow markdown is runtime contract; these assertions verify that
|
||||
// automated codex exec invocations carry the correct automation flags.
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
describe('enh-773: automated codex exec invocations include --ephemeral and --dangerously-bypass-hook-trust', () => {
|
||||
const workflow = fs.readFileSync(
|
||||
path.join(process.cwd(), 'gsd-core', 'workflows', 'review.md'),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
// Extract all codex exec invocation lines from code fences
|
||||
const codexExecLines = workflow
|
||||
.split('\n')
|
||||
.filter((line) => line.includes('codex exec'));
|
||||
|
||||
test('review.md contains at least one codex exec invocation', () => {
|
||||
assert.ok(
|
||||
codexExecLines.length > 0,
|
||||
'review.md must contain at least one codex exec invocation'
|
||||
);
|
||||
});
|
||||
|
||||
test('every codex exec invocation includes --ephemeral', () => {
|
||||
for (const line of codexExecLines) {
|
||||
assert.ok(
|
||||
line.includes('--ephemeral'),
|
||||
`codex exec invocation is missing --ephemeral:\n ${line.trim()}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('every codex exec invocation includes --dangerously-bypass-hook-trust', () => {
|
||||
for (const line of codexExecLines) {
|
||||
assert.ok(
|
||||
line.includes('--dangerously-bypass-hook-trust'),
|
||||
`codex exec invocation is missing --dangerously-bypass-hook-trust:\n ${line.trim()}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('--ephemeral appears before the prompt argument (flag ordering)', () => {
|
||||
for (const line of codexExecLines) {
|
||||
const ephemeralPos = line.indexOf('--ephemeral');
|
||||
const promptPos = line.indexOf(' - ');
|
||||
if (promptPos === -1) continue; // no stdin prompt arg on this line
|
||||
assert.ok(
|
||||
ephemeralPos < promptPos,
|
||||
`--ephemeral must appear before the stdin prompt argument:\n ${line.trim()}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('--skip-git-repo-check is preserved alongside automation flags', () => {
|
||||
for (const line of codexExecLines) {
|
||||
assert.ok(
|
||||
line.includes('--skip-git-repo-check'),
|
||||
`codex exec invocation lost --skip-git-repo-check:\n ${line.trim()}`
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
406
tests/enh-776-install-gemini-hook-events.test.cjs
Normal file
406
tests/enh-776-install-gemini-hook-events.test.cjs
Normal file
@@ -0,0 +1,406 @@
|
||||
'use strict';
|
||||
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
/**
|
||||
* Enhancement #776: Adopt new Gemini hook events + detect hooksConfig.enabled:false.
|
||||
*
|
||||
* Gemini CLI exposes several hook events beyond BeforeTool/AfterTool that gsd
|
||||
* previously did not register. This suite asserts that a Gemini install
|
||||
* registers the 3 new high-value events:
|
||||
* - BeforeAgent — fires before the agent plans (context headroom tracking)
|
||||
* - AfterAgent — fires after final response generation (context tracking)
|
||||
* - BeforeModel — fires before each LLM call (per-turn context awareness)
|
||||
*
|
||||
* All three are wired to gsd-context-monitor.js — the same hook used for
|
||||
* AfterTool — so context headroom warnings surface at these lifecycle moments.
|
||||
*
|
||||
* Also asserts:
|
||||
* - Claude Code installs do NOT gain these Gemini-only events (strict scope guard).
|
||||
* - Reinstalls are idempotent (no hook duplication).
|
||||
* - Uninstall removes the new event registrations.
|
||||
* - hooksConfig.enabled:false warning is emitted during a Gemini install.
|
||||
*
|
||||
* Source: https://github.com/google-gemini/gemini-cli/blob/main/docs/hooks/reference.md
|
||||
*/
|
||||
|
||||
const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const { install, uninstall, validateHookFields } = require('../bin/install.js');
|
||||
const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Extract all hook commands registered under `eventName` from settings. */
|
||||
function hooksForEvent(settings, eventName) {
|
||||
if (!settings || !settings.hooks || !Array.isArray(settings.hooks[eventName])) return [];
|
||||
return settings.hooks[eventName].flatMap(entry =>
|
||||
(entry && Array.isArray(entry.hooks) ? entry.hooks : [])
|
||||
.map(h => h && h.command)
|
||||
.filter(Boolean)
|
||||
);
|
||||
}
|
||||
|
||||
// Stub JS hook files that the installer checks with fs.existsSync() so hook
|
||||
// registration guards pass even when hooks/dist/ isn't built.
|
||||
//
|
||||
// For Gemini, the installer migration baseline includes 'hooks/' in its surface
|
||||
// list (unlike Qwen which excludes it). Pre-install stubs placed in .gemini/hooks/
|
||||
// are classified as 'bundled-gsd-hook' and auto-removed by the migration before
|
||||
// registration can succeed. The workaround: run a first install (which writes the
|
||||
// gsd-file-manifest.json), then add the stubs, then run install again. On the
|
||||
// second install the manifest marks the hook files as managed, so migration keeps
|
||||
// them and registration guards (fs.existsSync) pass.
|
||||
const HOOKS_SRC = path.join(__dirname, '..', 'hooks');
|
||||
const STUB_HOOKS = [
|
||||
'gsd-context-monitor.js',
|
||||
'gsd-prompt-guard.js',
|
||||
'gsd-check-update.js',
|
||||
];
|
||||
|
||||
function stubHooksIntoTarget(targetDir) {
|
||||
const hooksDest = path.join(targetDir, 'hooks');
|
||||
fs.mkdirSync(hooksDest, { recursive: true });
|
||||
for (const hookFile of STUB_HOOKS) {
|
||||
const src = path.join(HOOKS_SRC, hookFile);
|
||||
const dest = path.join(hooksDest, hookFile);
|
||||
if (fs.existsSync(src)) {
|
||||
fs.copyFileSync(src, dest);
|
||||
} else {
|
||||
// Minimal stub so existsSync passes
|
||||
fs.writeFileSync(dest, '#!/usr/bin/env node\n// stub\n');
|
||||
}
|
||||
try { fs.chmodSync(dest, 0o755); } catch { /* Windows */ }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Two-pass Gemini install.
|
||||
*
|
||||
* Pass 1: install() with no hook stubs — writes gsd-file-manifest.json.
|
||||
* Migration runs on an empty hooks/ so nothing gets auto-removed.
|
||||
* Pass 2: stub hooks into the target dir (now manifest-tracked on next scan),
|
||||
* then run install() again. Migration now classifies the hooks as
|
||||
* managed-unchanged and preserves them; registration guards pass.
|
||||
*
|
||||
* Returns the settings from pass 2.
|
||||
*/
|
||||
function twoPassGeminiInstall(tmpDir) {
|
||||
const targetDir = path.join(tmpDir, '.gemini');
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
|
||||
// Pass 1 — no hook stubs yet; writes the manifest
|
||||
const result1 = install(false, 'gemini');
|
||||
persistSettings(result1.settingsPath, result1.settings);
|
||||
|
||||
// Inject stubs so the registration guards (fs.existsSync) pass on pass 2
|
||||
stubHooksIntoTarget(targetDir);
|
||||
|
||||
// Pass 2 — manifest exists, migration keeps stubs, registration succeeds
|
||||
process.chdir(tmpDir);
|
||||
const result2 = install(false, 'gemini');
|
||||
return result2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist in-memory settings to disk, simulating what finishInstall() does
|
||||
* (finishInstall is not exported). Required for tests that call install()
|
||||
* twice and need the second call to read the first call's hook registrations.
|
||||
*/
|
||||
function persistSettings(settingsPath, settings) {
|
||||
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
|
||||
fs.writeFileSync(settingsPath, JSON.stringify(validateHookFields(settings), null, 2) + '\n', 'utf8');
|
||||
}
|
||||
|
||||
// ─── Suite 1: Gemini — new events are registered ─────────────────────────────
|
||||
|
||||
describe('enh-776: Gemini install registers 3 new hook events', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
let settings;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-776-gemini-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
|
||||
// Two-pass install: first pass writes manifest, second pass with stubs
|
||||
// so registration guards (fs.existsSync) pass.
|
||||
const result = twoPassGeminiInstall(tmpDir);
|
||||
settings = result.settings;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('install returns a settings object (not null)', () => {
|
||||
assert.ok(settings !== null && typeof settings === 'object',
|
||||
'Gemini install must return a non-null settings object');
|
||||
});
|
||||
|
||||
test('BeforeAgent event is registered with at least one hook', () => {
|
||||
const cmds = hooksForEvent(settings, 'BeforeAgent');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Expected BeforeAgent hooks; got hooks: ${JSON.stringify(settings && settings.hooks)}`);
|
||||
});
|
||||
|
||||
test('AfterAgent event is registered with at least one hook', () => {
|
||||
const cmds = hooksForEvent(settings, 'AfterAgent');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Expected AfterAgent hooks; got hooks: ${JSON.stringify(settings && settings.hooks)}`);
|
||||
});
|
||||
|
||||
test('BeforeModel event is registered with at least one hook', () => {
|
||||
const cmds = hooksForEvent(settings, 'BeforeModel');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Expected BeforeModel hooks; got hooks: ${JSON.stringify(settings && settings.hooks)}`);
|
||||
});
|
||||
|
||||
test('BeforeAgent / AfterAgent / BeforeModel all use gsd-context-monitor', () => {
|
||||
for (const event of ['BeforeAgent', 'AfterAgent', 'BeforeModel']) {
|
||||
const cmds = hooksForEvent(settings, event);
|
||||
assert.ok(
|
||||
cmds.some(c => c.includes('gsd-context-monitor')),
|
||||
`Event ${event} should use gsd-context-monitor; got commands: ${JSON.stringify(cmds)}`
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 2: Non-Gemini installs do NOT get the new events ──────────────────
|
||||
//
|
||||
// Two runtimes are particularly important to guard:
|
||||
// Claude — the canonical non-Gemini runtime
|
||||
// Antigravity — shares Gemini-style BeforeTool/AfterTool naming and uses
|
||||
// isGemini-adjacent logic; a future accidental
|
||||
// `isGemini || isAntigravity` change must be caught here.
|
||||
|
||||
describe('enh-776: Claude install does NOT register Gemini-only hook events', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
let settings;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-776-claude-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
|
||||
const result = install(false, 'claude');
|
||||
settings = result && result.settings;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('Claude install does not register BeforeAgent', () => {
|
||||
const cmds = hooksForEvent(settings, 'BeforeAgent');
|
||||
assert.strictEqual(cmds.length, 0,
|
||||
`Claude should NOT have BeforeAgent; got: ${JSON.stringify(cmds)}`);
|
||||
});
|
||||
|
||||
test('Claude install does not register AfterAgent', () => {
|
||||
const cmds = hooksForEvent(settings, 'AfterAgent');
|
||||
assert.strictEqual(cmds.length, 0,
|
||||
`Claude should NOT have AfterAgent; got: ${JSON.stringify(cmds)}`);
|
||||
});
|
||||
|
||||
test('Claude install does not register BeforeModel', () => {
|
||||
const cmds = hooksForEvent(settings, 'BeforeModel');
|
||||
assert.strictEqual(cmds.length, 0,
|
||||
`Claude should NOT have BeforeModel; got: ${JSON.stringify(cmds)}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('enh-776: Antigravity install does NOT register Gemini-only hook events', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
let settings;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-776-antigravity-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
|
||||
const result = install(false, 'antigravity');
|
||||
settings = result && result.settings;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('Antigravity install does not register BeforeAgent', () => {
|
||||
const cmds = hooksForEvent(settings, 'BeforeAgent');
|
||||
assert.strictEqual(cmds.length, 0,
|
||||
`Antigravity should NOT have BeforeAgent; got: ${JSON.stringify(cmds)}`);
|
||||
});
|
||||
|
||||
test('Antigravity install does not register AfterAgent', () => {
|
||||
const cmds = hooksForEvent(settings, 'AfterAgent');
|
||||
assert.strictEqual(cmds.length, 0,
|
||||
`Antigravity should NOT have AfterAgent; got: ${JSON.stringify(cmds)}`);
|
||||
});
|
||||
|
||||
test('Antigravity install does not register BeforeModel', () => {
|
||||
const cmds = hooksForEvent(settings, 'BeforeModel');
|
||||
assert.strictEqual(cmds.length, 0,
|
||||
`Antigravity should NOT have BeforeModel; got: ${JSON.stringify(cmds)}`);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 3: Idempotency — persisted reinstall does not duplicate hooks ──────
|
||||
|
||||
describe('enh-776: Gemini install is idempotent across persisted reinstalls', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-776-idem-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('re-running after persisted first install does not duplicate hook entries', () => {
|
||||
// Two-pass to get hooks installed.
|
||||
const result2 = twoPassGeminiInstall(tmpDir);
|
||||
const s2 = result2.settings;
|
||||
|
||||
// Assert hooks ARE registered after pass 2 (guards against false-pass where
|
||||
// hooks never registered and idempotency passes trivially at count=0).
|
||||
for (const event of ['BeforeAgent', 'AfterAgent', 'BeforeModel']) {
|
||||
const cmds = hooksForEvent(s2, event);
|
||||
assert.strictEqual(cmds.length, 1,
|
||||
`Event ${event} should have exactly 1 hook after two-pass install; got ${cmds.length}: ${JSON.stringify(cmds)}`);
|
||||
}
|
||||
|
||||
persistSettings(result2.settingsPath, s2);
|
||||
|
||||
// Third install: reads the persisted settings.json — dedup guards apply
|
||||
process.chdir(tmpDir);
|
||||
const result3 = install(false, 'gemini');
|
||||
const s3 = result3.settings;
|
||||
|
||||
for (const event of ['BeforeAgent', 'AfterAgent', 'BeforeModel']) {
|
||||
const cmds = hooksForEvent(s3, event);
|
||||
assert.strictEqual(cmds.length, 1,
|
||||
`Event ${event} should have exactly 1 hook command after idempotent reinstall; got ${cmds.length}: ${JSON.stringify(cmds)}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 4: Uninstall removes the new event registrations ──────────────────
|
||||
|
||||
describe('enh-776: Gemini uninstall removes new hook event entries', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-776-uninstall-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
|
||||
// Two-pass install and persist so uninstall has a settings.json to clean
|
||||
const result = twoPassGeminiInstall(tmpDir);
|
||||
persistSettings(result.settingsPath, result.settings);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('settings.json hook entries are removed on uninstall', () => {
|
||||
uninstall(false, 'gemini');
|
||||
const settingsPath = path.join(tmpDir, '.gemini', 'settings.json');
|
||||
if (!fs.existsSync(settingsPath)) return; // file removed entirely is fine
|
||||
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
||||
for (const event of ['BeforeAgent', 'AfterAgent', 'BeforeModel']) {
|
||||
const cmds = hooksForEvent(settings, event);
|
||||
assert.strictEqual(cmds.length, 0,
|
||||
`After uninstall, ${event} should have 0 hooks; got: ${JSON.stringify(cmds)}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 5: hooksConfig.enabled:false warning ───────────────────────────────
|
||||
|
||||
describe('enh-776: hooksConfig.enabled:false warning during Gemini install', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
let stderrLines;
|
||||
let originalWarn;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-776-hookscfg-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
|
||||
const targetDir = path.join(tmpDir, '.gemini');
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
|
||||
// Capture console.warn output
|
||||
stderrLines = [];
|
||||
originalWarn = console.warn;
|
||||
console.warn = (...args) => { stderrLines.push(args.join(' ')); };
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
console.warn = originalWarn;
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('emits a warning when hooksConfig.enabled is false', () => {
|
||||
// Write a settings.json with hooksConfig.enabled: false BEFORE install
|
||||
// (the check in install() reads the existing settings.json on disk).
|
||||
const targetDir = path.join(tmpDir, '.gemini');
|
||||
const settingsPath = path.join(targetDir, 'settings.json');
|
||||
fs.writeFileSync(settingsPath, JSON.stringify({ hooksConfig: { enabled: false } }, null, 2) + '\n', 'utf8');
|
||||
|
||||
install(false, 'gemini');
|
||||
const warnText = stderrLines.join('\n');
|
||||
assert.ok(
|
||||
warnText.includes('hooksConfig.enabled is false'),
|
||||
`Expected hooksConfig.enabled warning; got console.warn output:\n${warnText}`
|
||||
);
|
||||
});
|
||||
|
||||
test('does NOT emit the hooksConfig warning when hooksConfig.enabled is true', () => {
|
||||
const targetDir = path.join(tmpDir, '.gemini');
|
||||
const settingsPath = path.join(targetDir, 'settings.json');
|
||||
fs.writeFileSync(settingsPath, JSON.stringify({ hooksConfig: { enabled: true } }, null, 2) + '\n', 'utf8');
|
||||
|
||||
install(false, 'gemini');
|
||||
const warnText = stderrLines.join('\n');
|
||||
assert.ok(
|
||||
!warnText.includes('hooksConfig.enabled is false'),
|
||||
`Should NOT warn when hooksConfig.enabled is true; got:\n${warnText}`
|
||||
);
|
||||
});
|
||||
|
||||
test('does NOT emit the hooksConfig warning when hooksConfig is absent', () => {
|
||||
const targetDir = path.join(tmpDir, '.gemini');
|
||||
const settingsPath = path.join(targetDir, 'settings.json');
|
||||
fs.writeFileSync(settingsPath, JSON.stringify({}, null, 2) + '\n', 'utf8');
|
||||
|
||||
install(false, 'gemini');
|
||||
const warnText = stderrLines.join('\n');
|
||||
assert.ok(
|
||||
!warnText.includes('hooksConfig.enabled is false'),
|
||||
`Should NOT warn when hooksConfig is absent; got:\n${warnText}`
|
||||
);
|
||||
});
|
||||
});
|
||||
227
tests/enh-778-cross-runtime-command-enrichment.test.cjs
Normal file
227
tests/enh-778-cross-runtime-command-enrichment.test.cjs
Normal file
@@ -0,0 +1,227 @@
|
||||
// allow-test-rule: source-text-is-the-product
|
||||
// Reads .md/SKILL.md/.toml product files whose deployed text IS what the
|
||||
// runtime loads — testing text content tests the deployed contract.
|
||||
|
||||
/**
|
||||
* GSD Tools Tests — #778 cross-runtime command enrichment.
|
||||
*
|
||||
* Two independently-verified, additive sub-features:
|
||||
* (b) Qwen Code skills: numeric `priority` field (higher sorts earlier in the
|
||||
* /skills TUI listing per the Qwen skills spec). Scoped to runtime='qwen'.
|
||||
* (c) Gemini custom-command TOML: $ARGUMENTS → {{args}} interpolation, and a
|
||||
* fixed `!{cat .planning/STATE.md}` live-state injection on the
|
||||
* situational `progress` command (injection-safe — no interpolated input).
|
||||
*
|
||||
* The OpenCode sub-feature (per-command model/agent/subtask/variant) is
|
||||
* intentionally NOT implemented — see PR description: `model` reintroduces the
|
||||
* #1156 ProviderModelNotFoundError regression for non-Anthropic OpenCode users,
|
||||
* `subtask`/`agent` change execution semantics for GSD's interactive commands,
|
||||
* and `variant` is not in the OpenCode command schema.
|
||||
*
|
||||
* Uses node:test and node:assert (NOT Jest).
|
||||
*/
|
||||
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
const {
|
||||
convertClaudeCommandToClaudeSkill,
|
||||
convertClaudeToGeminiMarkdown,
|
||||
install,
|
||||
} = require('../bin/install.js');
|
||||
|
||||
// ─── (b) Qwen Code: priority ordering ───────────────────────────────────────
|
||||
|
||||
describe('#778 (b) Qwen skills priority', () => {
|
||||
const mk = (name, desc, body) =>
|
||||
['---', `name: gsd:${name}`, `description: ${desc}`, '---', '', body].join('\n');
|
||||
|
||||
test('emits numeric priority for a core-loop command (runtime=qwen)', () => {
|
||||
const result = convertClaudeCommandToClaudeSkill(
|
||||
mk('plan-phase', 'Plan a phase', 'Body.'),
|
||||
'gsd-plan-phase',
|
||||
'qwen',
|
||||
[]
|
||||
);
|
||||
const m = result.match(/^priority:\s*(\d+)\s*$/m);
|
||||
assert.ok(m, 'priority field present for gsd-plan-phase');
|
||||
assert.equal(Number(m[1]) > 0, true, 'priority is a positive number');
|
||||
});
|
||||
|
||||
test('core loop ranks higher than mid-tier (higher = earlier per spec)', () => {
|
||||
const np = convertClaudeCommandToClaudeSkill(
|
||||
mk('new-project', 'Start a project', 'Body.'), 'gsd-new-project', 'qwen', []
|
||||
).match(/^priority:\s*(\d+)/m);
|
||||
const help = convertClaudeCommandToClaudeSkill(
|
||||
mk('help', 'Help', 'Body.'), 'gsd-help', 'qwen', []
|
||||
).match(/^priority:\s*(\d+)/m);
|
||||
assert.ok(np && help, 'both core and mid-tier get a priority');
|
||||
assert.ok(
|
||||
Number(np[1]) > Number(help[1]),
|
||||
'new-project (core) sorts earlier than help (utility) — higher value'
|
||||
);
|
||||
});
|
||||
|
||||
test('utility command NOT in the priority map gets no priority field', () => {
|
||||
const result = convertClaudeCommandToClaudeSkill(
|
||||
mk('stats', 'Show stats', 'Body.'), 'gsd-stats', 'qwen', []
|
||||
);
|
||||
assert.ok(!/^priority:/m.test(result), 'no priority emitted for unmapped utility');
|
||||
});
|
||||
|
||||
test('does NOT emit priority for non-qwen runtimes (scoped to qwen)', () => {
|
||||
for (const rt of [null, 'claude', 'hermes']) {
|
||||
const result = convertClaudeCommandToClaudeSkill(
|
||||
mk('plan-phase', 'Plan a phase', 'Body.'), 'gsd-plan-phase', rt, []
|
||||
);
|
||||
assert.ok(!/^priority:/m.test(result), `no priority for runtime=${rt}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── (c) Gemini: {{args}} interpolation ─────────────────────────────────────
|
||||
|
||||
describe('#778 (c) Gemini {{args}} interpolation', () => {
|
||||
const cmd = (body) =>
|
||||
['---', 'name: gsd:demo', 'description: Demo', '---', '', body].join('\n');
|
||||
|
||||
test('maps $ARGUMENTS to {{args}} in the TOML prompt', () => {
|
||||
const out = convertClaudeToGeminiMarkdown(
|
||||
cmd('Operate on $ARGUMENTS now.'),
|
||||
{ isCommand: true, commandName: 'demo' }
|
||||
);
|
||||
assert.ok(out.includes('{{args}}'), '{{args}} present');
|
||||
assert.ok(!out.includes('$ARGUMENTS'), 'literal $ARGUMENTS removed');
|
||||
assert.ok(out.startsWith('description =') || out.includes('prompt ='), 'TOML shape');
|
||||
});
|
||||
|
||||
test('command without $ARGUMENTS gets no injected {{args}}', () => {
|
||||
const out = convertClaudeToGeminiMarkdown(
|
||||
cmd('No arguments referenced here.'),
|
||||
{ isCommand: true, commandName: 'demo' }
|
||||
);
|
||||
assert.ok(!out.includes('{{args}}'), 'no spurious {{args}}');
|
||||
});
|
||||
|
||||
test('non-command Gemini content is not TOML-converted and keeps $ARGUMENTS', () => {
|
||||
const out = convertClaudeToGeminiMarkdown(
|
||||
cmd('Reference $ARGUMENTS.'),
|
||||
{ isCommand: false }
|
||||
);
|
||||
// isCommand:false keeps markdown — no TOML wrap and no {{args}} mapping
|
||||
// (the $ARGUMENTS→{{args}} translation is scoped to the TOML command path).
|
||||
assert.ok(!out.startsWith('prompt ='), 'not wrapped as TOML prompt');
|
||||
assert.ok(out.includes('$ARGUMENTS'), '$ARGUMENTS left intact for non-command content');
|
||||
assert.ok(!out.includes('{{args}}'), 'no {{args}} injected outside the command path');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── (c) Gemini: end-to-end install wiring ──────────────────────────────────
|
||||
// Proves the install path derives the per-command name from the file stem so a
|
||||
// regression in the call-site wiring (not just the converter) is caught.
|
||||
|
||||
describe('#778 (c) Gemini install wiring (end-to-end)', () => {
|
||||
let tmpDir;
|
||||
let tmpHome;
|
||||
let prevCwd;
|
||||
let prevHome;
|
||||
let prevUserprofile;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-enh778-gem-');
|
||||
tmpHome = createTempDir('gsd-enh778-home-');
|
||||
prevCwd = process.cwd();
|
||||
prevHome = process.env.HOME;
|
||||
prevUserprofile = process.env.USERPROFILE;
|
||||
process.chdir(tmpDir);
|
||||
// Isolate HOME so a real ~/.gemini/commands/gsd/ doesn't trigger the #3037
|
||||
// local-install conflict-skip path.
|
||||
process.env.HOME = tmpHome;
|
||||
process.env.USERPROFILE = tmpHome;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(prevCwd);
|
||||
if (prevHome === undefined) delete process.env.HOME; else process.env.HOME = prevHome;
|
||||
if (prevUserprofile === undefined) delete process.env.USERPROFILE;
|
||||
else process.env.USERPROFILE = prevUserprofile;
|
||||
cleanup(tmpDir);
|
||||
cleanup(tmpHome);
|
||||
});
|
||||
|
||||
test('installed progress.toml carries the !{} block; arg-bearing commands get {{args}}', () => {
|
||||
const oldLog = console.log;
|
||||
console.log = () => {};
|
||||
try {
|
||||
install(false, 'gemini');
|
||||
} finally {
|
||||
console.log = oldLog;
|
||||
}
|
||||
|
||||
const commandsDir = path.join(tmpDir, '.gemini', 'commands', 'gsd');
|
||||
const progressToml = path.join(commandsDir, 'progress.toml');
|
||||
assert.ok(fs.existsSync(progressToml), 'progress.toml installed');
|
||||
const progress = fs.readFileSync(progressToml, 'utf8');
|
||||
// Proves commandName was derived as 'progress' from the file stem.
|
||||
assert.ok(
|
||||
progress.includes('!{cat .planning/STATE.md 2>/dev/null}'),
|
||||
'progress.toml has the live-state shell block'
|
||||
);
|
||||
|
||||
// A non-situational command must NOT receive the shell block.
|
||||
const helpToml = path.join(commandsDir, 'help.toml');
|
||||
if (fs.existsSync(helpToml)) {
|
||||
assert.ok(!fs.readFileSync(helpToml, 'utf8').includes('!{'), 'help.toml has no shell block');
|
||||
}
|
||||
|
||||
// At least one installed command must use {{args}} and none may retain a
|
||||
// literal $ARGUMENTS (every command body's $ARGUMENTS is translated).
|
||||
const tomls = fs.readdirSync(commandsDir).filter((f) => f.endsWith('.toml'));
|
||||
const withArgs = tomls.filter((f) =>
|
||||
fs.readFileSync(path.join(commandsDir, f), 'utf8').includes('{{args}}'));
|
||||
const withLiteral = tomls.filter((f) =>
|
||||
fs.readFileSync(path.join(commandsDir, f), 'utf8').includes('$ARGUMENTS'));
|
||||
assert.ok(withArgs.length > 0, 'at least one installed command interpolates {{args}}');
|
||||
assert.equal(withLiteral.length, 0, 'no installed command retains literal $ARGUMENTS');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── (c) Gemini: !{...} live-state injection (progress) ─────────────────────
|
||||
|
||||
describe('#778 (c) Gemini !{} live-state injection', () => {
|
||||
const cmd = (name) =>
|
||||
['---', `name: gsd:${name}`, `description: ${name}`, '---', '', 'Workflow body.'].join('\n');
|
||||
|
||||
test('progress command injects a fixed !{cat .planning/STATE.md} block', () => {
|
||||
const out = convertClaudeToGeminiMarkdown(
|
||||
cmd('progress'),
|
||||
{ isCommand: true, commandName: 'progress' }
|
||||
);
|
||||
assert.ok(out.includes('!{cat .planning/STATE.md'), 'STATE.md injection present');
|
||||
});
|
||||
|
||||
test('non-progress commands get no !{} shell block', () => {
|
||||
const out = convertClaudeToGeminiMarkdown(
|
||||
cmd('help'),
|
||||
{ isCommand: true, commandName: 'help' }
|
||||
);
|
||||
assert.ok(!out.includes('!{'), 'no shell block for non-situational command');
|
||||
});
|
||||
|
||||
test('SECURITY: the !{} block interpolates NO user input ({{args}})', () => {
|
||||
const out = convertClaudeToGeminiMarkdown(
|
||||
['---', 'name: gsd:progress', 'description: progress', '---', '',
|
||||
'Body uses $ARGUMENTS too.'].join('\n'),
|
||||
{ isCommand: true, commandName: 'progress' }
|
||||
);
|
||||
const blocks = out.match(/!\{([^}]*)\}/g) || [];
|
||||
assert.equal(blocks.length, 1, 'exactly one shell block');
|
||||
assert.ok(!/\{\{args\}\}/.test(blocks[0]), 'no {{args}} inside the shell block');
|
||||
assert.ok(/^!\{cat \.planning\/STATE\.md/.test(blocks[0]), 'fixed cat command only');
|
||||
});
|
||||
});
|
||||
280
tests/enh-788-qwen-hook-events.test.cjs
Normal file
280
tests/enh-788-qwen-hook-events.test.cjs
Normal file
@@ -0,0 +1,280 @@
|
||||
'use strict';
|
||||
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
/**
|
||||
* Enhancement #788: Expand Qwen Code hook-event coverage.
|
||||
*
|
||||
* Qwen Code supports 15 hook events; gsd previously registered only
|
||||
* SessionStart and PostToolUse. This suite asserts that a Qwen install
|
||||
* registers the 3 new high-value events:
|
||||
* - SubagentStop — subagent lifecycle finalisation (context tracking)
|
||||
* - Stop — model stop / final-response hook (context tracking)
|
||||
* - PreCompact — pre-compaction awareness (context tracking)
|
||||
*
|
||||
* All three are wired to gsd-context-monitor.js — the same hook used for
|
||||
* PostToolUse — so context headroom warnings surface at these moments too.
|
||||
*
|
||||
* Note: UserPromptSubmit is NOT wired — gsd-prompt-guard exits unless
|
||||
* tool_name is Write|Edit (PreToolUse shape), so it would be a no-op for
|
||||
* the UserPromptSubmit payload. Deferred to a follow-on issue.
|
||||
*
|
||||
* Also asserts the inverse: Claude Code installs do NOT gain these events
|
||||
* (strict isQwen scope guard).
|
||||
*
|
||||
* Source: https://qwenlm.github.io/qwen-code-docs/en/users/features/hooks/
|
||||
*/
|
||||
|
||||
const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const { install, uninstall, validateHookFields } = require('../bin/install.js');
|
||||
const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Extract all hook commands registered under `eventName` from settings. */
|
||||
function hooksForEvent(settings, eventName) {
|
||||
if (!settings || !settings.hooks || !Array.isArray(settings.hooks[eventName])) return [];
|
||||
return settings.hooks[eventName].flatMap(entry =>
|
||||
(entry && Array.isArray(entry.hooks) ? entry.hooks : [])
|
||||
.map(h => h && h.command)
|
||||
.filter(Boolean)
|
||||
);
|
||||
}
|
||||
|
||||
// Stub JS hook files that the installer checks with fs.existsSync() so hook
|
||||
// registration guards pass even when hooks/dist/ isn't built.
|
||||
const HOOKS_SRC = path.join(__dirname, '..', 'hooks');
|
||||
const STUB_HOOKS = [
|
||||
'gsd-context-monitor.js',
|
||||
'gsd-prompt-guard.js',
|
||||
'gsd-check-update.js',
|
||||
'gsd-config-reload.js', // Added in #770
|
||||
];
|
||||
|
||||
function stubHooksIntoTarget(targetDir) {
|
||||
const hooksDest = path.join(targetDir, 'hooks');
|
||||
fs.mkdirSync(hooksDest, { recursive: true });
|
||||
for (const hookFile of STUB_HOOKS) {
|
||||
const src = path.join(HOOKS_SRC, hookFile);
|
||||
const dest = path.join(hooksDest, hookFile);
|
||||
if (fs.existsSync(src)) {
|
||||
fs.copyFileSync(src, dest);
|
||||
} else {
|
||||
// Minimal stub so existsSync passes
|
||||
fs.writeFileSync(dest, '#!/usr/bin/env node\n// stub\n');
|
||||
}
|
||||
try { fs.chmodSync(dest, 0o755); } catch { /* Windows */ }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist in-memory settings to disk, simulating what finishInstall() does
|
||||
* (finishInstall is not exported). Required for tests that call install()
|
||||
* twice and need the second call to read the first call's hook registrations.
|
||||
*/
|
||||
function persistSettings(settingsPath, settings) {
|
||||
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
|
||||
fs.writeFileSync(settingsPath, JSON.stringify(validateHookFields(settings), null, 2) + '\n', 'utf8');
|
||||
}
|
||||
|
||||
// ─── Suite 1: Qwen — new events are registered ───────────────────────────────
|
||||
|
||||
describe('enh-788: Qwen install registers 3 new hook events', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
let settings;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-788-qwen-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
|
||||
const targetDir = path.join(tmpDir, '.qwen');
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
// Pre-populate hook files so installer registration guards (fs.existsSync)
|
||||
// pass and hooks are actually registered in settings.json.
|
||||
stubHooksIntoTarget(targetDir);
|
||||
|
||||
const result = install(false, 'qwen');
|
||||
settings = result.settings;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('install returns a settings object (not null)', () => {
|
||||
assert.ok(settings !== null && typeof settings === 'object',
|
||||
'Qwen install must return a non-null settings object');
|
||||
});
|
||||
|
||||
test('SubagentStop event is registered with at least one hook', () => {
|
||||
const cmds = hooksForEvent(settings, 'SubagentStop');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Expected SubagentStop hooks; got hooks: ${JSON.stringify(settings && settings.hooks)}`);
|
||||
});
|
||||
|
||||
test('Stop event is registered with at least one hook', () => {
|
||||
const cmds = hooksForEvent(settings, 'Stop');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Expected Stop hooks; got hooks: ${JSON.stringify(settings && settings.hooks)}`);
|
||||
});
|
||||
|
||||
test('PreCompact event is registered with at least one hook', () => {
|
||||
const cmds = hooksForEvent(settings, 'PreCompact');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Expected PreCompact hooks; got hooks: ${JSON.stringify(settings && settings.hooks)}`);
|
||||
});
|
||||
|
||||
test('UserPromptSubmit is NOT registered (handler not yet implemented for that payload shape)', () => {
|
||||
// gsd-prompt-guard exits unless tool_name is Write|Edit — it is a no-op
|
||||
// for UserPromptSubmit payloads. Registration is deferred until a
|
||||
// dedicated hook can process the user-prompt payload shape.
|
||||
const cmds = hooksForEvent(settings, 'UserPromptSubmit');
|
||||
assert.strictEqual(cmds.length, 0,
|
||||
`UserPromptSubmit should NOT be registered yet; got: ${JSON.stringify(cmds)}`);
|
||||
});
|
||||
|
||||
test('SubagentStop / Stop / PreCompact all use gsd-context-monitor', () => {
|
||||
for (const event of ['SubagentStop', 'Stop', 'PreCompact']) {
|
||||
const cmds = hooksForEvent(settings, event);
|
||||
assert.ok(
|
||||
cmds.some(c => c.includes('gsd-context-monitor')),
|
||||
`Event ${event} should use gsd-context-monitor; got commands: ${JSON.stringify(cmds)}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('FileChanged is NOT registered for Qwen (Claude-only event)', () => {
|
||||
// gsd-config-reload / FileChanged is a Claude Code-only registration.
|
||||
// Qwen does not support the FileChanged hook event at all.
|
||||
const cmds = hooksForEvent(settings, 'FileChanged');
|
||||
assert.strictEqual(cmds.length, 0,
|
||||
`FileChanged should NOT be registered for Qwen; got: ${JSON.stringify(cmds)}`);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 2: Claude install DOES get the context events (since #770) ───────
|
||||
// Note: Prior to #770, these were Qwen-only events. #770 extended them to
|
||||
// Claude Code. This suite is updated to match the new expected behavior.
|
||||
|
||||
describe('enh-788 (updated by #770): Claude install registers context lifecycle events', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
let settings;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-788-claude-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
stubHooksIntoTarget(path.join(tmpDir, '.claude'));
|
||||
|
||||
const result = install(false, 'claude', { installerMigrations: [] });
|
||||
settings = result && result.settings;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('Claude install registers SubagentStop (since #770)', () => {
|
||||
const cmds = hooksForEvent(settings, 'SubagentStop');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Claude should have SubagentStop since #770; got: ${JSON.stringify(cmds)}`);
|
||||
});
|
||||
|
||||
test('Claude install registers Stop (since #770)', () => {
|
||||
const cmds = hooksForEvent(settings, 'Stop');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Claude should have Stop since #770; got: ${JSON.stringify(cmds)}`);
|
||||
});
|
||||
|
||||
test('Claude install registers PreCompact (since #770)', () => {
|
||||
const cmds = hooksForEvent(settings, 'PreCompact');
|
||||
assert.ok(cmds.length > 0,
|
||||
`Claude should have PreCompact since #770; got: ${JSON.stringify(cmds)}`);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 3: Idempotency — persisted reinstall does not duplicate hooks ──────
|
||||
|
||||
describe('enh-788: Qwen install is idempotent across persisted reinstalls', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-788-idem-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
|
||||
const targetDir = path.join(tmpDir, '.qwen');
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
stubHooksIntoTarget(targetDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('re-running after persisted first install does not duplicate hook entries', () => {
|
||||
// First install: get settings and persist to disk (simulating finishInstall)
|
||||
const result1 = install(false, 'qwen');
|
||||
persistSettings(result1.settingsPath, result1.settings);
|
||||
|
||||
// Second install: reads the persisted settings.json — dedup guards apply
|
||||
process.chdir(tmpDir);
|
||||
const result2 = install(false, 'qwen');
|
||||
const s2 = result2.settings;
|
||||
|
||||
for (const event of ['SubagentStop', 'Stop', 'PreCompact']) {
|
||||
const cmds = hooksForEvent(s2, event);
|
||||
assert.strictEqual(cmds.length, 1,
|
||||
`Event ${event} should have exactly 1 hook command after idempotent reinstall; got ${cmds.length}: ${JSON.stringify(cmds)}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Suite 4: Uninstall removes the new event registrations ──────────────────
|
||||
|
||||
describe('enh-788: Qwen uninstall removes new hook event entries', () => {
|
||||
let tmpDir;
|
||||
let previousCwd;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempDir('gsd-788-uninstall-');
|
||||
previousCwd = process.cwd();
|
||||
process.chdir(tmpDir);
|
||||
|
||||
const targetDir = path.join(tmpDir, '.qwen');
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
stubHooksIntoTarget(targetDir);
|
||||
|
||||
// Install and persist to disk so uninstall has a settings.json to clean
|
||||
const result = install(false, 'qwen');
|
||||
persistSettings(result.settingsPath, result.settings);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('settings.json hook entries are removed on uninstall', () => {
|
||||
uninstall(false, 'qwen');
|
||||
const settingsPath = path.join(tmpDir, '.qwen', 'settings.json');
|
||||
if (!fs.existsSync(settingsPath)) return; // file removed entirely is fine
|
||||
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
||||
for (const event of ['SubagentStop', 'Stop', 'PreCompact']) {
|
||||
const cmds = hooksForEvent(settings, event);
|
||||
assert.strictEqual(cmds.length, 0,
|
||||
`After uninstall, ${event} should have 0 hooks; got: ${JSON.stringify(cmds)}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
259
tests/enh-789-codebuddy-commands.test.cjs
Normal file
259
tests/enh-789-codebuddy-commands.test.cjs
Normal file
@@ -0,0 +1,259 @@
|
||||
// allow-test-rule: source-text-is-the-product
|
||||
// Workflow .md / command .md / SKILL.md files — their text IS what the runtime
|
||||
// loads. Testing emitted text tests the deployed contract.
|
||||
// Per CONTRIBUTING.md exception matrix.
|
||||
|
||||
/**
|
||||
* Regression guard — enh(#789): elevate CodeBuddy slash-command surface.
|
||||
*
|
||||
* CodeBuddy (Tencent, @tencent-ai/codebuddy-code) reads user-level surfaces
|
||||
* (https://www.codebuddy.ai/docs/cli/slash-commands, /skills):
|
||||
* - commands/gsd-<stem>.md — slash commands shown in the '/' menu
|
||||
* - skills/gsd-<stem>/SKILL.md — model-invocable skills
|
||||
*
|
||||
* Before #789 gsd emitted only skills/. Because CodeBuddy skills default to
|
||||
* user-invocable:true (appear in '/'), emitting a commands/ surface AND leaving
|
||||
* skills user-invocable would duplicate every /gsd-* entry. #789 therefore:
|
||||
* 1. emits commands/gsd-<stem>.md (the '/' surface, peer-consistent with
|
||||
* Cursor #785 and Augment #790),
|
||||
* 2. marks skills user-invocable:false so they become model-invocable
|
||||
* background knowledge and the commands/ surface is the sole '/' surface.
|
||||
*
|
||||
* Subagents are already emitted via the generic agents block + convertClaude
|
||||
* AgentToCodebuddyAgent (~/.codebuddy/agents/), so #789 adds no agents change.
|
||||
*
|
||||
* mcp.json is intentionally NOT written: gsd ships no MCP server, and CodeBuddy's
|
||||
* mcp.json holds an `mcpServers` map of *external* servers to connect to —
|
||||
* there is nothing for gsd to register. Same exclusion as #784/#785/#790.
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
const {
|
||||
installRuntimeArtifacts,
|
||||
uninstallRuntimeArtifacts,
|
||||
convertClaudeCommandToCodebuddyCommand,
|
||||
convertClaudeCommandToCodebuddySkill,
|
||||
} = require('../bin/install.js');
|
||||
const { resolveRuntimeArtifactLayout } = require('../gsd-core/bin/lib/runtime-artifact-layout.cjs');
|
||||
const { loadSkillsManifest, resolveProfile } = require('../gsd-core/bin/lib/install-profiles.cjs');
|
||||
|
||||
const REAL_COMMANDS_DIR = path.join(__dirname, '..', 'commands', 'gsd');
|
||||
const MANIFEST = loadSkillsManifest(REAL_COMMANDS_DIR);
|
||||
const RESOLVED_CORE = resolveProfile({ modes: ['core'], manifest: MANIFEST });
|
||||
|
||||
// ─── Layout contract ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('enh-789 — codebuddy layout has commands + skills kinds', () => {
|
||||
test('resolveRuntimeArtifactLayout codebuddy returns 2 kinds', () => {
|
||||
const layout = resolveRuntimeArtifactLayout('codebuddy', '/tmp/fake-codebuddy-dir');
|
||||
assert.strictEqual(layout.kinds.length, 2, 'codebuddy must have exactly 2 artifact kinds');
|
||||
const kindNames = layout.kinds.map(k => k.kind).sort();
|
||||
assert.deepStrictEqual(kindNames, ['commands', 'skills']);
|
||||
});
|
||||
|
||||
test('codebuddy commands kind targets commands/ with gsd- prefix', () => {
|
||||
const layout = resolveRuntimeArtifactLayout('codebuddy', '/tmp/fake-codebuddy-dir');
|
||||
const commandsKind = layout.kinds.find(k => k.kind === 'commands');
|
||||
assert.ok(commandsKind, 'must have commands kind');
|
||||
assert.strictEqual(commandsKind.destSubpath, 'commands');
|
||||
assert.strictEqual(commandsKind.prefix, 'gsd-');
|
||||
assert.strictEqual(typeof commandsKind.stage, 'function');
|
||||
});
|
||||
|
||||
test('codebuddy skills kind targets skills/ with gsd- prefix', () => {
|
||||
const layout = resolveRuntimeArtifactLayout('codebuddy', '/tmp/fake-codebuddy-dir');
|
||||
const skillsKind = layout.kinds.find(k => k.kind === 'skills');
|
||||
assert.ok(skillsKind, 'must have skills kind');
|
||||
assert.strictEqual(skillsKind.destSubpath, 'skills');
|
||||
assert.strictEqual(skillsKind.prefix, 'gsd-');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Command converter contract ──────────────────────────────────────────────
|
||||
|
||||
describe('enh-789 — convertClaudeCommandToCodebuddyCommand', () => {
|
||||
const SRC = [
|
||||
'---',
|
||||
'name: gsd:new-project',
|
||||
'description: Initialize a project',
|
||||
'argument-hint: "[name]"',
|
||||
'allowed-tools:',
|
||||
' - Read',
|
||||
'---',
|
||||
'',
|
||||
'Use .claude/skills/ and run /gsd:help. Claude Code reads CLAUDE.md.',
|
||||
'',
|
||||
].join('\n');
|
||||
|
||||
test('emits a description-only frontmatter (no Claude-specific name: gsd:)', () => {
|
||||
const out = convertClaudeCommandToCodebuddyCommand(SRC, 'gsd-new-project');
|
||||
assert.ok(out.startsWith('---\n'), 'must begin with frontmatter');
|
||||
assert.ok(/^description:/m.test(out), 'must carry a description field');
|
||||
assert.ok(!out.includes('name: gsd:new-project'), 'must drop Claude colon-form name field');
|
||||
});
|
||||
|
||||
test('preserves a present argument-hint (CodeBuddy supports it)', () => {
|
||||
const out = convertClaudeCommandToCodebuddyCommand(SRC, 'gsd-new-project');
|
||||
assert.ok(/^argument-hint:\s*["']?\[name\]["']?\s*$/m.test(out),
|
||||
`argument-hint must be carried through when present in source. Got:\n${out}`);
|
||||
});
|
||||
|
||||
test('converts body Claude-isms to CodeBuddy equivalents', () => {
|
||||
const out = convertClaudeCommandToCodebuddyCommand(SRC, 'gsd-new-project');
|
||||
assert.ok(out.includes('.codebuddy/skills/'), out);
|
||||
assert.ok(out.includes('/gsd-help'), out);
|
||||
assert.ok(out.includes('CODEBUDDY.md'), out);
|
||||
assert.ok(!/\bClaude Code\b/.test(out), 'must rebrand "Claude Code"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('enh-789 — skills marked user-invocable:false', () => {
|
||||
test('convertClaudeCommandToCodebuddySkill emits user-invocable: false', () => {
|
||||
const src = [
|
||||
'---',
|
||||
'name: gsd:help',
|
||||
'description: Show help',
|
||||
'---',
|
||||
'',
|
||||
'# body',
|
||||
'',
|
||||
].join('\n');
|
||||
const out = convertClaudeCommandToCodebuddySkill(src, 'gsd-help');
|
||||
assert.ok(/^user-invocable:\s*false\s*$/m.test(out),
|
||||
`SKILL.md frontmatter must hide skill from '/' menu (user-invocable: false). Got:\n${out}`);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Install contract ────────────────────────────────────────────────────────
|
||||
|
||||
describe('enh-789 — installRuntimeArtifacts codebuddy emits commands and skills', () => {
|
||||
test('global codebuddy install: commands/gsd-help.md and skills/gsd-help/SKILL.md exist', (t) => {
|
||||
const configDir = createTempDir('gsd-enh789-codebuddy-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('codebuddy', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
const commandsDir = path.join(configDir, 'commands');
|
||||
assert.ok(fs.existsSync(commandsDir), 'commands/ dir must exist');
|
||||
const cmdFiles = fs.readdirSync(commandsDir).filter(f => f.startsWith('gsd-') && f.endsWith('.md'));
|
||||
assert.ok(cmdFiles.length > 0, 'at least one gsd-*.md command file must be installed');
|
||||
assert.ok(fs.existsSync(path.join(commandsDir, 'gsd-help.md')), 'commands/gsd-help.md must exist');
|
||||
|
||||
const skillsDir = path.join(configDir, 'skills');
|
||||
assert.ok(fs.existsSync(skillsDir), 'skills/ dir must exist');
|
||||
assert.ok(fs.existsSync(path.join(skillsDir, 'gsd-help', 'SKILL.md')), 'skills/gsd-help/SKILL.md must exist');
|
||||
});
|
||||
|
||||
test('installed commands/gsd-help.md is CodeBuddy-compatible (no raw ~/.claude/, rebranded)', (t) => {
|
||||
const configDir = createTempDir('gsd-enh789-content-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('codebuddy', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
const helpCmd = path.join(configDir, 'commands', 'gsd-help.md');
|
||||
const content = fs.readFileSync(helpCmd, 'utf8');
|
||||
assert.ok(!content.includes('~/.claude/'), 'commands must not contain raw ~/.claude/ refs');
|
||||
assert.ok(content.startsWith('---'), 'commands must carry frontmatter');
|
||||
});
|
||||
|
||||
test('installed skills/gsd-help/SKILL.md is hidden from the / menu', (t) => {
|
||||
const configDir = createTempDir('gsd-enh789-skillhide-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('codebuddy', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
const skill = fs.readFileSync(path.join(configDir, 'skills', 'gsd-help', 'SKILL.md'), 'utf8');
|
||||
assert.ok(/^user-invocable:\s*false\s*$/m.test(skill),
|
||||
'installed SKILL.md must set user-invocable: false');
|
||||
});
|
||||
|
||||
test('command count matches skill count (profile parity)', (t) => {
|
||||
const configDir = createTempDir('gsd-enh789-parity-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('codebuddy', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
const cmdCount = fs.readdirSync(path.join(configDir, 'commands'))
|
||||
.filter(f => f.startsWith('gsd-') && f.endsWith('.md')).length;
|
||||
const skillCount = fs.readdirSync(path.join(configDir, 'skills'), { withFileTypes: true })
|
||||
.filter(e => e.isDirectory() && e.name.startsWith('gsd-')).length;
|
||||
assert.strictEqual(cmdCount, skillCount, 'command count must equal skill count for same profile');
|
||||
});
|
||||
|
||||
test('full profile install: no $HOME/.codebuddy or ~/.codebuddy leak in any command', (t) => {
|
||||
// The codebuddy converter rewrites `.claude/` → `.codebuddy/`, so source
|
||||
// refs like `@$HOME/.claude/gsd-core/...` (e.g. plan-review-convergence.md)
|
||||
// must be normalized to the install target — not left as $HOME/.codebuddy.
|
||||
const RESOLVED_FULL = resolveProfile({ modes: ['full'], manifest: MANIFEST });
|
||||
const configDir = createTempDir('gsd-enh789-noleak-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('codebuddy', configDir, 'global', RESOLVED_FULL);
|
||||
|
||||
const commandsDir = path.join(configDir, 'commands');
|
||||
for (const f of fs.readdirSync(commandsDir).filter(n => n.endsWith('.md'))) {
|
||||
const content = fs.readFileSync(path.join(commandsDir, f), 'utf8');
|
||||
assert.ok(!content.includes('$HOME/.codebuddy'), `${f} must not leak $HOME/.codebuddy`);
|
||||
assert.ok(!content.includes('~/.codebuddy'), `${f} must not leak ~/.codebuddy`);
|
||||
assert.ok(!content.includes('.claude/'), `${f} must not retain raw .claude/ refs`);
|
||||
}
|
||||
});
|
||||
|
||||
test('full profile install does NOT mutate source commands/gsd/ files', (t) => {
|
||||
const RESOLVED_FULL = resolveProfile({ modes: ['full'], manifest: MANIFEST });
|
||||
assert.strictEqual(RESOLVED_FULL.skills, '*', 'full profile must have skills === "*"');
|
||||
|
||||
const configDir = createTempDir('gsd-enh789-full-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
const srcHelpPath = path.join(REAL_COMMANDS_DIR, 'help.md');
|
||||
const before = fs.readFileSync(srcHelpPath, 'utf8');
|
||||
|
||||
installRuntimeArtifacts('codebuddy', configDir, 'global', RESOLVED_FULL);
|
||||
|
||||
const after = fs.readFileSync(srcHelpPath, 'utf8');
|
||||
assert.strictEqual(before, after, 'source commands/gsd/help.md must not be mutated by the install');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Uninstall contract ──────────────────────────────────────────────────────
|
||||
|
||||
describe('enh-789 — uninstallRuntimeArtifacts removes codebuddy commands', () => {
|
||||
test('uninstall removes gsd-* commands but preserves user commands', (t) => {
|
||||
const configDir = createTempDir('gsd-enh789-uninstall-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
const commandsDir = path.join(configDir, 'commands');
|
||||
fs.mkdirSync(commandsDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(commandsDir, 'gsd-help.md'), '# help\n');
|
||||
fs.writeFileSync(path.join(commandsDir, 'user-custom.md'), '# user\n');
|
||||
|
||||
uninstallRuntimeArtifacts('codebuddy', configDir, 'global');
|
||||
|
||||
assert.ok(!fs.existsSync(path.join(commandsDir, 'gsd-help.md')), 'gsd-help.md must be removed');
|
||||
assert.ok(fs.existsSync(path.join(commandsDir, 'user-custom.md')), 'user-custom.md must be preserved');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── mcp.json exclusion ──────────────────────────────────────────────────────
|
||||
|
||||
describe('enh-789 — mcp.json excluded (gsd ships no MCP server)', () => {
|
||||
test('codebuddy install does not write mcp.json / .mcp.json', (t) => {
|
||||
const configDir = createTempDir('gsd-enh789-mcp-excluded-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('codebuddy', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
assert.ok(!fs.existsSync(path.join(configDir, 'mcp.json')), 'must not write mcp.json');
|
||||
assert.ok(!fs.existsSync(path.join(configDir, '.mcp.json')), 'must not write .mcp.json');
|
||||
});
|
||||
});
|
||||
177
tests/enh-790-augment-commands.test.cjs
Normal file
177
tests/enh-790-augment-commands.test.cjs
Normal file
@@ -0,0 +1,177 @@
|
||||
'use strict';
|
||||
/**
|
||||
* Regression guard — enh(#790): Augment commands/ emitted alongside skills/.
|
||||
*
|
||||
* Verifies that a global Augment install writes:
|
||||
* - commands/gsd-<stem>.md (slash command definitions)
|
||||
* - skills/gsd-<stem>/SKILL.md (existing skill definitions)
|
||||
*
|
||||
* mcpServers in settings.json is explicitly excluded: gsd ships no MCP server
|
||||
* and registering third-party servers is out of scope for the installer.
|
||||
*
|
||||
* Ref: https://docs.augmentcode.com/cli/reference — ~/.augment/commands/<name>.md
|
||||
*/
|
||||
|
||||
process.env.GSD_TEST_MODE = '1';
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
const { installRuntimeArtifacts } = require('../bin/install.js');
|
||||
const { resolveRuntimeArtifactLayout } = require('../gsd-core/bin/lib/runtime-artifact-layout.cjs');
|
||||
const { loadSkillsManifest, resolveProfile } = require('../gsd-core/bin/lib/install-profiles.cjs');
|
||||
|
||||
const REAL_COMMANDS_DIR = path.join(__dirname, '..', 'commands', 'gsd');
|
||||
const MANIFEST = loadSkillsManifest(REAL_COMMANDS_DIR);
|
||||
const RESOLVED_CORE = resolveProfile({ modes: ['core'], manifest: MANIFEST });
|
||||
|
||||
// ─── Layout contract ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('enh-790 — augment layout has commands + skills kinds', () => {
|
||||
test('resolveRuntimeArtifactLayout augment returns 2 kinds', () => {
|
||||
const layout = resolveRuntimeArtifactLayout('augment', '/tmp/fake-augment-dir');
|
||||
assert.strictEqual(layout.kinds.length, 2, 'augment must have exactly 2 artifact kinds');
|
||||
const kindNames = layout.kinds.map(k => k.kind).sort();
|
||||
assert.deepStrictEqual(kindNames, ['commands', 'skills']);
|
||||
});
|
||||
|
||||
test('augment commands kind targets commands/ with gsd- prefix', () => {
|
||||
const layout = resolveRuntimeArtifactLayout('augment', '/tmp/fake-augment-dir');
|
||||
const commandsKind = layout.kinds.find(k => k.kind === 'commands');
|
||||
assert.ok(commandsKind, 'must have commands kind');
|
||||
assert.strictEqual(commandsKind.destSubpath, 'commands');
|
||||
assert.strictEqual(commandsKind.prefix, 'gsd-');
|
||||
});
|
||||
|
||||
test('augment skills kind targets skills/ with gsd- prefix', () => {
|
||||
const layout = resolveRuntimeArtifactLayout('augment', '/tmp/fake-augment-dir');
|
||||
const skillsKind = layout.kinds.find(k => k.kind === 'skills');
|
||||
assert.ok(skillsKind, 'must have skills kind');
|
||||
assert.strictEqual(skillsKind.destSubpath, 'skills');
|
||||
assert.strictEqual(skillsKind.prefix, 'gsd-');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Install contract ────────────────────────────────────────────────────────
|
||||
|
||||
describe('enh-790 — installRuntimeArtifacts augment emits both commands and skills', () => {
|
||||
test('global augment install: commands/gsd-help.md and skills/gsd-help/SKILL.md exist', (t) => {
|
||||
const configDir = createTempDir('gsd-enh790-augment-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('augment', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
// Commands dir
|
||||
const commandsDir = path.join(configDir, 'commands');
|
||||
assert.ok(fs.existsSync(commandsDir), 'commands/ dir must exist');
|
||||
const cmdFiles = fs.readdirSync(commandsDir).filter(f => f.startsWith('gsd-') && f.endsWith('.md'));
|
||||
assert.ok(cmdFiles.length > 0, 'at least one gsd-*.md command file must be installed');
|
||||
assert.ok(fs.existsSync(path.join(commandsDir, 'gsd-help.md')), 'commands/gsd-help.md must exist');
|
||||
|
||||
// Skills dir (pre-existing behavior preserved)
|
||||
const skillsDir = path.join(configDir, 'skills');
|
||||
assert.ok(fs.existsSync(skillsDir), 'skills/ dir must exist');
|
||||
assert.ok(fs.existsSync(path.join(skillsDir, 'gsd-help', 'SKILL.md')), 'skills/gsd-help/SKILL.md must exist');
|
||||
});
|
||||
|
||||
test('commands/gsd-help.md has Augment-compatible content (no raw ~/.claude/ refs)', (t) => {
|
||||
const configDir = createTempDir('gsd-enh790-content-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('augment', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
const helpCmd = path.join(configDir, 'commands', 'gsd-help.md');
|
||||
assert.ok(fs.existsSync(helpCmd), 'gsd-help.md must exist');
|
||||
const content = fs.readFileSync(helpCmd, 'utf8');
|
||||
// Should not have raw ~/.claude/ references after path rewrite
|
||||
assert.ok(!content.includes('~/.claude/'), 'commands must not contain raw ~/.claude/ refs');
|
||||
});
|
||||
|
||||
test('command count matches skill count (profile parity)', (t) => {
|
||||
const configDir = createTempDir('gsd-enh790-parity-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('augment', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
const commandsDir = path.join(configDir, 'commands');
|
||||
const skillsDir = path.join(configDir, 'skills');
|
||||
const cmdCount = fs.readdirSync(commandsDir).filter(f => f.startsWith('gsd-') && f.endsWith('.md')).length;
|
||||
const skillCount = fs.readdirSync(skillsDir, { withFileTypes: true })
|
||||
.filter(e => e.isDirectory() && e.name.startsWith('gsd-')).length;
|
||||
assert.strictEqual(cmdCount, skillCount, 'command count must equal skill count for same profile');
|
||||
});
|
||||
|
||||
test('full profile install does NOT mutate source commands/gsd/ files', (t) => {
|
||||
// Regression guard: stageSkillsForProfile returns the real source dir on full profile
|
||||
// (skills === '*'). applyRuntimeContentRewritesForCommandsInPlace must copy to temp
|
||||
// before rewriting — it must NEVER write back to the source tree.
|
||||
const { resolveProfile } = require('../gsd-core/bin/lib/install-profiles.cjs');
|
||||
const RESOLVED_FULL = resolveProfile({ modes: ['full'], manifest: MANIFEST });
|
||||
assert.strictEqual(RESOLVED_FULL.skills, '*', 'full profile must have skills === "*"');
|
||||
|
||||
const configDir = createTempDir('gsd-enh790-full-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
// Record source file content before install
|
||||
const srcHelpPath = path.join(__dirname, '..', 'commands', 'gsd', 'help.md');
|
||||
const srcContentBefore = fs.readFileSync(srcHelpPath, 'utf8');
|
||||
|
||||
installRuntimeArtifacts('augment', configDir, 'global', RESOLVED_FULL);
|
||||
|
||||
// Source file must be identical after install
|
||||
const srcContentAfter = fs.readFileSync(srcHelpPath, 'utf8');
|
||||
assert.strictEqual(srcContentBefore, srcContentAfter,
|
||||
'source commands/gsd/help.md must not be mutated by the install');
|
||||
|
||||
// Installed command file must have rewrites applied (Augment path substitution)
|
||||
const installedHelp = path.join(configDir, 'commands', 'gsd-help.md');
|
||||
assert.ok(fs.existsSync(installedHelp), 'installed gsd-help.md must exist');
|
||||
const installedContent = fs.readFileSync(installedHelp, 'utf8');
|
||||
assert.ok(!installedContent.includes('~/.claude/'), 'installed command must not have raw ~/.claude/ refs');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Uninstall contract ──────────────────────────────────────────────────────
|
||||
|
||||
describe('enh-790 — uninstallRuntimeArtifacts removes augment commands', () => {
|
||||
test('uninstall removes gsd-* commands but preserves user commands', (t) => {
|
||||
const configDir = createTempDir('gsd-enh790-uninstall-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
const { uninstallRuntimeArtifacts } = require('../bin/install.js');
|
||||
|
||||
// Pre-create: a GSD command + a user-owned command
|
||||
const commandsDir = path.join(configDir, 'commands');
|
||||
fs.mkdirSync(commandsDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(commandsDir, 'gsd-help.md'), '# help\n');
|
||||
fs.writeFileSync(path.join(commandsDir, 'user-custom.md'), '# user\n');
|
||||
|
||||
uninstallRuntimeArtifacts('augment', configDir, 'global');
|
||||
|
||||
assert.ok(!fs.existsSync(path.join(commandsDir, 'gsd-help.md')), 'gsd-help.md must be removed');
|
||||
assert.ok(fs.existsSync(path.join(commandsDir, 'user-custom.md')), 'user-custom.md must be preserved');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── mcpServers exclusion ────────────────────────────────────────────────────
|
||||
|
||||
describe('enh-790 — mcpServers excluded (gsd ships no MCP server)', () => {
|
||||
test('augment install does not write settings.json mcpServers', (t) => {
|
||||
const configDir = createTempDir('gsd-enh790-mcp-excluded-');
|
||||
t.after(() => cleanup(configDir));
|
||||
|
||||
installRuntimeArtifacts('augment', configDir, 'global', RESOLVED_CORE);
|
||||
|
||||
// No settings.json with mcpServers should be written by the layout
|
||||
const settingsPath = path.join(configDir, 'settings.json');
|
||||
if (fs.existsSync(settingsPath)) {
|
||||
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
||||
assert.ok(!settings.mcpServers, 'settings.json must not contain mcpServers (gsd ships no MCP server)');
|
||||
}
|
||||
// If no settings.json at all, that is also correct
|
||||
});
|
||||
});
|
||||
@@ -317,6 +317,7 @@ describe('install.js update-banner wiring', () => {
|
||||
// Strip ANSI color escapes before structural assertions — the choice
|
||||
// digits are wrapped in color codes so word-boundary regex against the
|
||||
// raw text would miss them.
|
||||
// eslint-disable-next-line no-control-regex -- \x1b (ESC) is the required leading byte of ANSI SGR color sequences; matching it is the purpose of stripping ANSI codes from captured CLI/console output
|
||||
const stripped = text.replace(/\x1b\[[0-9;]*m/g, '');
|
||||
// Prompt must offer at least two choices (default + opt-in).
|
||||
assert.match(stripped, /\b1\b/);
|
||||
|
||||
@@ -46,8 +46,6 @@ const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
|
||||
const {
|
||||
resolveModelInternal,
|
||||
resolveModelForTier,
|
||||
|
||||
@@ -58,7 +58,8 @@ const MODE_FILES = ['brief.md', 'default.md', 'full.md', 'topic.md'];
|
||||
const BRIEF_BUDGET = 30;
|
||||
// DEFAULT ceiling lowered from 70 → 60 (actualMax=50; #597 ratchet-down).
|
||||
const DEFAULT_BUDGET = 60;
|
||||
// full.md is the LARGE tier (see workflow-size-budget.test.cjs — LARGE_BUDGET = 1500).
|
||||
// full.md is the LARGE tier (see workflow-size-budget.test.cjs — now byte-based per #717;
|
||||
// this FULL_BUDGET is a separate line-count budget for help/modes/full.md).
|
||||
// The size-budget test is non-recursive so full.md is not covered there; cap it here.
|
||||
// FULL ceiling lowered from 1500 → 844 (actualMax=784; #597 ratchet-down).
|
||||
const FULL_BUDGET = 844;
|
||||
|
||||
@@ -285,7 +285,7 @@ for (const payload of SHELL_PAYLOADS) {
|
||||
|
||||
// ─── Cross-cutting: --cwd points at a non-existent path ────────────────────
|
||||
|
||||
test('--cwd pointing at a non-existent path fails with a typed usage reason', (t) => {
|
||||
test('--cwd pointing at a non-existent path fails with a typed usage reason', (_t) => {
|
||||
const nonExistent = path.join(require('os').tmpdir(), 'cli-neg-no-such-dir-' + Date.now() + '-' + Math.random());
|
||||
assert.equal(fs.existsSync(nonExistent), false, 'pre-check: path must not exist');
|
||||
const result = runCli(['--cwd', nonExistent, 'config-get', 'model_profile'], { cwd: process.cwd() });
|
||||
|
||||
@@ -37,8 +37,6 @@ const { test, mock } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
|
||||
const {
|
||||
platformWriteSync,
|
||||
platformEnsureDir,
|
||||
@@ -83,7 +81,7 @@ test('platformWriteSync recovers when renameSync fails (EXDEV cross-device fallb
|
||||
// Simulate rename failing once (e.g. cross-device move on a CI runner
|
||||
// with overlayfs). The fallback path must write the content directly.
|
||||
let renameCalls = 0;
|
||||
const renameMock = mock.method(fs, 'renameSync', (src, dest) => {
|
||||
const renameMock = mock.method(fs, 'renameSync', (_src, _dest) => {
|
||||
renameCalls++;
|
||||
const err = new Error('EXDEV: cross-device link not permitted');
|
||||
err.code = 'EXDEV';
|
||||
|
||||
@@ -19,7 +19,7 @@ const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const { createTempProject, createTempDir, cleanup, runGsdTools } = require('./helpers.cjs');
|
||||
const { createTempProject, cleanup, runGsdTools } = require('./helpers.cjs');
|
||||
|
||||
const {
|
||||
resolveEffortInternal,
|
||||
|
||||
@@ -55,7 +55,6 @@ const { test, describe, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
|
||||
// ─── Imports (will fail until implementation exists) ────────────────────────
|
||||
// resolveModelPolicy is a new internal function that must be exported from core.cjs.
|
||||
|
||||
@@ -318,3 +318,193 @@ describe('#68 resolve-granularity command: CLI behavior', () => {
|
||||
assert.strictEqual(output.unknown_phase_type, undefined, 'known phase type must not have unknown_phase_type');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── #703 CLI override: --granularity flag ────────────────────────────────────
|
||||
|
||||
describe('#703 resolveGranularityInternal: CLI override param (3rd arg)', () => {
|
||||
let projectDir;
|
||||
beforeEach(() => { projectDir = makeTmp('cli-override'); });
|
||||
afterEach(() => { cleanup(projectDir); });
|
||||
|
||||
test('override fine beats per-phase config granularities.planning=coarse', () => {
|
||||
writeConfig(projectDir, {
|
||||
granularity: 'standard',
|
||||
granularities: { planning: 'coarse' },
|
||||
});
|
||||
assert.equal(resolveGranularityInternal(projectDir, 'planning', 'fine'), 'fine',
|
||||
'CLI override must beat per-phase config');
|
||||
});
|
||||
|
||||
test('override coarse beats top-level granularity=fine', () => {
|
||||
writeConfig(projectDir, {
|
||||
granularity: 'fine',
|
||||
});
|
||||
assert.equal(resolveGranularityInternal(projectDir, 'execution', 'coarse'), 'coarse',
|
||||
'CLI override must beat top-level granularity');
|
||||
});
|
||||
|
||||
test('override standard beats planning.granularity=fine global fallback (regardless of phase type)', () => {
|
||||
writeConfig(projectDir, {
|
||||
planning: { granularity: 'fine' },
|
||||
});
|
||||
assert.equal(resolveGranularityInternal(projectDir, 'execution', 'standard'), 'standard',
|
||||
'CLI override must beat planning.granularity fallback');
|
||||
});
|
||||
|
||||
test("override '' (empty string) falls through to config chain", () => {
|
||||
writeConfig(projectDir, {
|
||||
granularity: 'coarse',
|
||||
});
|
||||
assert.equal(resolveGranularityInternal(projectDir, 'planning', ''), 'coarse',
|
||||
'empty-string override must fall through to config chain');
|
||||
});
|
||||
|
||||
test('override undefined falls through to config chain', () => {
|
||||
writeConfig(projectDir, {
|
||||
granularity: 'fine',
|
||||
});
|
||||
assert.equal(resolveGranularityInternal(projectDir, 'planning', undefined), 'fine',
|
||||
'undefined override must fall through to config chain');
|
||||
});
|
||||
|
||||
test('override null falls through to config chain', () => {
|
||||
writeConfig(projectDir, {
|
||||
granularity: 'coarse',
|
||||
});
|
||||
assert.equal(resolveGranularityInternal(projectDir, 'planning', null), 'coarse',
|
||||
'null override must fall through to config chain');
|
||||
});
|
||||
|
||||
test('invalid override value falls through to config chain (not rejected in resolver)', () => {
|
||||
writeConfig(projectDir, {
|
||||
granularity: 'standard',
|
||||
});
|
||||
// Invalid override reaches resolver → falls through (validation is CLI boundary's job)
|
||||
assert.equal(resolveGranularityInternal(projectDir, 'planning', 'ultra'), 'standard',
|
||||
'invalid override must fall through to config chain in resolver');
|
||||
});
|
||||
});
|
||||
|
||||
describe('#703 cmdResolveGranularity: --granularity CLI flag', () => {
|
||||
let tmpDir;
|
||||
beforeEach(() => { tmpDir = createTempProject(); });
|
||||
afterEach(() => { cleanup(tmpDir); });
|
||||
|
||||
test('--granularity fine overrides config chain via CLI tool', () => {
|
||||
fs.writeFileSync(
|
||||
path.join(tmpDir, '.planning', 'config.json'),
|
||||
JSON.stringify({ granularity: 'coarse' })
|
||||
);
|
||||
const result = runGsdTools('resolve-granularity planning --granularity fine', tmpDir, { HOME: tmpDir });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
const output = JSON.parse(result.output);
|
||||
assert.strictEqual(output.granularity, 'fine', '--granularity fine must override config coarse');
|
||||
});
|
||||
|
||||
test('--granularity coarse overrides per-phase granularities.planning=fine', () => {
|
||||
fs.writeFileSync(
|
||||
path.join(tmpDir, '.planning', 'config.json'),
|
||||
JSON.stringify({
|
||||
granularity: 'standard',
|
||||
granularities: { planning: 'fine' },
|
||||
})
|
||||
);
|
||||
const result = runGsdTools('resolve-granularity planning --granularity coarse', tmpDir, { HOME: tmpDir });
|
||||
assert.ok(result.success, `Command failed: ${result.error}`);
|
||||
const output = JSON.parse(result.output);
|
||||
assert.strictEqual(output.granularity, 'coarse', '--granularity coarse must beat per-phase fine');
|
||||
});
|
||||
|
||||
test('invalid --granularity value exits with error', () => {
|
||||
const result = runGsdTools('resolve-granularity planning --granularity ultra', tmpDir);
|
||||
assert.ok(!result.success, 'should fail with invalid granularity');
|
||||
assert.ok(
|
||||
result.error.includes('ultra') || result.error.includes('invalid'),
|
||||
`error should mention invalid value; got: ${result.error}`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── #703 end-to-end: init.plan-phase path forwards and resolves granularity ──
|
||||
//
|
||||
// Fixture mirrors tests/pattern-mapper.test.cjs: createTempProject() +
|
||||
// minimal STATE.md + ROADMAP.md + phase directory — just enough for
|
||||
// cmdInitPlanPhase to succeed without agents / git.
|
||||
|
||||
function makeInitPlanPhaseFixture(prefix) {
|
||||
const tmpDir = createTempProject(prefix);
|
||||
const planningDir = path.join(tmpDir, '.planning');
|
||||
fs.writeFileSync(path.join(planningDir, 'STATE.md'), [
|
||||
'# State',
|
||||
'',
|
||||
'## Current Phase',
|
||||
'Phase 1 — Foundation',
|
||||
].join('\n'));
|
||||
fs.writeFileSync(path.join(planningDir, 'ROADMAP.md'), [
|
||||
'# Roadmap',
|
||||
'',
|
||||
'## Phase 1: Foundation',
|
||||
'Build the foundation.',
|
||||
'**Status:** Planning',
|
||||
'**Requirements:** [FOUND-01]',
|
||||
].join('\n'));
|
||||
fs.mkdirSync(path.join(planningDir, 'phases', '01-foundation'), { recursive: true });
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
describe('#703 init.plan-phase end-to-end: granularity resolution via CLI', () => {
|
||||
let tmpDir;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = makeInitPlanPhaseFixture('gsd-68-e2e-');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('(1) --granularity fine overrides config granularities.planning=coarse end-to-end', () => {
|
||||
fs.writeFileSync(
|
||||
path.join(tmpDir, '.planning', 'config.json'),
|
||||
JSON.stringify({ granularity: 'standard', granularities: { planning: 'coarse' } })
|
||||
);
|
||||
const result = runGsdTools('init plan-phase 1 --granularity fine', tmpDir, { HOME: tmpDir });
|
||||
assert.ok(result.success, `init plan-phase failed: ${result.error}`);
|
||||
const data = JSON.parse(result.output);
|
||||
assert.strictEqual(data.granularity, 'fine',
|
||||
'--granularity fine override must win over granularities.planning=coarse end-to-end');
|
||||
});
|
||||
|
||||
test('(2) no flag + config granularities.planning=fine → granularity=fine (Fix A: per-phase-type honored)', () => {
|
||||
fs.writeFileSync(
|
||||
path.join(tmpDir, '.planning', 'config.json'),
|
||||
JSON.stringify({ granularity: 'coarse', granularities: { planning: 'fine' } })
|
||||
);
|
||||
const result = runGsdTools('init plan-phase 1', tmpDir, { HOME: tmpDir });
|
||||
assert.ok(result.success, `init plan-phase failed: ${result.error}`);
|
||||
const data = JSON.parse(result.output);
|
||||
assert.strictEqual(data.granularity, 'fine',
|
||||
'granularities.planning=fine must be honored (phaseType=planning in resolveGranularityInternal)');
|
||||
});
|
||||
|
||||
test('(3) no flag + global granularity=coarse (no granularities.planning) → granularity=coarse', () => {
|
||||
fs.writeFileSync(
|
||||
path.join(tmpDir, '.planning', 'config.json'),
|
||||
JSON.stringify({ granularity: 'coarse' })
|
||||
);
|
||||
const result = runGsdTools('init plan-phase 1', tmpDir, { HOME: tmpDir });
|
||||
assert.ok(result.success, `init plan-phase failed: ${result.error}`);
|
||||
const data = JSON.parse(result.output);
|
||||
assert.strictEqual(data.granularity, 'coarse',
|
||||
'global granularity=coarse must be returned when no granularities.planning is set');
|
||||
});
|
||||
|
||||
test('(4) --granularity ultra → command errors (invalid value rejected on plan-phase path)', () => {
|
||||
const result = runGsdTools('init plan-phase 1 --granularity ultra', tmpDir, { HOME: tmpDir });
|
||||
assert.ok(!result.success, 'should fail with invalid granularity ultra');
|
||||
assert.ok(
|
||||
result.error.includes('ultra') || result.error.includes('invalid'),
|
||||
`error should mention invalid value; got: ${result.error}`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -16,7 +16,6 @@ const {
|
||||
reconstructFrontmatter,
|
||||
spliceFrontmatter,
|
||||
parseMustHavesBlock,
|
||||
FRONTMATTER_SCHEMAS,
|
||||
} = require('../gsd-core/bin/lib/frontmatter.cjs');
|
||||
|
||||
// ─── extractFrontmatter ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -13,7 +13,7 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('node:os');
|
||||
const { execFileSync, spawnSync } = require('child_process');
|
||||
const { createTempProject, cleanup, runGsdTools } = require('./helpers.cjs');
|
||||
const { createTempProject, cleanup, runGsdTools, delay } = require('./helpers.cjs');
|
||||
|
||||
const {
|
||||
graphifyStatus,
|
||||
@@ -263,20 +263,11 @@ describe('auto-update', () => {
|
||||
});
|
||||
}
|
||||
|
||||
// Shared 4-byte buffer used for Atomics.wait-based sleeps throughout the
|
||||
// hook-test helpers. Atomics.wait(sai, 0, 0, ms) yields the event loop for
|
||||
// exactly `ms` milliseconds without spawning an external process.
|
||||
const _sleepSab = new SharedArrayBuffer(4);
|
||||
const _sleepSai = new Int32Array(_sleepSab);
|
||||
function atomicSleep(ms) {
|
||||
Atomics.wait(_sleepSai, 0, 0, ms);
|
||||
}
|
||||
|
||||
// Wait until the detached rebuild writes a terminal status, with a generous
|
||||
// deadline. The detached subprocess can be slow under contended Docker; all
|
||||
// assertions here are outcome-based, so we wait for the real terminal state
|
||||
// rather than guessing a tight wall-clock budget (#382).
|
||||
function waitForBuildStatus(statusPath, terminal /* e.g. new Set(['ok']) */, { deadlineMs = 30000, stepMs = 25 } = {}) {
|
||||
async function waitForBuildStatus(statusPath, terminal /* e.g. new Set(['ok']) */, { deadlineMs = 30000, stepMs = 25 } = {}) {
|
||||
const deadline = Date.now() + deadlineMs;
|
||||
let status;
|
||||
while (Date.now() < deadline) {
|
||||
@@ -287,21 +278,20 @@ describe('auto-update', () => {
|
||||
if (parsed && terminal.has(parsed.status)) return parsed;
|
||||
} catch { /* detached writer can briefly expose a partial JSON write */ }
|
||||
}
|
||||
atomicSleep(stepMs);
|
||||
await delay(stepMs);
|
||||
}
|
||||
return status; // last seen (may be undefined / non-terminal) — assertions below will report
|
||||
}
|
||||
|
||||
function cleanupHookRepo(tmpDir) {
|
||||
async function cleanupHookRepo(tmpDir) {
|
||||
// The hook detaches a graphify-rebuild subprocess that may still be writing
|
||||
// into tmpDir when the test body returns. Wait for the rebuild PID to exit
|
||||
// (lock file disappears on subprocess EXIT trap), then retry rmSync to
|
||||
// absorb any remaining transient ENOTEMPTY race.
|
||||
//
|
||||
// Uses Atomics.wait instead of execFileSync('sleep', ...) so we yield the
|
||||
// CPU without spawning an external process per iteration. Budget: 15 s —
|
||||
// bumped from 4 s to give the detached child more time to exit under
|
||||
// contended Docker before we attempt removal (#382).
|
||||
// Uses delay() instead of Atomics.wait so we yield the event loop
|
||||
// without blocking the thread. Budget: 15 s — bumped from 4 s to give
|
||||
// the detached child more time to exit under contended Docker (#382).
|
||||
const lockPath = path.join(tmpDir, '.planning/graphs/.rebuild.lock');
|
||||
const lockDeadline = Date.now() + 15000;
|
||||
while (Date.now() < lockDeadline) {
|
||||
@@ -313,7 +303,7 @@ describe('auto-update', () => {
|
||||
} catch {
|
||||
break; // PID dead → safe to clean up
|
||||
}
|
||||
atomicSleep(50); // yield 50 ms, then re-check (replaces execFileSync('sleep'))
|
||||
await delay(50); // yield 50 ms, then re-check
|
||||
}
|
||||
try {
|
||||
// eslint-disable-next-line local/no-raw-rmsync-in-tests -- best-effort teardown: error is swallowed so cleanup() (which propagates) cannot be used here; a residual temp dir after a detached-subprocess race is harmless (#382)
|
||||
@@ -447,7 +437,7 @@ describe('auto-update', () => {
|
||||
assert.ok(/^[0-9a-f]{7,40}$/.test(status.head_at_build), 'head_at_build must be a commit sha');
|
||||
});
|
||||
|
||||
test('completes to status=ok after detached graphify run succeeds', (t) => {
|
||||
test('completes to status=ok after detached graphify run succeeds', async (t) => {
|
||||
const tmpDir = createTempGitRepo({
|
||||
config: { graphify: { enabled: true, auto_update: true } },
|
||||
});
|
||||
@@ -465,14 +455,14 @@ describe('auto-update', () => {
|
||||
// Docker is never racing a tight budget (#382). All assertions are
|
||||
// outcome-based; the deadline is deterministic, not a timing assertion.
|
||||
const statusPath = path.join(tmpDir, '.planning/graphs/.last-build-status.json');
|
||||
const status = waitForBuildStatus(statusPath, new Set(['ok']));
|
||||
const status = await waitForBuildStatus(statusPath, new Set(['ok']));
|
||||
assert.ok(status, 'status file must exist after dispatch');
|
||||
assert.strictEqual(status.status, 'ok', 'mock graphify exit=0 → status ok');
|
||||
assert.strictEqual(status.exit_code, 0);
|
||||
assert.ok(typeof status.duration_ms === 'number' && status.duration_ms >= 0);
|
||||
});
|
||||
|
||||
test('completes to status=failed when graphify exits non-zero', (t) => {
|
||||
test('completes to status=failed when graphify exits non-zero', async (t) => {
|
||||
const tmpDir = createTempGitRepo({
|
||||
config: { graphify: { enabled: true, auto_update: true } },
|
||||
});
|
||||
@@ -490,7 +480,7 @@ describe('auto-update', () => {
|
||||
// Docker is never racing a tight budget (#382). All assertions are
|
||||
// outcome-based; the deadline is deterministic, not a timing assertion.
|
||||
const statusPath = path.join(tmpDir, '.planning/graphs/.last-build-status.json');
|
||||
const status = waitForBuildStatus(statusPath, new Set(['failed']));
|
||||
const status = await waitForBuildStatus(statusPath, new Set(['failed']));
|
||||
assert.ok(status, 'status file must exist after dispatch');
|
||||
assert.strictEqual(status.status, 'failed', 'mock graphify exit=1 → status failed');
|
||||
assert.strictEqual(status.exit_code, 1);
|
||||
@@ -578,7 +568,7 @@ describe('auto-update', () => {
|
||||
'gsd-tools query commit "docs: probe" --files .planning/STATE.md',
|
||||
'npx gsd-tools query commit "docs: probe" --files .planning/STATE.md',
|
||||
]) {
|
||||
test(`dispatches on: ${cmd}`, (t) => {
|
||||
test(`dispatches on: ${cmd}`, async (t) => {
|
||||
const tmpDir = createTempGitRepo({
|
||||
config: { graphify: { enabled: true, auto_update: true } },
|
||||
});
|
||||
@@ -592,7 +582,7 @@ describe('auto-update', () => {
|
||||
const statusPath = path.join(tmpDir, '.planning/graphs/.last-build-status.json');
|
||||
// Wait for any terminal status; we only assert the file exists,
|
||||
// not which terminal value it holds (#382: generous deadline).
|
||||
waitForBuildStatus(statusPath, new Set(['ok', 'failed']));
|
||||
await waitForBuildStatus(statusPath, new Set(['ok', 'failed']));
|
||||
assert.ok(
|
||||
fs.existsSync(statusPath),
|
||||
`must dispatch for HEAD-advancing op: ${cmd}`,
|
||||
|
||||
@@ -214,7 +214,7 @@ describe('mvp-viz', () => {
|
||||
function parseSkillFrontmatter(text) {
|
||||
const lines = text.split(/\r?\n/);
|
||||
const out = {};
|
||||
let activeKey = null;
|
||||
let _activeKey = null;
|
||||
let activeList = null;
|
||||
for (const raw of lines) {
|
||||
const listItem = raw.match(/^\s+-\s+(.+?)\s*$/);
|
||||
@@ -227,11 +227,11 @@ describe('mvp-viz', () => {
|
||||
const [, key, rawValue] = kv;
|
||||
const value = rawValue.trim();
|
||||
if (value === '') {
|
||||
activeKey = key;
|
||||
_activeKey = key;
|
||||
activeList = [];
|
||||
out[key] = activeList;
|
||||
} else {
|
||||
activeKey = null;
|
||||
_activeKey = null;
|
||||
activeList = null;
|
||||
out[key] = value;
|
||||
}
|
||||
@@ -365,7 +365,7 @@ describe('regressions', () => {
|
||||
function parseBug3166SkillFrontmatter(text) {
|
||||
const lines = text.split(/\r?\n/);
|
||||
const out = {};
|
||||
let activeKey = null;
|
||||
let _activeKey = null;
|
||||
let activeList = null;
|
||||
for (const raw of lines) {
|
||||
const listItem = raw.match(/^\s+-\s+(.+?)\s*$/);
|
||||
@@ -378,11 +378,11 @@ describe('regressions', () => {
|
||||
const [, key, rawValue] = kv;
|
||||
const value = rawValue.trim();
|
||||
if (value === '') {
|
||||
activeKey = key;
|
||||
_activeKey = key;
|
||||
activeList = [];
|
||||
out[key] = activeList;
|
||||
} else {
|
||||
activeKey = null;
|
||||
_activeKey = null;
|
||||
activeList = null;
|
||||
out[key] = value;
|
||||
}
|
||||
@@ -469,8 +469,8 @@ describe('regressions', () => {
|
||||
'a bash code block must invoke `graphify update .`'
|
||||
);
|
||||
assert.ok(
|
||||
bashBlocks.some(b => /gsd-tools\.cjs["']?\s+graphify build snapshot/.test(b.content)),
|
||||
'a bash code block must invoke `gsd-tools.cjs graphify build snapshot`'
|
||||
bashBlocks.some(b => /gsd_run\s+graphify build snapshot/.test(b.content)),
|
||||
'a bash code block must invoke `gsd_run graphify build snapshot`'
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -334,6 +334,7 @@ describe('context meter respects CLAUDE_CODE_AUTO_COMPACT_WINDOW (#2219)', () =>
|
||||
|
||||
// Parse normalized used% from the statusline bar output (e.g. "60%")
|
||||
// Strip ANSI escape codes then extract the percentage digit(s) before "%"
|
||||
// eslint-disable-next-line no-control-regex -- \x1b (ESC) is the required leading byte of ANSI SGR color sequences; matching it is the purpose of stripping ANSI codes from captured CLI/console output
|
||||
const clean = stdout.replace(/\x1b\[[0-9;]*m/g, '');
|
||||
const match = clean.match(/(\d+)%/);
|
||||
const normalizedUsed = match ? parseInt(match[1], 10) : null;
|
||||
|
||||
@@ -4,14 +4,13 @@
|
||||
// Reads .md/.json/.yml product files whose deployed text IS what the
|
||||
// runtime loads — testing text content tests the deployed contract.
|
||||
|
||||
const { describe, it, test, beforeEach, afterEach } = require('node:test');
|
||||
const { describe, test, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { createTempDir, cleanup, runGsdTools } = require('./helpers.cjs');
|
||||
|
||||
const {
|
||||
findGsd2Root,
|
||||
parseSlicesFromRoadmap,
|
||||
parseMilestoneTitle,
|
||||
parseTaskTitle,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user