Files
msd-core/tests/qa/loop-walk.cjs
Tom Boucher 33fd203ccd test(#2966): loop QA walk — drive real scenarios across all five loop steps (#2976)
* test(#2966): loop QA walk — drive real scenarios across all five loop steps

Adds a headless walk that carries accumulating project state across
discuss -> plan -> execute -> verify -> ship against one temp project,
layered over the existing tests/helpers.cjs runGsdTools substrate.

Findings carry severity. A violation breaks a stated contract and fails
the build; a smell is legal under today's implementation but structurally
questionable, is recorded, and never reddens CI. Without that split an
oracle set derived from current behavior can only ever confirm current
behavior -- the harness could not say "this works and is still wrong".

The end-to-end test asserts the walk produces at least one smell: a QA
harness that reports nothing on a first run against a real engine is far
more likely mis-specified than the engine is perfect. It deliberately does
not pin smell ids or counts, which would re-freeze current behavior.

First run against the real engine: 0 violations, 3 smell classes --
init returns agents_dir outside the project tree; smart-entry emits prose
unconditionally so routing cannot be asserted; state-snapshot reports a
missing STATE.md through a payload key with exit 0.

Also fixes tests/fixtures/index.cjs: createFixture with git:true and
planning:false staged nothing, so the commit failed with "nothing to
commit". That combination was unreachable until greenfield needed it.

Extends RULESET.TESTS.feedback-loop-convergence from estimation to the
loop itself. Design lock: docs/adr/2966-loop-qa-walk.md.

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

* test(#2966): wire fault injection, make perturbations discriminating

Independent review found tests/qa/mutations.cjs entirely unwired: 462
lines exercised only by their own unit tests, with no mutation hook in
the scenario DSL and no scenario applying one, while the module header
and the ADR described fault injection in the present tense. Dead code
documented as live.

Adds a `mutate` step field, three perturbation scenarios, and a wiring
detector: a self-test scenario whose expectations are known-false and
which MUST fail. The previous anti-vacuity check asserted only that the
walk produced a smell, which passes on well-known engine behavior
regardless of whether the harness wiring works.

First perturbation attempt produced zero signal -- progress does not
structurally parse ROADMAP.md, so a corrupted roadmap sailed through. A
perturbation that cannot fail is the same defect in a new costume.
Probes now target roadmap get-phase, and each mutated step runs a clean
baseline first so `mutationObserved` records whether the corruption
changed anything at all.

Also clears four review findings: classify() returned PROSE for exit-0
with empty stdout; `warnings` was structurally unpopulatable on the
success path (execFileSync discards it) and is now documented as
error-path-only; read-only-idempotence passed vacuously when asked to
check idempotence without the data to check it; the ADR miscounted the
oracles.

Discrimination matrix across 8 mutations x 6 commands: bom,
duplicate-phase-id and escaped-pipes are absorbed silently by every
probed surface, and progress / smart-entry / roadmap validate never
reacted to any mutation.

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

* test(#2966): add path-containment guard for scenario-supplied targets

Security review found scenario-supplied paths joined to the temp project
with no containment check. step.mutate.target and agent.write keys were
validated only as non-empty strings, so a target of ../../../../etc/hosts
reached fs.unlinkSync / fs.writeFileSync / fs.symlinkSync outside the
project. The symlink mutation was worst: it read the traversed file, wrote
a sibling copy, deleted the original and symlinked it back.

Not exploitable today -- all shipped scenarios target .planning/ROADMAP.md
and scenarios are repo-committed, not runtime input. Fixed anyway: it is a
live primitive any future scenario or copied helper can reach.

Adds tests/qa/paths.cjs with resolveWithin(): rejects absolute paths, NUL
bytes and empty input, normalizes separators unconditionally, and requires
containment by path segment so a sibling like <base>-evil is not treated as
inside. Non-existent targets resolve via nearest existing ancestor rather
than falling back to a lexical compare. Scenario load now rejects traversing
or absolute targets up front.

oracles.cjs previously carried its own copy of the containment logic; both
now share paths.cjs, since a duplicated containment check is exactly the
divergence class this repo calls out.

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

* test(#2966): complete trajectory corpus, report emission, boundary-aware oracle

Adds the remaining trajectories and drives all 11 mutations end-to-end.
20 scenarios, 72 steps, 0 violations, 25 smells.

Adds qa-report.json with per-step verdicts and a copy-pasteable repro
command, plus --keep / GSD_QA_KEEP=1 to preserve a failing tree. A repro
line for a tree that was not preserved is marked NOT RUNNABLE rather than
emitting a command pointing at a deleted directory.

monotonic-progress is now boundary-aware. Two scenarios had been trimmed
to stop the oracle complaining at a milestone rollover, which destroys the
signal the trajectory exists to produce. Evidence: counters legitimately
reset to zero at milestone complete, but the payload milestone_version
lags until a new ROADMAP.md is written. So the oracle now scopes by
milestone plus workstream, keeps a same-scope decrease as a violation, and
records a boundary crossing as a smell. Both scenarios walk the real
boundary again.

Standards review fixes: oracle findings now carry a structured subject so
tests assert on typed fields instead of substring-matching the free-form
detail string, resolveWithin throws a typed EPATHESCAPE error, and the
absolute-path predicate scenario.cjs had re-implemented now comes from
paths.cjs.

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

* test(#2966): fix silently-vacuous fixtures and guard the class

Every fixture carried its #2371 provenance comment BEFORE the frontmatter
block, and extractFrontmatter returns {} when anything precedes the opening
---. So every scenario reading status/phase/name was operating on an empty
object and reporting green. Nine fixtures repositioned; the comment stays,
it just moves below the closing ---.

Both UAT fixtures lacked a parser-recognized result block, so
evaluateUatPassed saw checks.length===0 and could never return passed:true.
The uat-fail-then-remediate scenario could not have proven a remediation.
Its expect block only inspected blockers, which is empty before AND after,
which is why the corpus never noticed. Both fixtures now carry real result
blocks and the scenario asserts passed and no_uat_artifacts on each side of
the flip.

The actual deliverable is the guard: a fixture-integrity block asserting
every fixture with a frontmatter shape parses to a non-empty object, that
every fixture carries its provenance marker, and that the two UAT fixtures
produce opposite verdicts through the real evaluateUatPassed. The first
guard written required --- at byte 0, which would never have fired on the
regression it exists to prevent; it was rewritten and proven by deliberately
re-breaking a fixture.

No engine defect here. no_uat_artifacts means no parsed check items, not no
UAT files, and it was reporting correctly on fixtures that had none.

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

* test(#2966): make the walk report — smell ratchet, baseline, CI job

The harness computed smells into a gitignored qa-report.json that nothing
read. In CI it surfaced nothing at all: violations failed the build, but the
half of the tool that says "this works and is still wrong" was inert. A QA
tool nobody hears is decoration.

Adds a ratchet on the same idiom this repo already uses three times over
(the regression-test-name allowlist, the emitted-drift acks, the size
baseline): a committed smell-baseline.json, per-PR acknowledgment fragments
under tests/qa/smell-acks/, and a ratchet script wired into CI.

The design invariant is preserved exactly. A smell still never fails a build
on its own merits. What fails is an UNACKNOWLEDGED NEW smell -- the absence
of a decision -- leaving an author two honest exits: fix it, or record a
fragment with a real reason. An empty reason is rejected. The baseline is
shrink-only, so a fixed smell must prune its entry. Violations remain
unacknowledgeable.

Fingerprints are composed only from stable fields (oracle id, scenario,
argv, subject discriminator) -- never temp paths, timestamps or counts.
Verified byte-identical across two runs in separate temp dirs; an unstable
fingerprint would have false-positived every CI run.

CI gains a qa-loop-walk job that runs the suite and the ratchet, uploads the
report with `if: always()` (it matters most when it failed), and renders a
summary a reviewer reads without downloading anything.

Also fixes the report runner invoking main() unconditionally on require, so
importing it double-ran every scenario and clobbered its own output.

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

* test(#2966): every smell terminates in a defect or a fixed detector

The baseline accepted a smell with a free-text reason. That is a mechanism
for designing smells in -- an allowlist nobody revisits. The harness is
brand new, so nothing it found is inherited legacy; every finding is a
FIRST finding. Each must now terminate in exactly one of two states:

  REAL           -> an assigned defect, entry carries the issue number
  FALSE POSITIVE -> the detector is wrong and gets fixed, never baselined

There is no third "accepted with a good explanation" state, so the ratchet
now requires a positive-integer `issue` on every entry. A reason may remain
as a human note but can never substitute. `--update` refuses to invent
issue numbers: a new smell is written with `issue: null` and a TODO, and
the next plain run rejects it, forcing triage rather than accumulation.

Working the 21 existing entries through that rule found 16 were my own
detectors being wrong:

value-hygiene (10) flagged $.agents_dir, a field whose entire contract is
to point at the install tree outside any project. Fixed with a leaf-key
allowlist of contractually-external fields, verified as the only such key
in the init payload. Genuinely unexpected out-of-project paths still smell.

monotonic-progress (6) fired on legitimate boundary crossings -- milestone
v1.0 to v2.0, workstream beta to alpha -- and on one payload carrying no
scope fields at all, where a change cannot even be known. Scope changes now
reset silently and scope-less observations are skipped. The same-scope
decrease remains a violation; that is the real invariant and is regression-
guarded.

The five survivors are real and now tracked: soft-error-exit-zero (#2980),
untyped-success (#2979). Baseline 25 -> 5.

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

* test(#2966): keep the ratchet out of the tarball, unpin the qa CI job

The remote matrix returned failed -- 3 unique failures, identical on
node22 and node24, both root causes in this branch's own diff.

The ratchet lives under scripts/, which ships in the npm tarball, and it
requires three modules under tests/, which does not. In a published
install it is MODULE_NOT_FOUND at load. This is exactly the class the
#2858 guard was added to catch, and it caught it. Fixed the way #2858
fixed the same shape for its own repo-only CI script: a targeted files[]
negation, so the ratchet stays in the repo for CI and out of the tarball.
Not solved by moving or inlining the required modules -- the ratchet must
keep using the same code the harness uses, or the two drift.

Verified both directions: the script is no longer in the pack list, and
build-hooks.js, fix-slash-commands.cjs and gen-capability-registry.cjs are
all still shipped. Over-negating there would have broken installs, since
bin/install.js requires them.

The qa-loop-walk job also carried CI_REBASE_BASE_SHA copied from a
neighbouring job without the paired GSD_EMITTED_BASE, which the #2854
invariant forbids by name: diverging them makes the differential compare a
tree against a baseline from a different commit. The job runs only the qa
suite and the ratchet and invokes no emitted-attribution test, so it needs
no rebase-pinned base at all -- the step was removed rather than paired.

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

* test(#2966): stop monotonic-progress going blind on scope-less payloads

The full remote suite caught a false NEGATIVE I introduced while fixing a
false positive. Silencing the boundary-crossing noise had made the oracle
skip ANY observation lacking milestone fields -- so a minimal payload like
{total_summaries: n} produced no violation at all, and the oracle stopped
catching the exact defect it exists to catch. For a QA tool that is
strictly worse than the noise it replaced.

Scope is only indeterminate when the two observations DISAGREE about
having it:

  both scoped, same scope, decrease -> VIOLATION
  both scoped, different scope      -> reset silently
  NEITHER scoped, decrease          -> VIOLATION   (the regression)
  mixed                             -> skip the comparison

Implementing the mixed case surfaced a second blind spot: advancing the
reference point on a skipped pair lets a scope-less observation sitting
between two same-scope ones mask a real decrease. Mixed now leaves the
reference untouched. All four branches carry explicit coverage; only one
did before, which is why this shipped.

The self-test that failed was right and the code was wrong, so the code
moved. Corpus behavior is unchanged: still 5 smells, 0 new, 0 stale, 0
violations.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-01 16:13:28 -04:00

331 lines
15 KiB
JavaScript

'use strict';
/**
* loop-walk.cjs — a small stateful harness around `tests/helpers.cjs` for the
* loop QA walk. This module owns NONE of the subprocess mechanics itself
* (spawn, retry-on-kill, quote-splitting) — those live in `runGsdTools` /
* `createTempGitProject` and are reused verbatim. What this module adds is
* the walk-specific concerns: turning a raw helper result into the typed
* `RunResult` from `./result.cjs`, guaranteeing the child never inherits an
* ambient `GSD_*` variable that would silently redirect the engine, pinning
* the clock so output is reproducible run-to-run, and giving callers a
* content-free way to observe what the SUT wrote to disk.
*/
const fs = require('fs');
const path = require('path');
const { runGsdTools, cleanup } = require('../helpers.cjs');
const { classify } = require('./result.cjs');
const { createFixture } = require('../fixtures/index.cjs');
const { LOOP_HOST_CONTRACT } = require('../../gsd-core/bin/lib/loop-host-contract.cjs');
const { resolveWithin } = require('./paths.cjs');
/**
* WHY re-derive rather than re-list: `loop-host-contract.cjs` is itself
* generated (see its own header) from workflow markers by
* `scripts/gen-loop-host-contract.cjs`. If this file hardcoded
* `['discuss', 'plan', 'execute', 'verify', 'ship']`, a future regeneration
* that renames, adds, or removes a step would leave the QA walk silently
* testing a stale step list — a second source of truth that can drift out
* from under the generated one with no signal anywhere. Deriving `LOOP_STEPS`
* from the same contract object the generator produced means drift is
* structurally impossible: this array always has exactly the steps the
* contract currently declares.
*
* @type {string[]}
*/
const LOOP_STEPS = LOOP_HOST_CONTRACT.map((entry) => entry.step);
/** Default pinned clock value (2026-01-01T00:00:00.000Z) — see `create({nowMs})`. */
const DEFAULT_NOW_MS = 1767225600000;
/**
* Starting-world builders keyed by `fixture` name, each a thin wrapper over
* `createFixture` (`tests/fixtures/index.cjs`).
*
* WHY this exists at all: `createFixture`'s `projectDoc` option defaults to
* `projectDoc = git` (`tests/fixtures/index.cjs:21`) — so any caller that
* only passes `git: true` silently also gets `.planning/PROJECT.md` seeded.
* A "greenfield" walk built that way would report `project_exists: true`
* from its very first step, which makes the greenfield trajectory
* meaningless: it can never exercise the create path (`/gsd-new-project`)
* because a project already exists before the walk begins. Every entry
* below therefore states `projectDoc` explicitly rather than relying on
* that default, and `greenfield` is the harness default precisely because
* an empty git repo with no `.planning/` at all is what a real user's
* working tree looks like before running `/gsd-new-project` for the first
* time.
*
* @type {Record<string, (prefix: string) => string>}
*/
const FIXTURE_BUILDERS = {
// A git repo with NO `.planning/` at all — what a user has before
// `/gsd-new-project`.
greenfield: (prefix) => createFixture({ prefix, git: true, planning: false, projectDoc: false }),
// `.planning/phases/` exists, but no PROJECT.md yet.
planning: (prefix) => createFixture({ prefix, git: true, planning: true, projectDoc: false }),
// The old `createTempGitProject` behavior: a fully seeded project.
seeded: (prefix) => createFixture({ prefix, git: true, planning: true, projectDoc: true }),
};
/**
* Recursively collect `{size, mtimeMs}` stat facts for every regular file
* under `root`, excluding `.git/`.
*
* WHY stat-only, never read: `RULESET.TESTS.no-source-grep.tmp-file-traps`
* (see `result.cjs` header) forbids reading the content of files the SUT
* (system under test) wrote and then string-matching against it — that
* pattern is exactly the raw-text-matching anti-pattern the project's test
* conventions ban, just relocated from stdout to disk. `fs.statSync` proves
* a file exists, changed size, or changed mtime without ever opening its
* content, so a walk can assert "did this step write/touch a file" without
* ever being tempted into `readFileSync(...).includes(...)`.
*
* @param {string} root - absolute directory to walk.
* @returns {Map<string, {size: number, mtimeMs: number}>} keyed by
* POSIX-normalized path relative to `root`.
*/
function collectStatSnapshot(root) {
/** @type {Map<string, {size: number, mtimeMs: number}>} */
const out = new Map();
function walk(dir) {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
if (entry.name === '.git') continue;
const abs = path.join(dir, entry.name);
if (entry.isDirectory()) {
walk(abs);
continue;
}
if (!entry.isFile()) continue;
const stat = fs.statSync(abs);
// WHY unconditional replace, not platform-conditional: `path.sep` is
// '/' on POSIX so a conditional swap looks like a no-op there, but a
// path segment can still literally contain a backslash character
// (e.g. an artifact file the SUT names with one) on Linux — so the
// normalization must run every time, not only when path.sep === '\\'.
const rel = path.relative(root, abs).replace(/\\/g, '/');
out.set(rel, { size: stat.size, mtimeMs: stat.mtimeMs });
}
}
walk(root);
return out;
}
class LoopWalk {
/**
* @param {string} dir - absolute project root (an already-created temp git project).
* @param {number} nowMs - pinned epoch ms passed to every `run()` as `GSD_NOW_MS`.
*/
constructor(dir, nowMs) {
this.dir = dir;
this.nowMs = nowMs;
}
/**
* Alias for `this.dir` under the name `oracles.cjs`'s `ctx.projectDir`
* expects (see `value-hygiene`'s absolute-path-leak smell check). Kept as
* a getter rather than a second stored field so the two can never drift.
*
* @returns {string}
*/
get projectDir() {
return this.dir;
}
/**
* Create a fresh temp git project and a `LoopWalk` bound to it.
*
* WHY `fixture` defaults to `'greenfield'`, not the old seeded behavior:
* see `FIXTURE_BUILDERS` above — a walk that starts with
* `.planning/PROJECT.md` already present can never exercise the
* project-creation path, which is the whole point of a "greenfield" walk.
* An unrecognized `fixture` name throws rather than silently falling back
* to a default, because a typo'd fixture name silently testing the wrong
* starting world is exactly the failure this harness exists to catch.
*
* @param {{prefix?: string, nowMs?: number, fixture?: 'greenfield'|'planning'|'seeded'}} [opts]
* @returns {LoopWalk}
*/
static create(opts = {}) {
const { prefix = 'gsd-loop-walk-', nowMs = DEFAULT_NOW_MS, fixture = 'greenfield' } = opts;
const build = FIXTURE_BUILDERS[fixture];
if (!build) {
throw new Error(
`LoopWalk.create: unknown fixture "${fixture}" (expected one of: ${Object.keys(FIXTURE_BUILDERS).join(', ')})`
);
}
const dir = build(prefix);
return new LoopWalk(dir, nowMs);
}
/**
* Run a `gsd-tools` invocation inside this walk's project and return the
* typed `RunResult` from `classify()`.
*
* SIGNATURE: `run(...argvTokens)` where the LAST argument, if it is a
* plain object (not a string), is stripped off and treated as an options
* bag rather than an argv token — so `walk.run('progress')` and
* `walk.run('progress', { jsonErrors: false })` both read naturally
* against every existing call site in this repo (`walk.run(...argv)` in
* `scenario.cjs`, `walk.run('progress')` in the self-tests) without
* requiring callers to restructure a spread argv array around a leading
* options object.
*
* WHY `jsonErrors` defaults to `true`: `--json-errors` (`docs/json-errors.md`)
* is a real CLI flag, but it is the TOOLING/TEST surface — a human or a real
* workflow invokes `gsd_run <cmd>` directly, WITHOUT it. Defaulting to
* `true` keeps every pre-existing call site's behavior byte-for-byte
* unchanged (they all exercised `--json-errors` before this option
* existed), while `{ jsonErrors: false }` lets a scenario step opt into
* driving the human path instead — otherwise the harness would only ever
* prove the tooling surface works and could never catch a regression a
* real user would actually hit.
*
* WHY the env is built the way it is (ambient `GSD_*` sanitization):
* `runGsdTools` composes the child env as
* `{ ...process.env, ...TEST_ENV_BASE, ...env }` — so whatever `GSD_*`
* variables happen to be set in the *parent* shell (e.g. a developer or CI
* runner with `GSD_WORKSTREAM` / `GSD_PROJECT` exported for an unrelated
* reason) flow straight through into the child and can silently redirect
* the engine at a different workstream or project root than the one this
* walk created — an invisible, non-deterministic test-pollution vector.
* `runGsdTools`'s own merge order means the last object spread wins, so
* this method builds an `env` override that sets EVERY ambient `GSD_*` key
* (scanned live from `process.env`, not a hardcoded list — a new leaking
* var needs no code change here to be caught) to `undefined`, then layers
* the two intentionally-pinned vars on top.
*
* The `undefined` trick is deliberate, not a placeholder: Node's child
* process env normalization (`lib/child_process.js` `normalizeSpawnArgs`,
* exercised here via `execFileSync`) iterates `Object.keys(env)` and
* OMITS any key whose value is `undefined` from the actual `KEY=VALUE`
* pairs handed to the OS — it does not stringify it to the literal text
* `"undefined"`. That means `{ GSD_WORKSTREAM: undefined }` in the `env`
* option makes the child process behave exactly as if `GSD_WORKSTREAM`
* were never exported at all, even though `process.env.GSD_WORKSTREAM` is
* still set and non-empty in the parent. This was verified empirically
* (not assumed) — see the module verification transcript — because
* `delete`-based approaches were not available here (the merge is inside
* `runGsdTools`, not under this method's control) and a stringified
* `"undefined"` would have been a silent correctness bug indistinguishable
* from a passing run until an actual leak test caught it.
*
* ⚠️ KNOWN LIMIT — SUCCESS-PATH STDERR IS NOT OBSERVABLE THROUGH THIS
* SUBSTRATE, SO `result.warnings` IS ERROR-PATH-ONLY TODAY: this method
* builds `raw.stderr` as `result.success ? '' : (result.error ?? '')`
* (below), and `runGsdTools` (`tests/helpers.cjs`) invokes the child via
* `execFileSync`, which discards the child's stderr stream entirely on a
* clean (non-throwing) exit — Node never captures it, so there is no text
* to forward even if this method wanted to. The practical effect: for any
* exit-0 invocation, `classify()` always receives `stderr: ''`, so
* `result.warnings` can never be non-empty on the success path, no matter
* what the real `gsd-tools` process actually wrote to stderr. `warnings`
* only ever populates on the exit-1 (error) path, where `result.error`
* (helpers.cjs's captured stderr-on-failure text) is threaded through.
* Capturing success-path stderr would require changing `runGsdTools` /
* `tests/helpers.cjs` (e.g. to `spawnSync`) — out of scope here because
* that helper is shared by ~131 test files. DO NOT build an oracle that
* assumes `.warnings` reflects success-path stderr; it structurally cannot
* today, and a check written against that assumption is silently vacuous.
*
* @param {...(string|{jsonErrors?: boolean})} args - argv tokens, optionally
* followed by a trailing `{jsonErrors?: boolean}` options object.
* @returns {ReturnType<typeof classify>}
*/
run(...args) {
const trailing = args[args.length - 1];
const hasOptions = trailing !== null && typeof trailing === 'object' && !Array.isArray(trailing);
const options = hasOptions ? trailing : {};
const argvTokens = hasOptions ? args.slice(0, -1) : args;
const { jsonErrors = true } = options;
const argv = jsonErrors ? ['--json-errors', ...argvTokens] : argvTokens;
/** @type {Record<string, string|undefined>} */
const sanitize = {};
for (const key of Object.keys(process.env)) {
if (key.startsWith('GSD_')) sanitize[key] = undefined;
}
const env = {
...sanitize,
GSD_TEST_MODE: '1',
GSD_NOW_MS: String(this.nowMs),
};
let raw;
try {
const result = runGsdTools(argv, this.dir, env);
raw = {
exitCode: result.exitCode,
stdout: result.output,
stderr: result.success ? '' : (result.error ?? ''),
timedOut: false,
argv,
};
} catch {
// `runGsdTools` throws only after a retried, persistent subprocess
// kill (host OOM / scheduler contention — see helpers.cjs
// `throwResourceStarvation`). That is a statement about the HOST, not
// the engine under test, so a walk must degrade to a TIMEOUT result
// rather than propagate and abort the whole walk over a transient
// resource condition it cannot control.
raw = { exitCode: null, stdout: '', stderr: '', timedOut: true, argv };
}
return classify(raw);
}
/**
* Write a planning artifact into this walk's project, standing in for what
* a real agent (researcher/planner/executor/...) would produce mid-loop.
* Creates parent directories as needed.
*
* `relPath` is resolved via `resolveWithin` before any I/O — a scenario- or
* caller-supplied path that escapes `this.dir` (e.g. `"../../escaped.md"`)
* throws rather than reaching `fs.writeFileSync` outside the temp project.
*
* @param {string} relPath - path relative to `this.dir`.
* @param {string} content
*/
writeArtifact(relPath, content) {
const abs = resolveWithin(this.dir, relPath);
fs.mkdirSync(path.dirname(abs), { recursive: true });
fs.writeFileSync(abs, content, 'utf-8');
}
/**
* Content-free snapshot of every file under this walk's project (excluding
* `.git/`). See `collectStatSnapshot` for why this never reads file bytes.
*
* @returns {Map<string, {size: number, mtimeMs: number}>}
*/
statSnapshot() {
return collectStatSnapshot(this.dir);
}
/**
* Remove this walk's temp project. Safe to call multiple times.
*
* `opts.keep` (default `false`) skips the removal entirely — the caller
* (a QA-report run, typically via `--keep` / `GSD_QA_KEEP=1`) wants the
* failing/inspected tree left on disk for a human to `cd` into. When kept,
* this returns `this.dir` so the caller can record it (e.g. as
* `preservedDir` on a scenario report); when actually cleaned up, it
* returns `undefined`.
*
* @param {{keep?: boolean}} [opts]
* @returns {string|undefined}
*/
cleanup(opts = {}) {
const { keep = false } = opts;
if (keep) return this.dir;
cleanup(this.dir);
return undefined;
}
}
LoopWalk.LOOP_STEPS = LOOP_STEPS;
module.exports = { LoopWalk, LOOP_STEPS };