Files
msd-core/tests/windsurf-hooks-bridge.test.cjs
Tom Boucher c1885df9e5 chore(#2143): prohibition-with-teeth + migrate remaining ad-hoc table sites — Phase 4 (final) (#2253)
* chore(#2143): prohibition-with-teeth + migrate remaining table sites — Phase 4

Phase 4 of epic #2143 (ADR-2143 §7). Completes the markdown table/mutation
consolidation by (a) giving the ad-hoc-parsing prohibition teeth and (b)
migrating the last ad-hoc table sites onto the shared seam.

- src/markdown-table.cts: new formatting-preserving `updateTableCell` primitive
  (self-contained, ragged-row-tolerant header/delimiter/cell-range scan; splices
  only the target cell's raw span, preserving all other bytes incl. padding/CRLF;
  no-op-preserves-padding when a transformer returns the current value). Exports
  splitTableRow/isDelimiterRow/findTableStartOffset for tolerant reuse.
- eslint-rules/no-adhoc-markdown-parsing.cjs: TABLE-REGEX detector extended to
  `new RegExp(<literal|static-template>)`; new `.replace()`-mutation detector for
  roadmap/state/content receivers with a table/section-shaped pattern.
- scripts/lint-table-schema-drift.cjs (wired into lint:ci): fails if a TABLE_SCHEMA
  header drifts from its authored table; tests import its logic (single source).
- Migrated onto the seam (behaviour-preserving vs pre-Phase-4 HEAD, verified
  byte-diff old-vs-new): roadmap.cts cmdRoadmapUpdatePlanProgress, phase.cts
  cmdPhaseComplete + traceability, milestone.cts cmdRequirementsMarkComplete,
  uat.cts read path, state.cts metrics/decisions/By-Phase.
- Incidental correctness gains from the migration: a decoy table can no longer
  swallow a phase-progress update (## Progress scoping); a ragged neighbouring
  row no longer silently aborts an edit; completing integer phase N no longer
  touches a decimal sub-phase N.x row; record-metric no longer drops trailing
  section content or duplicates the ## Performance Metrics section.
- Kept justified allow-adhoc-markdown markers only where genuinely not a table
  (security.cts <|role|> token) or a loose non-GFM section (uat human-verify).

Two orthogonal isolated reviews (correctness/adversarial + security) passed;
correctness found 4 behaviour regressions in the first migration pass, all fixed
and re-verified byte-identical-or-better vs OLD.

Surfaced for maintainer (pre-existing, ambiguous domain logic, NOT changed here):
templates/state.md places a By-Phase table under ## Performance Metrics while
cmdStateRecordMetric assumes a Plan|Duration|Tasks|Files table.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): match traceability row by first-cell value, not Requirement header

Phase 4's migration matched the REQUIREMENTS.md traceability row by a column
literally named `Requirement` (`row['Requirement']`), but real tables head that
column `REQ-ID`. The by-name lookup found nothing, so `phase complete` and
`requirements mark-complete` left the Status cell `Pending` (regressed #2769 /
#2203, caught by gsd-test — 8 failures, both node 22/24).

- src/phase.cts, src/milestone.cts: match the row by its FIRST cell's value
  (the requirement-ID column) regardless of that column's HEADER name, via
  `Object.values(row)[0]` (updateTableCell builds the record in header order).
  This mirrors OLD's first-cell `\|\s*<id>\s*\|` anchor, restoring header-name
  independence while keeping the seam.
- src/milestone.cts hasTable: broadened from `Requirement`-only to also
  recognize `Requirement ID` / `REQ-ID` / `REQ ID` headers, kept in sync with
  the now-positional rowMatch/hasRow so a REQ-ID-headed table participates in
  the ADR-2143 §6 write-set and the #2140 table_unmatched drift check (it was
  silently omitted before — a checkbox-only partial reconcile against a REQ-ID
  table could report as fully reconciled). The `Requirement`-headed path is
  byte-identical to OLD.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(#2143): replace stale structural milestone guards with behavioural suite

The `milestone.cjs regex global state fix` block was a source-structure guard
(allow-test-rule: structural-regression-guard) — it readFileSync'd the compiled
milestone.cjs and asserted removed regex idioms (`tablePattern.test`,
`afterTable !== reqContent`, `doneTable = new RegExp(...)`). Phase 4's migration
deleted those regexes (table update is now updateTableCell), making the
assertions obsolete. Per the Test Cleanup rule, replace them in-PR with a
behavioural suite driving the compiled CLI:

- multi-ID mark-complete flips all IDs (guards the lastIndex/global-state class),
- Pending->Complete flip under both `REQ-ID` and `Requirement` headers (#2769),
- idempotent already_complete detection with no corruption,
- REQ-ID-headed table participates in write_set (traceability entry, applied),
- REQ-ID-headed table trips #2140 table_unmatched drift on a missing row.

Pruned the now-nonexistent structural-regression-guard entry from the
lint-allow-test-rule-refs allowlist (the source-text-is-the-product entry for
the same file remains valid).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(changeset): backfill PR number 2253

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): record-metric targets its own metrics table, not By-Phase velocity

`state record-metric` appended its per-plan row (`| Phase 1 P1 | 5min | 3 tasks |
4 files |`) into the FIRST table under `## Performance Metrics` — which on a real
template-derived STATE.md is the By-Phase velocity table `| Phase | Plans | Total
| Avg/Plan |`, polluting it on EVERY plan completion (execute-plan.md:414 is a
per-plan call). The command's own metrics table is `| Plan | Duration | Tasks |
Files |`, which the template does not ship, so the row never reached it; the
scaffold branch also emitted a wrong `| Phase | Plan | Duration | Notes |` header
matching neither the row nor the canonical table.

Pre-existing (predates Phase 4); surfaced while migrating this site and fixed here
per no-defer, on the user's explicit go-ahead.

- src/state.cts cmdStateRecordMetric: locate the metrics table by its own header
  shape (`Plan|Duration|Tasks|Files`, via splitTableRow/isDelimiterRow) rather
  than "first table in the section". When the section exists but has no metrics
  table (only the By-Phase table), self-heal by appending a fresh **Per-Plan
  Metrics:** table to the END of the section body — By-Phase table, Recent Trend
  and footer preserved verbatim, no duplicate `## Performance Metrics` heading,
  created stays false. Absent-section scaffold header corrected to the canonical
  `| Plan | Duration | Tasks | Files |`. Ragged-tolerance + None-yet preserved.
- Not touching templates/state.md (golden-install-parity hashed) — record-metric
  self-creates the table on first use instead.

Failing-first regression test (tests/state.test.cjs) demonstrates the By-Phase
pollution on the pre-fix build, then green after. Verified: no pollution, self-
heal idempotency, both-tables isolation, content/heading preservation, flags,
None-yet, corrected scaffold header (23-check adversarial harness + all existing
record-metric scenarios).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(#2143): deleteSection seam primitive (level-bounded whole-section removal)

ADR-2143 §4 shipped withSection/collectSection (replace a section BODY) but no
way to DELETE a section (heading + body). Phase 4 suppressed the phase-remove
section delete instead of building it. deleteSection(content, predicate, opts)
locates the section via the collectSection machinery and splices out from the
heading's start offset to the next same-or-higher-level heading — so a level-3
`### Phase N` delete stops at a following level-2 `## Progress`, never past it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): phase remove no longer deletes ## Progress on last-phase removal

updateRoadmapAfterPhaseRemoval deleted a `### Phase N` detail section with a
greedy raw regex whose lazy scan, on the LAST phase, ran to EOF and destroyed
the following `## Progress` heading and its entire tracking table — silent data
loss, uncovered by tests (removal tests only exercised a middle phase). Migrated
onto the new deleteSection seam (level-bounded, stops at `## Progress`); dropped
the allow-adhoc-markdown SECTION-DELETION suppression. Failing-first regression
(tests/phase.test.cjs) removes the LAST phase and asserts the ## Progress heading
+ table survive; middle-phase removal is byte-identical.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(#2143): deleteTableRow seam primitive (row removal, ragged-tolerant)

Sibling of updateTableCell: locates the first GFM table, matches a DATA row by
predicate (ragged-tolerant record build, header order), and splices out that
row's whole line preserving every other byte. Returns {ok:false,reason} on no
table / no match. Enables migrating the phase-remove Progress-table row delete
off its ad-hoc regex (ADR-2143 §7 — the "future row-delete seam" Phase 4 punted).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): phase remove deletes the Progress row via deleteTableRow

The Progress-table row delete used a whole-document regex with two defects:
(a) `\.?\s` required whitespace after the phase number, so a COMPACT row
`|2|Beta|` was never deleted (stale row left behind); (b) unscoped — it could
strike a row in a different table (e.g. an earlier `| Phase | Requirements |`
table). Migrated onto deleteTableRow, scoped to the `## Progress` section
(mirrors deriveProgressFromRoadmap), matching the row by first-cell phase number
(integer zero-pad-insensitive; decimal exact; removing `2` never touches `2.5`).
Both allow-adhoc-markdown suppressions removed. New behavioural tests: compact
unpadded row deleted; padded byte-parity on the surviving rows (their ordinal
correctly renumbers via the pre-existing renumber block).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): deleteTableRow leaves no dangling newline on last EOL-less row

Deleting the final row of a table with no trailing EOL sliced from the row's
start to end-of-string, stranding the newline that terminated the previous line.
Back rowStart over the preceding \r?\n in that branch so the table ends cleanly.
(Caught by the primitive's own unit test on gsd-test; local scenario checks
missed the no-trailing-EOL edge.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): migrate read-only section-collects onto collectSection

Six hand-rolled `## Section` read-extract regexes replaced by the collectSection
seam (behaviour-preserving; extracted bodies feed the same downstream parsers):
state.cts matchSessionSection (## Session / ## Session Continuity) + ## Blockers,
smart-entry.cts ## Blockers, audit.cts ## Current Focus + ## Open Questions.
Removes 6 allow-adhoc-markdown "pending #1372" suppressions. Incidental fix: the
old Session regex `## Session[ \t]*\n` silently failed on a CRLF `## Session\r\n`
heading (Windows STATE.md), nulling all session fields; collectSection is
CRLF-safe, so session state now resolves on Windows.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): fence-safe state-transition section writes + dedup stripFrontmatter

- milestoneCompleteCore's `## Current Position` and `## Operator Next Steps`
  section resets used fence-blind raw regexes that a fenced `##` inside the body
  could truncate/mis-target (#2130/#2067/#2080 class). Migrated onto a
  fence-aware tokenizeHeadings-based helper (resetSectionVerbatim) that is
  byte-identical to the old output on the canonical path (9/9 fixtures) and
  correctly ignores a fenced fake heading (proven robustness gain).
- mutateCurrentPositionFirstTime: hand-rolled locate+splice → collectSection +
  replaceSection (byte-parity).
- stripFrontmatter was inlined byte-identically in state.cts AND
  state-transition.cts; hoisted the single canonical copy into frontmatter.cts
  (both call sites now import it) + unit tests — eliminates the divergence risk
  per CLAUDE.md "Generative Fix Divergence". Removes 3 allow-adhoc-markdown /
  #1372 markers.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): name-address By-Phase sum + uat parse, eslint recall hole, catches

- state.cts By-Phase "Total plans completed" sum: positional 2nd-cell regex →
  name-addressed splitTableRow read (correct on a reordered header, where the
  old code silently summed the wrong column). Marker removed.
- uat.cts parseVerificationItems: loose pipe regex → splitTableRow within the
  existing table/numbered/bullet union scan (item list byte-identical; does NOT
  reintroduce the reverted strict-parseMarkdownTable item-drop). Marker removed.
- eslint no-adhoc-markdown-parsing: close the `new RegExp(identifier)` recall
  hole — resolve a const-declared table-shaped regex identifier (mirrors the
  .replace() detector) + RuleTester cases; param/call args stay out (boundary).
- commands.cts: delete a lying comment that claimed the scaffold date "stays on
  raw UTC / deferred" — #2136 already moved it to realClock.localToday().
- Empty catches (classified, not blind-swept): removed 4 dead try/catch;
  fixed 3 error-hiding (phase-insert decimal-dir I/O collision now fails loud;
  phase-remove rename partial-failure surfaced; milestone-archive true count via
  finally); left best-effort swallows with justification comments.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): extractFencedBlock seam + migrate api-coverage named fence

parseCoverageMatrix extracted its ```coverage fenced block with an ad-hoc regex
(the last real allow-adhoc-markdown suppression). Added extractFencedBlock to the
markdown-sectionizer seam (reuses stripFencedCode's CommonMark fence engine —
info-string match, ~~~/backtick, nesting, indent) and migrated onto it; byte-
parity on the parsed CoverageMatrix across 8 fixtures. Only security.cts:367
(a genuine `<|role|>` protocol-token false-positive, not a GFM table) remains
marked in src/ — the "prohibition with teeth" goal (nothing grandfathered but a
true FP) is met.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): By-Phase row insert is name-addressed (insertTableRow seam)

updatePerformanceMetricsSection's INSERT-new-row branch located the By-Phase
table with a canonical-column-order-only regex + a hardcoded positional row
literal, so on a reordered header it silently inserted nothing — inconsistent
with the now name-addressed UPDATE and SUM halves of the same function. Added
insertTableRow (markdown-table seam sibling of updateTableCell/deleteTableRow:
name-addressed, header-order-agnostic, EOL-preserving) and migrated the branch
onto it, mapping By-Phase values by column NAME. Canonical-order output is
byte-identical; a reordered header now inserts a correctly-mapped row; a
pre-existing CRLF mixed-EOL splice glitch is incidentally fixed. Retired the
now-dead byPhaseTablePattern const.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): phase-list checkbox flip via updateBullet seam

Added updateBullet (markdown-sectionizer): a fence-aware, offset-tracked
single-bullet write primitive (GFM 1–4-space marker tolerance) — the write
counterpart to read-only iterateBullets. Migrated mutateMilestonePhase's
phase-list checkbox flip (`- [ ] Phase N …` → `- [x] … (completed <date>)`)
off its whole-slice regex onto it, same milestone-slice scope + clock seam.
Byte-identical across simple / idempotent / metachar-title / double-space /
CRLF scenarios.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): scope the Progress-ordinal renumber to ## Progress via seam

phase remove's integer-renumber decremented Progress-table phase ordinals with a
whole-document `content.replace(/(\|\s*)(\d+)(\.\s)/g, …)` — unscoped, so it also
rewrote any `| N. …` cell in an unrelated/decoy table (same class as the batch-2
row-delete scoping bug). Migrated onto updateTableCell, scoped to the ## Progress
section, decrementing each affected row's leading phase ordinal by column name.
Byte-identical on canonical Progress tables + multi-row + decimal-sibling cases;
a decoy `| 3. … |` row before ## Progress is now correctly left untouched. The
sibling heading / checkbox-bullet / PLAN.md-filename / Depends-on-prose renumbers
are not GFM-table mutations (outside ADR-2143's table/section mandate) — left as-is.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2143): review fixes — scope traceability write, restore Current Position H3-stop

Adversarial review of the remediation (BLOCK verdict) — all 9 findings fixed:
- F1 (BLOCKER): requirements mark-complete / phase complete flipped the checkbox
  but NOT the traceability row on the shipped template, because updateTableCell
  bound to the FIRST table (## Out of Scope, no Status column) instead of the
  ## Traceability table — the #2140 silent-divergence class, re-introduced by the
  seam migration and missed by tests (fixtures had Traceability first). Scoped
  the write + hasRow probe to the ## Traceability section slice (updateTraceability
  Cell helper) in milestone.cts + phase.cts. Failing-first tests on the
  Out-of-Scope-before-Traceability layout; the #2769 first-cell match preserved.
- F2 (MAJOR): mutateCurrentPositionFirstTime restored to locateCurrentPosition
  (STOP_H2_PLUS) — collectSection's default H2-stop swallowed a level-3 subsection
  and the field regexes clobbered it (#2130 class).
- F3/F8: Progress-ordinal renumber re-escapes via escapeCell + keys padding
  recovery by row index (was de-escaping `\|` and losing padding on dup values).
- F4: insertTableRow escapes cell values internally.
- F5: updateBullet accepts a tab after the marker (`[ \t]{1,4}`).
- F7: resetSectionVerbatim consumes CRLF blank lines (byte-parity on CRLF).
- F6/F9: corrected two misleading comments.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(changeset): data-loss + CRLF-session user-facing fixes (#2253)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(#2143): de-flake the G10 windsurf ReDoS-guard wall-clock assertion

The G10 test asserted `elapsedMs < 1000` for a 200k-char payload — a wall-clock
assertion (CLAUDE.md: never assert on wall-clock time) that flaked on a loaded
node24 bench at ~1.1s. It was redundant: runHook's spawnSync `timeout: 10000`
already SIGKILLs a catastrophic-backtracking hook, so the exit-0 assertion is the
real ReDoS guard. Removed the timing assertion; kept exit-0 + documented the
subprocess-timeout mechanism. Surfaced (not caused) by this branch's gsd-test
runs loading the bench; unrelated to the markdown-parsing changes but fixed in
place per the no-flaky-tests rule.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 14:25:44 -04:00

378 lines
18 KiB
JavaScript

'use strict';
/**
* Windsurf/Cascade HOOK-BRIDGE upgrade — ADR-1239 / #2100 Stage 2.
*
* Stage 1 (folds) drove Windsurf's install onto the declarative capability
* descriptor (hostBehaviors) while leaving `hooksSurface: "none"`. Stage 2
* wires GSD's guard logic into Cascade's native hook bus: `.windsurf/hooks.json`
* (local) / `~/.codeium/windsurf/hooks.json` (global), with TWO blocking
* events — `pre_write_code` and `pre_run_command`. Cascade blocks via EXIT
* CODE 2 (+ a stderr reason), unlike Cursor's stdout-JSON `{ block, reason }`
* form — so this is a DIFFERENT protocol wired through the SAME infra shape
* as writeCursorHooksJson/removeCursorHooksJson (mirrors
* tests/cursor-hooks.test.cjs + tests/cursor-hook-bus-upgrade.test.cjs).
*
* Cascade has no context-injection channel (no `additional_context`-style
* advisory response), so the 4 advisory hooks GSD registers on Cursor
* (sessionStart, postToolUse, stop, subagentStart/subagentStop) have no
* Windsurf counterpart and are deliberately NOT ported.
*
* Test plan:
* Guard scripts (spawned directly, real process, real exit codes):
* G1 pre-write: file resolves to a different git root than cwd -> exit 2 + stderr
* G2 pre-write: file resolves to the SAME git root as cwd -> exit 0
* G3 pre-write: malformed JSON on stdin -> fail-open exit 0
* G4 pre-write: empty stdin -> fail-open exit 0
* G5 pre-command: a destructive command_line -> exit 2 + stderr
* G6 pre-command: a benign command_line -> exit 0
* G8 pre-command: prefixed/evasive rm -rf and force-push refspec forms -> exit 2
* G9 pre-command: force-push false-positive forms (comment/branch-name-contains) -> exit 0
* G10 pre-command: ReDoS-guard — oversized rm-shaped payload -> exit 0 in well under 1s
* G7 pre-command: malformed JSON on stdin -> fail-open exit 0
* Writer/reconcile (in-process, pure + one real install):
* W1 writeWindsurfHooksJson installs both scripts + both hooks.json entries
* W2 reconcileWindsurfHooksJson preserves user-owned entries
* W3 removeWindsurfHooksJson removes hooks.json when it becomes empty
* W4 removeWindsurfHooksJson preserves hooks.json when user entries remain
* W5 WINDSURF_HOOK_EVENTS / WINDSURF_EVENT_SCRIPT_MAP shape
* W6 hook scripts exist under hooks/
*/
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 { spawnSync, execFileSync } = require('node:child_process');
const { createTempDir, cleanup } = require('./helpers.cjs');
const {
WINDSURF_HOOK_EVENTS,
WINDSURF_EVENT_SCRIPT_MAP,
GSD_WINDSURF_HOOK_MARKER,
GSD_WINDSURF_PRE_WRITE_HOOK_SCRIPT,
GSD_WINDSURF_PRE_COMMAND_HOOK_SCRIPT,
isManagedWindsurfHookEntry,
reconcileWindsurfHooksJson,
writeWindsurfHooksJson,
removeWindsurfHooksJson,
} = require('../gsd-core/bin/lib/runtime-hooks-surface.cjs');
const HOOKS_DIR = path.join(__dirname, '..', 'hooks');
const PRE_WRITE_SCRIPT = path.join(HOOKS_DIR, GSD_WINDSURF_PRE_WRITE_HOOK_SCRIPT);
const PRE_COMMAND_SCRIPT = path.join(HOOKS_DIR, GSD_WINDSURF_PRE_COMMAND_HOOK_SCRIPT);
function runHook(scriptPath, payload, opts = {}) {
const input = payload === undefined ? '' : (typeof payload === 'string' ? payload : JSON.stringify(payload));
return spawnSync(process.execPath, [scriptPath], {
input,
encoding: 'utf8',
timeout: 10000,
cwd: opts.cwd || os.tmpdir(),
});
}
function initGitRepo(dir) {
execFileSync('git', ['init', '-q', '.'], { cwd: dir, stdio: 'pipe' });
execFileSync('git', ['config', 'user.email', 'gsd-test@example.com'], { cwd: dir, stdio: 'pipe' });
execFileSync('git', ['config', 'user.name', 'gsd-test'], { cwd: dir, stdio: 'pipe' });
execFileSync('git', ['commit', '--allow-empty', '-q', '-m', 'init'], { cwd: dir, stdio: 'pipe' });
}
// ---------------------------------------------------------------------------
// Guard scripts — spawned directly, real exit codes
// ---------------------------------------------------------------------------
describe('gsd-windsurf-pre-write.js (pre_write_code guard)', () => {
test('G1: a write resolving to a DIFFERENT git root than cwd -> exit 2 + stderr reason', (t) => {
const cwdRepo = createTempDir('gsd-windsurf-write-cwd-');
const otherRepo = createTempDir('gsd-windsurf-write-other-');
t.after(() => { cleanup(cwdRepo); cleanup(otherRepo); });
initGitRepo(cwdRepo);
initGitRepo(otherRepo);
fs.writeFileSync(path.join(otherRepo, 'target.txt'), 'x');
const result = runHook(PRE_WRITE_SCRIPT, {
agent_action_name: 'pre_write_code',
tool_info: { file_path: path.join(otherRepo, 'target.txt') },
}, { cwd: cwdRepo });
assert.equal(result.status, 2, `expected exit 2, got ${result.status} (stderr: ${result.stderr})`);
assert.match(result.stderr, /differs from the active project root|inside a git internal/);
});
test('G1b: a write inside a DIFFERENT repo\'s .git internals -> exit 2 + stderr reason', (t) => {
const cwdRepo = createTempDir('gsd-windsurf-write-cwd-');
const otherRepo = createTempDir('gsd-windsurf-write-other-');
t.after(() => { cleanup(cwdRepo); cleanup(otherRepo); });
initGitRepo(cwdRepo);
initGitRepo(otherRepo);
const result = runHook(PRE_WRITE_SCRIPT, {
tool_info: { file_path: path.join(otherRepo, '.git', 'config') },
}, { cwd: cwdRepo });
assert.equal(result.status, 2, `expected exit 2, got ${result.status} (stderr: ${result.stderr})`);
assert.match(result.stderr, /inside a git internal \(\.git\) directory/);
});
test('G2: a write resolving to the SAME git root as cwd -> exit 0 (allowed)', (t) => {
const repo = createTempDir('gsd-windsurf-write-same-');
t.after(() => cleanup(repo));
initGitRepo(repo);
fs.mkdirSync(path.join(repo, 'sub'));
const result = runHook(PRE_WRITE_SCRIPT, {
tool_info: { file_path: 'sub/new-file.txt' },
}, { cwd: repo });
assert.equal(result.status, 0, `expected exit 0, got ${result.status} (stderr: ${result.stderr})`);
});
test('G3: malformed JSON on stdin -> fail-open exit 0', () => {
const result = runHook(PRE_WRITE_SCRIPT, 'not-json-at-all{{{');
assert.equal(result.status, 0);
});
test('G4: empty stdin -> fail-open exit 0', () => {
const result = runHook(PRE_WRITE_SCRIPT, '');
assert.equal(result.status, 0);
});
test('missing tool_info.file_path -> fail-open exit 0', () => {
const result = runHook(PRE_WRITE_SCRIPT, { tool_info: {} });
assert.equal(result.status, 0);
});
});
describe('gsd-windsurf-pre-command.js (pre_run_command guard)', () => {
test('G5: a destructive command_line (rm -rf /) -> exit 2 + stderr reason', () => {
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: { command_line: 'rm -rf /' } });
assert.equal(result.status, 2, `expected exit 2, got ${result.status} (stderr: ${result.stderr})`);
assert.match(result.stderr, /rm -rf targeting the filesystem root/);
});
test('G5b: git push --force targeting a protected branch -> exit 2 + stderr reason', () => {
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: { command_line: 'git push --force origin main' } });
assert.equal(result.status, 2, `expected exit 2, got ${result.status} (stderr: ${result.stderr})`);
assert.match(result.stderr, /protected branch 'main'/);
});
test('G6: a benign command_line -> exit 0 (allowed)', () => {
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: { command_line: 'npm test' } });
assert.equal(result.status, 0, `expected exit 0, got ${result.status} (stderr: ${result.stderr})`);
});
test('G6b: rm -rf against an ordinary project path -> exit 0 (allowed, not a root wipe)', () => {
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: { command_line: 'rm -rf /tmp/gsd-scratch-dir' } });
assert.equal(result.status, 0, `expected exit 0, got ${result.status} (stderr: ${result.stderr})`);
});
test('G6c: git push --force to a feature branch -> exit 0 (allowed, not protected)', () => {
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: { command_line: 'git push --force origin feature/123' } });
assert.equal(result.status, 0, `expected exit 0, got ${result.status} (stderr: ${result.stderr})`);
});
test('G8: sudo-prefixed rm -rf / -> exit 2 (evasion via command prefix)', () => {
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: { command_line: 'sudo rm -rf /' } });
assert.equal(result.status, 2, `expected exit 2, got ${result.status} (stderr: ${result.stderr})`);
assert.match(result.stderr, /rm -rf targeting the filesystem root/);
});
test('G8b: absolute-path rm -rf / (/bin/rm) -> exit 2 (evasion via basename)', () => {
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: { command_line: '/bin/rm -rf /' } });
assert.equal(result.status, 2, `expected exit 2, got ${result.status} (stderr: ${result.stderr})`);
assert.match(result.stderr, /rm -rf targeting the filesystem root/);
});
test('G8c: git push -f origin HEAD:main -> exit 2 (refspec targeting protected branch)', () => {
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: { command_line: 'git push -f origin HEAD:main' } });
assert.equal(result.status, 2, `expected exit 2, got ${result.status} (stderr: ${result.stderr})`);
assert.match(result.stderr, /protected branch 'main'/);
});
test('G8d: git push origin +main -> exit 2 (+-prefixed force refspec)', () => {
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: { command_line: 'git push origin +main' } });
assert.equal(result.status, 2, `expected exit 2, got ${result.status} (stderr: ${result.stderr})`);
assert.match(result.stderr, /protected branch 'main'/);
});
test('G9: git push --force to a feature branch with a trailing comment mentioning main -> exit 0 (not a false positive)', () => {
const result = runHook(PRE_COMMAND_SCRIPT, {
tool_info: { command_line: 'git push --force origin feature/foo # deploy to main' },
});
assert.equal(result.status, 0, `expected exit 0, got ${result.status} (stderr: ${result.stderr})`);
});
test('G9b: git push --force to feature/main-fix -> exit 0 (branch name only CONTAINS "main", not a false positive)', () => {
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: { command_line: 'git push --force origin feature/main-fix' } });
assert.equal(result.status, 0, `expected exit 0, got ${result.status} (stderr: ${result.stderr})`);
});
test('G9c: env-prefixed benign command -> exit 0 (env prefix alone is not destructive)', () => {
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: { command_line: 'env FOO=1 npm test' } });
assert.equal(result.status, 0, `expected exit 0, got ${result.status} (stderr: ${result.stderr})`);
});
test('G10: ReDoS-guard — a 200000+-char rm -rf-shaped payload is handled without catastrophic backtracking (length cap)', () => {
const payload = `rm -${'r'.repeat(200000)}!`;
// The ReDoS guard is `runHook`'s spawnSync `timeout: 10000`: catastrophic
// backtracking on this payload would run for minutes, so the hook is
// SIGKILL'd and returns a non-zero status — the exit-0 assertion below IS
// the ReDoS check. (The prior `elapsedMs < 1000` wall-clock assertion was
// redundant with that and flaked on a loaded bench at ~1.1s — CLAUDE.md:
// do not assert on wall-clock time.)
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: { command_line: payload } });
assert.equal(result.status, 0, `expected exit 0 (length-capped allow, no ReDoS timeout), got ${result.status} (stderr: ${result.stderr})`);
});
test('G7: malformed JSON on stdin -> fail-open exit 0', () => {
const result = runHook(PRE_COMMAND_SCRIPT, 'not-json-at-all{{{');
assert.equal(result.status, 0);
});
test('empty stdin -> fail-open exit 0', () => {
const result = runHook(PRE_COMMAND_SCRIPT, '');
assert.equal(result.status, 0);
});
test('missing tool_info.command_line -> fail-open exit 0', () => {
const result = runHook(PRE_COMMAND_SCRIPT, { tool_info: {} });
assert.equal(result.status, 0);
});
});
// ---------------------------------------------------------------------------
// W5/W6: constants + on-disk scripts
// ---------------------------------------------------------------------------
test('W5: WINDSURF_HOOK_EVENTS is exactly the 2 wired Cascade events', () => {
assert.deepEqual([...WINDSURF_HOOK_EVENTS].sort(), ['pre_run_command', 'pre_write_code']);
});
test('W5b: WINDSURF_EVENT_SCRIPT_MAP maps every event to a .js script', () => {
for (const ev of WINDSURF_HOOK_EVENTS) {
const script = WINDSURF_EVENT_SCRIPT_MAP[ev];
assert.ok(typeof script === 'string' && script.endsWith('.js'), `${ev} must map to a .js script, got: ${script}`);
}
});
test('W6: both hook scripts exist under hooks/', () => {
assert.ok(fs.existsSync(PRE_WRITE_SCRIPT), 'hooks/gsd-windsurf-pre-write.js must exist');
assert.ok(fs.existsSync(PRE_COMMAND_SCRIPT), 'hooks/gsd-windsurf-pre-command.js must exist');
});
// ---------------------------------------------------------------------------
// W1: writeWindsurfHooksJson — direct writer call
// ---------------------------------------------------------------------------
describe('writeWindsurfHooksJson', () => {
test('W1: installs both scripts and both hooks.json entries with the marker', (t) => {
const targetDir = createTempDir('gsd-windsurf-writer-');
t.after(() => cleanup(targetDir));
const src = path.join(__dirname, '..');
const result = writeWindsurfHooksJson(targetDir, src, { platform: process.platform });
assert.equal(result.hooksJsonPath, path.join(targetDir, 'hooks.json'));
assert.ok(result.changed, 'first write must report changed=true');
assert.ok(fs.existsSync(path.join(targetDir, 'hooks', GSD_WINDSURF_PRE_WRITE_HOOK_SCRIPT)), 'pre-write script must be installed');
assert.ok(fs.existsSync(path.join(targetDir, 'hooks', GSD_WINDSURF_PRE_COMMAND_HOOK_SCRIPT)), 'pre-command script must be installed');
const written = JSON.parse(fs.readFileSync(result.hooksJsonPath, 'utf8'));
assert.ok(written.hooks && typeof written.hooks === 'object', 'hooks.json must have a nested hooks table');
for (const ev of WINDSURF_HOOK_EVENTS) {
assert.ok(Array.isArray(written.hooks[ev]), `hooks.json must have a ${ev} array`);
assert.equal(written.hooks[ev].length, 1, `${ev} must have exactly 1 managed entry`);
assert.equal(written.hooks[ev][0][GSD_WINDSURF_HOOK_MARKER], true, `${ev} entry must carry the GSD managed marker`);
assert.equal(typeof written.hooks[ev][0].command, 'string', `${ev} entry command must be a bare string (Cascade shape, not Cursor's {type,command})`);
assert.equal(written.hooks[ev][0].type, undefined, `${ev} entry must NOT have Cursor's 'type' field`);
}
});
test('W1b: is idempotent (second write reports changed=false)', (t) => {
const targetDir = createTempDir('gsd-windsurf-writer-idem-');
t.after(() => cleanup(targetDir));
const src = path.join(__dirname, '..');
writeWindsurfHooksJson(targetDir, src, { platform: process.platform });
const second = writeWindsurfHooksJson(targetDir, src, { platform: process.platform });
assert.equal(second.changed, false, 're-running the writer with no changes must report changed=false');
});
});
// ---------------------------------------------------------------------------
// W2/W3/W4: reconcileWindsurfHooksJson / removeWindsurfHooksJson
// ---------------------------------------------------------------------------
describe('reconcileWindsurfHooksJson / removeWindsurfHooksJson', () => {
function managedEntry(command) {
return { command, [GSD_WINDSURF_HOOK_MARKER]: true };
}
function userEntry(command) {
return { command };
}
test('W2: preserves user-owned entries across both events', (t) => {
const dir = createTempDir('gsd-windsurf-reconcile-');
t.after(() => cleanup(dir));
const hooksJsonPath = path.join(dir, 'hooks.json');
fs.writeFileSync(hooksJsonPath, JSON.stringify({
hooks: {
pre_write_code: [userEntry('echo user-write-hook')],
pre_run_command: [userEntry('echo user-command-hook')],
},
}, null, 2) + '\n');
const managedEntries = {
pre_write_code: managedEntry('node /gsd/pre-write.js'),
pre_run_command: managedEntry('node /gsd/pre-command.js'),
};
reconcileWindsurfHooksJson(hooksJsonPath, managedEntries);
const written = JSON.parse(fs.readFileSync(hooksJsonPath, 'utf8'));
assert.equal(written.hooks.pre_write_code.length, 2, 'pre_write_code: 1 user + 1 managed');
assert.equal(written.hooks.pre_run_command.length, 2, 'pre_run_command: 1 user + 1 managed');
assert.ok(written.hooks.pre_write_code.some((e) => e.command === 'echo user-write-hook'));
assert.ok(written.hooks.pre_write_code.some((e) => isManagedWindsurfHookEntry(e)));
});
test('W3: removeWindsurfHooksJson removes hooks.json when it becomes empty', (t) => {
const dir = createTempDir('gsd-windsurf-remove-empty-');
t.after(() => cleanup(dir));
const hooksJsonPath = path.join(dir, 'hooks.json');
reconcileWindsurfHooksJson(hooksJsonPath, {
pre_write_code: managedEntry('node /gsd/pre-write.js'),
pre_run_command: managedEntry('node /gsd/pre-command.js'),
});
assert.ok(fs.existsSync(hooksJsonPath));
const result = removeWindsurfHooksJson(dir);
assert.equal(result.changed, true);
assert.equal(fs.existsSync(hooksJsonPath), false, 'empty hooks.json must be removed');
});
test('W4: removeWindsurfHooksJson preserves hooks.json when user entries remain', (t) => {
const dir = createTempDir('gsd-windsurf-remove-preserve-');
t.after(() => cleanup(dir));
const hooksJsonPath = path.join(dir, 'hooks.json');
fs.writeFileSync(hooksJsonPath, JSON.stringify({
hooks: {
pre_write_code: [
managedEntry('node /gsd/pre-write.js'),
userEntry('echo user-write-hook'),
],
},
}, null, 2) + '\n');
removeWindsurfHooksJson(dir);
assert.ok(fs.existsSync(hooksJsonPath), 'hooks.json must remain (user entries present)');
const written = JSON.parse(fs.readFileSync(hooksJsonPath, 'utf8'));
assert.equal(written.hooks.pre_write_code.length, 1);
assert.equal(written.hooks.pre_write_code[0].command, 'echo user-write-hook');
});
});