mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-31 14:06:50 +01:00
* fix(autoplan): empty findings fences, repo-relative rows, PLAN_REALITY flags, pending/--all/provider (Lane B: B3 B6 B7 B8 B9 B10 B11)
B3 parseFences: the body group is optional (lazy), so an LF/CRLF empty fence is zero
findings in both the canonical and record grammars; opener without closer still
RESULT_FINDINGS_MISSING.
B6 plan-reality/3: item/section references are not quantities; backtick phrases are
exempt only from the plan-scope rule-phrase check (B-f); a measured number inside
backticks stays flagged in review scope. vaguePlanTerms() feeds an advisory
`flagged: PLAN_REALITY ...` line under the p1 approval item (never blocking).
B7 canonical rows: absolute repo paths become repo-relative; snapshot/active-plan
citations become the plan file name with the source line mapped (or dropped).
B8 `status` prints `PENDING: <id> phase=<p> voice=<v> result=<file>` per open attempt.
B9 `gstack-gate render --all`; paged output says to relay every page.
B10 `gstack-plan-reality check --plan <snapshot>`: a number in a "quoted" span copied
verbatim from the reviewed plan needs no receipt (reviewer scope only).
B11 submit defaults the provider to host-subagent when --runner is omitted.
Lane B files: lib/autoplan-reconcile.ts lib/plan-reality.ts lib/autoplan-gate.ts
lib/gate-list.ts lib/autoplan-plan-text.ts lib/autoplan-run.ts bin/gstack-gate
bin/gstack-plan-reality scripts/resolvers/plan-reality.ts autoplan/sections/ceo-phase.md
autoplan/sections/eng-phase.md test/plan-reality.test.ts test/autoplan-gate-artifacts.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(ubicloud): ubi-runner up/run -S accepts only Ubicloud's storage sizes, before any API call (A11)
Files: scripts/ubicloud/ubi-runner.sh, test/ubicloud-runner.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(issue-links): promotion candidates, Related PRs, validated flake issues, body/receipt consistency (Lane D: D1-D3)
D1: the GBRA-40 fix wave's gbrain #6279 body had no `## Issues` section and no
receipt (it was not composed by /ship, so gstack-issue-links never ran), and
#6252 appeared only as a subject parenthetical `(#6252)`, which the closure
rule correctly treats as Refs. The rule is kept. Same-repo references are now
printed as promotion candidates (`(promote: fix #N)`, `candidates` in --json),
and `gstack-ship-receipt write --issues ... --body` refuses a body that lacks a
line its issues object records (ISSUE_LINKS_MISSING), so a /ship body can no
longer drop its closing lines.
D2: open PRs by other authors whose closing set overlaps this PR's Fixes are
`Related: #N (@author)` (paged GraphQL closedByPullRequestsReferences; viewer
and this branch excluded; cross-repo PRs keep owner/repo#N). `Supersedes` and
`Contributed by` only with --supersedes/--credit; --no-auto-links skips the
lookup; the stderr preview names each added line's source. A failed lookup is
ISSUE_LOOKUP_FAILED (installer form with docs anchor) and keeps the other lines.
D3: a --ci-run match becomes a Flake line only for a bot-opened issue of this
repository that names that run (flake:json first_seen.run_id or this repo's
actions/runs URL) and a test; duplicates of one test keep the lowest number;
every refused match prints its reason.
Files: bin/gstack-issue-links, bin/gstack-ship-receipt, lib/issue-links.ts,
lib/ship-receipt.ts, lib/headless-artifacts.ts (ship-receipt issues.related),
lib/result-codes.ts (ISSUE_LOOKUP_FAILED, ISSUE_LINKS_MISSING,
resultLineWithDocs), bin/gstack-doctor-components.sh (regenerated),
docs/pregate.md, docs/troubleshooting.md, test/ship-issue-intent.test.ts,
test/helpers/pregate-fixture.ts (gh shim: repo view, api graphql, full issue rows).
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(ship): link issues by intent at publish and handoff; Fixes: trailer at commit (Lane D: D1, D2, D-a)
- Step 15: a commit fixing a user-named issue carries a `Fixes: #<n>` trailer
(offset by tightening Step 15 so the skeleton stays at 80,998 <= 81,000).
- pr-body: an explicit "Issue links" step runs gstack-issue-links before the
body is composed (previously only a placeholder inside the body template);
interactive runs ask once about `(promote: fix #N)` references and add
`--supersedes`/`--credit` only on the owner's confirmation; unattended runs
keep Refs and list unpromoted candidates, Related lines and lookup failures
in the completion message; `ISSUE_LINKS_MISSING` from the receipt write.
- handoff (no-PR lanes): runs gstack-issue-links and passes --issues to the
receipt; the completion message gains an `issues:` line.
- Regenerated ship/SKILL.md and sections; refreshed the four ship goldens.
- Parity: union 309,431 / 187,706 = 1.6485 (> 1.6450 by 655 bytes); maxSizeRatio
raised to the measured 1.6485 with its justification, as previous waves did.
Files: ship/SKILL.md.tmpl, ship/SKILL.md, ship/sections/pr-body.md.tmpl,
ship/sections/pr-body.md, ship/sections/handoff.md.tmpl, ship/sections/handoff.md,
test/fixtures/golden/{claude,codex,factory,agy}-ship-SKILL.md,
test/helpers/carve-guards.ts (ship maxSizeRatio).
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(install): one Bun resolution contract, versioned runtime store, verdict per (checkout, project), drift and wrapper rows (A1-A3, A5, A6, A8, A-c, A-d, A-f, A-h, A-i)
- bin/gstack-bun-version.sh: GSTACK_BUN_DEFAULT=1.4.3 beside the 1.4.2 floor,
gstack_bun_install_version (GSTACK_BUN_INSTALL_VERSION override),
gstack_bun_store, portable gstack_realpath, and gstack_bun_resolve (pin and
default in the store, $BUN_INSTALL/bin, ~/.bun/bin, PATH; first candidate
satisfying every pin; shim-marked files never returned). gstack_bun_launch_dir
is replaced by it.
- lib/pregate/runtime.ts: resolveBun, the TypeScript twin; launchRuntime runs
the Bun the install verdict recorded under the admission condition and
explains the skip otherwise.
- bin/gstack-capy-install: install and --check resolve through the contract;
verified archives publish atomically to <state root>/runtimes/bun/<v>/bun
under ~/.gstack-runtime.lock and ~/.bun/bin is never written; the "no Bun
satisfies" line names the candidates judged; --check reports
BUN_RESOLUTION_DRIFT with one converging fix.
- bin/gstack-install-verdict.sh, lib/install-verdict.ts: schema 2 verdicts
keyed by (checkout, project) with pin, bun_path, bun_version, bun_rule;
schema 1 path still read; admission binds test-running workflows to the
project and refuses a running Bun the verdict did not record.
- bin/gstack-doctor-check.sh, lib/doctor-components.ts: wrapper core row
(CAPY_WRAPPER_STALE by active provenance, WARN for stale Drive copies),
runtime drift row, shim note, install-version note.
- lib/result-codes.ts: BUN_RESOLUTION_DRIFT, BUN_INSTALL_VERSION_INVALID;
CAPY_WRAPPER_STALE fix names the workaround and the owner action.
Files: bin/gstack-bun-version.sh, bin/gstack-capy-install,
bin/gstack-doctor-check.sh, bin/gstack-doctor-components.sh (generated),
bin/gstack-install-verdict.sh, lib/doctor-components.ts,
lib/install-verdict.ts, lib/pregate/runtime.ts, lib/result-codes.ts,
test/bun-resolve.test.ts, test/gstack-capy-install.test.ts,
test/gstack-doctor.test.ts, test/install-verdict.test.ts,
test/pregate-guards.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(issue-links): --author for the Related lookup when gh runs as an app (Lane D: D2)
On a Capy machine the gh viewer is `capy-ai[bot]`, not the owner (checked live
against garrytan/gbrain #6252), so "other authors" needs the PR author named:
`--author <login>` overrides the viewer; the pr-body Issue links step says to
pass it when gh runs as an app.
Files: bin/gstack-issue-links, docs/pregate.md, ship/sections/pr-body.md.tmpl,
ship/sections/pr-body.md, test/ship-issue-intent.test.ts,
test/helpers/carve-guards.ts (ship maxSizeRatio re-measured: 309,483 / 187,706 = 1.6488).
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs(troubleshooting): BUN_RESOLUTION_DRIFT and BUN_INSTALL_VERSION_INVALID anchors; CAPY_WRAPPER_STALE covers the wrapper row (A5, A8, A-f, G1)
Files: docs/troubleshooting.md, bin/gstack-capy-install, bin/gstack-doctor-check.sh, test/gstack-capy-install.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* feat(install): marked per-directory bun and bunx shims for fresh Capy shells (A4, A-e)
gstack-capy-install (install mode, Capy machines only, GSTACK_BUN_SHIM=0 opts
out) writes ~/.local/bin/bun and bunx under ~/.gstack-runtime.lock. The shim
bakes the store, verdict directory, checkout and install default, walks up to
.git without spawning git, runs the Bun the (checkout, project) verdict
recorded, else a store Bun matching the .bun-version/package.json subset
(stderr names the --check to run when none matches), else the install
default, else the next unmarked bun on PATH. A foreign file or dangling link
is never touched. GSTACK_BUN_SHIM_EXPLAIN=1 prints project, record, choice and
rule; the doctor's runtime row shows the shim and its target.
Files: bin/gstack-capy-install, test/gstack-capy-install.test.ts, test/gstack-doctor.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): test stage never hangs silently; small machines record the remote gate (Lane C, GBRA-95)
C1 diagnosis (gbrain 92f0ea87, a core edit selecting 3,683 local files, 358
serial; Bun 1.4.2 and 1.4.3 identical): --timeout was applied per runner
spawn (unit group plus one per serial file), so the check was unbounded, and
spawnSync buffered all output until it returned: 360 s with 0 bytes on stdout
and stderr. A backgrounded child holding stdout made spawnSync wait the full
timeout and then report exit 0 (a silent wait, then green). Not the Bun 1.4.2
spawnSync hang.
C2/C-b: test-tier commands (lanes runner, guards, the --remote gate) run via
lib/pregate/supervise.ts: own process group (setsid), stdout/stderr appended
to a log file (no pipes), async supervision; CheckDef.run may return a
promise and runPregate/withFingerprint await it (a rejection is incomplete).
Leftover group members are killed after exit; SIGINT/SIGTERM to pregate
SIGKILLs running groups, writes no pregate.json, exits 130/143. Windows:
taskkill /T /F (reparented or detached descendants can survive; documented).
C3/C-a: --timeout bounds the whole check; groups past the deadline are not
started. --stall-timeout <s> (default stall_timeout_s, else 300; 0 disables)
kills a group whose log stops growing and records PREGATE_STALLED naming the
last file started. Live stderr: PREGATE_TEST per file (bun test adapter; any
runner for one-file runs), PREGATE_HEARTBEAT after 60 s without progress,
PREGATE: tests <verdict>. --json stdout unchanged.
C4/C-c: under 8 cores, a base-branch remote_gate or a non-local test_backend
records the local tier as a requires-remote obligation with its command
(pregate.json/remote_gate or test_backend/<backend>). --remote runs the
declared remote_gate now (needs --allow-repo-commands, never --policy-from
head) under --spend-cap/GSTACK_SPEND_CAP_USD; it clears only on
PREGATE_REMOTE: tree=<tested tree> tests>0 failed=0 with exit 0, and reports
spent/reserved/unknown.
G1: new code PREGATE_STALLED has its result-codes row, troubleshooting anchor
and the installer-form error line (CODE; url#anchor).
Files (G2): lib/pregate/supervise.ts (new), lib/pregate/types.ts,
lib/pregate/context.ts, lib/pregate/index.ts, lib/pregate/checks/lanes.ts,
lib/pregate/checks/guards.ts, lib/pregate/config.ts, lib/headless-artifacts.ts,
lib/result-codes.ts, bin/gstack-pregate, bin/gstack-doctor-components.sh
(generated), docs/pregate.md, docs/troubleshooting.md,
test/pregate-supervise.test.ts (new), test/pregate-remote.test.ts (new).
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs(ship): Step 5 pre-gate text for stalls and the small-machine remote gate (Lane C-c)
The pre-gate paragraph now says `incomplete` blocks (a stall is incomplete)
and that `requires-remote` covers the remote gate under 8 cores, cleared by
`gstack-pregate clear` or `--remote --spend-cap <usd>` only under a cap the
user gave. Kept within the ship parity size cap (union 308,771 of 308,776
bytes; base 308,767), so the `--explain` hint moved to docs/pregate.md. The
handoff's escalation line already names any `requires-remote` lane; unchanged.
Files (G2): ship/sections/tests.md.tmpl, ship/sections/tests.md (generated).
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(install): one ok-trailer grammar with requested, pins-skipped and latest notes; bootstrapper revision 2 exports origin's VERSION (A9, A-a)
Notes ride only on the ok trailer in fixed order; the failure head is
unchanged, pinned by a test that runs the Capy skill's dispatch examples
against real doctor output. The latest note comes only from
GSTACK_CAPY_REMOTE_VERSION, which the bootstrapper sets from a fetch in this
run and unsets otherwise (a stale FETCH_HEAD never reaches the installer).
Files: bin/gstack-capy-install, bin/gstack-capy-session,
capy/skill/gstack/scripts/install.sh, capy/skill/gstack/SKILL.md,
test/gstack-capy-install.test.ts, test/capy-skill-wrapper.test.ts,
test/gstack-doctor.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(upgrade): every success path certifies the caller's project; a pins failure keeps the move, ends on gstack: fail pins, exit 1, no pending marker (A7, A-b)
gstack-upgrade captures the caller's directory and git toplevel before any
cd. Already-current, fast-forwarded and resumed-pending paths run
bin/gstack-capy-install --project <it> on Capy (installing a verified pinned
Bun) or gstack-doctor --check --require runtime,pins elsewhere. The
reinstall's own trailer is held back when a project certification follows,
so no ok precedes a pins failure; a RUNTIME_PIN_CONFLICT stop becomes
gstack: fail pins — <conflict>. --check and --ff-only-no-reinstall certify
nothing.
Files: bin/gstack-upgrade, test/gstack-upgrade-bin.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(install): fresh-install log lines name the clone and every host installed (A10)
gstack-capy-install prints `cloned <repo> at <sha> (<version>)` for a checkout
it cloned, or one the bootstrapper (revision 2, GSTACK_CAPY_CLONED) cloned in
this run, instead of `reusing`. setup's final line is
`gstack ready (<hosts>)` from the same rows as its summary table, including
the --refresh-registered upgrade summary.
Files: bin/gstack-capy-install, bin/gstack-capy-session,
capy/skill/gstack/scripts/install.sh, setup, test/gstack-capy-install.test.ts,
test/host-conformance.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): --remote runs the gate only when local tests are selected (Lane C4)
With only platform lanes selected, --remote no longer launches the remote
gate with an empty file list; the existing no-local-lane path applies.
Files (G2): lib/pregate/checks/lanes.ts.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(autoplan): one-word rec, verified pairing, sealed attempt results, deferred reopen (Lane B: B1 B2 B4 B5)
B1/B-b/B-c `rec` (aliases: all, approve all, accept all, take all recommendations)
takes every recommendation, plan changes included; `as-is` keeps every
direction. The render offers `rec` first and prints what it resolves to
with gate_rev and rec_hash. `gstack-autoplan recommend` changes one
recommendation before relay (provenance recorded, p1 and decisions follow)
and bumps rec_rev, so a `rec` without the new --rec-hash is refused
(GATE_REC_STALE). An agent answer needs the owner's words verbatim
(--owner-reply <text>|-, --owner-reply-file; OWNER_REPLY_REQUIRED); a
parseable owner reply that resolves differently from the relay is refused
(GATE_OWNER_REPLY_MISMATCH). Supersedes field-wave R1 per the owner's
gate_rev 1 decision.
B2/B-a reconcile associates by title first; a file:line-only match is
`unverified` (associated, never confirmed). `b` is recommended only for a
confirmed pair with the same `changes` and one shared proposal (override)
or the same normalized remedy; the basis says which. Negative control and
positives copied from run-20261014225954 (test/fixtures/autoplan-pairing).
B4/B-e each attempt writes <phase>-<voice>.<attempt>.md; submit refuses another
attempt's file (ATTEMPT_MISMATCH) and binds a sealed 0444
<phase>-<voice>.<attempt>.bound.md copy, so a late write changes nothing
bound; reopen keeps sealed copies in place.
B5/B-d answer records accepted changes as amendments (status amend_pending) and
reopens nothing; revise reopens what changed. `revise --settle <id|d4>`
discharges a packaging/ordering change on an unchanged plan
(AMENDMENT_NOT_SETTLEABLE otherwise). APPLY/NEXT/status lines say which.
DRIVER.md and the reply table move to the rec grammar.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* feat(autoplan): durable checkpoint and resume --from; Capy checklist (Lane B: B12)
With GSTACK_AUTOPLAN_CHECKPOINT_DIR set, every command that leaves a run at
rest (gate_pending, amend_pending, complete, incomplete) publishes
<dir>/<run>/: checkpoint.json listing every file's sha256, the run under run/,
the owner's plan file under plan-input/ when it lives outside the run, and
restore.md as the human index. Publication swaps in a fully written sibling.
Checkpointing at every rest state, not only gate_pending, keeps accepted
decisions from rolling back on restore.
`gstack-autoplan resume --out <new dir> --from <checkpoint>` checks
containment (no absolute or .. paths, regular files only) and every hash
before publishing the run with one rename. It restores a missing plan file
into the run, journals `restored` with both hosts, and takes the lock.
CHECKPOINT_INVALID and CHECKPOINT_TARGET_EXISTS each get a result-codes row
and a troubleshooting anchor. Journal and revise staging paths are now
run-relative, so a moved run recovers.
DRIVER.md and the Capy skill's autoplan section get a short Capy checklist:
always drive gstack-autoplan, never present a hand review as an autoplan run,
relay every gate page with rec as the default, pass --owner-reply, and point
the checkpoint at the private project-user Drive folder.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* A-g: run the quick free tier on GSTACK_BUN_DEFAULT in CI; drift test pins it
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs(autoplan): unattended contract and reply-unparsed fix move to rec, sealed results, settle and checkpoints (Lane B)
docs/unattended.md: rec/as-is/rec except grammar, --owner-reply and recommend/--rec-hash, unverified pairing and the shared-proposal rule for b, amend_pending and revise --settle, attempt-owned result paths with the sealed .bound.md copy, render --all, and the checkpoint/resume --from paragraph. GATE_REPLY_UNPARSED's fix names rec/as-is (DRIVER.md regenerated).
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs/capy-install: resolver, versioned store, bun shim, trailer notes; wrapper minimum 2
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): --timeout bounds each runner process again, not the whole lanes check
Lane C made --timeout a deadline for the whole lanes check, so a repo whose
unit group and serial files each fit in 600 s but exceed it together ended
incomplete and blocked /ship. --timeout is per runner process again (unit
group, each serial file); the stall timeout still catches hung or silent
processes. A timed-out process is incomplete naming its last file, and the
next serial file still runs. Regression: three 1.5 s serial files under
--timeout 3 pass; one 5 s file is incomplete.
Files (G2): lib/pregate/checks/lanes.ts, bin/gstack-pregate (help),
docs/pregate.md, test/pregate-supervise.test.ts.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pins): CI exact pins for this platform are alternatives; the installer prefers a non-CI exact pin, else the install default among CI alternatives, else the highest verified (integration item 1)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): clear validates the remote gate receipt; test_backend run URLs are attested
`gstack-pregate clear` accepted any --run-url for a small machine's
obligation. A pregate.json/remote_gate obligation now clears only with
--receipt <file> holding the gate's PREGATE_REMOTE: line, validated as
--remote validates it (tree equals the tested tree, tests > 0, failed = 0;
shared parseRemoteReport/remoteReportProblem); a run URL is usage (exit 2)
and a bad receipt is PREGATE_RECEIPT_INVALID (exit 1, obligation unchanged).
A test_backend/<backend> obligation has no machine-checkable receipt: its
--run-url is recorded as attested:<url> and the output says attested, not
validated. Platform lanes are unchanged. Hints name the right clear form.
New code PREGATE_RECEIPT_INVALID: result-codes row, troubleshooting anchor,
installer-form error line, regenerated doctor components.
Files (G2): lib/pregate/index.ts, lib/pregate/checks/lanes.ts,
bin/gstack-pregate, lib/result-codes.ts, bin/gstack-doctor-components.sh
(generated), docs/pregate.md, docs/troubleshooting.md,
test/pregate-remote.test.ts.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(issue-links): derive this PR's author when gh runs as an app, so handoff and pr-body exclude the owner's own PRs (Lane D fix 1)
The handoff ran gstack-issue-links without --author, and the pr-body step only
asked the agent to pass one, so under Capy's app identity (viewer
`capy-ai[bot]`) the owner's own open PRs were listed as `Related:`. The bin now
derives the author itself: --author, else the gh viewer, else (for a `…[bot]`
viewer) the HEAD commit's GitHub user, else the owner of a user-owned
repository; with none it keeps every PR and reports ISSUE_LOOKUP_FAILED.
`--json` gains `author: {login, source}`; the stderr preview names it. Both ship
steps work unchanged, so the pr-body `--author` clause is dropped (union
309,487 -> 309,435 bytes, under the unchanged 1.6488 cap; skeleton 80,998).
Files: bin/gstack-issue-links, lib/result-codes.ts (ISSUE_LOOKUP_FAILED row),
docs/troubleshooting.md (#issue-lookup-failed), docs/pregate.md,
ship/sections/pr-body.md.tmpl, ship/sections/pr-body.md,
test/helpers/pregate-fixture.ts (gh stub: PR-author query),
test/ship-issue-intent.test.ts.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(wrapper): GSTACK_CAPY_MIN_WRAPPER back to 1; an active wrapper below the minimum is a WARN; gstack-upgrade never leaves a pending marker for the wrapper row and maps every installer stop to a trailer (integration items 2, 9)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(shim): validate and contain store pins, read the 'none' record outside projects and in the checkout, fall back in the resolver's order, stay quiet without a pin; quote baked paths; publish bunx and replace store entries without a window (integration items 3, 4, 6, 9)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(install): --check fails BUN_RESOLUTION_DRIFT only when the recorded Bun is gone, changed or no longer satisfies the pins; a newer candidate is a note and the recorded Bun stays the launch Bun (integration item 5)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(install): one final 'gstack ready (claude, codex)' after both host setups (integration item 7)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): lanes and guards validate the install verdict like admission and return incomplete (INSTALL_UNVERIFIED, BUN_RESOLUTION_DRIFT) before launching; the checkout binds the 'none' verdict (integration item 8)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs: CI pin alternatives, shim order and containment, drift note, wrapper WARN, final ready line
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(autoplan): settle after or with a revise, title pairs need the same remedy, legacy gates refuse rec (integration items 1, 7, 8)
1. A gate with a scope change (uc1) and a packaging change (uc2) answered
`rec` deadlocked: after `revise --plan v2 --incorporates uc1` reopened the
phases, `revise --settle uc2` compared against the first phase snapshot
(now undefined) and was refused forever. Settle evidence is now the plan
hash recorded when the owner accepted the change (Amendment.plan_sha256)
or a later plan_revised hash, plus "the plan file has no unrevised edits".
`--settle` may ride the same revise as `--plan/--incorporates` and binds
to the revision's hash. Settling the last amendment after a reopen leaves
the run `running` (the reopened phases rerun) instead of approving it.
NEXT and PLAN_AMEND_PENDING list the settle step before the edit step.
7. A title association alone no longer confirms: the same remedy confirms,
opposite remedies (one keeps, drops or negates what the other changes)
disagree, different or missing remedies stay `unverified`. The pairing
fixture gains same-title negative controls (opposite and different
remedies) and a same-remedy positive, for ordinary findings and user
challenges.
8. A gate.json without rec_rev (written by 1.91.101.0, whose render said
`all` leaves b items pending) refuses rec/all/approve all/`all except`
with GATE_REC_STALE until a re-render binds --rec-hash; explicit tokens
still answer. New gates carry rec_rev: 0.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(autoplan): checkpoints never touch the live run; generations, newest-valid restore, validated staging (integration items 2-6)
2. checkpointRun canonicalizes the collection and the run directory (symlinks
resolved through the deepest existing ancestor) and refuses, before
touching anything, when they are the same or one contains the other
(CHECKPOINT_OVERLAP); restore applies the same check to source, target and
staging. Before, <root>/<run> equal to the live run replaced it.
3. Publication writes an immutable generation (generations/g<revision>-…),
renames it into place complete, then switches current.json with one
rename; the previous generation is kept, so an interruption at the publish
boundary (fault hook checkpoint-before-pointer) leaves the last checkpoint
current. A generation never replaces a newer one (higher run revision):
"CHECKPOINT: skipped … newer". Publication and restore hold the
collection's .lock; restore also holds <out>.lock.
4. Restore checks every listed file's real path stays inside the generation
(an ancestor symlink no longer copies outside files), parses run.json and
runs validateRun on the staged run before publishing; a refusal leaves
--out absent. readState reroots plan_input and plan_source for moved runs,
and a restore with the owner's plan file gone points both at the restored
copy, so a second restore cycle and a later revise work.
5. A checkpoint failure after a committed command prints
"CHECKPOINT: failed for <run>: … ; the command's result stands" on stderr
and keeps the command's exit code.
6. `gstack-autoplan checkpoints --from <dir>` lists generations newest first
(run, gate_rev, status, revision, time, hash ok|bad, current).
`resume --from <collection or root>` restores the newest generation that
verifies, printing each corrupt newer one it skipped; a root holding
several runs must name one.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* chore: budget the Capy skill's autoplan checklist and trim its install notes
Files: capy/skill/gstack/SKILL.md, test/fixtures/context-budget.json (capy/skill/gstack ceiling only: 2364 tok x 1.10)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* chore: release 1.91.102.0 (tentative stamp) — GBRA-40 field list
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test: supply _setup_ready_line to setup-tail harnesses, register the pairing fixture, make the admission test runner-Bun independent; announce shim writes
Files: test/setup-hook-syntax-gate.test.ts, test/redact-prepush-hook.test.ts, test/setup-playwright-best-effort.test.ts, test/helpers/free-fixtures-data.ts, test/pregate-guards.test.ts, bin/gstack-capy-install
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* ci: run quick-bun-default on the ubicloud-standard-8 class the free suite uses
The ubuntu-24.04 runner timed out two Swift typecheck tests at 30 s (render @Observable marker, ios-qa-regen); both pass on Bun 1.4.3 on Ubicloud.
Files: .github/workflows/free-tests.yml
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): read bun test's GitHub Actions group headers; exclude pregate-remote from the Windows subset; give quick-bun-default the free suite's flake policy
Files: lib/pregate/supervise.ts, test/pregate-supervise.test.ts, scripts/lib/windows-curation.ts, .github/workflows/free-tests.yml
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test: run the Capy wrapper and shim doctor-row tests on POSIX only (Git Bash prints MSYS paths)
Files: test/gstack-doctor.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* chore: restamp 1.91.107.0 (1.91.106.0 is claimed by #3209)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): spawn the supervised shell through lib/script-invocation (#3197 tripwire)
The supervisor now resolves bash via bashCommandInvocation, so Windows uses
Git Bash instead of a PATH bash, and an unresolvable bash reports spawn-failed.
guards.ts and lanes.ts no longer spawn bash (they run through supervise.ts),
so their KNOWN_SITES entries are removed.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(qa-functional): disable auto gc and maintenance in the fixture repo
On eval-slices (9), qa-functional-webhook-fix failed mid-run with 100+
'directory watch lost: .git/objects/..' entries and forbidden writes to
.git/info/refs and .git/objects/pack. That is git's detached auto
maintenance repacking the fixture under the write observer. This applies the
same gc.auto=0 / maintenance.auto=false config qa-callers-fixture uses.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(autoplan-guard-pty): say Phase 2 starts without waiting for user input
On eval-slices (1), haiku published Phase 1 and then ended its turn with
'Waiting for next invocation to continue with step 8'. Step 5 tells it to end
its turn while the reviewer runs, so step 8's 'In a later message' read as a
later user turn. Phase 2 never started, the guard logged 2 of the 4 expected
allows, and the run hit its deadline. Step 8 now says to continue in the next
assistant message, still separate from the step 7 publication message.
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>
359 lines
20 KiB
TypeScript
359 lines
20 KiB
TypeScript
/**
|
||
* plan-reality — the reality rows every plan review must carry (multi-agent
|
||
* wave D1, release promise P5). One table owns the rows: the resolver
|
||
* scripts/resolvers/plan-reality.ts renders them into the plan-review
|
||
* templates, bin/gstack-plan-reality prints them at run time and checks a
|
||
* review for them, and the tests pin the row ids and the line grammar.
|
||
*
|
||
* A review emits one grep-able line per row:
|
||
*
|
||
* REALITY: <row-id> <pass|finding|n/a> <summary carrying a receipt>
|
||
*
|
||
* A receipt is `path:line`, `path:line-line` or a commit sha; a row without one
|
||
* is not a row. Tier 1 rows are required in every review. Tier 2 rows are
|
||
* required only when the review's detected scope (the manifest `scope` field
|
||
* from plan B4, passed to the checker as `--scope`) names theirs; otherwise
|
||
* they may be omitted or marked `n/a`. A tier 1 row marked `n/a` is missing.
|
||
*
|
||
* `checkRealityRows` is deterministic and returns the missing rows; the
|
||
* session kind decides what a miss means (unattended: the phase is
|
||
* `incomplete`; interactive: repair twice, then warn at the gate). The row
|
||
* table carries each row's incident, so the deep section can say why the row
|
||
* exists without a second table drifting.
|
||
*/
|
||
|
||
export const REALITY_SCOPES = ['always', 'db', 'perf', 'search', 'incident', 'dependency'] as const;
|
||
export type RealityScope = typeof REALITY_SCOPES[number];
|
||
export const REALITY_STATUSES = ['pass', 'finding', 'n/a'] as const;
|
||
export type RealityStatus = typeof REALITY_STATUSES[number];
|
||
|
||
export interface RealityRow {
|
||
id: string;
|
||
title: string;
|
||
tier: 1 | 2;
|
||
/** `always` for tier 1; the scope signal a tier 2 row needs. */
|
||
scope: RealityScope;
|
||
/** The operative check, one line, imperative. */
|
||
check: string;
|
||
/** The incident in the gbrain feedback that earned the row, one line. */
|
||
incident: string;
|
||
/** Optional `key=value` the line must carry (scored in the Completion Summary). */
|
||
metric?: string;
|
||
}
|
||
|
||
export const REALITY_ROWS: readonly RealityRow[] = [
|
||
{
|
||
id: 'premise-table', title: 'Premise table', tier: 1, scope: 'always',
|
||
check: '`premise | claim | file:line receipt | verdict` for every factual claim; no receipt means `unverified`, and `unverified=<n>` is scored in the Completion Summary.',
|
||
incident: 'A wave rested on "13 of 28 threads ran nothing" with no per-thread evidence; the first table found 1 FALSE and 3 UNVERIFIED claims in 27.',
|
||
metric: 'unverified',
|
||
},
|
||
{
|
||
id: 'already-done', title: 'Already done', tier: 1, scope: 'always',
|
||
check: '`git fetch origin <base>`, then `git log origin/<base> --since=<ask date> -- <named files>` and `--grep <symbols>`; report a hit before any task is written.',
|
||
incident: 'A fix was re-planned and rebuilt the day after main merged it; nobody read the base log.',
|
||
},
|
||
{
|
||
id: 'surface-check', title: 'Surface check', tier: 1, scope: 'always',
|
||
check: 'Every named CLI command, flag or HTTP route verified against the registry or `--help`; a miss is a finding.',
|
||
incident: 'The installer relied on `bun upgrade --version`; `bun upgrade --help` on the target listed only `--canary`.',
|
||
},
|
||
{
|
||
id: 'binding-decisions', title: 'Binding decisions', tier: 1, scope: 'always',
|
||
check: 'Read `gstack-decision-search --scope branch --recent 50` and the plan\'s `## Binding decisions`; they outrank project defaults and CLAUDE.md, and a reintroduced overruled default is a finding.',
|
||
incident: 'An owner decision taken mid-review was undone two phases later by the project default it had replaced.',
|
||
},
|
||
{
|
||
id: 'numbers', title: 'Numbers', tier: 1, scope: 'always',
|
||
check: 'Every number re-derived from raw data and tagged `[measured: <source>]` or `[estimated]`; a cited baseline is `[re-measure before gate]`.',
|
||
incident: 'An effort table with no basis was credited until a reviewer re-counted it; quoted parity ratios were off by two decimals.',
|
||
},
|
||
{
|
||
id: 'deferred-asks', title: 'Deferred asks', tier: 1, scope: 'always',
|
||
check: 'The linked issue\'s requests the plan leaves out, each with its reason, listed in the gate template.',
|
||
incident: 'An issue asked for six things; the plan shipped four and the owner found the other two after merge.',
|
||
},
|
||
{
|
||
id: 'pr-count', title: 'PR count', tier: 1, scope: 'always',
|
||
check: '`pr_count` from `.gstack/ship-policy.json` (default one PR per wave); a split shows the queue cost per extra PR and checks user-facing references across it.',
|
||
incident: 'A five-PR wave became seven in the Eng phase; the cost of each extra gate had never been stated.',
|
||
},
|
||
{
|
||
id: 'prior-art', title: 'Prior art', tier: 2, scope: 'dependency',
|
||
check: 'For a vendored or patched dependency or a known library behavior: search the upstream tracker and open PRs; record `adopt <link>` or `diverge because <reason>`.',
|
||
incident: 'A patched vendored hunk was dropped on upgrade because nobody had recorded why the fork diverged.',
|
||
},
|
||
{
|
||
id: 'transaction-semantics', title: 'Transaction semantics', tier: 2, scope: 'db',
|
||
check: 'For a driver, pool or protocol change: the surrounding transaction on idle, pooled and reserved connections; crash robot rerun after the change.',
|
||
incident: 'A pool change ended transactions on idle connections; the crash robot was not rerun.',
|
||
},
|
||
{
|
||
id: 'contract-assumptions', title: 'Contract assumptions', tier: 2, scope: 'dependency',
|
||
check: 'One row per default or flag assumed from another repo, rechecked against merged code before the next stage.',
|
||
incident: 'A sibling repo\'s default changed between planning and build; the plan still assumed the old flag.',
|
||
},
|
||
{
|
||
id: 'falsification-box', title: 'Falsification box', tier: 2, scope: 'incident',
|
||
check: 'Top hypothesis, the evidence that kills it, a time box, and the action in each branch.',
|
||
incident: 'An outage plan chased its first hypothesis for a day with nothing stated that would have killed it.',
|
||
},
|
||
{
|
||
id: 'stop-reasons', title: 'Stop reasons', tier: 2, scope: 'incident',
|
||
check: 'Every new stop reason, hold code and progress line names the test that triggers it.',
|
||
incident: 'A hold code shipped with no test that could produce it; it first fired in production.',
|
||
},
|
||
{
|
||
id: 'reporter-environment', title: 'Reporter environment', tier: 2, scope: 'incident',
|
||
check: 'A repro that does not match the reporter\'s environment is `class not confirmed`, never `ruled out`.',
|
||
incident: 'A bug was "ruled out" on a different runtime than the reporter\'s; the reporter still had it.',
|
||
},
|
||
{
|
||
id: 'units', title: 'Units', tier: 2, scope: 'perf',
|
||
check: 'A change to an input\'s units or accuracy lists every threshold that consumes it and shows the re-tune.',
|
||
incident: 'A timing input moved from ms to s; three downstream thresholds kept their numbers.',
|
||
},
|
||
{
|
||
id: 'perf-table', title: 'Perf table', tier: 2, scope: 'perf',
|
||
check: 'Machine, engine, data size, N, p50/p95, statistics state, base and branch interleaved, pathological and steady-state cases, `reproduced on main?`.',
|
||
incident: 'A speedup came from one warm-cache run with no base comparison; main was as fast.',
|
||
},
|
||
{
|
||
id: 'recall', title: 'Recall', tier: 2, scope: 'search',
|
||
check: 'A search or query-plan change reports recall against exact search across scope buckets.',
|
||
incident: 'A query-plan change sped up the hot path and dropped recall on the smallest bucket.',
|
||
},
|
||
{
|
||
id: 'dependency-fallback', title: 'Dependency fallback', tier: 2, scope: 'dependency',
|
||
check: 'What ships without each predecessor, and by when.',
|
||
incident: 'A stacked PR waited on a predecessor that never merged; nothing said what it could ship alone.',
|
||
},
|
||
{
|
||
id: 'obligation-tiers', title: 'Obligation tiers', tier: 2, scope: 'dependency',
|
||
check: 'Must-ship, next PR, deferred, under a stated size budget; the ledger status column carries the tier.',
|
||
incident: 'A PR outgrew review because every accepted finding was treated as must-ship.',
|
||
},
|
||
];
|
||
|
||
export const TIER1_ROW_IDS: readonly string[] = REALITY_ROWS.filter(r => r.tier === 1).map(r => r.id);
|
||
|
||
export function rowById(id: string): RealityRow | undefined {
|
||
return REALITY_ROWS.find(r => r.id === id);
|
||
}
|
||
|
||
/** Rows a review must carry for the given scopes: tier 1 always, tier 2 when its scope is detected. */
|
||
export function requiredRows(scopes: readonly string[]): RealityRow[] {
|
||
return REALITY_ROWS.filter(r => r.tier === 1 || scopes.includes(r.scope));
|
||
}
|
||
|
||
export function parseScopes(csv: string | undefined): { scopes: RealityScope[]; unknown: string[] } {
|
||
const scopes: RealityScope[] = [];
|
||
const unknown: string[] = [];
|
||
for (const raw of (csv ?? '').split(',').map(s => s.trim()).filter(Boolean)) {
|
||
if ((REALITY_SCOPES as readonly string[]).includes(raw)) scopes.push(raw as RealityScope);
|
||
else unknown.push(raw);
|
||
}
|
||
return { scopes, unknown };
|
||
}
|
||
|
||
/** `path:line` or `path:line-line` (the path has a letter, may start with a dot, no spaces), or a 7–40 hex sha with a hex letter, or digits-only after `commit ` or in backticks. */
|
||
export const RECEIPT_RE = /(?:(?<![\w./-])\.?[A-Za-z~$][\w./~$@-]*:\d+(?:-\d+)?)|(?<![0-9a-f])(?=[0-9]*[a-f])[0-9a-f]{7,40}(?![0-9a-f])|\bcommit [0-9]{7,40}\b|`[0-9]{7,40}`/;
|
||
export const REALITY_LINE_RE = /^\s*(?:[-*>|]\s*)?`?REALITY:\s+(?<id>[a-z][a-z0-9-]*)\s+(?<status>pass|finding|n\/a)\b(?<rest>.*)$/;
|
||
|
||
export interface RealityLine { id: string; status: RealityStatus; rest: string; receipt: string | null; line: number; metrics: Record<string, string> }
|
||
|
||
export function parseRealityLines(text: string): RealityLine[] {
|
||
const out: RealityLine[] = [];
|
||
text.split('\n').forEach((raw, i) => {
|
||
const m = REALITY_LINE_RE.exec(raw);
|
||
if (!m?.groups) return;
|
||
const rest = m.groups.rest!.replace(/`\s*$/, '').trim();
|
||
const receipt = RECEIPT_RE.exec(rest)?.[0] ?? null;
|
||
const metrics: Record<string, string> = {};
|
||
for (const kv of rest.matchAll(/\b([a-z_]+)=([^\s,;|]+)/g)) metrics[kv[1]!] = kv[2]!;
|
||
out.push({ id: m.groups.id!, status: m.groups.status as RealityStatus, rest, receipt, line: i + 1, metrics });
|
||
});
|
||
return out;
|
||
}
|
||
|
||
export type RealityVerdict = 'complete' | 'incomplete' | 'repair';
|
||
export interface RealityCheck {
|
||
phase: string;
|
||
required: string[];
|
||
present: string[];
|
||
/** Required rows with no line, or a tier 1 row marked n/a. */
|
||
missing: string[];
|
||
/** Required rows whose line carries no receipt. */
|
||
unreceipted: string[];
|
||
/** Clauses stating a measured number without a receipt of their own. */
|
||
unreceipted_numbers: string[];
|
||
/** Lines claiming a decision rule exists without quoting or linking its text. */
|
||
unquoted: string[];
|
||
/** One `NUMBER_UNRECEIPTED: <clause>` line per unreceipted number. */
|
||
numberLines: string[];
|
||
/** Lines naming a row id the table does not define. */
|
||
unknownRows: string[];
|
||
metrics: Record<string, string>;
|
||
verdict: RealityVerdict;
|
||
line: string;
|
||
}
|
||
|
||
/**
|
||
* A measured quantity: a number with a unit (s, ms, %, $, USD, tokens, ×, MB, GB) or a number shortly after
|
||
* measured/costs/takes/took. Receipts, versions and ids are removed before matching, so they never count.
|
||
*/
|
||
const MEASURED_RE = /\$\s?\d|\b\d[\d,]*(?:\.\d+)?\s?[kKM]?\s?(?:ms|s|%|USD|tokens?|MB|GB)(?![\w])|\b\d[\d,]*(?:\.\d+)?\s?[×x](?![\w])|\b(?:measured|costs?|takes|take|took)\b\W+(?:[A-Za-z]+\W+){0,3}?\$?\d/i;
|
||
const ITEM_REF_RE = /\b(?:items?|sections?)\s+\d+(?:\s*[–-]\s*\d+)?(?:\s*(?:,|and)\s*\d+(?:\s*[–-]\s*\d+)?)*|§\s?\d+(?:\.\d+)*/;
|
||
const NOT_A_QUANTITY_RE = new RegExp(`${RECEIPT_RE.source}|${ITEM_REF_RE.source}|\\bv?\\d+(?:\\.\\d+){2,}\\b|#\\d+|\\b[A-Za-z]+\\d+[a-z]?\\b`, 'g');
|
||
const EXEMPT_TAG_RE = /\[(?:estimated|re-measure before gate)\]/i;
|
||
const SCRIPT_RE = /(?:^|[\s(`"'])(?:\.?[\w-]+\/)*[\w.-]+\.(?:ts|js|mjs|cjs|sh|py|rb|go)\b|(?:^|[\s(`"'])(?:bin|scripts)\/[\w.-]+/;
|
||
const COMMAND_RE = /`(?!\s*\$?\d)[^`]*\s[^`]*`/;
|
||
const RULE_CLAIM_RE = /\b(?:decision rule|rules? (?:was |were )?written first|pre-?registered rule)\b/i;
|
||
const QUOTED_RULE_RE = /"[^"]{8,}"|\u201c[^\u201d]{8,}\u201d/;
|
||
const LINK_RE = /(?<![\w./-])\.?[A-Za-z~$][\w./~$@-]*:\d+/;
|
||
|
||
/** Split on `;`, `, ` and sentence ends, never inside brackets, parentheses or backticks. */
|
||
export function splitClauses(text: string): string[] {
|
||
const out: string[] = [];
|
||
let depth = 0, tick = false, start = 0;
|
||
for (let i = 0; i < text.length; i++) {
|
||
const c = text[i]!;
|
||
if (c === '`') tick = !tick;
|
||
else if (!tick && '([{'.includes(c)) depth++;
|
||
else if (!tick && ')]}'.includes(c)) depth = Math.max(0, depth - 1);
|
||
else if (!tick && depth === 0 && (c === ';' || ((c === ',' || c === '.') && /\s/.test(text[i + 1] ?? '')))) {
|
||
out.push(text.slice(start, c === '.' ? i + 1 : i)); start = i + 1;
|
||
}
|
||
}
|
||
out.push(text.slice(start));
|
||
return out.map(c => c.trim()).filter(Boolean);
|
||
}
|
||
|
||
const QUOTED_SPAN_RE = /"([^"]+)"|\u201c([^\u201d]+)\u201d/g;
|
||
const BACKTICK_SPAN_RE = /`[^`]*`/g;
|
||
|
||
/**
|
||
* Clauses of one line that state a measured number and carry no receipt of their own. With `quotedFrom` (the
|
||
* reviewed plan, reviewer scope only), a span quoted verbatim from it is the plan's number, not the reviewer's claim.
|
||
*/
|
||
export function unreceiptedNumbers(line: string, quotedFrom?: string): string[] {
|
||
const text = quotedFrom ? line.replace(QUOTED_SPAN_RE, (span, a, b) => (quotedFrom.includes((a ?? b) as string) ? '""' : span)) : line;
|
||
return splitClauses(text).filter(c => MEASURED_RE.test(c.replace(NOT_A_QUANTITY_RE, ' '))
|
||
&& !RECEIPT_RE.test(c) && !SCRIPT_RE.test(c) && !COMMAND_RE.test(c) && !EXEMPT_TAG_RE.test(c));
|
||
}
|
||
|
||
/** A rule claim needs the rule: a quoted span, a file:line link on the line, or a fenced or quoted block right after it. Plan scope ignores phrases inside backticks (a phrase named, not claimed). */
|
||
function ruleUnquoted(lines: string[], i: number, scope: 'plan' | 'review' = 'review'): boolean {
|
||
const line = lines[i]!;
|
||
if (!RULE_CLAIM_RE.test(scope === 'plan' ? line.replace(BACKTICK_SPAN_RE, ' ') : line) || QUOTED_RULE_RE.test(line) || LINK_RE.test(line)) return false;
|
||
const after = lines.slice(i + 1).find(l => l.trim());
|
||
return !after || !/^\s*(?:```|~~~|>)/.test(after);
|
||
}
|
||
|
||
const verdictFor = (ok: boolean, sessionKind?: string): RealityVerdict => (ok ? 'complete' : sessionKind === 'unattended' ? 'incomplete' : 'repair');
|
||
|
||
export interface CheckOptions { phase: string; scopes?: readonly string[]; sessionKind?: string;
|
||
/** The reviewed plan snapshot: a number inside a span quoted verbatim from it needs no receipt of its own. */
|
||
planText?: string }
|
||
|
||
/** Deterministic: which required rows the review carries. The verdict word depends on the session kind only. */
|
||
export function checkRealityRows(reviewText: string, o: CheckOptions): RealityCheck {
|
||
const required = requiredRows(o.scopes ?? []).map(r => r.id);
|
||
const lines = parseRealityLines(reviewText);
|
||
const byId = new Map<string, RealityLine>();
|
||
const unknownRows: string[] = [];
|
||
for (const l of lines) {
|
||
if (!rowById(l.id)) { if (!unknownRows.includes(l.id)) unknownRows.push(l.id); continue; }
|
||
if (!byId.has(l.id) || (byId.get(l.id)!.status === 'n/a' && l.status !== 'n/a')) byId.set(l.id, l);
|
||
}
|
||
const present: string[] = [], missing: string[] = [], unreceipted: string[] = [];
|
||
const metrics: Record<string, string> = {};
|
||
for (const id of required) {
|
||
const l = byId.get(id);
|
||
if (!l || l.status === 'n/a') { missing.push(id); continue; }
|
||
if (!l.receipt) { unreceipted.push(id); continue; }
|
||
present.push(id);
|
||
const metric = rowById(id)!.metric;
|
||
if (metric && l.metrics[metric] !== undefined) metrics[metric] = l.metrics[metric]!;
|
||
}
|
||
const rows = lines.filter(l => rowById(l.id) && l.status !== 'n/a');
|
||
const numbers = rows.flatMap(l => unreceiptedNumbers(l.rest, o.planText));
|
||
const rawLines = reviewText.split('\n');
|
||
const unquoted = rows.filter(l => ruleUnquoted(rawLines, l.line - 1)).map(l => rawLines[l.line - 1]!.trim());
|
||
const verdict = verdictFor(missing.length === 0 && unreceipted.length === 0 && numbers.length === 0 && unquoted.length === 0, o.sessionKind);
|
||
const parts = [`PLAN_REALITY: phase=${o.phase}`, `rows=${present.length}/${required.length}`,
|
||
`missing=${missing.length ? missing.join(',') : 'none'}`];
|
||
if (unreceipted.length) parts.push(`unreceipted=${unreceipted.join(',')}`);
|
||
if (numbers.length) parts.push(`unreceipted_numbers=${numbers.length}`);
|
||
if (unquoted.length) parts.push(`unquoted=${unquoted.length}`);
|
||
for (const [k, v] of Object.entries(metrics)) parts.push(`${k}=${v}`);
|
||
parts.push(`verdict=${verdict}`);
|
||
return { phase: o.phase, required, present, missing, unreceipted, unreceipted_numbers: numbers, unquoted,
|
||
numberLines: numbers.map(c => `NUMBER_UNRECEIPTED: ${c}`), unknownRows, metrics, verdict, line: parts.join(' ') };
|
||
}
|
||
|
||
/** Bumped whenever checkPlanReality's rules change, so a cached verdict keyed on the plan hash is recomputed. */
|
||
export const PLAN_REALITY_CHECKER = 'plan-reality/3';
|
||
export interface PlanRealityCheck { checker: string; unreceipted_numbers: string[]; unquoted: string[]; numberLines: string[]; verdict: RealityVerdict; line: string }
|
||
|
||
/**
|
||
* The same number and rule checks over plan prose (the Implementation plan the caller passes), outside fenced blocks.
|
||
* Pure: reads nothing, writes nothing. `gstack-autoplan submit` records it per plan hash; it never refuses a submit.
|
||
*/
|
||
export function checkPlanReality(planText: string, o: { sessionKind?: string } = {}): PlanRealityCheck {
|
||
const lines = planText.split('\n');
|
||
const numbers: string[] = [], unquoted: string[] = [];
|
||
let fence: string | null = null;
|
||
lines.forEach((line, i) => {
|
||
const delimiter = /^\s{0,3}(`{3,}|~{3,})/.exec(line)?.[1];
|
||
if (delimiter && (!fence || delimiter.startsWith(fence))) { fence = fence ? null : delimiter; return; }
|
||
if (fence || /^\s*<!--/.test(line)) return;
|
||
numbers.push(...unreceiptedNumbers(line));
|
||
if (ruleUnquoted(lines, i, 'plan')) unquoted.push(line.trim());
|
||
});
|
||
const verdict = verdictFor(numbers.length === 0 && unquoted.length === 0, o.sessionKind);
|
||
return { checker: PLAN_REALITY_CHECKER, unreceipted_numbers: numbers, unquoted, numberLines: numbers.map(c => `NUMBER_UNRECEIPTED: ${c}`), verdict,
|
||
line: `PLAN_REALITY: scope=plan unreceipted_numbers=${numbers.length} unquoted=${unquoted.length} verdict=${verdict}` };
|
||
}
|
||
|
||
const VAGUE_RE = /\b(minimum (?:detectable )?effect|margins?|decision rule|dollar cost|cost in dollars|USD cost)\b/i;
|
||
const DETAIL_AFTER_RE = /^\s*(?:[-*+]\s|\d+[.)]\s|\||```|~~~|>)/;
|
||
|
||
/**
|
||
* PLAN_REALITY flags for the gate (advisory, never blocking): a plan line naming a minimum effect, a margin, a
|
||
* decision rule or a dollar cost with no number on it (item references and phrases in backticks do not count)
|
||
* and no arm list, table, quoted rule or block right after it. `line` is 1-based in `planText`.
|
||
*/
|
||
export function vaguePlanTerms(planText: string): Array<{ phrase: string; line: number; text: string }> {
|
||
const lines = planText.split('\n');
|
||
const out: Array<{ phrase: string; line: number; text: string }> = [];
|
||
let fence: string | null = null;
|
||
lines.forEach((raw, i) => {
|
||
const delimiter = /^\s{0,3}(`{3,}|~{3,})/.exec(raw)?.[1];
|
||
if (delimiter && (!fence || delimiter.startsWith(fence))) { fence = fence ? null : delimiter; return; }
|
||
if (fence || /^\s*<!--/.test(raw)) return;
|
||
const prose = raw.replace(BACKTICK_SPAN_RE, ' ');
|
||
const m = VAGUE_RE.exec(prose);
|
||
if (!m) return;
|
||
if (/\d/.test(prose.replace(NOT_A_QUANTITY_RE, ' ')) || QUOTED_RULE_RE.test(prose)) return;
|
||
const after = lines.slice(i + 1).find(l => l.trim());
|
||
if (after && DETAIL_AFTER_RE.test(after)) return;
|
||
out.push({ phrase: m[1]!.toLowerCase(), line: i + 1, text: raw.trim() });
|
||
});
|
||
return out;
|
||
}
|
||
|
||
/** The example line every template quotes; one grammar, stated once. */
|
||
export const REALITY_LINE_SHAPE = 'REALITY: <row> pass|finding|n/a <summary> <file:line>';
|
||
|
||
/** The operative rows as the bin prints them (`deep` adds each row's incident). */
|
||
export function renderRows(rows: readonly RealityRow[], o: { deep: boolean }): string {
|
||
return rows.map(r => `- ${r.id} (tier ${r.tier}${r.scope === 'always' ? '' : `, scope ${r.scope}`}): ${r.check}${o.deep ? `\n Incident: ${r.incident}` : ''}`).join('\n');
|
||
}
|
||
|
||
/** The deep-section table: why each row exists. The check itself is what `rows` prints. */
|
||
export function renderIncidentTable(rows: readonly RealityRow[]): string {
|
||
const head = '| Row | Tier | Scope | Incident that earned it |\n|---|---|---|---|';
|
||
return [head, ...rows.map(r => `| \`${r.id}\` | ${r.tier} | ${r.scope} | ${r.incident.replace(/\|/g, '\\|')} |`)].join('\n');
|
||
}
|