Files
msd-core/tests/gsd-write-guard.test.cjs
0xdhx c61dd49d95 enhance(#2255): blocking catastrophic-shrink guard for curated .planning/ writes (#2301)
* feat(#2255): blocking catastrophic-shrink guard for .planning writes

Adds hooks/gsd-write-guard.js, a PreToolUse hook that hard-blocks
(decision: 'block', exit 2) a whole-file Write collapsing a curated
.planning/ artifact (ROADMAP.md, .planning/milestones/*-ROADMAP.md,
STATE.md) below 40% of its on-disk line count. Files under 40 lines
are exempt; GSD_ALLOW_PLANNING_SHRINK=1 (named in the block message)
bypasses for legitimate milestone resets.

Fix 3 of #973 — the only defense independent of per-agent tool config.
Registered on the Claude plugin surface (hooks.json), settings-json
runtimes (runtime-hooks-surface.cts, self-contained pattern), Kimi
spec, and the OpenCode/Kilo plugin buses. Golden install fixtures and
INVENTORY regenerated; regression tests negative-controlled (16/16
RED with the hook absent, 16/16 GREEN with it present).

* chore(#2255): backfill changeset pr number to 2301

* enhance(#2255): address review — fail-closed reads, typed block output, registration, property test

Review fixes for trek-e's CHANGES_REQUESTED on PR #2301:

- Blocker 2: register gsd-write-guard.js in BUNDLED_GSD_HOOK_FILES
  (no-shipping-drift test).
- Blocker 3: update the always-on hook enumerations in ADR-766 and
  CONTEXT.md from six to seven.
- Major 4: fail CLOSED on non-ENOENT read errors — only a missing file
  (new-file Write) passes; EACCES/EISDIR/ELOOP/etc now block, with a
  typed readError field and the override still honored. Tested, with a
  negative control against the pre-fix hook.
- Major 5: fast-check property test for the SHRINK_RATIO/FLOOR_LINES
  budget contract (blocked ⟺ newLines < oldLines*SHRINK_RATIO above the
  floor; sub-floor always exempt), boundary examples pinned.
- Major 6: block output now carries typed oldLines/newLines/
  overrideEnvVar fields; tests assert on those instead of regexing the
  free-form reason string.
- Minor: CURATED_PATTERNS are case-insensitive (case-insensitive-FS
  bypass on macOS/Windows); limit+1 boundary tests added for both the
  floor and the ratio.

* enhance(#2255): engage the write guard on Kimi's native payload shape

The guard shipped with Claude-vocabulary checks (tool_name 'Write',
tool_input.file_path), which #2304 showed leaves a guard dormant on
Kimi: the [[hooks]] matcher is registered pre-translated but kimi-cli
forwards its native payload verbatim — tool_name 'WriteFile' (bare or
module-qualified) and tool_input.path per its tool schemas
(src/kimi_cli/tools/file/write.py). The guard matched, saw an unknown
name, and exited 0.

Apply the same per-guard normalization PR #2326 gives the three
sibling guards (name + field mapping, inlined — hook scripts stage as
standalone files), and write the block reason to stderr as well as
stdout JSON: Kimi feeds stderr, not stdout, back to the model on
exit 2, so a stdout-only reason blocks without telling the model why
or naming the documented override.

Regression tests pipe Kimi-shaped payloads (engage, qualified-name,
stderr-reason) plus exemption pins (StrReplaceFile stays out of scope
by design; non-curated paths pass) — verified red against the pre-fix
guard, green after.

* enhance(#2255): rebase onto next; regenerate golden-parity fixtures

* enhance(#2255): wire the escape hatch into complete-milestone's reorganize step

Review Blocker 1: the guard hard-blocked /gsd:complete-milestone's ROADMAP
reorganize — the tree's only legitimate milestone reset and the exact caller
GSD_ALLOW_PLANNING_SHRINK was built for. The reorganize step now performs the
rewrite through a shell write with the hatch set on the command (a hook
inherits the runtime env, so a bare Write cannot carry a per-step override),
and a binding test derives the env var name from the guard's typed output and
asserts (a) the workflow step sets it and (b) the guard passes the identical
catastrophic payload under it — so the next complete-milestone.md edit cannot
silently re-break the wiring.

* enhance(#2255): drop dead Edit-class mapping from normalizeKimiPayload

Review Major 1: StrReplaceFile -> 'Edit' and the old_string/new_string
reconstruction were unreachable-by-effect — the guard exits 0 for any
tool_name !== 'Write', so nothing ever read the fields they set, leaving
guaranteed-surviving mutants against the Stryker bar. The map now carries
only WriteFile -> 'Write'; the StrReplaceFile exemption test message states
the fall-through it actually exercises.

* enhance(#2255): review minors — American spellings; writeSync before exit(2)

Minor 1: normalised/normalise -> American house style. Minor 2: the two
block paths wrote stdout+stderr via async pipe writes then exit(2) —
async-on-Windows, unflushed at exit; fs.writeSync(1/2, ...) makes the block
payload durable.

* enhance(#2255): assert stderr equals the typed reason, not raw prose

Minor 3: the last raw-text match in the suite pinned override-name prose on
stderr. The contract is "stderr carries the reason Kimi feeds back" — now
asserted as stderr non-empty and byte-equal to the parsed stdout.reason.

* enhance(#2255): bind the write-guard's Kimi normalization into the parity test

Review Major 2: the guard's normalizeKimiPayload is a 4th inlined copy with
nothing binding it. This extends PR #2326's kimi-guard-normalization-parity
test (same path and helpers, authored as a superset so either merge order
resolves cleanly): sibling byte-parity is existence-gated zero-or-all —
trivially green until #2326 lands, full-strength after — and the write-guard
copy is bound semantically (map is the value-inverse of convertKimiToolName;
the Kimi name for Write must map, or the guard is dormant on Kimi; the
path -> file_path half must be present). Byte-parity is deliberately not
asserted for this copy: it legitimately omits the Edit-class mapping
(Major 1 — dead code in a Write-only guard).

* enhance(#2255): refresh golden-parity fixtures for revised guard + workflow

* chore(#2255): regenerate golden fixtures after rebase onto next

The committed fixture hashes were generated against a tree predating
next's latest 11 commits, which independently modified the same
install-parity surface. Rebased onto next and regenerated with
`npm run gen:golden`.

Verified: against upstream/next the regenerated fixtures differ by
exactly this PR's own entries -- hooks/gsd-write-guard.js (new),
hooks/managed-hooks-registry.cjs, plugins/gsd-core.js, and
gsd-core/workflows/complete-milestone.md. No unrelated drift.

* fix(#2255): regenerate workflow size baseline for complete-milestone

`complete-milestone.md` grew 31071 -> 32061 (+990) when the round-2
review fix bound GSD_ALLOW_PLANNING_SHRINK=1 into the reorganize step,
but tests/workflow-size-baseline.json was never regenerated. The
per-file workflow baseline test (issue #1074) failed on
ubuntu-latest/22 and both macOS shard 1/3 jobs.

The growth is justified: it is the escape-hatch binding requested in
review round 2 (the guard must not hard-block the tree's only
legitimate milestone reset), not incidental bloat.

Regenerated via `npm run size:baseline`; the diff is exactly the one
entry.

* chore(#2255): regenerate golden fixtures and size baseline after rebase onto next

* enhance(#2255): bind the shrink escape hatch mechanically — single-use sentinel the guard consumes

Round-5 M1: the per-step `GSD_ALLOW_PLANNING_SHRINK=1 tee` prefix was inert
(no PreToolUse hook exists on Bash in this family; the write succeeded by
dodging the guard, not by the override firing) and the protection was prose.
The hatch is now a transport code consults: complete-milestone's reorganize
step arms `.planning/.gsd-allow-shrink` with the target's path, keeps the
Write tool as the sanctioned path, and the guard — at the block point only —
verifies the sentinel is fresh (15 min) and names the pending target, then
CONSUMES it and allows that one write. Path-bound + single-use + freshness
keep it from becoming a standing unlock. The env var remains as the
interactive transport, where it can actually reach the hook.

Regression tests written first (negative control: 3 failed pre-fix): the
armed-sentinel Write passes and consumes; stale does not exempt; a token for
a different file neither exempts nor is consumed; the binding test now takes
the sentinel name from the guard's typed output (overrideSentinel), asserts
the step arms it, and asserts the step no longer routes the rewrite around
Write via a shell pipe.

Also in this commit, same file:
- m2: block emission is exception-safe — emitBlock() wraps both writeSync
  sites in their own try/catch that still exits 2, so an EPIPE can no longer
  convert fail-closed into the outer catch's fail-open.
- Header discloses the two reviewed design limits (cumulative sequential
  shrink; lexical match vs symlinked paths) per round-5 scoping.

* docs(#2255): document the sentinel transport across guard surfaces; changeset ends with the (#2255) parenthetical (m4)

USER-GUIDE bullet, INVENTORY row (en + ja/ko/pt/zh), the
runtime-hooks-surface registration comment, and the changeset now describe
both hatches — the single-use sentinel for workflow steps and the env var
for interactive use — instead of implying a per-step env can reach a hook.
The changeset's trailing `Resolves #2255.` prose becomes the `(#2255)`
parenthetical the repo's fragments use (round-5 m4).

* chore(#2255): regenerate derived families on the rebased tree (full sweep)

Full generator sweep after rebasing onto next @ the body-parser-patched
lockfile: build, gen-inventory-manifest, gen:golden, size:baseline. Every
regen delta verified to be either a PR-owned entry (gsd-write-guard.js,
complete-milestone.md, INVENTORY/USER-GUIDE) or exact convergence to next's
committed value for entries our arbitrary-side conflict resolution had left
stale (all 18 runtime fixtures checked mechanically).

* test(#2255): use helpers.cleanup for sentinel teardown, not raw fs.rmSync

The repo's local/no-raw-rmsync-in-tests rule exists for the Windows-EBUSY
retry budget; the sentinel disarm now rides it like every other teardown.

* chore(#2255): regenerate derived families after rebase onto next

Full sweep on the rebased tree (build -> gen-inventory-manifest ->
gen:golden -> size:baseline). Every delta is either a PR-owned entry
(hooks/gsd-write-guard.js, its registration surfaces
hooks/managed-hooks-registry.cjs and the two plugin buses,
gsd-core/workflows/complete-milestone.md) or exact convergence to
next's committed value across all 18 runtime fixtures.

* chore(#2255): regenerate derived families after rebase onto next @ a5180d96

Rebase onto current `next` (a5180d96) resolved 12 conflicting
golden-install-parity fixtures; all regenerated via the full generator
sweep (build, gen:golden, size:baseline) rather than a single generator.

`lint:generated-sync` reports every generated artifact in sync. All 45
differing fixture keys and the single workflow-size-baseline entry map
to files this PR actually touches; no foreign drift.

* fix(#2255): remove the stale unguarded reorganize_roadmap step (round-8 blocker)

complete-milestone.md carried a second ROADMAP-collapsing step,
`reorganize_roadmap`, distinct from the sentinel-armed
`reorganize_roadmap_and_delete_originals` this PR wired. It is a vestige
of the pre-archive-then-reorganize design: it sits BEFORE
archive_milestone, so executing it as written would collapse ROADMAP.md
before the archive snapshots the full phase detail — and its Write is
exactly the shape gsd-write-guard hard-blocks, with no hatch armed. The
file's own success criteria describe only one reorganize outcome
(Backlog-preserving, overwrite-in-place — the later step's properties),
and archive_milestone points forward to "the reorganize step".

Removed rather than wired, per the round-8 review's confirm-and-remove
option. A new binding test asserts the sentinel-armed step is the ONLY
reorganize step in the workflow, so an unguarded collapse step cannot be
silently reintroduced (negative-controlled: fails against the pre-fix
tree). Golden-parity fixtures and the size baseline regenerate for the
shrunk file; every changed fixture key is complete-milestone.md's own.

* test(#2255): document why the read-error injection is a path collision, not an fs monkeypatch

Round-8 nit: the non-ENOENT tests inject via a directory-at-target-path
collision instead of the repo's fs-method monkeypatch pattern. That is
deliberate, not drift — runHook exercises the hook as a spawnSync child
process, so an in-process fs.readFileSync patch (the pattern the cited
siblings use on require'd, in-process code) can never reach the code
under test. Record the reasoning at the injection site.

* chore(#2255): regenerate derived families after rebase onto next @ 0d08c320

Rebase onto current next (0d08c320) for the CONFLICTING/DIRTY state. All 32
conflicts were generated artifacts (19 golden-install-parity, 12 install-tree,
workflow-size-baseline); resolved arbitrarily and regenerated via a full
generator sweep (build, gen:golden, size:baseline, gen-inventory-manifest)
rather than hand-merged. No source conflicts.

Regen diff verified against the PR's changed-file set: 7 distinct differing
keys, all PR-owned (gsd-write-guard.js, managed-hooks-registry.cjs,
plugins/gsd-core.js, complete-milestone.md, and their .kimi mirrors).
lint:generated-sync clean.

* chore(#2255): regenerate derived families after rebase onto next @ 9138271b

Conflict set was 20 paths, every one a generated artifact, zero source
conflicts — resolved arbitrarily during the replay and regenerated here,
per the maintainer's round-9 recipe (never hand-merged).

Generator sweep (not just gen:golden): npm run build, gen:golden,
size:baseline, gen-inventory-manifest, gen:registry. INVENTORY-MANIFEST
came back byte-identical, so the merged value was already correct.

Regen diff verified == PR-touched entries: every differing leaf key
attributes to a file this PR changes (complete-milestone.md, the guard,
managed-hooks-registry.cjs, both plugin buses) — derived from the
changed-file set, not a feature-name filter.

* fix(#2255): port the #2595 Kimi-payload hardening the base landed for the sibling guards

Self-found via the round-10 base sweep: a8b40fa5 (#2547/PR #2595) hardened
gsd-prompt/read/worktree-path-guard's normalizeKimiPayload after this PR was
authored, and this guard carried all three pre-fix shapes:

- `path` now wins outright over a model-supplied `file_path` — kimi-cli's
  WriteFile schema carries no `file_path`, so a payload pairing a curated
  `path` with a spurious `file_path: ""` had the guard reading '' and
  exiting 0 while kimi-cli wrote to `path` (one-key bypass, no crash needed).
- null/primitive payloads pass through deliberately instead of throwing into
  the fail-open catch.
- the `file_path` read is typed (`typeof === 'string'`), closing the
  crash-to-allow on `[]`/`{}` — this is what the base-added
  kimi-guard-typed-payload-reads scan flags.

Negative-controlled: the shadowing payload exits 0 against the pre-fix guard
and 2 against this one.

* fix(#2255): round 9 Major 2 — stop printing the sentinel recipe in the agent-facing denial

The block message ended by telling the blocked agent exactly how to arm the
single-use sentinel — handing the #973 actor a mechanical self-authorization
in the moment it is blocked. The recipe is gone from the prose; the
corrective advice and the env override's name stay (the latter is a #2255
acceptance criterion, and a per-step env prefix cannot reach a hook anyway),
and the typed overrideSentinel field stays for the binding tests. The hatch
remains documented in USER-GUIDE.md and complete-milestone.md, where humans
and the workflow engine read.

* fix(#2255): round 9 Minors 1-2 — realpath-resolve the target before the curated match; disclose the /i Linux cost

Minor 1: a Write to a non-curated path that symlinks into a curated file was
not matched while writeFileSync followed the link — the target is now
realpath-resolved before the curated match (ENOENT keeps the lexical
resolution so new-file Writes still pass; any other realpath error falls
through to the read, which fails closed). Negative-controlled: the symlink
payload exits 0 against the pre-fix guard, 2 against this one. Test skips on
win32, where symlink creation needs privilege.

Minor 2: the header's design-limits block now names the unconditional /i
cost on case-sensitive Linux (a genuinely distinct .planning/roadmap.md is
also treated as curated) next to the stateless limit, and drops the closed
symlink limit.

* test(#2255): round 9 Minors 3-4 — CRLF counting pin + a passing Write leaves a fresh sentinel unburned

Minor 3: countLines' split('\n') is CRLF-safe for a count (the \r rides
along), confirmed by trace in the review — this pins it against this repo's
recurring CRLF regressions, on both sides of the compare and at the 40%
boundary.

Minor 4: consumeSentinelFor runs only after the ratio check would block, so
a within-tolerance Write never burns the workflow's token — true by
construction, previously un-asserted.

* fix(#2255): round 9 Major 3 — correct the stale env-var line in archive_milestone's summary

complete-milestone.md's "After archival" bullet still said the reorganize
happens "under GSD_ALLOW_PLANNING_SHRINK=1" — the wording from the round-2
design this PR's own history rejected in round 5 (a per-step env var cannot
reach a hook; setting it in a Bash step silently does nothing). It now points
at the sentinel mechanics the reorganize step actually documents, matching
that step and USER-GUIDE.md.

* docs(#2255): round 9 Major 1 — user-facing docs state the stateless per-Write limit

The changeset and USER-GUIDE described the guard as covering "catastrophically
shrinks" with no caveat, while the stateless design was disclosed only in the
hook header — an operator reading the shipped docs would conclude iterative
erosion is covered. Both surfaces now state the per-Write comparison and the
erosion non-goal explicitly, in line with what the guard does.

* fix(#2255): round 10 Blocker 1 — arm the hatch in the roadmapper's curated writes

gsd-roadmapper Step 7 Writes both .planning/ROADMAP.md and .planning/STATE.md
wholesale, and /gsd:new-milestone spawns it against the OUTGOING milestone's
files. new-milestone's `phases.clear` archives phase DIRECTORIES, never
ROADMAP.md, so nothing compacts it first, and no ordering rule forces
/gsd:complete-milestone to run before /gsd:new-milestone.

Measured against the shipped hook at the #973 file size (292 lines): a new
4-phase roadmap lands at 18.2% and an 8-phase one at 31.8% — both blocked; only
a 12-phase replacement (45.5%) clears. So the collapse is reachable on a
first-party flow, which is the failure mode #2255 para 4 says the guard must not
have.

Arms the single-use sentinel immediately before each Write, one per target
(the token is path-bound and single-use, so one arming cannot cover both), and
gates each arming on `[ -f ]` so the /gsd:new-project path — where the guard
already exempts via ENOENT — strands no unconsumed token.

Binding test derives the sentinel name from the guard's own typed output, so a
rename on either side fails the suite instead of silently unwiring the hatch.
Negative-controlled: 2 assertions fail against the pre-fix roadmapper.

* docs(#2255): round 10 Major 2 — scope the claim to the guarantee that ships

The sentinel is a plain file, so an agent that would reason past an advisory
can arm one with a single Bash call it is already permitted to make. The
"only defense independent of per-agent tool config" framing outran that, and
the changeset was on its way into CHANGELOG.md.

Retitles the claim on all three surfaces (changeset, guard header, USER-GUIDE)
to what the guard actually delivers: it blocks accidental and single-shot
collapse and is not a defense against a determined agent; what it converts is
"ignore a sentence" into "take one deliberate, path-bound, single-use,
auditable action".

Pinned by test on the DURABLE surfaces only — the guard header and USER-GUIDE.
The changeset fragment is deliberately not pinned: it is consumed at release,
so a test reading it would start failing the moment the release lands. The
bound-statement assertion normalizes comment markers and whitespace first, so
it pins the claim rather than the paragraph's line wrapping.

Negative-controlled: both assertions fail against the pre-fix surfaces.

* test(#2255): acknowledge the roadmapper growth from the round 10 Blocker 1 wiring

The emitted-attribution gate (#2719/#2767) flags gsd-roadmapper.md growing 1130
bytes without an acknowledgment. The growth is the Blocker 1 sentinel wiring
plus the rationale a future editor needs to keep it, so it gets an ack fragment
rather than a silencing regen — the gate's own message is explicit that there is
nothing left to regenerate.

Fragment is PR-scoped (2301-…) per the gate's naming instruction, and uses the
plain-string reason form the shipped fragments use.

Verified against the TRUE upstream tip, not the fork's origin/next: a stale
origin made this same gate report unrelated phantom drift (1 emitted path + 6
grown files + 5 stale acks) that vanishes when GSD_EMITTED_BASE is pinned.

* test(#2255): renumber the roadmapper PROSE_ALLOWLIST pin after the Step 7 wiring

CI red on shard 2/3, all four platforms. The #2751 gate keys PROSE_ALLOWLIST on
{file, line}; the Blocker 1 wiring added 18 lines above the allowlisted
parenthetical in agents/gsd-roadmapper.md, moving it 624 -> 642. Both halves of
the gate then fired: the moved line reads as a new offender, and the stale
entry no longer matches anything.

Line content at 642 is byte-identical to what the entry describes — a
descriptive "e.g." naming SDK queries a user could run — so this is a
renumber, not a re-classification.

Swept the defect class rather than the instance: agents/gsd-roadmapper.md is
the only line-pinned reference to any file this round changed.

Negative-controlled: both assertions fail against the un-renumbered allowlist.

---------

Co-authored-by: Tom Boucher <trekkie@nomorestars.com>
2026-08-01 21:19:49 -04:00

647 lines
32 KiB
JavaScript

'use strict';
/**
* gsd-write-guard.js — catastrophic-shrink guard for curated .planning/ writes
*
* Seam: hooks/gsd-write-guard.js (PreToolUse hook, spawned with a JSON payload
* on stdin, exactly as every runtime bus invokes it).
*
* #2255 (fix 3 of #973): a planner read a ~16-line window of ROADMAP.md and
* Write-overwrote the whole 292-line file with it. This hook hard-blocks
* (decision: 'block', exit 2) a whole-file Write that shrinks a curated
* .planning/ artifact below SHRINK_RATIO (40%) of its on-disk line count,
* with a FLOOR_LINES (40) exemption for small stubs and a documented
* GSD_ALLOW_PLANNING_SHRINK=1 escape hatch named in the block message.
*
* Acceptance criteria covered:
* 1. Blocking polarity — decision: 'block' + exit 2, not advisory.
* 2. Fires ONLY on the curated set — a wholesale rewrite of an arbitrary
* .md passes untouched.
* 3. Compares the pending payload against the on-disk file.
* 4. Documented env override exists and its name is in the block message.
* 5. Line-count floor — a sub-floor file is exempt.
*/
const { describe, test, before, after } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { createTempDir, cleanup } = require('./helpers.cjs');
const HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-write-guard.js');
/**
* Run the hook with a given payload. The override env var is stripped by
* default so an outer environment can never leak a bypass into the tests;
* pass extraEnv to set it explicitly.
*/
function runHook(payload, extraEnv = {}) {
const env = { ...process.env };
delete env.GSD_ALLOW_PLANNING_SHRINK;
Object.assign(env, extraEnv);
return spawnSync(process.execPath, [HOOK_PATH], {
input: typeof payload === 'string' ? payload : JSON.stringify(payload),
encoding: 'utf8',
env,
});
}
function lines(n, tag = 'line') {
return Array.from({ length: n }, (_, i) => `${tag} ${i + 1}`).join('\n') + '\n';
}
function writePayload(filePath, content, overrides = {}) {
return {
hook_event_name: 'PreToolUse',
tool_name: 'Write',
tool_input: { file_path: filePath, content },
...overrides,
};
}
let projectDir;
let planningDir;
let roadmapPath;
before(() => {
projectDir = createTempDir('gsd-write-guard-');
planningDir = path.join(projectDir, '.planning');
fs.mkdirSync(path.join(planningDir, 'milestones'), { recursive: true });
roadmapPath = path.join(planningDir, 'ROADMAP.md');
});
after(() => {
cleanup(projectDir);
});
describe('gsd-write-guard.js: catastrophic shrink of curated artifacts', () => {
test('#973 shape: 292-line ROADMAP.md overwritten with 16 lines is BLOCKED (exit 2, decision block)', () => {
fs.writeFileSync(roadmapPath, lines(292));
const r = runHook(writePayload(roadmapPath, lines(16)));
assert.equal(r.status, 2, `expected exit 2, got ${r.status}; stdout: ${r.stdout}`);
const out = JSON.parse(r.stdout);
assert.equal(out.decision, 'block', 'must emit decision: block (hard-block, not advisory)');
assert.equal(out.oldLines, 292, 'typed oldLines field must carry the on-disk line count');
assert.equal(out.newLines, 16, 'typed newLines field must carry the payload line count');
});
test('block output names the documented override in the typed overrideEnvVar field', () => {
fs.writeFileSync(roadmapPath, lines(292));
const r = runHook(writePayload(roadmapPath, lines(16)));
assert.equal(r.status, 2);
const out = JSON.parse(r.stdout);
assert.equal(
out.overrideEnvVar, 'GSD_ALLOW_PLANNING_SHRINK',
'the escape hatch must be named in the block output — an undocumented bypass gets bypassed with the blunt instrument instead'
);
});
test('GSD_ALLOW_PLANNING_SHRINK=1 bypasses the block (documented escape hatch)', () => {
fs.writeFileSync(roadmapPath, lines(292));
const r = runHook(writePayload(roadmapPath, lines(16)), { GSD_ALLOW_PLANNING_SHRINK: '1' });
assert.equal(r.status, 0, `override must pass; stdout: ${r.stdout}`);
assert.equal(r.stdout, '', 'override path must be silent');
});
test('milestone roadmap (.planning/milestones/v1-ROADMAP.md) is curated — blocked', () => {
const msPath = path.join(planningDir, 'milestones', 'v1-ROADMAP.md');
fs.writeFileSync(msPath, lines(120));
const r = runHook(writePayload(msPath, lines(10)));
assert.equal(r.status, 2, `expected exit 2, got ${r.status}; stdout: ${r.stdout}`);
assert.equal(JSON.parse(r.stdout).decision, 'block');
});
test('STATE.md under .planning/ is curated — blocked', () => {
const statePath = path.join(planningDir, 'STATE.md');
fs.writeFileSync(statePath, lines(90));
const r = runHook(writePayload(statePath, lines(5)));
assert.equal(r.status, 2, `expected exit 2, got ${r.status}; stdout: ${r.stdout}`);
assert.equal(JSON.parse(r.stdout).decision, 'block');
});
test('non-ENOENT read error fails CLOSED — curated target unreadable blocks (exit 2)', () => {
// A directory at the curated path makes readFileSync throw EISDIR (or the
// platform's equivalent) — any non-ENOENT read error must block, not wave
// the Write through on a transient failure.
// Injected via a directory-at-path collision rather than the usual
// fs.readFileSync monkeypatch: runHook spawns the hook as a child process
// (spawnSync), so an in-process fs patch can never reach the code under
// test — the on-disk collision is the only injection that crosses the
// process boundary, and it reproduces on all 3 CI platforms.
const dirAsRoadmap = path.join(planningDir, 'milestones', 'vX-ROADMAP.md');
fs.mkdirSync(dirAsRoadmap, { recursive: true });
const r = runHook(writePayload(dirAsRoadmap, lines(300)));
assert.equal(r.status, 2, `unreadable curated target must fail closed; stdout: ${r.stdout}`);
const out = JSON.parse(r.stdout);
assert.equal(out.decision, 'block');
assert.equal(out.overrideEnvVar, 'GSD_ALLOW_PLANNING_SHRINK');
assert.notEqual(out.readError, undefined, 'typed readError field must carry the error code');
});
test('non-ENOENT read error still honors the documented override (fails open when set)', () => {
const dirAsRoadmap = path.join(planningDir, 'milestones', 'vY-ROADMAP.md');
fs.mkdirSync(dirAsRoadmap, { recursive: true });
const r = runHook(writePayload(dirAsRoadmap, lines(300)), { GSD_ALLOW_PLANNING_SHRINK: '1' });
assert.equal(r.status, 0, `override must bypass the fail-closed branch; stdout: ${r.stdout}`);
});
test('differently-cased path to a curated file is still guarded (case-insensitive FS bypass)', () => {
fs.writeFileSync(roadmapPath, lines(292));
// On a case-insensitive filesystem (macOS/Windows default) this path IS
// ROADMAP.md; on a case-sensitive one it's a new file and ENOENT fails
// open — either way the pattern match itself must be case-insensitive,
// which this payload exercises via the resolved-path match.
const casedPath = path.join(planningDir, 'roadmap.MD');
const r = runHook(writePayload(casedPath, lines(16)));
if (fs.existsSync(casedPath) && fs.statSync(casedPath).size > 0) {
// case-insensitive FS: same real file — must block
assert.equal(r.status, 2, `case-variant Write to the same real file must block; stdout: ${r.stdout}`);
} else {
// case-sensitive FS: genuinely a new file — new-file Writes pass
assert.equal(r.status, 0, `stdout: ${r.stdout}`);
}
});
test('relative file_path resolves against the payload cwd — blocked', () => {
fs.writeFileSync(roadmapPath, lines(292));
const payload = writePayload('.planning/ROADMAP.md', lines(16), { cwd: projectDir });
const r = runHook(payload);
assert.equal(r.status, 2, `expected exit 2, got ${r.status}; stdout: ${r.stdout}`);
assert.equal(JSON.parse(r.stdout).decision, 'block');
});
});
describe('round 9: symlink resolution, CRLF counting, and denial-content pins', () => {
test('a Write to a non-curated SYMLINK into a curated file is guarded (realpath before the match)',
{ skip: process.platform === 'win32' ? 'symlink creation needs privilege on Windows' : false }, () => {
fs.writeFileSync(roadmapPath, lines(292));
const linkPath = path.join(projectDir, 'innocent-notes.md');
fs.symlinkSync(roadmapPath, linkPath);
try {
const r = runHook(writePayload(linkPath, lines(16)));
assert.equal(r.status, 2,
`writeFileSync follows the link into ROADMAP.md, so the guard must too. Got ${r.status}; stdout: ${r.stdout}`);
assert.equal(JSON.parse(r.stdout).decision, 'block');
} finally {
cleanup(linkPath);
}
});
test('the denial prose does NOT publish the sentinel recipe; the typed field still names it (round 9 Major 2)', () => {
fs.writeFileSync(roadmapPath, lines(292));
const r = runHook(writePayload(roadmapPath, lines(16)));
assert.equal(r.status, 2);
const out = JSON.parse(r.stdout);
assert.equal(out.overrideSentinel, '.planning/.gsd-allow-shrink',
'the typed field stays — the binding tests and workflow consumers key on it');
assert.ok(!out.reason.includes(out.overrideSentinel),
'#973 was an agent reasoning past an advisory: the agent-facing denial must not print the sentinel recipe');
assert.ok(out.reason.includes(out.overrideEnvVar),
"#2255 acceptance criterion: the env override's name stays in the block message");
});
test('CRLF content counts lines correctly on both sides of the compare', () => {
const crlf = (n) => Array.from({ length: n }, (_, i) => `line ${i + 1}`).join('\r\n') + '\r\n';
fs.writeFileSync(roadmapPath, crlf(100));
const blocked = runHook(writePayload(roadmapPath, crlf(39)));
assert.equal(blocked.status, 2, `39/100 CRLF lines is under the 40% ratio and must block. Got ${blocked.status}`);
const out = JSON.parse(blocked.stdout);
assert.equal(out.oldLines, 100, 'CRLF on disk must not inflate or deflate the count');
assert.equal(out.newLines, 39, 'CRLF in the payload must not inflate or deflate the count');
const pass = runHook(writePayload(roadmapPath, crlf(40)));
assert.equal(pass.status, 0, '40/100 CRLF lines sits exactly on the tolerated boundary and must pass');
});
});
describe('gsd-write-guard.js: deliberately narrow trigger (no-op paths)', () => {
test('wholesale rewrite of a NON-curated .md passes untouched (no override-fatigue)', () => {
const notesPath = path.join(projectDir, 'docs-notes.md');
fs.writeFileSync(notesPath, lines(200));
const r = runHook(writePayload(notesPath, lines(5)));
assert.equal(r.status, 0, `non-curated file must pass; stdout: ${r.stdout}`);
assert.equal(r.stdout, '');
});
test('non-roadmap file under .planning/milestones/ is not curated — passes', () => {
const auditPath = path.join(planningDir, 'milestones', 'v1-MILESTONE-AUDIT.md');
fs.writeFileSync(auditPath, lines(200));
const r = runHook(writePayload(auditPath, lines(5)));
assert.equal(r.status, 0, `stdout: ${r.stdout}`);
});
test('sub-floor file (39 lines) is exempt from the ratio check', () => {
fs.writeFileSync(roadmapPath, lines(39));
const r = runHook(writePayload(roadmapPath, lines(2)));
assert.equal(r.status, 0, `sub-floor stub must pass; stdout: ${r.stdout}`);
});
test('at-floor file (40 lines) IS guarded — the floor is exclusive', () => {
fs.writeFileSync(roadmapPath, lines(40));
const r = runHook(writePayload(roadmapPath, lines(15)));
assert.equal(r.status, 2, `40-line file collapsing to 15 (37.5%) must block; stdout: ${r.stdout}`);
});
test('above-floor file (41 lines) IS guarded — floor boundary from above', () => {
fs.writeFileSync(roadmapPath, lines(41));
const r = runHook(writePayload(roadmapPath, lines(15)));
assert.equal(r.status, 2, `41-line file collapsing to 15 (~36.6%) must block; stdout: ${r.stdout}`);
});
test('ratio boundary: exactly 40% of old passes; one line either side behaves', () => {
fs.writeFileSync(roadmapPath, lines(100));
const atThreshold = runHook(writePayload(roadmapPath, lines(40)));
assert.equal(atThreshold.status, 0, `100 → 40 (exactly 40%) must pass; stdout: ${atThreshold.stdout}`);
const belowThreshold = runHook(writePayload(roadmapPath, lines(39)));
assert.equal(belowThreshold.status, 2, `100 → 39 (39%) must block; stdout: ${belowThreshold.stdout}`);
const aboveThreshold = runHook(writePayload(roadmapPath, lines(41)));
assert.equal(aboveThreshold.status, 0, `100 → 41 (41%) must pass; stdout: ${aboveThreshold.stdout}`);
});
test('creating a curated file that does not exist yet passes', () => {
const freshPath = path.join(planningDir, 'milestones', 'v9-ROADMAP.md');
const r = runHook(writePayload(freshPath, lines(3)));
assert.equal(r.status, 0, `new-file Write must pass; stdout: ${r.stdout}`);
});
test('Edit tool call is out of scope — passes even on a curated target', () => {
fs.writeFileSync(roadmapPath, lines(292));
const payload = {
hook_event_name: 'PreToolUse',
tool_name: 'Edit',
tool_input: { file_path: roadmapPath, old_string: 'line 1', new_string: 'line one' },
};
const r = runHook(payload);
assert.equal(r.status, 0, `Edit is scoped by construction; stdout: ${r.stdout}`);
});
test('MultiEdit tool call is out of scope — passes', () => {
fs.writeFileSync(roadmapPath, lines(292));
const payload = {
hook_event_name: 'PreToolUse',
tool_name: 'MultiEdit',
tool_input: { file_path: roadmapPath, edits: [] },
};
const r = runHook(payload);
assert.equal(r.status, 0);
});
test('payload without content (non-string) fails open', () => {
fs.writeFileSync(roadmapPath, lines(292));
const payload = {
hook_event_name: 'PreToolUse',
tool_name: 'Write',
tool_input: { file_path: roadmapPath },
};
const r = runHook(payload);
assert.equal(r.status, 0, `missing content must fail open; stdout: ${r.stdout}`);
});
test('malformed JSON on stdin fails open (silent fail, never blocks)', () => {
const r = runHook('{not json');
assert.equal(r.status, 0);
assert.equal(r.stdout, '');
});
});
// ────────────────────────────────────────────────────────────────────────
// #2304 — Kimi tool vocabulary engages the guard
// Payload shapes mirror kimi-cli's actual tool schemas
// (src/kimi_cli/tools/file/write.py): WriteFile takes `path`/`content`,
// not Claude's `file_path`. See PR #2326 for the sibling guards.
// ────────────────────────────────────────────────────────────────────────
describe('#2304: Kimi tool vocabulary engages the write guard', () => {
test('Kimi WriteFile catastrophic shrink is BLOCKED like Write', () => {
fs.writeFileSync(roadmapPath, lines(292));
const r = runHook({
hook_event_name: 'PreToolUse',
tool_name: 'WriteFile',
tool_input: { path: roadmapPath, content: lines(16) },
});
assert.equal(r.status, 2, `Kimi WriteFile shrink must be blocked. Got ${r.status}; stdout: ${r.stdout}`);
const out = JSON.parse(r.stdout);
assert.equal(out.decision, 'block');
assert.equal(out.oldLines, 292);
assert.equal(out.newLines, 16);
});
test('module-qualified kimi_cli.tools.file:WriteFile is recognized', () => {
fs.writeFileSync(roadmapPath, lines(292));
const r = runHook({
hook_event_name: 'PreToolUse',
tool_name: 'kimi_cli.tools.file:WriteFile',
tool_input: { path: roadmapPath, content: lines(16) },
});
assert.equal(r.status, 2, `qualified Kimi WriteFile shrink must be blocked. Got ${r.status}; stdout: ${r.stdout}`);
assert.equal(JSON.parse(r.stdout).decision, 'block');
});
test('block reason reaches stderr (Kimi feeds stderr back to the model on exit 2)', () => {
fs.writeFileSync(roadmapPath, lines(292));
const r = runHook({
hook_event_name: 'PreToolUse',
tool_name: 'WriteFile',
tool_input: { path: roadmapPath, content: lines(16) },
});
assert.equal(r.status, 2);
assert.ok(r.stderr.length > 0, 'stderr must be non-empty — it is the channel Kimi feeds back');
assert.equal(r.stderr, JSON.parse(r.stdout).reason,
'stderr must carry exactly the typed reason — the same contract, without pinning prose');
});
test('Kimi StrReplaceFile stays exempt (Edit-class, out of scope by design)', () => {
fs.writeFileSync(roadmapPath, lines(292));
const r = runHook({
hook_event_name: 'PreToolUse',
tool_name: 'StrReplaceFile',
tool_input: { path: roadmapPath, edit: { old: 'line 1', new: 'line one' } },
});
assert.equal(r.status, 0, 'StrReplaceFile is unmapped in this guard (Edit-class, out of scope by design #2255) and must fall through to the non-Write exemption');
assert.equal(r.stdout, '');
});
test('Kimi WriteFile of a non-curated path stays exempt', () => {
const otherPath = path.join(projectDir, 'notes.md');
fs.writeFileSync(otherPath, lines(300));
const r = runHook({
hook_event_name: 'PreToolUse',
tool_name: 'WriteFile',
tool_input: { path: otherPath, content: lines(5) },
});
assert.equal(r.status, 0);
assert.equal(r.stdout, '');
});
test("a spurious model-supplied file_path cannot shadow Kimi's authoritative path (#2595 class)", () => {
fs.writeFileSync(roadmapPath, lines(292));
const r = runHook({
hook_event_name: 'PreToolUse',
tool_name: 'WriteFile',
tool_input: { path: roadmapPath, file_path: '', content: lines(16) },
});
assert.equal(r.status, 2,
`kimi-cli executes on \`path\`, so \`path\` must win outright — a spurious file_path:'' shadowed it pre-fix and the guard read '' and exited 0. Got ${r.status}; stdout: ${r.stdout}`);
assert.equal(JSON.parse(r.stdout).decision, 'block');
});
test('null and primitive payloads fall through deliberately (total normalization, #2595 class)', () => {
for (const payload of ['null', '42', '"write"']) {
const r = runHook(payload);
assert.equal(r.status, 0, `payload ${payload} has nothing to guard and must exit 0 without crashing`);
assert.equal(r.stdout, '');
}
});
});
describe('single-use sentinel exemption (.planning/.gsd-allow-shrink) — the mechanical hatch the workflow uses', () => {
// #2255 round 5 M1: a per-step env prefix cannot reach a PreToolUse hook
// (the hook inherits the RUNTIME's environment), so the workflow's hatch is
// a sentinel FILE the guard itself consults: the step writes the target's
// path into .planning/.gsd-allow-shrink, and the guard consumes it (single
// use) to allow exactly one otherwise-blocked shrink of exactly that file.
const sentinelName = '.gsd-allow-shrink';
let sentinelPath;
before(() => {
sentinelPath = path.join(planningDir, sentinelName);
});
function armSentinel(target = '.planning/ROADMAP.md') {
fs.writeFileSync(sentinelPath, target + '\n');
}
function disarm() {
cleanup(sentinelPath); // helpers.cleanup — carries the Windows-EBUSY retry budget
}
test('a reorganize-shaped Write PASSES under a fresh sentinel naming the target — and the sentinel is CONSUMED', () => {
fs.writeFileSync(roadmapPath, lines(292));
armSentinel();
const r = runHook(writePayload(roadmapPath, lines(16), { cwd: projectDir }));
assert.equal(r.status, 0,
`fresh sentinel naming the target must exempt the shrink. Got ${r.status}; stdout: ${r.stdout}`);
assert.equal(fs.existsSync(sentinelPath), false,
'the sentinel must be consumed by the allow — single-use, never a standing unlock');
// Single-use for real: the identical payload immediately after is blocked.
const again = runHook(writePayload(roadmapPath, lines(16), { cwd: projectDir }));
assert.equal(again.status, 2, 'the sentinel is spent — the identical second Write must block');
});
test('a STALE sentinel does not exempt', () => {
fs.writeFileSync(roadmapPath, lines(292));
armSentinel();
const old = (Date.now() - 16 * 60 * 1000) / 1000; // past the 15-minute freshness window
fs.utimesSync(sentinelPath, old, old);
const r = runHook(writePayload(roadmapPath, lines(16), { cwd: projectDir }));
assert.equal(r.status, 2, 'a stale sentinel is a leftover, not an authorization');
disarm();
});
test('a sentinel naming a DIFFERENT file neither exempts nor is consumed', () => {
fs.writeFileSync(roadmapPath, lines(292));
armSentinel('.planning/STATE.md');
const r = runHook(writePayload(roadmapPath, lines(16), { cwd: projectDir }));
assert.equal(r.status, 2, 'the sentinel is path-bound — a token for STATE.md must not exempt ROADMAP.md');
assert.equal(fs.existsSync(sentinelPath), true,
'a mismatched sentinel must survive — it still authorizes the write it was armed for');
disarm();
});
test('a within-tolerance Write does NOT consume a fresh sentinel (consulted only at the block point)', () => {
fs.writeFileSync(roadmapPath, lines(292));
armSentinel();
const r = runHook(writePayload(roadmapPath, lines(200), { cwd: projectDir }));
assert.equal(r.status, 0, `200/292 is within tolerance and must pass. Got ${r.status}; stdout: ${r.stdout}`);
assert.equal(fs.existsSync(sentinelPath), true,
'a passing Write must not burn the token the workflow armed for its collapse — true by construction, now asserted');
disarm();
});
test('the block output names the sentinel via a typed field (consumers never regex the prose)', () => {
fs.writeFileSync(roadmapPath, lines(292));
const r = runHook(writePayload(roadmapPath, lines(16), { cwd: projectDir }));
assert.equal(r.status, 2);
const out = JSON.parse(r.stdout);
assert.equal(out.overrideSentinel, `.planning/${sentinelName}`,
'blocked callers are told the mechanical hatch by typed field, same contract as overrideEnvVar');
});
});
describe('guard <-> complete-milestone workflow binding (the escape hatch is WIRED, not just present)', () => {
// #2255 review Blocker 1 (reopened round 5 as M1): the one first-party
// legitimate milestone reset — complete-milestone's reorganize step — must
// route through a hatch the guard MECHANICALLY honors, on the tool the
// guard actually watches. Round 3's fix routed around Write via Bash+tee
// with an env prefix nothing reads; this binding asserts the opposite: the
// step arms the sentinel the guard consumes, keeps Write as the sanctioned
// path, and no longer smuggles the rewrite through a shell pipe. The
// sentinel name is taken from the guard's typed output, so a rename on
// EITHER side fails here instead of silently unwiring the hatch.
const workflowPath = path.join(
__dirname, '..', 'gsd-core', 'workflows', 'complete-milestone.md'
);
test('the reorganize step arms the exact sentinel the guard consumes, and keeps Write as the path', () => {
const src = fs.readFileSync(workflowPath, 'utf8');
const stepStart = src.indexOf('<step name="reorganize_roadmap_and_delete_originals">');
assert.notEqual(stepStart, -1,
'reorganize step missing or renamed in complete-milestone.md — rebind this test');
const step = src.slice(stepStart, src.indexOf('</step>', stepStart));
fs.writeFileSync(roadmapPath, lines(292));
const blocked = runHook(writePayload(roadmapPath, lines(16), { cwd: projectDir }));
assert.equal(blocked.status, 2, 'baseline: the reorganize-shaped Write must block without the hatch');
const sentinel = JSON.parse(blocked.stdout).overrideSentinel;
assert.ok(sentinel, 'the guard must publish its sentinel path as a typed field');
assert.ok(step.includes(sentinel),
`complete-milestone.md's reorganize step no longer arms ${sentinel} — ` +
'its whole-file ROADMAP.md rewrite would be hard-blocked by gsd-write-guard (#2255 M1)');
assert.ok(!/GSD_ALLOW_PLANNING_SHRINK=1\s+tee/.test(step) && !/\btee\s+\.planning\/ROADMAP\.md/.test(step),
'the reorganize step must not route the rewrite around Write via a shell pipe — ' +
'that is the prose-level protection M1 exists to eliminate');
// The real failure round 5 named: agent follows the step, arms the
// sentinel, then calls Write — this exact sequence must pass.
fs.writeFileSync(path.join(planningDir, '.gsd-allow-shrink'), '.planning/ROADMAP.md\n');
const allowed = runHook(writePayload(roadmapPath, lines(16), { cwd: projectDir }));
assert.equal(allowed.status, 0,
'the identical catastrophic payload must pass under the sentinel the workflow step arms');
});
test('the sentinel-armed reorganize step is the ONLY ROADMAP-collapsing step in the workflow', () => {
// #2255 round 8 Blocker: a second, hatch-less `reorganize_roadmap` step —
// a vestige of the pre-archive-then-reorganize design, sitting BEFORE
// archive_milestone, so running it would collapse ROADMAP.md before the
// archive snapshots the full detail — was removed rather than wired. This
// binding fails if any reorganize step other than the sentinel-armed one
// is (re)introduced without hatch wiring of its own.
const src = fs.readFileSync(workflowPath, 'utf8');
const names = [...src.matchAll(/<step name="([^"]*reorganize[^"]*)">/g)].map((m) => m[1]);
assert.deepEqual(names, ['reorganize_roadmap_and_delete_originals'],
'complete-milestone.md must contain exactly one ROADMAP-reorganize step — the ' +
'sentinel-armed reorganize_roadmap_and_delete_originals; any additional reorganize ' +
'step is an unguarded catastrophic-shrink Write (#2255 round 8 Blocker)');
});
});
describe('the shipped claim matches the shipped guarantee (round 10 Major 2)', () => {
// The guard's reach is bounded: the sentinel is a plain file, so an agent
// that would reason past an advisory can arm one with a single Bash call.
// Round 10 asked that the claim not outrun that, and specifically that the
// stronger wording not reach CHANGELOG.md. Pinned on the DURABLE surfaces
// only — a changeset fragment is consumed at release, so a test reading it
// would start failing the moment the release lands.
const RETIRED = 'the only defense independent of per-agent tool config';
const surfaces = [
['hooks/gsd-write-guard.js', path.join(__dirname, '..', 'hooks', 'gsd-write-guard.js')],
['docs/USER-GUIDE.md', path.join(__dirname, '..', 'docs', 'USER-GUIDE.md')],
];
for (const [label, file] of surfaces) {
test(`${label} does not restate the retired unbounded claim`, () => {
const src = fs.readFileSync(file, 'utf8');
assert.ok(!src.includes(RETIRED),
`${label} carries the retired claim "${RETIRED}" — it overstates what the guard ` +
'delivers, because the sentinel is agent-armable (#2255 round 10 Major 2)');
});
test(`${label} states the determined-agent bound`, () => {
// Normalize before matching: the claim is prose, and in a source file it
// is prose wrapped in `//` across several lines. A pin that breaks when
// a paragraph is reflowed tests the formatter, not the claim.
const src = fs.readFileSync(file, 'utf8')
.replace(/^\s*\/\/ ?/gm, '')
.replace(/\s+/g, ' ');
assert.match(src, /not a defense against (a determined agent|an evader)/,
`${label} must state that the guard does not stop a determined agent — the bound is ` +
'the half a reader acts on (#2255 round 10 Major 2)');
});
}
});
describe('guard <-> gsd-roadmapper binding (the /gsd:new-milestone collapse path is hatched)', () => {
// #2255 round 10 Blocker 1: complete-milestone was not the only first-party
// flow that overwrites a curated artifact wholesale. gsd-roadmapper's Step 7
// Writes BOTH .planning/ROADMAP.md and .planning/STATE.md, and
// /gsd:new-milestone spawns it against the OUTGOING milestone's files —
// new-milestone's `phases.clear` archives phase DIRECTORIES, never
// ROADMAP.md, so nothing compacts it first and no ordering rule forces
// /gsd:complete-milestone to run before /gsd:new-milestone.
//
// Measured against the shipped hook at the #973 file size (292 lines): a new
// 4-phase roadmap lands at 18.2% and an 8-phase one at 31.8% — both blocked;
// only a 12-phase replacement (45.5%) clears. The sentinel is path-bound and
// single-use, so each Write needs its own arming. As in the sibling binding
// above, the sentinel name is taken from the guard's typed output so a
// rename on EITHER side fails here instead of silently unwiring the hatch.
const roadmapperPath = path.join(__dirname, '..', 'agents', 'gsd-roadmapper.md');
test('the roadmapper write step arms the exact sentinel the guard consumes, for BOTH curated targets', () => {
const src = fs.readFileSync(roadmapperPath, 'utf8');
const stepStart = src.indexOf('## Step 7: Write Files Immediately');
assert.notEqual(stepStart, -1,
'roadmapper Step 7 missing or renamed in gsd-roadmapper.md — rebind this test');
const step = src.slice(stepStart, src.indexOf('## Step 8', stepStart));
fs.writeFileSync(roadmapPath, lines(292));
const blocked = runHook(writePayload(roadmapPath, lines(53), { cwd: projectDir }));
assert.equal(blocked.status, 2,
'baseline: the new-milestone-shaped roadmap Write must block without the hatch');
const sentinel = JSON.parse(blocked.stdout).overrideSentinel;
assert.ok(sentinel, 'the guard must publish its sentinel path as a typed field');
assert.ok(step.includes(sentinel),
`gsd-roadmapper.md Step 7 no longer arms ${sentinel} — its whole-file ROADMAP.md ` +
'write would be hard-blocked by gsd-write-guard on /gsd:new-milestone (#2255 round 10 Blocker 1)');
// Both curated targets the step writes must be armed by name — one arming
// cannot cover both, because the token is path-bound and single-use.
for (const target of ['.planning/ROADMAP.md', '.planning/STATE.md']) {
assert.ok(step.includes(`printf '${target}\\n' > ${sentinel}`),
`Step 7 must arm ${sentinel} for ${target} immediately before writing it — ` +
'the sentinel is path-bound and single-use, so a single arming covers only one file');
}
});
test('the armed sequence passes the exact collapse /gsd:new-milestone produces', () => {
// The real failure: roadmapper follows Step 7, arms the sentinel, Writes.
fs.writeFileSync(roadmapPath, lines(292));
fs.writeFileSync(path.join(planningDir, '.gsd-allow-shrink'), '.planning/ROADMAP.md\n');
const allowed = runHook(writePayload(roadmapPath, lines(53), { cwd: projectDir }));
assert.equal(allowed.status, 0,
'the identical collapse must pass under the sentinel the roadmapper step arms');
// And the STATE.md leg, which the same step writes seconds later — its own
// arming, because the ROADMAP arming was consumed by the write above.
const statePath = path.join(planningDir, 'STATE.md');
fs.writeFileSync(statePath, lines(195));
const stateBlocked = runHook(writePayload(statePath, lines(60), { cwd: projectDir }));
assert.equal(stateBlocked.status, 2,
'a collapsing STATE.md rewrite must block once the ROADMAP arming is spent');
fs.writeFileSync(path.join(planningDir, '.gsd-allow-shrink'), '.planning/STATE.md\n');
const stateAllowed = runHook(writePayload(statePath, lines(60), { cwd: projectDir }));
assert.equal(stateAllowed.status, 0,
'the STATE.md collapse must pass under its own arming');
});
test('arming is conditional on the target existing, so /gsd:new-project leaves no unconsumed token', () => {
// A new-project run has no ROADMAP.md: the guard exempts via ENOENT and
// never consumes a token, so an unconditional arming would strand a live
// 15-minute unlock on disk. The step must guard both armings with [ -f ].
const src = fs.readFileSync(roadmapperPath, 'utf8');
const stepStart = src.indexOf('## Step 7: Write Files Immediately');
const step = src.slice(stepStart, src.indexOf('## Step 8', stepStart));
for (const target of ['.planning/ROADMAP.md', '.planning/STATE.md']) {
assert.ok(step.includes(`[ -f ${target} ] &&`),
`Step 7 must gate the ${target} arming on the file existing — an unconditional ` +
'arming on the new-project path strands an unconsumed sentinel (#2255 round 10)');
}
});
});