Files
msd-core/tests/bug-3127-state-begin-phase-idempotent.test.cjs
Tom Boucher a28dcec981 chore(#597): replace count-based ratchet guards with AST lint + named-set allowlists (#603)
The windows-test-parity ratchet greps test source for fs.rmSync-without-
maxRetries (and six other Windows-portability anti-patterns), failing when an
integer offender COUNT exceeds a frozen baseline (rmSync: 95). A count ratchet
is a Goodhart metric: fixing one offender and adding another keeps the count
constant, so a new defect slips through green. Replace it — and every other
count ratchet in the repo — with a layered, masking-proof design.

Behavioral seam test
- tests/helpers-cleanup.test.cjs proves helpers.cleanup() carries the Windows
  EBUSY retry budget. cleanup() delegates retries to Node's fs.rmSync via
  maxRetries (it owns no loop), so the test asserts the option contract
  (recursive/force/maxRetries>0/retryDelay>0) + real-FS removal + the cwd-guard,
  rather than a loop that does not exist. The EBUSY risk is now tested ONCE at
  the helper, not approximated textually at every call site.

Write-time ESLint rule (AST-accurate, replaces the grep)
- eslint-rules/no-raw-rmsync-in-tests.cjs (error in tests/**/*.test.cjs) bans
  raw fs.rmSync, steering to cleanup(). Catches member, computed (fs['rmSync']),
  destructured and aliased forms; escape hatch is inline
  `// eslint-disable-next-line local/no-raw-rmsync-in-tests -- <reason>` only.
- Migrated 336 raw fs.rmSync teardown calls across ~116 test files to cleanup().
  ~18 genuinely load-bearing sites (mid-test SUT/fault-injection removals,
  error-swallowing or name-colliding local teardown helpers) keep the raw call
  with an inline eslint-disable + reason.

Shared anti-ratchet primitive
- scripts/lib/allowlist-ratchet.cjs:
  - assertWithinAllowlist: fails on NOVEL ids (new offender introduced) AND on
    STALE ids (a known offender was fixed but not pruned) — identity, not count,
    and a ratchet DOWN toward zero.
  - assertTightCeiling: a size/length budget whose ceiling must stay within a
    grace band of the high-water mark, so budgets may only tighten, never creep.

Ratchets converted onto the primitive
- windows-test-parity-guard.test.cjs: rmSync rule deleted (now ESLint-enforced);
  the remaining six patterns moved from integer baselines to named-set
  allowlists with ratchet-down.
- scripts/lint-test-file-count.{cjs,allowlist.json}: per-module integer counts →
  named filename sets (closes the swap-a-file-keep-the-count blind spot); a
  module dropping under cap now FAILS to force pruning its allowlist entry.
- enh-2790 skill-count `<= 63` → named skill allowlist (ratchets toward ~58).

Size budgets hardened (tighten-only)
- agent-size / workflow-size / feat-3039 help-tiered: ceilings lowered to the
  current high-water mark and an assertTightCeiling anti-creep check added per
  tier. Fixed external-contract limits (description ≤100 chars, agent ≤100 KB)
  are intentionally left as-is — they are not grandfathered creeping budgets.

No user-facing behavior change (tests + tooling only); no USER_FACING_PREFIXES
touched, so no changeset fragment is required.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-01 22:43:49 -04:00

180 lines
6.5 KiB
JavaScript

'use strict';
// allow-test-rule: reads runtime STATE.md written to temp dir — behavioral output test, not source-grep
// Regression tests for bug #3127.
//
// state.begin-phase is non-idempotent: when execute-phase calls it on a phase
// that is already mid-flight (e.g. --wave N resume), the handler unconditionally
// overwrites execution-progress fields with stale values from the last plan-phase run:
// - stopped_at / Last Activity Description reset to "context gathered; ready for plan-phase"
// - Current Plan reset to 1 (from plan being executed, e.g. 3)
// - Plan: N of M body line reset to "Plan: 1 of M"
// - Last activity timestamp reverted to an older value
// - progress.percent may decrease
//
// Fix: read the current Status field before writing. If the phase is already
// "Executing Phase N", skip the execution-progress fields (Current Plan, plan body
// line, Last Activity Description) and only update fields safe to overwrite on
// resume (Last Activity date, Status if somehow wrong).
// A --force flag bypasses the guard for intentional full resets.
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { cleanup } = require('./helpers.cjs');
const ROOT = path.join(__dirname, '..');
// Load the state.cjs module internals via the command router
function requireStateCjs() {
return require(path.join(ROOT, 'get-shit-done', 'bin', 'lib', 'state.cjs'));
}
function makeTempPlanning(stateContent) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3127-'));
const planningDir = path.join(dir, '.planning');
fs.mkdirSync(planningDir, { recursive: true });
fs.writeFileSync(path.join(planningDir, 'STATE.md'), stateContent, 'utf8');
return dir;
}
// A STATE.md that is mid-flight on Phase 5 (Plan 3 of 8 in progress)
const MID_FLIGHT_STATE = `# GSD State
## Configuration
Current Phase: 5
Current Phase Name: test-phase
Total Plans in Phase: 8
Current Plan: 3
Status: Executing Phase 5
## Current Position
Phase: 5 (test-phase) — EXECUTING
Plan: 3 of 8 (Plan 00 SHIPPED — wave 1 complete; Plan 01 SHIPPED; Plan 02 next)
Status: Executing Phase 5
Last activity: 2026-05-05 -- Plan 02 SHIPPED wave 2 GREEN
## Progress
progress:
total_phases: 10
completed_phases: 4
percent: 89
stopped_at: Phase 5 Plan 02 SHIPPED — Wave 2 GREEN detailed narrative here; ready for Plan 03
`;
// A STATE.md that is NOT yet executing (plan-phase just ran)
const PRE_EXECUTE_STATE = `# GSD State
## Configuration
Current Phase: 5
Current Phase Name: test-phase
Total Plans in Phase: 8
Current Plan: 1
Status: Ready to execute
## Current Position
Phase: 5 (test-phase) — READY
Plan: 1 of 8
Status: Ready to execute
Last activity: 2026-05-04 -- context gathered; ready for plan-phase
stopped_at: Phase 5 context gathered; ready for plan-phase
`;
describe('bug #3127: state.begin-phase idempotency guard', () => {
test('begin-phase on a mid-flight phase does not reset Current Plan', () => {
const stateModule = requireStateCjs();
const { cmdStateBeginPhase } = stateModule;
if (!cmdStateBeginPhase) {
// Skip if not exported — the guard may be inside a private function
return;
}
const dir = makeTempPlanning(MID_FLIGHT_STATE);
try {
cmdStateBeginPhase(dir, '5', 'test-phase', 8, false);
const after = fs.readFileSync(path.join(dir, '.planning', 'STATE.md'), 'utf8');
// Current Plan must not have been reset to 1
const planMatch = after.match(/^Current Plan:\s*(\S+)/m);
if (planMatch) {
assert.notStrictEqual(planMatch[1], '1',
'begin-phase reset Current Plan to 1 on a mid-flight phase — idempotency guard not applied');
}
} finally {
cleanup(dir);
}
});
test('begin-phase on a mid-flight phase does not overwrite stopped_at narrative', () => {
const stateModule = requireStateCjs();
const { cmdStateBeginPhase } = stateModule;
if (!cmdStateBeginPhase) return;
const dir = makeTempPlanning(MID_FLIGHT_STATE);
try {
cmdStateBeginPhase(dir, '5', 'test-phase', 8, false);
const after = fs.readFileSync(path.join(dir, '.planning', 'STATE.md'), 'utf8');
// The rich stopped_at narrative must be preserved
assert.ok(
after.includes('Plan 02 SHIPPED') || after.includes('Wave 2 GREEN'),
'begin-phase overwrote stopped_at narrative on a mid-flight phase',
);
} finally {
cleanup(dir);
}
});
test('begin-phase on a NOT-yet-executing phase sets Current Plan to 1 (normal path)', () => {
const stateModule = requireStateCjs();
const { cmdStateBeginPhase } = stateModule;
if (!cmdStateBeginPhase) return;
const dir = makeTempPlanning(PRE_EXECUTE_STATE);
try {
cmdStateBeginPhase(dir, '5', 'test-phase', 8, false);
const after = fs.readFileSync(path.join(dir, '.planning', 'STATE.md'), 'utf8');
// Normal path: Current Plan should become 1 (or stay 1)
const planMatch = after.match(/^Current Plan:\s*(\S+)/m);
if (planMatch) {
assert.strictEqual(planMatch[1], '1',
'begin-phase should set Current Plan to 1 on a fresh phase');
}
} finally {
cleanup(dir);
}
});
test('begin-phase always updates Last Activity date (safe on resume, pinned via GSD_NOW_MS)', () => {
const stateModule = requireStateCjs();
const { cmdStateBeginPhase } = stateModule;
if (!cmdStateBeginPhase) return;
const dir = makeTempPlanning(MID_FLIGHT_STATE);
const PINNED_MS = Date.parse('2020-11-25T09:00:00.000Z');
const PINNED_DATE = '2020-11-25';
// Pin the in-process clock via env vars before calling the function directly.
const origTestMode = process.env.GSD_TEST_MODE;
const origNowMs = process.env.GSD_NOW_MS;
process.env.GSD_TEST_MODE = '1';
process.env.GSD_NOW_MS = String(PINNED_MS);
try {
cmdStateBeginPhase(dir, '5', 'test-phase', 8, false);
const after = fs.readFileSync(path.join(dir, '.planning', 'STATE.md'), 'utf8');
assert.ok(
after.includes(PINNED_DATE),
`begin-phase must update Last Activity date to the pinned date ${PINNED_DATE} even on resume (safe field)`,
);
} finally {
// Restore env vars before cleanup to avoid leaking state to other tests.
if (origTestMode === undefined) delete process.env.GSD_TEST_MODE;
else process.env.GSD_TEST_MODE = origTestMode;
if (origNowMs === undefined) delete process.env.GSD_NOW_MS;
else process.env.GSD_NOW_MS = origNowMs;
cleanup(dir);
}
});
});