Files
gstack/test/qa-functional-evidence.test.ts
Garry Tanandcapy-ai[bot] 77d125e0bc v1.91.127.0 fix(evals): paid-gate reliability round 2: docsync candidate protocol, scope-block detection, qa fix-loop budgets, lettered consent (#3260)
* test(qa-callers): bind QA section names in the caller prompt instead of teaching helper forms (W3-4)

The caller session prompt taught full capture/checkpoint syntax but only
mentioned materialize, so two ship-exploratory-small-cli sessions (paid
gate runs 38973329985, 38993076767) skipped qa/sections/exploratory.md and
system-functional.md and guessed a bare materialize. The prompt now
declares only fixture bindings (DEADLINE_TOOL, EVIDENCE_TOOL, PROBE_DIR,
DEADLINE_FILE, --public approval, --timeout-ms 10000 for plan probes) and
points to the section for every form. The read requirement is unchanged;
both captured transcripts are kept as negative controls.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(review-army): run the state-machine detector in the scope block and check its exit status (W3-5)

Specialist 9 named gstack-state-matrix detect only in selection prose, and
small diffs keep only State Machines, so agents ran an undeclared command
(paid gate run 39002269281). The generated scope block now runs the
detector with its exit status checked: on failure it keeps the detector's
diagnostics and sets SCOPE_STATE_MACHINE=unknown, and selection dispatches
State Machines when the signal is true or unknown. The check step becomes a
declared heredoc block. The clarity test requires every non-diff-scope
signal to come from a detect helper the scope block runs; a free test runs
the block against a failing detector stub; the captured standalone call
stays outside the caller interface.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(third-party-actions): letter the absent-Aside consent options B/C/D (W3-7)

The contract fixed letters only when Aside is detected, so a tpa-absent-linux
agent numbered its consent question 1/2/3 (paid run 39011101113), which the
lettered-offer inspection cannot read. The absent branch now offers
B) gstack's own visible browser, C) manual instructions, D) defer and omits
A). The paid test's assertion is unchanged; the captured numbered answer is
a documented fail example in the unit test.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(plan-reality): say tier 1 rows are never n/a (W3-8)

The plan-review reality block offered pass|finding|n/a without saying tier 1
rows may never be n/a, so a plan-mode-no-op session wrote
`REALITY: deferred-asks n/a ...`, check returned repair, and the repair loop
ran past the 300 s capture (paid run 39004466422). The block now says tier
1 rows are never n/a and that with no linked issue deferred-asks is pass
with a receipt showing none. The captured line is pinned through check as
missing=deferred-asks verdict=repair.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(qa-functional): webhook fix runs re-verify the repaired invariant and rerun superseded captures (W3-6, W3-14)

W3-6: stage 2 of the fix-run prompt asked only for the original, happy,
cancel and dependency probes while verifyQANativeRegression reruns all
eight, so a status-only repair that left partial broken reached the verifier
(paid run 38986120559). The webhook fix prompt now states the capture budget
up front (at most 5 pre-repair captures, then the 7 post-repair scenarios:
duplicate, partial, concurrent-ab, concurrent-ba, happy, cancel, dependency;
12 in total; report incomplete if 5 cannot establish the defect). That list
feeds the capture nudge (GSTACK_QA_REQUIRED_PROBES);
QA_WEBHOOK_REQUIRED_SCENARIOS and the verdict are unchanged.

W3-14: the fix prompt now says to rerun every pre-repair capture the
verdict relies on after the final repair, and that a superseded row stays
open until its command reran on the repaired source (paid run 39053431488
labelled a pre-repair duplicate superseded and never reran it). The
detector and its negative test are unchanged; the captured shape joins them
as a negative control.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(qa): tie the exploratory stop rule to per-rule input probes; fix runs close superseded captures (W3-9, W3-14)

W3-9: two qa-functional-cli-report sessions stopped at 5-7 of 12 probes
without probing a non-digit amount (paid runs 38983306684, 39001107574),
though system-functional.md requires one probe per documented input rule.
The single stop rule shared by both exploratory templates now says each
documented input rule needs its own probe breaking only that rule, and
rules left uncovered at a probe or time cap go in limits.

W3-14: for fix runs (not qa-only), every capture taken before a fix is
superseded even when its client prints no snapshot; before completion the
agent reruns each one its verdict relies on or reports it as an open
remainder. Production superseded/open semantics are unchanged.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(qa-functional): keep the captured webhook-report cat attempts as denied negative controls (Q3)

Paid run 39006896632 (qa-functional-webhook-report) attempted
`cat package.json probe.ts .gitignore` and `cat src/*.ts test/*.ts`; the
PreToolUse hook denied both. This is a model miss, not a detector defect, so
both commands are pinned as denied by the registered hook and outside
qaCommandAllowed. No detector change.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(docs-candidate): per-subcommand --help and a compare reject that names the fix (W3-2)

snapshot --help and compare --help print the usage and exit 0 before any side
effect; the docsync observer admits exactly those two forms. compare names the
record path, each missing or wrong field (schema_version, base, hashes) and
the snapshot command that writes a valid record, keeping exit 1. The captured
ship-docsync-stale-after commands from PR gate run 38990111230 replay inside
the interface; help with any other argument stays rejected.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(docsync-fault): prepare writes the production candidate through the installed snapshot (W3-1)

The fault actor prepare wrote its own {base_sha, content_hashes, ...} record,
which the installed gstack-docs-candidate compare rejects, while
ship/sections/documentation.md requires running compare; 79 of 198 docsync
captures (and the red in PR gate run 38990111230) were pushed off the
documented path by it.

prepare now runs the installed snapshot under a 30 s timeout for the same
selection, returns its exact command as snapshot_command so the post-child
rerun is literal, publishes prompt and event only after a valid record
exists, and removes a record its own failed snapshot left. dispatch observes
the candidate with the same installed snapshot; inspect returns base, index
and per-file git blob ids in the record representation; the legacy re-audit
check reads selected/hashes. The fault prompt names snapshot_command and the
new field names.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(todos): file the qa-quick capture headroom follow-up (fix wave 3, T)

qa-quick timed out once at 300 s (paid run 38980005793) against passing
runs of 164-272 s. Trimming what the Quick tier loads is a product call, so
it is filed, not repaired; no budget change.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(docsync): keep the two docsync model misses as negative controls (W3-3)

The Bash grep of ship-docsync-missing-asset (PR gate run 38983306684,
bash#13) and the composed cat; cat of ship-docsync-failure (38984977679,
bash#12) were correct rejections. They join the stored known_bad commands
(with a {home} placeholder for the fixture home); no detector change.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(golden): refresh the ship goldens for the W3-5 scope block and W3-7 consent letters

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(third-party-actions): state the absent-Aside letters in fewer characters (W3-7)

Same contract (B), C), D) when Aside is not detected; the next sentence
already omits the Aside option), 67 fewer characters on the pinned
land-and-deploy and office-hours skills.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(skill-md-size): re-pin 31 over-limit skills grown by fix wave 3 prompt repairs (owner sign-off needed)

CREW rule 11: these skills were already over 100,000 characters and grow
by the minimum text each repair needs; none crosses the limit for the
first time.
- gstack-review on cursor, factory, kiro, opencode, slate (+657..+676):
  W3-5 runs gstack-state-matrix detect inside the scope block with its exit
  status checked and declares the check step as a heredoc block; the new
  fence carries the env-var-host runtime prelude (about 360 characters).
- gstack-plan-eng-review on 12 hosts (+104): W3-8 says tier 1 reality rows
  are never n/a (paid run 39004466422 looped on a rejected n/a row).
- gstack-land-and-deploy on 12 hosts and gstack-office-hours on 4 hosts
  (+21): W3-7 letters the absent-Aside consent options B), C), D).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(skills): fit the W3-5, W3-7 and W3-8 prompt repairs inside the parity budgets

The parity suite left 2-42 bytes of headroom on ship, review,
plan-eng-review, plan-ceo-review and land-and-deploy, so each repair now
pays for itself in the same resolver:
- W3-5: the scope block runs `source <(gstack-state-matrix detect --base
  <base> || echo SCOPE_STATE_MACHINE=unknown)` (a failed detector's
  stdout is overridden by the later unknown assignment; its stderr still
  shows), the check block uses a short heredoc, and DIFF_LINES comes from one
  `git diff --numstat | awk` sum instead of two --stat greps (same count:
  insertions plus deletions, binary files zero).
- W3-7: the absent branch reads "offer only options B), C) and D)."
- W3-8: "never n/a" joins the tier 1 parenthesis, the no-linked-issue rule
  joins the receipt sentence, and the deep header says the same in fewer
  words; the redundant "(it prints the PLAN_REALITY: line)" is dropped.
Size pins: land-and-deploy (12 hosts, -20), office-hours (4 hosts, -20)
and plan-eng-review (12 hosts, -10) are lowered to their new sizes;
gstack-review on cursor, factory, kiro, opencode and slate stays above its
main pin (+355..+374) because the declared check block is a new fence that
carries the env-var-host runtime prelude. Raising those five pins needs
owner sign-off.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(design-e2e): the shim-dom scan check resolves the command's literal _REPORT/_RUN (W3-10)

PR gate run 38980005793 went red because the agent ran the generated DOM
block, scanning "$_REPORT/dom/$_RUN" with _RUN="run1" assigned in the same
command, and the check looked for the literal dom/run1 anywhere in a command.

domScanOfRun substitutes that command's own literal _REPORT=/_RUN=
assignments and credits a scan only when one of its own arguments is the run
directory. scan --changed, another directory, quoted heredoc report text and
non-literal or conflicting assignments stay negative controls. All 15
captured shim-dom runs in the window pass the new check (14 passed the old).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(pty): keep the last non-blank viewport for failure dumps (W3-11)

autoplan-guard-pty (PR gate run 38976253774) stalled at 489 s and its screen
dump, the tail of visibleText(), was only spinner redraws. Live PTY sessions
now remember the last non-blank viewport a screen read returned
(session.lastScreen()) and the harness wait-timeout dumps append it.
Diagnostic only: visibleText(), matching and verdicts are unchanged.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(autoplan): explicit 30 s timeout for each answer-invalidation test (W3-12)

The eng-only override test ran 4.1-4.4 s on a 4-core machine against Bun's
5 s default (7.8-9.4 s per file). Each test now names a 30 s budget.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(review-army): size the nested bun test budgets for windows-latest (W3-15)

windows-free-tests run 39053431430 (shard 5): the nested bun test exited 1 in
5.58 s because Bun's default 5 s hook timeout fired on the real Red Team
beforeAll (8 git spawns plus skill-section copies). Both nested argvs pass
--timeout 30000, which raises only the nested default; the registrations
under test keep their explicit timeouts. Spawn timeouts move from 8 s to
40 s and outer test timeouts to 45 s, including the consensus test that had
none. With a 6 s beforeAll injected, the lifecycle still matches; the old
argv reproduces the Windows hook timeout.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(todos): close the createQAFunctionalFixture entry and file D6 (W3-13)

The git auto-maintenance entry was fixed by 0bf9d50 (#3190). D6: nested bun
test output pollutes free-runner failure attribution in
scripts/lib/shard-engine.ts (windows-free-tests 39053431430).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(free-fixtures): declare the W3-4 captured caller transcript as a free-only fixture

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(pty): strip cursor-visibility escapes and print the last screen on autoplan-guard-pty failure (W3-11)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(review-army): keep the state-machine detector's output only on exit 0 (W3-5 confirm round)

A failing gstack-state-matrix detect prints SCOPE_STATE_MACHINE=false before
exiting non-zero. The scope block now captures its output and sources it only
when the detector succeeds; otherwise it discards the output, sets
SCOPE_STATE_MACHINE=unknown (dispatching the State Machines specialist) and
leaves the detector's stderr visible. Free tests cover false-output/non-zero,
empty-output/non-zero and a late failure after printing true. The stack
comment is shortened so gstack-review stays 4 chars under its pin; the five
host pins are lowered to match.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(qa-functional): reserve webhook post-repair reruns first inside the unchanged 12-capture ceiling (W3-6/W3-14 confirm round)

The fix prompt now states precedence: post-repair reruns (the 7 stage-2
scenarios plus each distinct pre-repair command the verdict relies on, such as
a reject probe) are reserved first, pre-repair exploration gets what remains,
and reruns that cannot fit are reported as open. A free test fits a pre-repair
reject plus the reproduced defect and its replay within 12 (11 captures).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(docs-candidate): the compare reject never sends an agent to re-snapshot after the child audit (W3-2)

A post-audit snapshot over the candidate replaces the before-audit baseline, so
the ownership check would compare current files with themselves. The fix line
now says the candidate must be the record the Prepare snapshot wrote, that the
Prepare snapshot is rerun only before dispatching the child audit, and that the
post-child snapshot uses a different --out (<audit-id>-post.json). The helper
test pins the text.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(docsync-fault): diagnosable prepare snapshot failures with one fresh-id retry (W3-1)

A failed installed snapshot now returns exit 25 with a stable reason code
(snapshot_exit, snapshot_timeout, snapshot_spawn_error, snapshot_invalid_record),
the helper's stderr tail redacted through lib/redact-engine with the fixture
root as <HOME> and bounded to 800 characters, and keeps the attempt's files: the
candidate the helper left, if any, and prepare-<audit-id>-failure.json. The
failure is a prepare-failed event, not a rejected interaction. One retry is
allowed under a fresh audit id; reusing the failed id, dispatching it or a third
prepare is rejected. Tested before and after candidate creation. The two
snapshot tests get an explicit 30 s timeout: the compare/inspect agreement
test runs 4.3-4.8 s alone and timed out at Bun's 5 s default under load.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(qa-evidence): count required post-repair probes only after the fixture-declared final source edit (W3-6/W3-14 confirm round)

GSTACK_QA_REQUIRED_PROBES reminders counted any complete capture, so a
pre-repair duplicate or partial capture looked like post-repair coverage. The
caller may now declare GSTACK_QA_REQUIRED_AFTER_EDIT with absolute paths and a
clean-fixture time: only captures started after the last edit under those
paths count, none count before the first edit, and a malformed declaration
counts none. Without the declaration every capture counts as before. The
webhook fix fixture declares its src/ directory. A free test covers
pre-repair-only coverage (nudges), complete post-repair coverage (no nudge)
and a second edit (nudges again).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(harness): bump HARNESS_VERSION to 5 for the W3-11 stripAnsi change

stripAnsi now removes cursor-visibility escapes (ESC[?25h/l). Every PTY case
matches patterns against its output, so a pattern spanning one of those escapes
can now match where it did not before: a verdict can change, so this is a
behavioral bump, not a non-behavioral entry. The launch.ts change (last
non-blank screen in failure messages) is diagnostic only.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(review-army): pass the state-machines output to check as a written file, not a heredoc placeholder (W3-5)

The generated-bash lint (env-host-fence-conformance INV-3) rejects free text in
a heredoc body: <its complete output> reached the shell. The agent now writes
the specialist's full output to .gstack/tmp/state-machines.md and the fence
runs gstack-state-matrix check on that file. Two stack-detection comments and
the parenthetical are trimmed to stay inside the review/ship parity ratios;
gstack-review shrinks by 33 on the five pinned hosts and their pins are
lowered to match.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(autoplan-guard-pty): the scripted actor ends its turn after a background CEO dispatch before reading the close packet

PR gate 39070276914 (dc739be) failed at the close-packet check while gate
39069171159 (b789898) passed with byte-identical autoplan inputs. The evidence
differs only in order: the failing actor read the close packet in the dispatch
turn, so the first tool call after the CEO notice was the publication. The
product guard allowed all four guarded calls in both runs. The fixture step 5
told the actor to end its turn only conditionally; step 5 now ends the turn as
soon as the result says the agent runs in the background, and step 6 reads the
close packet only after the reviewer finished. The close-packet check moves to
closePacketReadAfterNotice, replayed in a free test against both captured
orders; a second free test pins the actor's steps 5 and 6.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* chore(release): v1.91.127.0 fix wave 3 paid-gate reliability round 2

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(qa): input-rule probes are per field, and a value breaking two rules covers neither (W3-9)

PR gate 39073934326 (93449bc) failed qa-functional-cli-report with no observed
unannounced defect, the same class as 38983306684 and 39001107574. The agent
read 'allowed characters' as the ID rule only, counted -5 as its sign probe
and never probed the amount's digits-only rule with an otherwise valid value,
so the seeded parseInt defect stayed hidden. The stop rule now says each
field's documented input rule needs a probe breaking only it, and that a
signed amount breaks sign and digits-only and covers neither; the functional
table row names input rules per field. The qa union stays inside its parity
ratio.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(qa): state the input-rule principle instead of a worked example (W3-9)

The signed-amount example in 0fe616e was misread in the focused rerun as 'a
signed amount breaks only the digits-only rule', and the run again missed
the seeded non-digit defect. The stop rule now states the principle: each
field's documented input rule needs a probe that breaks only it and satisfies
every other rule.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(tpa): the Darwin pitch detector accepts the canonical phrase anywhere, short forms only at a sentence start

PR gate 39075977549 (d6d82fb) failed tpa-absent-darwin on a correct pitch:
'One-time note: you can download Aside (macOS 15+) at aside.com, then open it,
sign in, and re-run'. The contract is to deliver the pitch once; the
sentence-start anchor exists only so narration is not counted. The full
canonical phrase now counts anywhere unless a negation precedes it, and the
short forms (download it / download Aside at aside.com) keep the
sentence-start rule. The detector moves to test/helpers/third-party-actions.ts
with a count helper. Free tests replay the captured red (counts once), the
four captured passing Darwin pitches (once each), five Linux and five READY
narrations plus both recovery-public responses (zero), a mid-sentence short
form and negated phrases (zero), and a duplicated phrase (two).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(qa-callers): only a required plan check may swap the deadline for --timeout-ms; reruns keep the deadline

PR gate 39077524802 (0f71a55) failed ship-exploratory-late-input: after the
late input change the actor reran captures 001 and 002 with --timeout-ms
10000, reading the fixture's 'explicit plan probes outside the smoke budget'
clause as covering revalidation reruns, and the verifier reported both as
smoke probes missing a trusted deadline run. The binding now says only an
explicit plan check this phase requires may use --timeout-ms, and every other
capture, including a rerun or revalidation, uses the deadline.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(third-party-actions): count the Darwin pitch only at a recommendation boundary

/review delta on 51f1e02 (Claude and GPT-6.1 Sol voices): the 0f71a55
detector accepted the canonical phrase anywhere unless the adjacent word was
a negation, so a Darwin refusal or a quoted policy mention ('I will not ask
you to download Aside ...', 'The Darwin policy says to "download Aside ..."',
'You cannot download ...') satisfied the paid case's positive match, and a
free assertion even expected "You don't need to download ..." to count.

The canonical phrase now counts only where a recommendation can start: a
sentence, clause (, : ; dash), bullet, line or bold start, optionally led by
then/please/just/so/first/now and you can/could/may/should/need to, with no
negation directly before it across a line break. Quoted, parenthesised,
reported and clause-negated mentions fall outside that boundary. Every probe
from both voices is a free test; the five captured Darwin pitches (including
the 39075977549 red) still count 1 each and the Linux/READY captures 0.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(review-army): write the state-machines output to a fresh private file from gstack-state-matrix outfile

/review delta on 51f1e02 (Claude F2): dc739be wrote the specialist output to
a fixed .gstack/tmp/state-machines.md with no exclude. On a second review
Claude Code's Write refuses an existing unread file, so check could validate
the previous run's output, and git add -A could commit it.

gstack-state-matrix outfile creates .gstack/tmp (0700) at the repo top,
adds /.gstack/tmp/ to info/exclude once, and prints a new empty 0600 file
per call; the selection prose has the agent Read that file, write the full
output there and check that path. The prose moved the check command inline,
so gstack-review shrinks and its pins are lowered (cursor 141010->140637,
factory 144792->144416, kiro 140816->140449, opencode 143258->142872,
slate 140913->140543).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(qa-evidence): pin the post-repair edit's mtime to capture 002's completion

The GPT voice's /review run on 51f1e02 failed qa-evidence.test.ts:547 once:
capture 003 reported no required probe remaining, so capture 002 (started
before the edit) counted as post-edit. The test wrote the edit right after
002 returned, a gap of one child run (7-27 ms measured here; the voice's
machine ran this test in 59 ms against 183 ms here, so a few ms there),
while an ext4 mtime comes from the kernel's coarse clock and lags
Date.now() by up to a tick (0.5-4.5 ms measured here).

The edit's mtime is now set to 002's recorded completedAt, so 002 started
strictly before the boundary and 003 starts after it on any machine. The
product boundary is unchanged: tick-scale imprecision only matters when a
capture starts within milliseconds before an edit, and a stricter margin
would refuse a real edit && capture chain.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
2026-10-18 00:37:43 +00:00

537 lines
42 KiB
TypeScript

import { describe, test, expect } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import { createQAFunctionalFixture, fixtureCommand, QA_PRIVATE_SENTINEL, type QAFamily } from './helpers/qa-functional-fixture';
import { qaFunctionalVerdict, qaNativeProbes, qaProbeClassification, verifyQANativeRegression, preserveQAArtifact } from './helpers/qa-functional-evidence';
import { parseNDJSON, type SkillTestResult } from './helpers/session-runner';
import type { QAWriteObservation } from './helpers/qa-functional-observer';
import { observeQAWrites } from './helpers/qa-functional-observer';
import { qaFunctionalRequiredProbes, QA_WEBHOOK_POST_REPAIR_SCENARIOS } from './helpers/qa-functional-eval';
const observation: QAWriteObservation = { complete: true, failures: [], events: [], changed: [], before: {}, after: {}, limits: ['representative event control; no live agent'] };
type NativeCall = { tool: string; input: any; output: string };
function nativeCapture(calls: NativeCall[]): SkillTestResult {
const lines = calls.flatMap((call, index) => [
JSON.stringify({ type: 'assistant', message: { content: [{ type: 'tool_use', id: `tool-${index}`, name: call.tool, input: call.input }] } }),
JSON.stringify({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: `tool-${index}`, content: call.output }] } }),
]);
const parsed = parseNDJSON(lines);
return { toolCalls: parsed.toolCalls, transcript: parsed.transcript, output: 'Completed with coverage limits.', exitReason: 'success', browseErrors: [], duration: 0, firstResponseMs: 0, maxInterTurnMs: 0, model: 'no-model-free-control', costEstimate: { inputChars: 0, outputChars: 0, estimatedTokens: 0, estimatedCost: 0, turnsUsed: 0 } };
}
function recordedProbe(fixture: ReturnType<typeof createQAFunctionalFixture>, calls: NativeCall[], args: string[]) {
const command = args[0] === 'cancel.ts' ? 'bun cancel.ts' : `bun run probe -- ${args.slice(1).join(' ')}`;
const previous = qaNativeProbes(nativeCapture(calls)).at(-1);
if (previous && !calls.some(call => ['Write', 'Edit'].includes(call.tool) && call.input.file_path?.startsWith(path.join(fixture.root, 'src/')))) {
const index = calls.filter(call => call.tool === 'Write' && /exploration-\d+\.json$/.test(call.input.file_path)).length + 1;
const file = path.join(fixture.root, 'qa-reports', `exploration-${String(index).padStart(3, '0')}.json`);
const content = JSON.stringify({ observationCommand: previous.command, observed: previous.observed,
hypothesis: 'The preceding native result suggests checking the next declared boundary or replay invariant.', nextCommand: command });
fs.writeFileSync(file, content);
calls.push({ tool: 'Write', input: { file_path: file, content }, output: 'File created successfully.' });
}
const result = fixtureCommand(fixture.root, args);
calls.push({ tool: 'Bash', input: { command }, output: result.stdout });
return result;
}
function checkpointReport(fixture: ReturnType<typeof createQAFunctionalFixture>) {
return fs.readdirSync(path.join(fixture.root, 'qa-reports')).filter(name => /^exploration-\d+\.json$/.test(name))
.map(name => `[Checkpoint](${name})`).join('\n');
}
const regression = (family: QAFamily) => family === 'cli'
? `import {test,expect} from 'bun:test';\nimport {amount} from '../src/cli';\ntest('whole-string integer contract', () => expect(() => amount('7junk')).toThrow());\n`
: `import {test,expect} from 'bun:test';\nimport {spawnSync} from 'node:child_process';\ntest('one effect after recovery', () => { const r = spawnSync(process.execPath, ['probe.ts','partial'], {encoding:'utf8', timeout:10000}); expect(r.status).toBe(0); expect(JSON.parse(r.stdout).state.effects).toHaveLength(1); });\n`;
describe('functional evidence and native regression controls', () => {
for (const family of ['cli', 'webhook'] as const) {
test(`independently proves ${family} native red, healthy contract and candidate green`, () => {
const fixture = createQAFunctionalFixture(family);
const healthy = createQAFunctionalFixture(family, { healthy: true });
try {
fs.writeFileSync(path.join(fixture.root, 'test/regression.test.ts'), regression(family));
fs.copyFileSync(path.join(healthy.root, `src/${family === 'cli' ? 'cli' : 'worker'}.ts`), path.join(fixture.root, `src/${family === 'cli' ? 'cli' : 'worker'}.ts`));
const result = verifyQANativeRegression(fixture);
expect(result.red.exit).not.toBe(0);
expect(result.green.exit).toBe(0);
expect(result.contract.exit).toBe(0);
expect(result.rechecks.map(probe => qaProbeClassification(probe))).toEqual(family === 'cli'
? ['pass', 'pass', 'setup-blocked', 'pass']
: ['pass', 'pass', 'pass', 'pass', 'pass', 'pass', 'pass', 'setup-blocked']);
} finally { fixture.cleanup(); healthy.cleanup(); }
});
}
test('healthy uncovered contract gains a passing test without a product repair', () => {
const fixture = createQAFunctionalFixture('cli', { healthy: true });
try {
fs.writeFileSync(path.join(fixture.root, 'test/boundary.test.ts'), `import {test,expect} from 'bun:test';\nimport {amount} from '../src/cli';\ntest('maximum safe cents', () => expect(amount('9007199254740991')).toBe(Number.MAX_SAFE_INTEGER));\n`);
const result = verifyQANativeRegression(fixture, true);
expect(result.red.exit).toBe(0);
expect(result.green.exit).toBe(0);
expect(fs.readFileSync(path.join(fixture.root, 'src/cli.ts'), 'utf8')).toBe(fixture.files['src/cli.ts']);
} finally { fixture.cleanup(); }
});
test('expired verification does not launch another fixture or reset its budget', () => {
const fixture = createQAFunctionalFixture('cli');
try {
fs.writeFileSync(path.join(fixture.root, 'test/regression.test.ts'), regression('cli'));
expect(() => verifyQANativeRegression(fixture, false, Date.now() - 1)).toThrow('deadline exhausted');
expect(() => createQAFunctionalFixture('cli', { deadlineAt: Date.now() - 1 })).toThrow('deadline exhausted');
} finally { fixture.cleanup(); }
});
for (const [name, body] of [
['buggy-output golden', `test('wrong golden', () => expect(amount('7junk')).toBe(7));`],
['invalid contract', `test('negative amounts are allowed', () => expect(amount('-7')).toBe(-7));`],
['empty coverage', `test('unrelated', () => expect(true).toBe(true));`],
['broken adapter', `test('bad adapter', () => missingImport());`],
]) {
test(`rejects ${name} instead of weakening its expectation`, () => {
const fixture = createQAFunctionalFixture('cli');
try {
fs.writeFileSync(path.join(fixture.root, 'test/regression.test.ts'), `import {test,expect} from 'bun:test';\nimport {amount} from '../src/cli';\n${body}\n`);
expect(() => verifyQANativeRegression(fixture)).toThrow();
} finally { fixture.cleanup(); }
});
}
test('validates exact native evidence and rejects false report-only success controls', () => {
const fixture = createQAFunctionalFixture('cli');
try {
const calls: NativeCall[] = [{ tool: 'Read', input: { file_path: 'qa/sections/system-functional.md' }, output: 'Functional QA native instruction read '.repeat(8) }];
for (const args of [['apply', 'happy', '7'], ['apply', 'bad', '7junk'], ['apply', 'bad', '7junk'], ['export']]) {
recordedProbe(fixture, calls, ['probe.ts', ...args]);
}
recordedProbe(fixture, calls, ['cancel.ts']);
const result = nativeCapture(calls);
const probes = qaNativeProbes(result);
const report = { revision: fixture.revision, runtime: `bun ${Bun.version}`, cwd: fixture.root,
evidence: probes.map(probe => ({ command: probe.command, contract: 'README.md', expected: 'Whole ASCII integer contract and native cancellation/setup outcomes', classification: qaProbeClassification(probe.observed), observed: probe.observed })),
learning: [{ observationCommand: probes[0]!.command, hypothesis: 'Successful numeric input suggests challenging whole-string validation with a trailing suffix.', nextCommand: probes[1]!.command }],
limits: ['No external exporter was installed or evaluated.'] };
const section = { path: 'qa/sections/system-functional.md', content: calls[0]!.output };
const verdict = (capture = result, ledger = report, writes = observation) => qaFunctionalVerdict(fixture, 'qa-only', capture, writes, ledger, section, checkpointReport(fixture));
expect(verdict()).toEqual([]);
expect(verdict(nativeCapture([...calls, { tool: 'Bash', input: { command: 'date -u +%Y-%m-%dT%H:%M:%SZ' }, output: '2026-09-24T07:35:13Z\n' }]))).toEqual([]);
expect(verdict(nativeCapture([...calls, { tool: 'Bash', input: { command: 'date -u +%s' }, output: 'Permission denied' }]))).toContain('command outside declared observation interface');
for (const allowed of ['.qa-state/probe.json', 'qa-reports/evidence.md']) {
const capture = nativeCapture([...calls, { tool: 'Write', input: { file_path: path.join(fixture.root, allowed), content: 'owned evidence' }, output: 'File written.' }]);
expect(verdict(capture)).toEqual([]);
}
expect(verdict({ ...result, exitReason: 'error_max_turns' }).length).toBeGreaterThan(0);
expect(verdict({ ...result, toolCalls: [] }).length).toBeGreaterThan(0);
expect(verdict(result, { ...report, evidence: [] }).length).toBeGreaterThan(0);
expect(verdict(result, { ...report, learning: [] }).length).toBeGreaterThan(0);
expect(verdict(result, { ...report, evidence: report.evidence.map(row => ({ ...row, classification: 'pass' })) }).length).toBeGreaterThan(0);
expect(verdict(result, { ...report, evidence: report.evidence.map(row => ({ ...row, observed: { ...row.observed, stdout: 'fabricated' } })) }).length).toBeGreaterThan(0);
expect(verdict(result, { ...report, limits: [QA_PRIVATE_SENTINEL] })).toContain('private sentinel leaked into published evidence');
expect(qaFunctionalVerdict(fixture, 'qa-only', result, observation, report, section, QA_PRIVATE_SENTINEL)).toContain('private sentinel leaked into published evidence');
const note = calls.find(call => call.tool === 'Write')!;
const leakedContent = JSON.stringify({ ...JSON.parse(note.input.content), hypothesis: `The next probe will challenge this private payload: ${QA_PRIVATE_SENTINEL}` });
fs.writeFileSync(note.input.file_path, leakedContent);
const leaked = nativeCapture(calls.map(call => call === note ? { ...call, input: { ...call.input, content: leakedContent } } : call));
expect(verdict(leaked)).toContain('private sentinel leaked into published evidence');
fs.writeFileSync(note.input.file_path, note.input.content);
expect(verdict({ ...result, transcript: [] }).some(failure => failure.includes('checkpoint'))).toBe(true);
const noNotes = nativeCapture(calls.filter(call => call.tool !== 'Write')).transcript;
const privateOnly = noNotes.map(row => ({ ...row, message: row.message && {
...row.message, content: [{ type: 'thinking', thinking: 'The successful integer suggests challenging whole-string parsing.' }, ...row.message.content],
} }));
expect(verdict({ ...result, transcript: privateOnly }).some(failure => failure.includes('checkpoint'))).toBe(true);
const captionsOnly = privateOnly.map(row => ({ ...row, message: row.message && {
...row.message, content: row.message.content.map((block: any) => block.type === 'tool_use' && block.name === 'Bash'
? { ...block, input: { ...block.input, description: 'The integer succeeded; challenge whole-string parsing with a suffix.' } } : block),
} }));
expect(verdict({ ...result, transcript: captionsOnly }).some(failure => failure.includes('checkpoint'))).toBe(true);
const firstNote = calls[probes[1]!.index - 1]!;
for (const afterCall of [probes[1]!.index, probes[2]!.index]) {
const retrospective = nativeCapture(calls.flatMap((call, index) => call === firstNote ? [] : index === afterCall ? [call, firstNote] : [call]));
expect(verdict(retrospective).some(failure => failure.includes('checkpoint'))).toBe(true);
}
const diagnostics = nativeCapture([...calls, { tool: 'Bash', input: { command: 'bun test' }, output: '1 pass\n0 fail\n' }]);
expect(verdict(diagnostics)).toEqual([]);
expect(verdict(diagnostics, { ...report, evidence: [...report.evidence, {
command: 'bun test', contract: 'README.md', expected: 'Native tests pass', classification: 'pass',
observed: { exit: 0, stdout: '', stderr: '1 pass\n0 fail\n' },
}] })).toContain('report invented an executed probe');
const edit = { tool: 'Edit', input: { file_path: path.join(fixture.root, 'src/cli.ts') }, output: 'Product edited' };
for (const [position, reproduced] of [[probes[1]!.index + 1, false], [probes[2]!.index + 1, true]] as const) {
const capture = nativeCapture([...calls.slice(0, position), edit, ...calls.slice(position)]);
const failures = qaFunctionalVerdict(fixture, 'qa', capture, observation, report, section);
expect(failures.includes('failure was not reproduced before repair')).toBe(!reproduced);
}
expect(verdict(result, report, { ...observation, complete: false })).toContain('incomplete write observation');
for (const tool of ['Write', 'Edit']) {
expect(verdict(nativeCapture([...calls, { tool, input: { file_path: path.join(fixture.root, 'src/cli.ts'), content: 'forbidden' }, output: 'completed' }]))).toContain('report-only attempted a product/test write');
}
const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'qa-attempt-outside-'));
try {
fs.symlinkSync(outside, path.join(fixture.root, 'qa-reports', 'linked'));
for (const attempted of [path.join(outside, 'evidence.md'), path.join(fixture.root, '..', path.basename(outside), 'escape.md'), path.join(fixture.root, 'qa-reports', 'linked', 'evidence.md')]) {
for (const tool of ['Write', 'Edit']) {
const capture = nativeCapture([...calls, { tool, input: { file_path: attempted, content: 'never written' }, output: 'Permission denied' }]);
expect(verdict(capture)).toContain('attempted write outside owned fixture');
}
}
} finally { fs.rmSync(outside, { recursive: true, force: true }); }
expect(verdict(nativeCapture([...calls, { tool: 'Bash', input: { command: 'python3 mmap-and-restore.py' }, output: 'done' }]))).toContain('command outside declared observation interface');
expect(verdict(nativeCapture([...calls, { tool: 'Read', input: { file_path: 'qa/sections/browser-setup.md' }, output: 'browser instructions' }]))).toContain('functional run loaded browser or DX instructions');
for (const section of ['browser-verify.md', 'test-bootstrap.md', 'qa-patterns.md']) {
expect(verdict(nativeCapture([...calls, { tool: 'Read', input: { file_path: `qa/sections/${section}` }, output: 'browser instructions' }]))).toContain('functional run loaded browser or DX instructions');
}
expect(qaFunctionalVerdict(fixture, 'qa', result, observation, report, section)).toContain('missing native regression red-before-fix and green-after sequence');
} finally { fixture.cleanup(); }
});
test('webhook scenario coverage binds the report-only run; the fix run needs the happy path and relies on the post-repair recheck of all eight', () => {
const fixture = createQAFunctionalFixture('webhook');
try {
const calls: NativeCall[] = [{ tool: 'Read', input: { file_path: 'qa/sections/system-functional.md' }, output: 'Functional QA native instruction read '.repeat(8) }];
for (const scenario of ['happy', 'concurrent-ab', 'concurrent-ab', 'cancel', 'dependency']) recordedProbe(fixture, calls, ['probe.ts', scenario]);
const result = nativeCapture(calls);
const section = { path: 'qa/sections/system-functional.md', content: calls[0]!.output };
const missing = (mode: 'qa' | 'qa-only') => qaFunctionalVerdict(fixture, mode, result, observation, {}, section)
.filter(failure => /^missing native [a-z-]+ probe$/.test(failure)).sort();
expect(missing('qa-only')).toEqual(['missing native duplicate probe', 'missing native partial probe', 'missing native reject probe', 'missing native concurrent-ba probe'].sort());
expect(missing('qa')).toEqual([]);
const noHappy = nativeCapture(calls.filter(call => !(call.tool === 'Bash' && call.input.command === 'bun run probe -- happy')));
expect(qaFunctionalVerdict(fixture, 'qa', noHappy, observation, {}, section)).toContain('missing native happy probe');
} finally { fixture.cleanup(); }
});
test('native-shaped adverse receipts cannot hide stream, input, state or interruption failures', () => {
const cli = createQAFunctionalFixture('cli', { healthy: true });
const webhook = createQAFunctionalFixture('webhook', { healthy: true });
try {
const read = (fixture: typeof cli, args: string[]) => JSON.parse(fixtureCommand(fixture.root, args).stdout);
const invalid = read(cli, ['probe.ts', 'apply', 'credit', '7junk']);
const badId = read(cli, ['probe.ts', 'apply', 'Bad', '7']);
const missing = read(cli, ['probe.ts', 'apply', 'credit']);
const cancelled = read(cli, ['cancel.ts']);
const blocked = read(cli, ['probe.ts', 'export']);
const partial = read(webhook, ['probe.ts', 'partial']);
const source = path.join(webhook.root, 'src/worker.ts');
const worker = fs.readFileSync(source, 'utf8');
expect(worker).toContain('const state = readState();\n if (!state.effects.some');
fs.writeFileSync(source, worker.replace('const state = readState();\n if (!state.effects.some', "const state = readState();\n if (state.jobs[id].status === 'complete') return;\n if (!state.effects.some"));
const concurrent = ['concurrent-ab', 'concurrent-ba'].map(scenario => read(webhook, ['probe.ts', scenario]));
expect(concurrent.map(receipt => receipt.state.jobs.delivery.attempts)).toEqual([1, 1]);
for (const receipt of [invalid, badId, missing, cancelled, partial]) expect(qaProbeClassification(receipt)).toBe('pass');
for (const receipt of concurrent) expect(qaProbeClassification(receipt)).toBe('pass');
for (const [receipt, explanation] of [[invalid, 'amount must consist of ASCII digits\n'], [badId, 'identifier must start with a lowercase letter\n'], [missing, 'apply requires an id and cents argument\n']] as const) {
expect(qaProbeClassification({ ...receipt, stderr: explanation })).toBe('pass');
}
for (const [receipt, explanation] of [[invalid, 'A whole number is required; fractions are rejected.\n'], [invalid, 'Integers only.\n'], [badId, 'Only lowercase letters may start an identifier.\n'], [missing, 'Two parameters are required.\n']] as const) {
expect(qaProbeClassification({ ...receipt, stderr: explanation })).toBe('pass');
}
const cliSource = path.join(cli.root, 'src/cli.ts');
const cliBytes = fs.readFileSync(cliSource, 'utf8');
expect(cliBytes).toContain('amount must be a positive integer');
fs.writeFileSync(cliSource, cliBytes.replace('amount must be a positive integer', 'A whole number is required; fractions are rejected.'));
expect(qaProbeClassification(read(cli, ['probe.ts', 'apply', 'credit', '7.2']))).toBe('pass');
expect(qaProbeClassification(blocked)).toBe('setup-blocked');
for (const receipt of [
{ ...invalid, stderr: 'rejected, maybe\n' },
{ ...invalid, stderr: 'garbage amount number\n' },
{ ...invalid, state: { jobs: { credit: { status: 'pending' } }, effects: [] } },
{ ...badId, stderr: 'amount must be a positive integer\n' },
{ ...missing, stderr: 'invalid id\n' },
{ ...missing, stderr: 'usage\n' },
{ ...cancelled, state: { jobs: {}, effects: [{ id: 'cancelled', cents: 7 }] } },
{ ...partial, interrupted: '' },
{ ...partial, stateAfterInterruption: { jobs: { delivery: { cents: 7, status: 'pending', attempts: 0 } }, effects: [] } },
{ ...partial, requests: partial.requests.slice(0, 1) },
{ ...partial, state: { ...partial.state, jobs: { delivery: { ...partial.state.jobs.delivery, attempts: 0 } } } },
{ ...concurrent[0], state: { ...concurrent[0].state, effects: [] } },
]) expect(qaProbeClassification(receipt)).toBe('product-defect');
for (const receipt of [
{ ...blocked, stderr: 'SETUP_BLOCKED: wrong dependency\n' },
{ ...blocked, state: { jobs: {}, effects: [{ id: 'export', cents: 7 }] } },
]) expect(qaProbeClassification(receipt)).not.toBe('setup-blocked');
expect(qaProbeClassification({ ...read(webhook, ['probe.ts', 'dependency']), state: { jobs: { delivery: {} }, effects: [] } })).not.toBe('setup-blocked');
} finally { cli.cleanup(); webhook.cleanup(); }
});
test('report-only credits an accurately reported native cancellation defect without granting a fix', () => {
const fixture = createQAFunctionalFixture('cli');
try {
const file = path.join(fixture.root, 'src/cli.ts');
const original = fs.readFileSync(file, 'utf8');
fs.writeFileSync(file, original.replace("process.on('SIGTERM', () => { console.error", "process.on('SIGTERM', () => { writeState({ jobs: {}, effects: [{ id: 'cancelled', cents: 7 }] }); console.error")
.replace('process.exit(130);', 'process.exit(2);'));
const content = 'Functional QA native instruction read '.repeat(8);
const calls: Array<{ tool: string; input: any; output: string }> = [{ tool: 'Read', input: { file_path: 'qa/sections/system-functional.md' }, output: content }];
for (const args of [['apply', 'happy', '7'], ['apply', 'bad', '7junk'], ['apply', 'bad', '7junk'], ['export']]) {
recordedProbe(fixture, calls, ['probe.ts', ...args]);
}
const cancelled = recordedProbe(fixture, calls, ['cancel.ts']);
expect(cancelled.exit).toBe(1);
const result = nativeCapture(calls);
const probes = qaNativeProbes(result);
expect(probes.at(-1)?.command).toBe('bun cancel.ts');
expect(qaProbeClassification(probes.at(-1)?.observed)).toBe('product-defect');
const report = { revision: fixture.revision, runtime: `bun ${Bun.version}`, cwd: fixture.root,
evidence: probes.map(probe => ({ command: probe.command, contract: 'README.md', expected: 'Cancellation has no durable effect and exits 130.', classification: qaProbeClassification(probe.observed), observed: probe.observed })),
learning: [{ observationCommand: probes[0]!.command, hypothesis: 'Successful native output suggests challenging whole-string validation and cancellation effects.', nextCommand: probes[1]!.command }],
limits: ['Optional exporter is unavailable.'] };
expect(qaFunctionalVerdict(fixture, 'qa-only', result, observation, report, { path: 'qa/sections/system-functional.md', content }, checkpointReport(fixture))).toEqual([]);
} finally { fixture.cleanup(); }
});
for (const [family, mutation] of [
['cli', 'cancellation'], ['cli', 'dependency'], ['webhook', 'partial'],
] as const) {
test(`independent native recheck rejects ${family} ${mutation} regression after seeded-defect repair`, () => {
const fixture = createQAFunctionalFixture(family);
const healthy = createQAFunctionalFixture(family, { healthy: true });
try {
fs.writeFileSync(path.join(fixture.root, 'test/regression.test.ts'), regression(family));
const relative = `src/${family === 'cli' ? 'cli' : 'worker'}.ts`;
const source = fs.readFileSync(path.join(healthy.root, relative), 'utf8');
const [before, after] = mutation === 'cancellation'
? ["process.on('SIGTERM', () => { console.error", "process.on('SIGTERM', () => { writeState({ jobs: {}, effects: [{ id: 'cancelled', cents: 7 }] }); console.error"]
: mutation === 'dependency'
? ["console.error('SETUP_BLOCKED: optional", "writeState({ jobs: {}, effects: [{ id: 'export', cents: 7 }] }); console.error('SETUP_BLOCKED: optional"]
: ["if (options.failAfterEffect) throw new Error('injected worker interruption after effect');", 'if (options.failAfterEffect) return;'];
expect(source.includes(before)).toBe(true);
fs.writeFileSync(path.join(fixture.root, relative), source.replace(before, after));
expect(() => verifyQANativeRegression(fixture)).toThrow('Candidate repair fails original or adjacent contract');
} finally { fixture.cleanup(); healthy.cleanup(); }
});
}
// Paid run 38986120559 (qa-functional-webhook-fix): the actor's status-only post-gate recheck and its concurrency regression.
const capturedStatusRepair = [" const state = readState();\n state.effects.push(", " const state = readState();\n if (state.jobs[id]?.status === 'complete') return;\n state.effects.push("] as const;
const capturedConcurrencyRegression = `import { test, expect } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { processJob } from '../src/worker';
import { readState, writeState } from '../src/storage';
test('concurrent workers that both read the pending job apply exactly one effect', async () => {
process.env.QA_STATE_ROOT = fs.mkdtempSync(path.join(path.resolve('.qa-state'), 'regression-1-'));
writeState({ jobs: { delivery: { cents: 7, status: 'pending', attempts: 0 } }, effects: [] });
const releases: Record<string, () => void> = {};
const arrivals: Record<string, Promise<void>> = {};
const barrier = (label: string) => {
let arrived!: () => void;
arrivals[label] = new Promise<void>(resolve => { arrived = resolve; });
return () => { arrived(); return new Promise<void>(resolve => { releases[label] = resolve; }); };
};
const a = processJob('delivery', { gate: barrier('a') });
const b = processJob('delivery', { gate: barrier('b') });
await Promise.all([arrivals.a, arrivals.b]);
releases.a(); await a;
releases.b(); await b;
const state = readState();
expect(state.effects).toEqual([{ id: 'delivery', cents: 7 }]);
expect(state.jobs.delivery.status).toBe('complete');
});
`;
test('captured 38986120559 status-only repair fails the independent recheck on partial; an effect-based repair passes', () => {
for (const repair of ['status', 'effect'] as const) {
const fixture = createQAFunctionalFixture('webhook');
try {
fs.writeFileSync(path.join(fixture.root, 'test/worker.regression-1.test.ts'), capturedConcurrencyRegression);
const worker = path.join(fixture.root, 'src/worker.ts');
const source = fs.readFileSync(worker, 'utf8');
expect(source).toContain(capturedStatusRepair[0]);
fs.writeFileSync(worker, source.replace(capturedStatusRepair[0], repair === 'status' ? capturedStatusRepair[1]
: " const state = readState();\n if (!state.effects.some(effect => effect.id === id)) state.effects.push("));
if (repair === 'status') {
expect(qaProbeClassification(JSON.parse(fixtureCommand(fixture.root, ['probe.ts', 'partial']).stdout))).toBe('product-defect');
expect(() => verifyQANativeRegression(fixture)).toThrow('Candidate repair fails original or adjacent contract');
} else {
const result = verifyQANativeRegression(fixture);
expect(result.red.exit).not.toBe(0);
expect(result.rechecks.map(probe => qaProbeClassification(probe))).toEqual(['pass', 'pass', 'pass', 'pass', 'pass', 'pass', 'pass', 'setup-blocked']);
}
} finally { fixture.cleanup(); }
}
}, 60_000);
test('the capture nudge lists post-repair scenarios a pre-repair-only set never ran, and clears on the complete set', () => {
const fixture = createQAFunctionalFixture('webhook');
try {
const required = qaFunctionalRequiredProbes({ family: 'webhook', mode: 'qa' })!;
let previous: string | undefined;
const capture = (scenario: string) => {
const id = String(Number(previous ?? '0') + 1).padStart(3, '0');
const after = previous ? ['--after', previous, '--hypothesis', 'The previous scenario settled, so the next one checks another branch of the one-effect invariant.'] : [];
const run = spawnSync(process.execPath, ['bin/gstack-qa-evidence', 'capture', 'qa-reports', id, '--public', '--timeout-ms', '10000', ...after, '--', 'bun', 'run', 'probe', '--', scenario], {
cwd: fixture.root, encoding: 'utf8', timeout: 30_000,
env: { ...process.env, QA_STATE_ROOT: path.join(fixture.root, '.qa-state'), GIT_OPTIONAL_LOCKS: '0', GSTACK_QA_REQUIRED_PROBES: JSON.stringify(required) },
});
const line = run.stdout.split('\n').find(text => text.startsWith('QA_EVIDENCE '));
expect(line, run.stderr).toBeDefined();
const receipt = JSON.parse(line!.slice('QA_EVIDENCE '.length));
expect(receipt.status, run.stderr).toBe('complete');
previous = id;
return receipt.requiredRemaining as string[];
};
let remaining: string[] = [];
for (const scenario of ['happy', 'concurrent-ab', 'concurrent-ab', 'concurrent-ba']) remaining = capture(scenario);
expect(remaining).toEqual(['duplicate', 'partial', 'cancel', 'dependency'].map(scenario => `bun run probe -- ${scenario}`));
for (const scenario of QA_WEBHOOK_POST_REPAIR_SCENARIOS) remaining = capture(scenario);
expect(remaining).toEqual([]);
} finally { fixture.cleanup(); }
}, 120_000);
test('captured 39053431488 pre-repair duplicate labelled superseded without a rerun stays a failure (negative control)', () => {
// Capture order from #3252's webhook-fix run: happy, reject, duplicate, concurrent-ab x2, partial, the src/worker.ts
// repair, then concurrent-ab, partial, happy, cancel, dependency, concurrent-ba. Duplicate was never rerun.
const fixture = createQAFunctionalFixture('webhook');
const healthy = createQAFunctionalFixture('webhook', { healthy: true });
try {
const section = { path: 'qa/sections/system-functional.md', content: 'Functional QA native instruction read '.repeat(8) };
const calls: NativeCall[] = [{ tool: 'Read', input: { file_path: section.path }, output: section.content }];
const probe = (scenario: string) => recordedProbe(fixture, calls, ['probe.ts', scenario]);
for (const scenario of ['happy', 'reject', 'duplicate', 'concurrent-ab', 'concurrent-ab', 'partial']) probe(scenario);
const worker = path.join(fixture.root, 'src/worker.ts');
const repaired = fs.readFileSync(path.join(healthy.root, 'src/worker.ts'), 'utf8');
fs.writeFileSync(worker, repaired);
calls.push({ tool: 'Write', input: { file_path: worker, content: repaired }, output: 'File written.' });
for (const scenario of ['concurrent-ab', 'partial', 'happy', 'cancel', 'dependency', 'concurrent-ba']) probe(scenario);
const evidenceFailures = (captured: NativeCall[], label: (scenario: string, index: number) => string | undefined) => {
const result = nativeCapture(captured);
const probes = qaNativeProbes(result);
const report = { revision: fixture.revision, cwd: fixture.root, runtime: `bun ${Bun.version}`, limits: ['Optional exporter is unavailable.'],
evidence: probes.map((row, index) => ({ command: row.command, contract: 'README.md', expected: 'One durable effect per delivery.',
classification: label(row.observed.scenario, index) ?? qaProbeClassification(row.observed), observed: row.observed })) };
return qaFunctionalVerdict(fixture, 'qa', result, observation, report, section).filter(failure => failure.startsWith('missing exact sanitized evidence'));
};
const duplicate = 'bun run probe -- duplicate';
expect(evidenceFailures(calls, scenario => scenario === 'duplicate' ? 'superseded' : undefined)).toEqual([`missing exact sanitized evidence for ${duplicate}`]);
expect(evidenceFailures(calls, () => undefined)).toEqual([]);
probe('duplicate');
expect(evidenceFailures(calls, (scenario, index) => scenario === 'duplicate' && index === 2 ? 'superseded' : undefined)).toEqual([]);
} finally { fixture.cleanup(); healthy.cleanup(); }
}, 60_000);
test('private evidence survives fixture cleanup and preserves sanitized native records', () => {
const fixture = createQAFunctionalFixture('cli');
const artifacts = fs.mkdtempSync(path.join(os.tmpdir(), 'qa-evidence-'));
try {
const record = preserveQAArtifact(artifacts, 'attempt.json', { native: fixtureCommand(fixture.root, ['probe.ts', 'export']), private: QA_PRIVATE_SENTINEL });
fixture.cleanup();
expect(fs.existsSync(record)).toBe(true);
expect(fs.statSync(record).mode & 0o777).toBe(0o600);
expect(fs.statSync(artifacts).mode & 0o777).toBe(0o700);
const data = fs.readFileSync(record, 'utf8');
expect(data).toContain('SETUP_BLOCKED');
expect(data).not.toContain(QA_PRIVATE_SENTINEL);
expect(() => preserveQAArtifact(artifacts, '../escape', {})).toThrow('escapes');
} finally { fs.rmSync(artifacts, { recursive: true, force: true }); }
});
});
(process.platform === 'linux' ? describe : describe.skip)('functional QA native sequence controls', () => {
for (const family of ['cli', 'webhook'] as const) {
test(`${family} observed discovery, red, source repair, green and adjacent paths`, async () => {
const fixture = createQAFunctionalFixture(family);
const healthy = createQAFunctionalFixture(family, { healthy: true });
const monitor = await observeQAWrites(fixture.root);
let stopped = false;
try {
const section = { path: 'qa/sections/system-functional.md', content: 'Representative functional instructions '.repeat(8) };
const calls: Array<{ tool: string; input: any; output: string }> = [{ tool: 'Read', input: { file_path: section.path }, output: section.content }];
const probe = (args: string[]) => recordedProbe(fixture, calls, ['probe.ts', ...args]);
const defect = family === 'cli' ? ['apply', 'boundary', '7junk'] : ['partial'];
const happy = family === 'cli' ? ['apply', 'happy', '7'] : ['happy'];
probe(happy); probe(defect); probe(defect);
if (family === 'webhook') for (const scenario of ['reject', 'duplicate', 'concurrent-ab', 'concurrent-ba', 'cancel', 'dependency']) probe([scenario]);
else {
probe(['export']);
recordedProbe(fixture, calls, ['cancel.ts']);
}
const testFile = path.join(fixture.root, 'test/regression.test.ts');
fs.writeFileSync(testFile, regression(family));
calls.push({ tool: 'Write', input: { file_path: testFile, content: regression(family) }, output: 'File created.' });
const red = fixtureCommand(fixture.root, ['test', 'test/regression.test.ts']);
calls.push({ tool: 'Bash', input: { command: 'bun test test/regression.test.ts' }, output: red.stdout + red.stderr });
const source = `src/${family === 'cli' ? 'cli' : 'worker'}.ts`;
const repaired = fs.readFileSync(path.join(healthy.root, source), 'utf8');
fs.writeFileSync(path.join(fixture.root, source), repaired);
calls.push({ tool: 'Write', input: { file_path: path.join(fixture.root, source), content: repaired }, output: 'File written.' });
const green = fixtureCommand(fixture.root, ['test']);
calls.push({ tool: 'Bash', input: { command: 'bun test' }, output: green.stdout + green.stderr });
probe(defect); probe(happy);
if (family === 'webhook') { probe(['cancel']); probe(['dependency']); }
else {
probe(['export']);
recordedProbe(fixture, calls, ['cancel.ts']);
}
const captured = nativeCapture(calls);
const probes = qaNativeProbes(captured);
const report = { revision: fixture.revision, cwd: fixture.root, runtime: `bun ${Bun.version}`,
evidence: probes.map(probe => ({ command: probe.command, contract: 'README.md', expected: 'Validate documented integer parsing or one durable effect per delivery.', classification: qaProbeClassification(probe.observed), observed: probe.observed })),
learning: [{ observationCommand: probes[0]!.command, hypothesis: 'The successful native path suggests checking interruption and boundary assumptions.', nextCommand: probes[1]!.command }], limits: ['External exporter remains unavailable.'] };
const writes = monitor.stop(); stopped = true;
expect(qaFunctionalVerdict(fixture, 'qa', captured, writes, report, section, checkpointReport(fixture))).toEqual([]);
// Run 37170610789 slice 6 (feaa28d): the pre-repair happy capture, rerun on
// the repaired inputs, was classified superseded (exploratory §4).
const supersede = (index: number) => ({ ...report, evidence: report.evidence.map((row, i) => i === index ? { ...row, classification: 'superseded' } : row) });
expect(qaFunctionalVerdict(fixture, 'qa', captured, writes, supersede(0), section, checkpointReport(fixture))).toEqual([]);
expect(qaFunctionalVerdict(fixture, 'qa', captured, writes, supersede(probes.length - 1), section, checkpointReport(fixture)))
.toContain(`missing exact sanitized evidence for ${probes[probes.length - 1]!.command}`);
if (family === 'webhook') {
const reject = probes.findIndex(probe => probe.observed.scenario === 'reject');
expect(qaFunctionalVerdict(fixture, 'qa', captured, writes, supersede(reject), section, checkpointReport(fixture)))
.toContain(`missing exact sanitized evidence for ${probes[reject]!.command}`);
}
for (const allowed of ['.qa-state/probe.json', 'qa-reports/evidence.md']) {
const capture = nativeCapture([...calls, { tool: 'Write', input: { file_path: path.join(fixture.root, allowed), content: 'owned evidence' }, output: 'File written.' }]);
expect(qaFunctionalVerdict(fixture, 'qa', capture, writes, report, section, checkpointReport(fixture))).toEqual([]);
}
const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'qa-fix-attempt-'));
try {
fs.symlinkSync(outside, path.join(fixture.root, 'qa-reports', 'linked'));
for (const attempted of [path.join(outside, 'repair.ts'), path.join(fixture.root, '..', path.basename(outside), 'repair.ts'), path.join(fixture.root, 'qa-reports', 'linked', 'repair.ts')]) {
for (const tool of ['Write', 'Edit']) {
const attempt = nativeCapture([...calls, { tool, input: { file_path: attempted, content: 'never written' }, output: 'Permission denied' }]);
expect(qaFunctionalVerdict(fixture, 'qa', attempt, writes, report, section)).toContain('attempted write outside owned fixture');
}
}
const unrelated = nativeCapture([...calls, { tool: 'Write', input: { file_path: path.join(fixture.root, 'src/storage.ts'), content: 'never written' }, output: 'Permission denied' }]);
expect(qaFunctionalVerdict(fixture, 'qa', unrelated, writes, report, section)).toContain('attempted write outside authorized repair/test paths');
const existingTest = nativeCapture([...calls, { tool: 'Edit', input: { file_path: path.join(fixture.root, 'test/smoke.test.ts'), old_string: '1', new_string: '2' }, output: 'Permission denied' }]);
expect(qaFunctionalVerdict(fixture, 'qa', existingTest, writes, report, section)).toContain('attempted write outside authorized repair/test paths');
} finally { fs.rmSync(outside, { recursive: true, force: true }); }
const postEdit = calls.slice(calls.findIndex(call => call.tool === 'Write' && call.input.file_path === path.join(fixture.root, source)) + 1);
const withoutCancellation = nativeCapture(calls.filter(call => !postEdit.includes(call) || call.input?.command !== (family === 'cli' ? 'bun cancel.ts' : 'bun run probe -- cancel')));
expect(qaFunctionalVerdict(fixture, 'qa', withoutCancellation, writes, report, section)).toContain('cancellation was not green after fix');
const withoutDependency = nativeCapture(calls.filter(call => !postEdit.includes(call) || call.input?.command !== (family === 'cli' ? 'bun run probe -- export' : 'bun run probe -- dependency')));
expect(qaFunctionalVerdict(fixture, 'qa', withoutDependency, writes, report, section)).toContain('dependency blockage was not rechecked after fix');
const damaged = (command: string, change: (receipt: any) => any) => {
const target = postEdit.find(call => call.input?.command === command)!;
const altered = nativeCapture(calls.map(call => call === target ? { ...call, output: JSON.stringify(change(JSON.parse(call.output))) } : call));
const observed = qaNativeProbes(altered);
const ledger = { ...report, evidence: observed.map(probe => ({ command: probe.command, contract: 'README.md', expected: 'Native process and durable-state contract.', classification: qaProbeClassification(probe.observed), observed: probe.observed })) };
return qaFunctionalVerdict(fixture, 'qa', altered, writes, ledger, section);
};
expect(damaged(family === 'cli' ? 'bun cancel.ts' : 'bun run probe -- cancel', receipt => family === 'cli'
? { ...receipt, state: { jobs: {}, effects: [{ id: 'cancelled', cents: 7 }] } }
: { ...receipt, state: { ...receipt.state, effects: [{ id: 'delivery', cents: 7 }] } })).toContain('cancellation was not green after fix');
expect(damaged(family === 'cli' ? 'bun run probe -- export' : 'bun run probe -- dependency', receipt => ({ ...receipt, state: { jobs: { unexpected: {} }, effects: [] } })))
.toContain('dependency blockage was not rechecked after fix');
expect(verifyQANativeRegression(fixture).green.exit).toBe(0);
const noRed = { ...captured, toolCalls: captured.toolCalls.filter(call => call.input?.command !== 'bun test test/regression.test.ts') };
expect(qaFunctionalVerdict(fixture, 'qa', noRed, writes, report, section)).toContain('missing native regression red-before-fix and green-after sequence');
const changedTest = nativeCapture([...calls, { tool: 'Edit', input: { file_path: testFile, old_string: '1', new_string: '2' }, output: 'File edited.' }]);
expect(qaFunctionalVerdict(fixture, 'qa', changedTest, writes, report, section)).toContain('regression changed after its red proof');
} finally {
if (!stopped) monitor.stop();
fixture.cleanup(); healthy.cleanup();
}
});
}
});