Files
msd-core/tests/safe-resume-gate-anchoring.test.cjs
Tom Boucher db4d8a9bae fix(#4619): execute-phase computes decimal/N-segment phase numbers without breaking shell arithmetic (#4644)
* fix(#4619): execute-phase computes decimal/N-segment phase numbers without breaking shell arithmetic

$((10#${PHASE_NUMBER})) is a hard bash/zsh syntax error when PHASE_NUMBER is
decimal (01.1, from an inserted phase) or N-segment (23.1.2) — neither is
valid shell-arithmetic syntax at all, and the failed expansion aborts the
rest of the snippet in a non-interactive shell. safe_resume_gate runs
unconditionally before trusting STATE.md or dispatching any executor, so
execute-phase failed at its own gate before the first executor on any
decimal phase, regardless of workflow.tdd_mode. Regression from #4194.

Fixes all 4 sites: safe_resume_gate and the TDD gate in
workflows/execute-phase.md, the completion-signal spot-check fallback in
workflows/execute-phase/steps/completion-reconciliation.md, and the
executor gate validation example in references/tdd.md. Each now zero-strips
only the leading integer segment into a *_INT variable (via %%.* / #
parameter expansion — always valid shell syntax regardless of what follows)
and keeps the remainder as an escaped-dot string for the anchored commit-
scope regex, exactly as issue #4619 verified in both bash and zsh. A plain
integer phase (12, 01) computes byte-identically to before.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(#4619): pin the decimal/N-segment fix and characterize the pre-fix bug

Behavioral coverage via real bash execution: the old $((10#01.1)) form
throws (characterizes the bug, matching the issue's own reproduction); the
new form resolves 01.1 -> 1\.1 and 23.1.2 -> 23\.1\.2, unchanged for plain
integers (12 -> 12, 01 -> 1); the resulting anchored ERE matches
feat(01.1-03):/test(1.1-3): and correctly rejects feat(01-03):,
feat(01.2-03):, feat(011-03):, feat(12-03): for a decimal phase — mirroring
issue #4619's own verified table exactly. Updates
safe-resume-gate-anchoring.test.cjs's 4 existing source-text assertions
(one per site) to the new fixed text.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(#4634): refine the shell-arith drift detector to distinguish safe from unsafe arithmetic

With #4619's fix in place, the guard's original "ban $((10#... outright,
match any occurrence" was too blunt: it flagged a comment merely mentioning
the pattern in prose, the now-safe $((10#$PHASE_INT)) arithmetic on an
already-%%.*-stripped integer, and the always-safe plan-id arithmetic
(plan ids are plain integers, never decimal). Refines the detector to skip
full-line comments and to only flag a captured variable/placeholder name
that contains "phase" and does NOT end in _INT/_int — the naming convention
the #4619 fix establishes at all four sites for "already reduced to a safe
integer." A plan-id variable was never phase-number arithmetic in the first
place and is excluded on the same basis.

This closes epic #4634's D6 ("lint-phase-id-drift... passes with no new
exemptions") and D7 ("a decimal and N-segment phase id survive an
end-to-end execute-phase selection without error") for real — the guard now
reports zero violations across all five .cts/.md rules.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore: regenerate conformance-tier manifests for the new test file

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(#4619): cover the plain-padded-integer near-miss matrix too

Review found the anchored-ERE near-miss coverage only exercised the
decimal case (PHASE_NUMBER=01.1); issue #4619's own worked table also
verifies the plain padded-integer case (01 -> PHASE_N=1) against its own
near-miss set (matches 01-03, rejects 01.1-03/011-03/12-03). Adds the
missing assertion.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(#4619): add Fixed changeset

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(#4619): correct JS backslash-escaping in safe-resume-gate anchoring test

The test's string-literal assertions for the PHASE_FRAC//./\\.} pattern wrote
only 2 backslash characters in JS source, which single-quoted-string parsing
collapses to 1 real backslash at runtime -- but the workflow/reference files
actually contain 2 raw backslash bytes at that position (needed so bash's
${var//pattern/replacement} produces the correct single-backslash output).
Write 4 backslash characters in the JS source at all 4 occurrences so the
runtime string matches the files' real bytes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(#4619): refresh the committed compact-content benchmark baseline

The new PHASE_INT/PHASE_FRAC arithmetic lines added to
gsd-core/workflows/execute-phase.md shifted its committed compaction-ratio
baseline. Regenerate via `node scripts/benchmark-compact-content.cjs --write`.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(#4619): note the safe_resume_gate arithmetic growth in the test header

The emitted-attribution gate flags execute-phase.md growing 91253 -> 91846
bytes (593 bytes). The growth is the fix: the safe_resume_gate and TDD RED
block now derive PHASE_INT/PHASE_FRAC before computing PHASE_N, so a
decimal/N-segment phase number (e.g. 01.1, 2.3.1) zero-strips its leading
integer segment via base-10 arithmetic instead of forcing the whole value
through $((10#...)) and hitting a hard shell syntax error on the first dot.

A blank line previously separated the Emitted-Drift-Ack-Growth trailer from
the Co-Authored-By trailer below it, which splits git's trailer-block
detection: only the last contiguous non-blank run of Key: Value lines at the
end of a commit message is recognized as trailers, so the growth ack was
silently read as ordinary body text and the differential-attribution gate
failed with the growth unacknowledged. Joining the two trailers into one
contiguous block fixes it.

Emitted-Drift-Ack-Growth: execute-phase.md — adds PHASE_INT/PHASE_FRAC derivation to the safe_resume_gate and TDD RED commit-scope grep so a decimal/N-segment phase number zero-strips its leading integer segment via base-10 arithmetic instead of failing on a non-numeric value (#4619)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(#4208): replace chmod-based restore-failure injection with a root-proof git shim

`tests/commit-files-deletion.test.cjs`'s two restore-failure tests simulated
an unwritable index via a `post-index-change` hook running `chmod a-w` on
the git dir. That relies on the OS enforcing the *owner's own* permission
bits against itself, which uid 0 (a routine identity inside this repo's
Docker-based gsd-test benches) does not: every DAC check short-circuits true
for root, so the write the chmod meant to block silently succeeds, the
restore comes back clean, and the disclosure/rollback behavior under test
never actually gets exercised.

This is CLAUDE.md's own named anti-pattern for I/O-failure injection
("Cross-platform test IO-failure injection" — chmod tricks fail under root
Docker/CI). It is confirmed as the actual root cause here, not a production
defect: `src/commands.cts`'s `restoreRemovedEntries`/rollback-disclosure
logic (added by #4253, merged just before this run) was hand-traced and
manually reproduced end to end on an unprivileged workstation against a
freshly built `gsd-core/bin/lib/commands.cjs`, and it already produces
exactly the `staging_failed` + "could not be restored" / "could NOT be
restored during rollback" results both tests assert. The other
`post-index-change`-based tests in this file (a `sleep` to force a timeout;
a real `update-index` to flip a restored entry's mode) are unaffected
because neither depends on a permission check — consistent with only the
two chmod-based tests failing on the real remote run.

Replaces the chmod fixture with a fake `git` placed ahead of the real one on
PATH that fails only `update-index --add --cacheinfo` — the one call the
restore makes — unconditionally, regardless of privilege level. Every other
git invocation execs straight through to the real binary, so the rest of
each scenario (`rm --cached`, the restore's own `ls-files` verification,
etc.) is exercised exactly as before.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(#4619): backfill changeset pr number to 4644

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(#4619): feed the bash fixture script via stdin, not argv, to fix Windows CI

Passing the script as a `-c "<script>"` argv element made it subject to
Windows' CreateProcess command-line argument encoding, which silently
dropped the escaped-dot backslashes before bash ever saw them (observed on
PR #4644's windows-latest CI shard: `1\.1` came back as `1.1`). Feeding the
same script via stdin instead removes argv entirely from the transport, so
there is nothing for Windows to re-encode. POSIX behavior is unchanged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 15:47:14 -04:00

140 lines
9.1 KiB
JavaScript

'use strict';
/**
* #4003 — the safe_resume_gate / TDD RED / completion spot-check commit greps.
*
* The gate keyed on the padded `{phase_number}-{plan_padded}` as a bare substring:
* unanchored (any prior milestone's same-numbered plan matches) and padding-blind
* (the commit protocol — agents/gsd-executor.md <task_commit_protocol>,
* gsd-core/references/tdd.md:99 — specifies no padding rule, and both spellings are
* live in this repository's history). Workflow text IS the deployed product here, so
* the shape assertions are the faithful check; the behavioral fixture row runs the
* actual pipeline against a crafted history.
*
* #4619 — the gate's PHASE_N derivation grew to zero-strip only the leading
* integer segment of a decimal/N-segment phase number (`01.1`, `23.1.2`) via
* base-10 arithmetic, instead of forcing the whole value through
* `$((10#...))` and hitting a hard shell syntax error on the first dot.
*/
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { createTempGitProject, cleanup } = require('./helpers.cjs');
const { gitOrThrow } = require('./helpers/git-fixture.cjs');
const WORKFLOW = path.join(__dirname, '..', 'gsd-core', 'workflows', 'execute-phase.md');
describe('#4003 — safe_resume_gate commit-scope greps', () => {
test('safe_resume_gate greps an anchored, padding-tolerant plan scope', () => {
const w = fs.readFileSync(WORKFLOW, 'utf8');
// Anchored, ERE, zero-pad-tolerant on BOTH components — matches feat(2-02): and
// feat(02-02): alike, never a substring elsewhere in the message.
assert.ok(w.includes('PHASE_INT=${PHASE_NUMBER%%.*}; PHASE_FRAC=${PHASE_NUMBER#"$PHASE_INT"}') &&
w.includes('PHASE_N="$((10#$PHASE_INT))${PHASE_FRAC//./\\\\.}"'),
'phase component must be zero-stripped via arithmetic base-10 (#4619: leading integer segment only, decimal/N-segment tolerant)');
assert.ok(w.includes('PLAN_N=$((10#{plan_padded}))'),
'plan component must be zero-stripped via arithmetic base-10');
assert.ok(w.includes('PLAN_SCOPE_RE="^[a-z]+\\((0*${PHASE_N})-(0*${PLAN_N})\\):"'),
'the scope regex must be anchored to the commit-scope position and zero-pad-tolerant');
assert.ok(w.includes('--grep="${PLAN_SCOPE_RE}"'),
'the gate must grep the derived scope regex, not a padded literal');
// The old unanchored padded-literal grep must be gone.
assert.ok(!w.includes('--grep="${CURRENT_PLAN_ID}"'),
'the bare substring grep over the padded id must not remain');
assert.ok(!w.includes('CURRENT_PLAN_ID="{phase_number}-{plan_padded}"'),
'the padded id derivation must not remain');
});
test('the gate bounds history to the current milestone with a no-tag fallback', () => {
const w = fs.readFileSync(WORKFLOW, 'utf8');
assert.ok(w.includes('git describe --tags --abbrev=0'),
'the milestone bound derives from the most recent reachable tag (complete-milestone git_tag)');
assert.ok(w.includes('${MILESTONE_BASE:+"$MILESTONE_BASE..HEAD"}'),
'the bounded invocation must range BASE..HEAD only when a base resolved');
// Degrade must keep the anchor: a repo with no tags still gets the positional grep.
assert.ok(w.includes('MILESTONE_BASE=$(git describe --tags --abbrev=0 2>/dev/null || echo "")'),
'a missing tag base must degrade to empty, not fail the gate');
});
test('tdd red gate tolerates both commit-scope spellings (#4011 keying untouched)', () => {
const w = fs.readFileSync(WORKFLOW, 'utf8');
assert.ok(w.includes('PHASE_INT=${PHASE_NUMBER%%.*}; PHASE_FRAC=${PHASE_NUMBER#"$PHASE_INT"}') &&
w.includes('PHASE_N="$((10#$PHASE_INT))${PHASE_FRAC//./\\\\.}"') && w.includes('PLAN_N=$((10#${PLAN_ID}))'),
'the TDD block derives zero-stripped components (#4619: leading integer segment only, decimal/N-segment tolerant)');
assert.ok(w.includes('RED_COMMIT=$(git log --oneline -E ${TDD_MILESTONE_BASE:+"$TDD_MILESTONE_BASE..HEAD"} --grep="${PLAN_SCOPE_RE}" -- "**/*.test.*"'),
'the RED grep must use the same anchored padding-tolerant scope, milestone-bounded');
assert.ok(!w.includes('--grep="^test(${PHASE_NUMBER}-${PLAN_ID})"'),
'the padded-literal RED grep must not remain');
assert.ok(w.includes('TDD_MILESTONE_BASE=$(git describe --tags --abbrev=0 2>/dev/null || echo "")'),
'the RED grep carries the same milestone bound as the resume gate (#4003 review)');
assert.ok(w.includes('${TDD_MILESTONE_BASE:+"$TDD_MILESTONE_BASE..HEAD"}'),
'the RED grep range bound is applied');
assert.ok(w.includes('if [ "$TDD_MODE" = "true" ]'), '#4011 TDD_MODE keying preserved');
});
test('tdd.md gate-enforcement examples use the anchored padding-tolerant scope', () => {
const ref = fs.readFileSync(path.join(__dirname, '..', 'gsd-core', 'references', 'tdd.md'), 'utf8');
assert.ok(!ref.includes('--grep="^test(${PHASE}-${PLAN})"'),
'the padded-literal example grep must not remain');
assert.ok(ref.includes('--grep="^test\\((0*${PHASE_N})-(0*${PLAN_N})\\):"'),
'the RED example is anchored and zero-pad-tolerant');
assert.ok(ref.includes('PHASE_INT=${PHASE%%.*}; PHASE_FRAC=${PHASE#"$PHASE_INT"}') &&
ref.includes('PHASE_N="$((10#$PHASE_INT))${PHASE_FRAC//./\\\\.}"') && ref.includes('PLAN_N=$((10#${PLAN}))'),
'the examples derive zero-stripped components (#4619: leading integer segment only, decimal/N-segment tolerant)');
});
test('completion spot-check uses the anchored scope and keeps its time bound', () => {
// #4217 moved the completion spot-check probes (with the whole reconciliation
// policy, both arms) into execute-phase/steps/completion-reconciliation.md —
// "extract, not bump" against the frozen host ceiling. The anchoring contract
// travels with them: negative shape against the host, positives against the
// fragment that now owns the probes.
const w = fs.readFileSync(WORKFLOW, 'utf8');
const frag = fs.readFileSync(path.join(__dirname, '..', 'gsd-core', 'workflows',
'execute-phase', 'steps', 'completion-reconciliation.md'), 'utf8');
assert.ok(!w.includes('--grep="{phase_number}-{plan_padded}"') && !frag.includes('--grep="{phase_number}-{plan_padded}"'),
'the raw padded placeholder substring grep must not remain');
assert.ok(frag.includes('SPOT_PHASE_INT=${SPOT_PHASE_NUMBER%%.*}; SPOT_PHASE_FRAC=${SPOT_PHASE_NUMBER#"$SPOT_PHASE_INT"}') &&
frag.includes('SPOT_PHASE_N="$((10#$SPOT_PHASE_INT))${SPOT_PHASE_FRAC//./\\\\.}"') &&
frag.includes('SPOT_PLAN_N=$((10#{plan_padded}))'),
'the spot-check derives zero-stripped components (#4619: leading integer segment only, decimal/N-segment tolerant)');
assert.ok(frag.includes('--since="1 hour ago"'), 'the spot-check keeps its temporal bound');
});
test('the gate pipeline separates same-scope commits across a milestone tag (behavioral)', (t) => {
// Reproduces the report on a crafted history: an OLD milestone commit with the
// same scope, a tag, then THIS plan's unpadded commits. The pipeline shape is
// the workflow's: tag base (when present) + anchored, padding-tolerant ERE.
const repo = createTempGitProject('gsd-4003-gate-');
t.after(() => cleanup(repo));
const g = (args) => gitOrThrow(args, { cwd: repo });
g(['commit', '--allow-empty', '-m', 'feat(02-02): old milestone same-scope commit']);
// Annotated: a plain `git tag` can demand a message under some git configs.
g(['tag', '-a', 'v9.0.0', '-m', 'milestone close']);
g(['commit', '--allow-empty', '-m', 'test(2-02): RED for this plan']);
g(['commit', '--allow-empty', '-m', 'feat(2-02): GREEN for this plan']);
g(['commit', '--allow-empty', '-m', 'feat(2-20): adjacent plan must not match']);
g(['commit', '--allow-empty', '-m', 'feat: mentions 02-02 in prose but not in scope']);
const scope = '^[a-z]+\\((0*2)-(0*2)\\):';
const base = g(['describe', '--tags', '--abbrev=0']).trim();
const bounded = g(['log', '--oneline', '-E', `${base}..HEAD`, `--grep=${scope}`]).trim().split('\n');
assert.ok(bounded.some((l) => /test\(2-02\): RED for this plan/.test(l)), 'this plan RED commit is found');
assert.ok(bounded.some((l) => /feat\(2-02\): GREEN for this plan/.test(l)), 'this plan GREEN commit is found');
assert.ok(!bounded.some((l) => /old milestone same-scope/.test(l)), 'the pre-tag same-scope commit is excluded');
assert.ok(!bounded.some((l) => /adjacent plan/.test(l)), 'an adjacent plan scope does not match');
assert.ok(!bounded.some((l) => /in prose/.test(l)), 'a prose mention outside the scope position does not match');
// No-tag fallback: strip the tag, keep the anchor — the old milestone commit
// becomes reachable again, but prose/adjacent scopes still never match.
g(['tag', '-d', 'v9.0.0']);
const unbounded = g(['log', '--oneline', '-E', `--grep=${scope}`]).trim().split('\n');
assert.ok(unbounded.some((l) => /old milestone same-scope/.test(l)),
'without a tag base the anchor alone cannot exclude prior milestones (degrade is honest)');
assert.ok(!unbounded.some((l) => /in prose/.test(l)), 'the anchor still holds without a tag');
});
});