mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-03 09:56:57 +02:00
* refactor(resolvers): split review.ts into MECE resolver modules (pure move) Move every function from scripts/resolvers/review.ts, unchanged, into: - review-dashboard.ts: review dashboard, plan-file review report - plan-gates.ts: approval check, exit-plan-mode gate, plan-file discovery, plan-completion audit/gate (ship + review), plan verification exec - spec-review.ts: both spec review loops, benefits-from, anti-shortcut clause - outside-voice-steps.ts: Codex second opinion, adversarial step, Codex plan review, Codex doc review, disabled-outside record - review-scope.ts: scope drift, cross-review dedup, shared-code reuse review.ts is deleted; index.ts imports the new modules. gen-skill-docs output is byte-identical for every host (--host all). Test imports and source-path references are re-pointed; the two source-text report/gate tests in gen-skill-docs.test.ts become behavioral renders across every consuming skill and host. All 46 touchfile entries that named review.ts now name all five modules, guarded by a recorded selection golden. * test(browse): black-box auth matrix for every server route and both surfaces Drives buildFetchHandler fetchLocal/fetchTunnel with no token, wrong token, root token, scoped token and the SSE cookie for all 33 routes, plus unmatched paths and wrong methods. Denials assert today's exact status, body and content type; allowed credentials assert the handler was reached. Written against the unchanged if-chain server so the W3 route-table refactor must keep it green. * refactor(shard-engine): move scripts/test-strict-output.ts to scripts/lib/shard-engine.ts The shared shard engine grows from the existing strict-output module (runShardChild, killProcessGroup, signal forwarding, strict classifier). scripts/test-strict-output.ts stays as a re-export so existing importers, mock.module paths and the strict-output/run-shard-child tests are unchanged. The engine inherits the global touchfile entry; the free runner's CLI-routing fixture copies the new module. * refactor(resolvers): decompose the three >150-line review resolvers (output-neutral) Split generateAdversarialStep, generateCodexPlanReview and generatePlanCompletionAuditInner into per-section helpers whose template literals are copied verbatim, so every function in the new modules is at or under 150 lines. gen-skill-docs output is byte-identical for every host (--host all, compared against96764e80with a fixed --link-root). * refactor(resolvers): one outside-voice failure policy (deliberate prose unification) outsideVoiceFailurePolicy(ctx, opts) in outside-voice.ts now renders the auth / timeout / empty-response bullets for all four call sites that hand-typed them (Codex second opinion, adversarial step, Codex plan review, design outside voices). Options are explicit per site (timeoutMinutes, onTimeout, stderrOnEmpty, fallback, escape) with no defaults. Deliberate generated-prose changes (every host): - office-hours: 'Fall back to <native> subagent.' becomes 'Fall back to the <native> subagent below.' - plan-devex-review: the plain 'Auth failure (stderr contains ...)' bullets become the canonical bold bullets; auth also triggers on 'API key'; 'auth failed' becomes 'authentication failed'. - review/ship adversarial: 'exceeded 9 minutes and was terminated' becomes 'timed out after 9 minutes and was terminated'; the timeout is still MISSING COVERAGE. - design outside voices: unchanged. Adds ratchet (d) (test/outside-voice-failure-policy.test.ts) with a reasoned allowlist for /codex's own CLI errors, the MISSING COVERAGE retention test, refreshed codex/factory ship goldens, and outside-voice.ts in every touchfile entry of review.ts and design.ts (selection golden extended). * test(pty): fake PTY session driver with an injectable clock through the runner launch seam The three plan-skill runners take an optional PtyDriver (launch, now, monotonic, sleep); omitted, they use the real launcher and clocks exactly as before. test/helpers/pty/fake-session.ts feeds scripted frames through that seam, and claude-pty-runner.runners.unit.test.ts runs observation, counting and floor for success, deadline timeout, permission prompt and plan-ready outcomes with no CLI or real timers. These cases must stay green unchanged through the W4 split and the runPtySession extraction. Touchfiles: every entry that lists claude-pty-runner.ts or pty-screen.ts now also lists test/helpers/pty/**. * refactor(shard-engine): run both lanes on the shared engine; lane policy injected Engine (scripts/lib/shard-engine.ts) gains the W2 primitives: per-shard tmp/Chromium sandbox + async cleanup backstop, log-path allocation and full-stream log capture, one duration-seed reader/writer with a lane predicate, LanePolicy (seed predicate + zero-execution verdict), strictShardStatus, and the shared CLI flag loop. runShardChild takes an optional companion (signal/settle) and waits a bounded 250ms to reap a wall-killed child. Free lane stops spawning shards itself: runFreeShard uses runShardChild with trackShardBrowser as the companion (win32 path unchanged: no process group, no negative-pid kill). Its sync state-dir removal stays lane policy. Paid lane uses the sandbox, log, seed, verdict and flag primitives; the hollow-shard guard applies PAID_LANE_POLICY. Lane outcomes are unchanged (free keeps >= 0 seeds and file-count zero-exec rule; paid keeps > 0 seeds, warning under selection and passed-empty under EVALS_ALL). paid-free-boundary's closure assertion now names the engine module, where the strict classifier lives. * test(shard-engine): engine unit tests, fixture-corpus equivalence, per-lane CLI parity - test/shard-engine.test.ts: failing/unhandled/module-load output fails both lanes, per-lane zero-execution and seed rules, whole-group kill on a wall timeout (both lanes), mocked-win32 path with no negative-pid kill, companion settle order, log capture, sandbox isolation, flag loop. - test/shard-engine-equivalence.test.ts + test/fixtures/shard-equivalence: seven outcome fixtures plus one real shard, run through both lanes and compared with classifications recorded from the base runners (96764e80). - test/shard-cli-parity.test.ts + test/fixtures/shard-cli-parity: flag set, defaults, validation errors and the Unknown argument error per lane match the base runners. * refactor(shard-engine): decompose runFreeShard and runPaidShard to <= 150 lines Output-neutral extraction under the fixture-corpus equivalence and runner tests: captureFreeStream, explainFreeVerdict and logFreeRecovery (free); paidShardCommand, settleShardSpool, settleBootstrapRetention and printLogTail (paid). The bootstrap scope-creation block that bootstrap-retention.test.ts evaluates stays verbatim. * refactor(pty): split claude-pty-runner.ts into test/helpers/pty/* behind a barrel Pure move: every line of the former 5,047-line runner lands verbatim in one module (four private helpers gain `export` for cross-module use): binary, screen (absorbs test/helpers/pty-screen.ts, which now re-exports it), launch, session (PtyDriver), judge, classify, auq, plan-native, boundaries, runners/{observation,counting,floor}. claude-pty-runner.ts re-exports the original public surface by name; pty/ modules import siblings directly. Tests that read the runner's source text: - rewritten as behavioral: the unit test's model-pin tripwire (fake CLI argv: fallback chain, --model before extraArgs, hermetic --strict-mcp-config), pty-skill-seeding-wiring (runners through the fake driver; launcher through a fake CLI reporting CLAUDE_CONFIG_DIR). The "three wrappers forward model" grep is replaced by the runners' fake-driver launch assertions. - pty-screen-session / pty-screen-supervision: stop copying runner source; they mock.module the real pty/screen.ts (and the fixture cleanup) instead. - re-pointed to the owning module (they execute a sliced runner body with injected boundaries; no seam exists for those boundaries yet): eng-seeded-completion-ai, plan-floor-permission, plan-create-prepublication, plan-count-completion; hermetic-wiring's source guard now reads pty/launch.ts and scans every pty/ module for raw process.env spreads. - plan-count-timeout and pty-output-wake mock the viewport at pty/screen.ts. * test(ratchet-c): enforcing module/function size ratchet and moved-code touchfile coverage Ratchet (c) ships enforcing: test/helpers/module-size.ts counts file and top-level function lengths by brace matching over masked source (strings, comments, regex literals and template text masked; ${} expressions kept), covering function declarations, arrow functions assigned to consts and route-table handler properties, with no parser dependency. Its self-test uses template literals and code-fence braces copied from scripts/resolvers/review.ts and design.ts. test/fixtures/module-size-ratchet.json binds scripts/lib/shard-engine.ts (<= 800 lines, <= 150 per function) and records the residual runner sizes (free 2352, paid 1921) as non-growth caps; allowlist entries are keyed on file plus matched text and need a reason. Failure output lists file:line, the rule, Fix: and the allowlist path. touchfiles.test.ts gains the moved-code superset check over test/fixtures/touchfile-move-goldens/ (W2 golden recorded at96764e80: test-strict-output.ts and test-paid-shards.ts global, test-free-shards.ts none). * refactor(browse): declared route table replaces the buildFetchHandler if-chain The ~1,300-line if-chain in buildFetchHandler becomes a route table: each entry declares method, path, auth kind and surfaces, and one auth gate in browse/src/routes/table.ts returns the per-kind denial (root-bearer, scoped, root-or-sse-cookie: 401 Unauthorized; root-token: 403 Root token required; extension-origin: 403 Forbidden). Unmatched requests take the declared fallthrough (root-bearer check, then plain-text 404). Handlers move to browse/src/routes/{core,pairing,pty,tokens,tunnel,activity,commands,files, inspector}.ts and receive a RouteContext with auth checks as functions instead of closing over factory locals. Dispatch order is unchanged: tunnel filter, beforeRoute overlay, gate, handler. TUNNEL_PATHS stays a literal in server.ts. Behavior-preserving: the black-box auth matrix from the previous commit passes unchanged. /memory and /inspector/events are declared root-bearer because the blanket check always ran before their SSE-cookie branch. Source-text route tests are rewritten as behavioral tests through buildFetchHandler or a route's real handler with a stub RouteContext (browse/test/route-test-harness.ts). Checks with no runtime seam are re-pointed to the route modules: Surface type, /inspector/events SSE helper, sanitizeReplacer imports, /pty-inject-scan sidecar-client import, and the ngrok config lookup and startTunnel wiring that stay in server.ts. * test(browse): stubbed-handler auth matrix and route inventory for the route table Every ROUTES entry runs through the real dispatcher and gate with stub handlers on each declared surface and six credentials; denials assert the exact status and body each auth kind returned at96764e8, admitted credentials assert the handler ran (with the gate's TokenInfo for scoped routes). Also pins the reviewed route inventory (method, path, auth kind, surfaces), that every entry declares auth and surfaces, that the table's tunnel paths equal the TUNNEL_PATHS literal with GET /connect admitted, the unmatched fallthrough, and that the root token is rejected on every tunnel route through buildFetchHandler. * test(browse): ratchet (b) keeps route dispatch inside the route table Scans browse/src/server.ts and browse/src/routes/*.ts for pathname comparisons; only the table matcher and the tunnel-surface filter are allowed, listed with reasons in browse/test/fixtures/route-dispatch-allowlist.json (keyed on file plus line text). Also checks every entry declares auth and surfaces and that gstack registers no beforeRoute overlay itself. Self-tests plant a violation and assert the file:line, Fix: and allowlist path in the message, that a shifted line stays allowlisted, and that a reasonless entry is rejected. * test: touchfile superset check for modules moved out of browse/src/server.ts Records the paid evals selected by touching browse/src/server.ts at96764e80(17 E2E, 1 LLM judge) and asserts every browse/src/routes/*.ts module selects a superset. The test reads every golden in test/fixtures/moved-module-selection/ so other moved-code goldens can sit beside it. * test(shard-engine): give non-timeout corpus fixtures CI headroom; keep the POSIX golden off the Windows lane Only the wall-timeout fixture keeps a 3s wall; the rest get 60s so a loaded host cannot turn a pass into a timeout. Base and branch runners still agree on every classification under the new walls. The Windows exclusion entry moves the free runner's ratchet (c) residual cap to 2356 lines. * refactor(pty): one runPtySession loop drives observation, counting and floor test/helpers/pty/session.ts owns launch -> start -> (poll -> tick)* -> timeout and the failure contract the three runners each hand-rolled: the run's own error wins over capture and close errors, close always runs, owned fixture cleanup runs last (also when launch fails). Each runner now supplies a PtySessionPlan: its boot/command step, poll cadence (2s observation/floor sleep; counting's output wake + 250ms coalesce), tick policy (permission handling, native identity, terminal rules stay per runner because they differ) and capture hooks. The runner bodies are decomposed into top-level steps so no function exceeds 150 lines; behavior is unchanged and the fake-driver cases from the first W4 commit pass unmodified. The counting capture step and the native completion-summary predicate are now named functions (countingCapture, isNativeCompletionSummary), so plan-create-prepublication and plan-count-completion call them directly instead of executing sliced source. The two harnesses that still execute a sliced runner body with injected boundaries (eng-seeded-completion-ai, plan-floor-permission) pass the PtyDriver seam instead of overriding Date/Bun.sleep. * test(ratchet-c): register route modules, review resolver modules and server.ts residual cap * refactor(pty): decompose launchClaudePty and engNumberedFindingAUQ under 150 lines launchClaudePty (349 lines) becomes launch preparation (args, hermetic child env, owned state roots), recorder creation, spawn, the trust-dialog watcher, close, and the session handle over one PtyProcess state object. The failure order is unchanged: abort the viewport, dispose any recorders created so far, dispose the viewport, rethrow. The --model / --strict-mcp-config ordering and seedSkills wiring stay pinned by the behavioral fake-CLI tests. engNumberedFindingAUQ (345 lines) keeps its guards and dispatch; each self-contained issue family (declared cache, library retry hooks, cache owner, injected singleton, shared writers, injected export) moves verbatim into its own function. Every pty/ module is now <= 800 lines and every top-level function <= 150 lines. * test(pty): split claude-pty-runner.unit.test.ts along the pty/ module seams The 188 unit tests move verbatim into claude-pty-runner.{screen,classify, auq,launch,plan-native,boundaries}.unit.test.ts (test names unchanged; each file imports only what it uses from the barrel). The five files that no longer read a SKILL.md template join the test-of-test ratchet baseline with a reason. * test(touchfiles): moved PTY modules keep their paid-eval selection test/fixtures/touchfile-selection/w4-pty.json records, at96764e8, the paid evals selected by touching test/helpers/claude-pty-runner.ts (20) and test/helpers/pty-screen.ts (20). touchfiles.test.ts now asserts every .ts file under test/helpers/pty/ (and pty/screen.ts for both sources) selects a superset, reading every golden in that directory so later moves can add one; a planted-violation case pins the report and its Fix line. * fix(browse): unexchanged pair setup keys no longer authenticate bearer requests validateToken accepted a gsk_setup_ key as a bearer on /command, /batch and /file (found while building the W3 auth matrix). A setup key now only authenticates the /connect exchange. * W1: one state-root owner (lib/state-root.ts + bin/gstack-state-root.sh), gstack-paths --explain and fail-stop, parity tests * W1: guarded migration of every executable state-root site; uninstall deletes only ~/.gstack Bins, careful/freeze hooks, setup, upgrade migrations, browse/src, design, ios-qa daemon, lib and scripts resolve the state root through bin/gstack-state-root.sh (bash) or lib/state-root.ts (TS). Bins source the twin and stop with a reinstall message when it is missing; hooks source it and never spawn gstack-paths. browse/src/config.ts and lib/cso/state.ts delegate to resolveStateRoot. Analytics writers and readers move together so the usage log stays one file. gstack-uninstall deletes state only at ~/.gstack, refuses (exit 2) when it resolves to /, $HOME or an ancestor, the checkout or the git root, and leaves any other resolved root in place with the removal command. Fixtures that copy single bins now copy the twin. * W1: privacy keys and trust-policy deny tiers merge across state roots; gstack-config reporting; test hermeticity readConfigKey / gstack_read_config_key return the most restrictive telemetry, memorable_recall, codex_reviews and update_check across the resolved root and ~/.gstack; other keys read the resolved root only. gstack-config set reports an overriding root with the exact override command, list shows the winning root and a root-variable disagreement line. gstack-gbrain-repo-policy get merges deny/read-only tiers. gstack-egress reads through readConfigKey. test-setup.ts strips inherited GSTACK_STATE_ROOT/GSTACK_STATE_DIR and redirects the legacy root. * W1: shared hook logging helper (hosts/claude/hooks/hook-log.ts) One hook-errors.log writer: root from resolveStateRoot, 0600 on every append, opt-in rate limit used only by memorable-user-prompt. The five hooks route through it. * W1: docs/state-root.md and README troubleshooting pointer Precedence table, a real --explain example, the move-your-state recipe, merged privacy keys, the uninstall rule, the resolver-failure fix, and the plugin-mode note (evidence gate: no official plugin distribution). * W1b: template and resolver prose resolve state through guarded gstack-paths; ratchet (a) Every gstack-paths eval in templates and resolvers carries the fail-stop guard; executable ~/.gstack paths in bash blocks (context recovery preamble, eureka log, analytics, project artifacts, upgrade snooze, setup-gbrain lock, retro snapshots, ship consent marker) use $GSTACK_STATE_ROOT, and the writer prose that pairs with them points at the printed PROJECT_DIR / RETRO_FILE. ship drops export GSTACK_STATE_ROOT. SKILL.md regenerated (claude + codex), ship goldens re-pinned, parity and context-budget caps raised to the measured sizes with notes. test/state-root-ratchet.test.ts enforces the rule with a reasoned allowlist; W1 touchfile entries plus a superset golden. * refactor: apply W1 state-root edits in W2/W3/W5-owned files; one moved-code touchfile golden for all workstreams * test: fold the moved-code touchfile golden into touchfiles.test.ts; fix integration fixture closure and caps * v1.91.11.0: CHANGELOG, TODOS, docs and conventions for the refactor wave * test: re-measure plan-ceo/design-consultation caps and ship goldens after the guarded plan-discovery and spec-review blocks; add the state-root twin to the workflow-boundaries fixture * fix(windows): migrations resolve their directory with either path separator; state-root parity compares under the HOME Git Bash actually sees * fix(review,ship): state plan-check timing after smoke expiry and test_stub Skip semantics (review workflow judge clarity) * test(qa-eval): webhook fix eval asks for the fix loop's post-repair probes; eight-scenario coverage stays in the report-only case and the harness recheck * test(qa-eval): re-pin the webhook prompt contract to the fix-loop stage; R29 coverage omissions stay bound by the report-only case * fix(review,ship): plan checks publish a checkpoint before each probe; only the smoke expiry stop is skipped * fix(qa): carry #2999's checkpoint receipt link, report-template line and full-revision placeholder (identical hunks) * test(qa-callers): disable git auto maintenance in the caller fixture Git 2.47+ runs auto maintenance detached after commit; on the CI runner's git 2.55 it rewrote .git/objects fan-out directories while the write observer was running, which surfaced as unauthorized mutations. Same gc.auto=0 / maintenance.auto=false guard the shared-libs fixture already uses. * test(plan-mode-no-op): require prose evidence for the prose-fallback members so a spinner-frame judge verdict cannot end the run as asked * test(ship-docsync): carry #2999's seeded-attempt docsync harness (identical files) The doc-sync fault cases replayed attempt 1 before reaching their gate and ran out of their 285s budget. The fixture now seeds attempt 1 and the parent starts at the gate under test. Taken byte-identical from origin/capy/audit-fix-wave (fb526898,e6ac813d,6ce10ff7,d0c53577,77cce3be). Local: stale-before, recovery and late-result 6/6 PASS (97-164s); the whole file 12/12 PASS.
803 lines
33 KiB
TypeScript
803 lines
33 KiB
TypeScript
/**
|
||
* Deterministic unit tests for the frame classifiers (test/helpers/pty/classify.ts).
|
||
* Split along the W4 module seams from the former claude-pty-runner.unit.test.ts;
|
||
* tests import the public barrel, test/helpers/claude-pty-runner.ts.
|
||
*/
|
||
import { describe, test, expect } from 'bun:test';
|
||
import {
|
||
isNumberedOptionListVisible,
|
||
isProseAUQVisible,
|
||
isScopeGateQuestionVisible,
|
||
isScopeGateAutoSelectVisible,
|
||
isPlanReadyVisible,
|
||
parseNumberedOptions,
|
||
classifyVisible,
|
||
TAIL_SCAN_BYTES,
|
||
optionsSignature,
|
||
stripAnsi,
|
||
COMPLETION_SUMMARY_RE,
|
||
classifyPlanCountFrame,
|
||
capturePlanCountQuestion,
|
||
planCountSubmissionInput,
|
||
} from './claude-pty-runner';
|
||
|
||
describe('scope-gate render detectors', () => {
|
||
// The verbatim announcement string from the plan-eng/plan-design SKILL.md
|
||
// templates. If the template rewording drifts, THIS fixture fails first —
|
||
// before the paid plan-mode smokes silently degrade to vacuous asserts.
|
||
const TEMPLATE_ANNOUNCEMENT =
|
||
'Scope gate: plan mode — auto-selected B (reviewing <target>).';
|
||
|
||
describe('isScopeGateQuestionVisible', () => {
|
||
test('matches the clean prose gate render (question + option bodies)', () => {
|
||
const sample = `
|
||
What should I review?
|
||
A) The current branch diff — the work in progress on this branch.
|
||
B) A plan or design doc I'll paste or point you to.
|
||
C) A specific file, directory, or path.
|
||
Recommendation: A when a branch diff exists, otherwise B.
|
||
`;
|
||
expect(isScopeGateQuestionVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('matches the native numbered render (no lettered markers)', () => {
|
||
const sample = `
|
||
What should I review?
|
||
|
||
❯ 1. The current branch diff — the work in progress on this branch.
|
||
2. A plan or design doc I'll paste or point you to.
|
||
3. A specific file, directory, or path.
|
||
`;
|
||
expect(isScopeGateQuestionVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('matches the PTY-collapsed render (stripAnsi squished spaces)', () => {
|
||
const sample = 'WhatshouldIreview?A)Thecurrentbranchdiff—theworkinprogress';
|
||
expect(isScopeGateQuestionVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('stays false on narration quoting only the question', () => {
|
||
const sample =
|
||
"Normally I'd ask 'What should I review?' but plan mode is active, so I'm proceeding.";
|
||
expect(isScopeGateQuestionVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('stays false on unrelated review prose', () => {
|
||
const sample = 'I will review the current branch diff and report findings.';
|
||
expect(isScopeGateQuestionVisible(sample)).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe('isScopeGateAutoSelectVisible', () => {
|
||
test('matches the verbatim template announcement', () => {
|
||
expect(isScopeGateAutoSelectVisible(TEMPLATE_ANNOUNCEMENT)).toBe(true);
|
||
});
|
||
|
||
test('matches a real announcement with a concrete target', () => {
|
||
const sample =
|
||
'Scope gate: plan mode — auto-selected B (reviewing ~/.claude/plans/my-feature.md). Running the Design Doc Check next.';
|
||
expect(isScopeGateAutoSelectVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('matches the PTY-collapsed announcement', () => {
|
||
const sample = 'Scopegate:planmode—auto-selectedB(reviewingPLAN.md).';
|
||
expect(isScopeGateAutoSelectVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('stays false on narration about the behavior', () => {
|
||
const sample = "In plan mode I'd auto-select B and review the active plan.";
|
||
expect(isScopeGateAutoSelectVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('stays false on a VERBATIM QUOTE of the announcement (negation narration)', () => {
|
||
// The exact announcement line sits quoted in the skill context, so a
|
||
// model explaining why it is NOT firing it can reproduce it byte-exact
|
||
// inside quotes — that must not trip a must-stay-false assert.
|
||
const sample =
|
||
'Not in plan mode, so I won\'t announce "Scope gate: plan mode — auto-selected B (reviewing <target>)." and will ask instead.';
|
||
expect(isScopeGateAutoSelectVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('a later real render still matches after an earlier quoted mention', () => {
|
||
const sample =
|
||
'Earlier I said I would render "Scope gate: plan mode — auto-selected B (…)" and now:\n' +
|
||
'Scope gate: plan mode — auto-selected B (reviewing PLAN.md).';
|
||
expect(isScopeGateAutoSelectVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('matches tense paraphrases WITH the announcement prefix (auto-selecting / auto-selects)', () => {
|
||
expect(
|
||
isScopeGateAutoSelectVisible('Scope gate: plan mode — auto-selecting B (reviewing the drafted plan).'),
|
||
).toBe(true);
|
||
expect(isScopeGateAutoSelectVisible('Scope gate: plan mode — auto-selects B.')).toBe(true);
|
||
});
|
||
|
||
test('stays false on tense paraphrases WITHOUT the announcement prefix', () => {
|
||
expect(isScopeGateAutoSelectVisible('Auto-selecting B since we are in plan mode.')).toBe(false);
|
||
});
|
||
|
||
test('stays false on AUTO_DECIDE preamble output', () => {
|
||
const sample = 'Auto-decided scope question → B (your preference). Change with /plan-tune.';
|
||
expect(isScopeGateAutoSelectVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('stays false on a bare "selected B" without the announcement prefix', () => {
|
||
const sample = 'I selected B as the review target.';
|
||
expect(isScopeGateAutoSelectVisible(sample)).toBe(false);
|
||
});
|
||
});
|
||
});
|
||
|
||
describe('isProseAUQVisible', () => {
|
||
test('matches 4 lettered options A) B) C) D) at line starts (plan-eng prose AUQ shape)', () => {
|
||
const sample = `
|
||
What would you like me to review? Options:
|
||
A) Point me at an existing design doc or plan file (path).
|
||
B) Describe new work you're planning — I'll explore the codebase.
|
||
C) You meant /review for the diff already on this branch.
|
||
D) Something else (tell me).
|
||
Recommendation: A if you have a doc in mind, otherwise B.
|
||
❯
|
||
`;
|
||
expect(isProseAUQVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('matches 2 lettered options (minimum threshold)', () => {
|
||
const sample = `
|
||
A) First option
|
||
B) Second option
|
||
`;
|
||
expect(isProseAUQVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('matches 3 numbered options 1. 2. 3. without ❯ 1. cursor (autoplan prose AUQ shape)', () => {
|
||
const sample = `
|
||
What's the task? A few options:
|
||
1. You have a plan idea in mind — describe it.
|
||
2. You want to review an existing plan elsewhere.
|
||
3. You meant a different command — /plan-ceo-review etc.
|
||
❯
|
||
`;
|
||
expect(isProseAUQVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('returns false when ❯ 1. cursor is present in the recent tail (native UI handled by isNumberedOptionListVisible)', () => {
|
||
const sample = `
|
||
❯ 1. First option
|
||
2. Second option
|
||
3. Third option
|
||
`;
|
||
expect(isProseAUQVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('does NOT suppress numbered-prose detection when ❯ 1. is only in early scrollback (trust dialog)', () => {
|
||
// Boot trust dialog rendered ❯ 1. Yes at startup, then a long body of
|
||
// model output, then prose-rendered numbered options now. The historic
|
||
// ❯ 1. is in the full buffer but NOT in the recent tail. Should detect
|
||
// the prose AUQ.
|
||
const trustHeader = '❯ 1. Yes, trust\n 2. No\n';
|
||
const filler = 'x'.repeat(5000); // pushes trust dialog out of last 4KB tail
|
||
const proseAUQ = `\n 1. Review the docs\n 2. Investigate the code\n 3. Defer to next session\n❯ \n`;
|
||
const sample = trustHeader + filler + proseAUQ;
|
||
expect(isProseAUQVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('returns false on single lettered option', () => {
|
||
const sample = `
|
||
A) Only one option mentioned in passing.
|
||
`;
|
||
expect(isProseAUQVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('matches 2 numbered options (threshold matches lettered branch — tails miss option 1)', () => {
|
||
const sample = `
|
||
1. First note.
|
||
2. Second note.
|
||
`;
|
||
expect(isProseAUQVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('returns false on a single numbered option', () => {
|
||
const sample = `
|
||
1. Only one option mentioned.
|
||
`;
|
||
expect(isProseAUQVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('does not match mid-prose lettered text like "(see option B) above"', () => {
|
||
const sample = `
|
||
This refers to (see option B) above and also to point A) earlier.
|
||
`;
|
||
// The B) and A) markers are mid-line, not at line starts, so they don't count.
|
||
expect(isProseAUQVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('matches with leading whitespace and ❯ prefix on options', () => {
|
||
const sample = `
|
||
A) Option with whitespace prefix
|
||
❯ B) Option with cursor prefix
|
||
C) Another option
|
||
`;
|
||
expect(isProseAUQVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('returns false on plain text with no option markers', () => {
|
||
expect(isProseAUQVisible('Just some plain text output from the model.')).toBe(false);
|
||
expect(isProseAUQVisible('')).toBe(false);
|
||
});
|
||
|
||
// Pattern 3: markdown bold-bullet options — office-hours renders its mode
|
||
// question this way under --disallowedTools, with no letter/number marker.
|
||
test('matches office-hours markdown bold-bullet mode question (Pattern 3)', () => {
|
||
const sample = `
|
||
> Before we dig in — what's your goal with this?
|
||
>
|
||
> - **Building a startup** (or thinking about it)
|
||
> - **Intrapreneurship** — internal project at a company, need to ship fast
|
||
> - **Hackathon / demo** — time-boxed, need to impress
|
||
> - **Open source / research** — building for a community
|
||
> - **Learning** — teaching yourself to code
|
||
❯
|
||
`;
|
||
expect(isProseAUQVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('bold-bullets require a preceding interrogative — no "?" => false', () => {
|
||
// 3+ bold bullets but no question stem: this is a feature list, not an AUQ.
|
||
const sample = `
|
||
Here is what shipped:
|
||
- **Faster builds** via caching
|
||
- **Smaller binaries** through tree-shaking
|
||
- **Better errors** with source maps
|
||
`;
|
||
expect(isProseAUQVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('a question with fewer than 3 bold bullets stays false (guard)', () => {
|
||
const sample = `
|
||
Which approach do you prefer?
|
||
- **Option one** is simpler
|
||
- **Option two** is faster
|
||
`;
|
||
expect(isProseAUQVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('plain (non-bold) bullets after a question do not trigger Pattern 3', () => {
|
||
// Only bold bullets count — plain "- text" prose lists are too common.
|
||
const sample = `
|
||
What should we do about this?
|
||
- run the tests
|
||
- ship the fix
|
||
- file a follow-up
|
||
`;
|
||
expect(isProseAUQVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('Pattern 3 still defers to a live native cursor list (❯ 1.)', () => {
|
||
const sample = `
|
||
> What's your goal?
|
||
❯ 1. **Building a startup**
|
||
2. **Intrapreneurship**
|
||
3. **Hackathon**
|
||
`;
|
||
// The ❯1. cursor gate fires first — native list handling owns this.
|
||
expect(isProseAUQVisible(sample)).toBe(false);
|
||
});
|
||
|
||
// Pattern 4/5: collapsed-form prose AUQ. stripAnsi destroys the newlines +
|
||
// inter-word spaces, so a real prose AUQ arrives collapsed and defeats the
|
||
// line-anchored Patterns 1-3. These are the dominant Shape-B render mode in
|
||
// the plan-design smoke + floor timeouts — verbatim de-spinnered bytes from
|
||
// the real failing runs (bdm3sucql.output).
|
||
test('matches the real collapsed floor render (colon-delimited, Pattern 4/5)', () => {
|
||
const sample =
|
||
'The review is blocked on D1—reply withA, B, r Cabovetocontinue:' +
|
||
'- A(recommended): Spec thefull P1AskUserQuestioncopy in this review' +
|
||
'-B:LeaveP1copytotheimplementerwithstructuralrequirements' +
|
||
'C: Add a placeholder template to the plan';
|
||
expect(isProseAUQVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('matches the real collapsed plan-mode render (Recommendation + collapsed A)/B), Pattern 4/5)', () => {
|
||
const sample =
|
||
'Recommendation:A—writethecopynow.(recommended)A) Writ the fullcopy in thisdesign review— now.' +
|
||
'(recommended) Completeness:10/10 B) Leveit to theimplemente — task spec is enough.' +
|
||
'Reply withA (write the copy now)orB(leavetoimplementer)';
|
||
expect(isProseAUQVisible(sample)).toBe(true);
|
||
});
|
||
|
||
test('collapsed-form requires BOTH signals — single B) + word "recommendation" stays false', () => {
|
||
// Only one punctuated letter marker: the two-signal contract is not met.
|
||
const sample =
|
||
'We should consider option B) here. My recommendation is to do it now.';
|
||
expect(isProseAUQVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('collapsed-form requires letter punctuation — comma-only "ReplywithA,B,orC" stays false', () => {
|
||
// Reply-instruction present, but the letters carry no ) : or ( punctuation,
|
||
// so they could be incidental enumerations in running prose. Stays false.
|
||
const sample = 'ReplywithA,B,orC';
|
||
expect(isProseAUQVisible(sample)).toBe(false);
|
||
});
|
||
|
||
test('collapsed-form does not regress the existing FP guard (see option B) ... point A))', () => {
|
||
// The classic citation FP: a model referencing prior options in prose.
|
||
// No reply-instruction / recommendation marker on its own line, so the
|
||
// collapsed-form signal does not fire either.
|
||
const sample =
|
||
'As noted (see option B) above, and the earlier point A) we discussed, this is fine.';
|
||
expect(isProseAUQVisible(sample)).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe('classifyVisible (runtime path through the runner classifier)', () => {
|
||
// These tests call the actual classifier so a future contributor who
|
||
// reorders branches (e.g. moves the permission short-circuit before
|
||
// isPlanReadyVisible) is caught deterministically.
|
||
|
||
test('skill question → returns asked', () => {
|
||
const visible = `
|
||
D1 — Choose your scope mode
|
||
|
||
❯ 1. HOLD SCOPE
|
||
2. SCOPE EXPANSION
|
||
3. SELECTIVE EXPANSION
|
||
4. SCOPE REDUCTION
|
||
`;
|
||
const result = classifyVisible(visible);
|
||
expect(result?.outcome).toBe('asked');
|
||
});
|
||
|
||
test('permission dialog (Bash) → returns null (skip, keep polling)', () => {
|
||
const visible = `
|
||
Bash command \`gstack-update-check\` requires permission to run.
|
||
|
||
❯ 1. Yes
|
||
2. No
|
||
`;
|
||
expect(isNumberedOptionListVisible(visible)).toBe(true); // pre-filter
|
||
expect(classifyVisible(visible)).toBeNull(); // post-filter
|
||
});
|
||
|
||
test('plan-ready confirmation → returns plan_ready (wins over asked)', () => {
|
||
const visible = `
|
||
Ready to execute the plan?
|
||
|
||
❯ 1. Yes, proceed
|
||
2. No, keep planning
|
||
`;
|
||
const result = classifyVisible(visible);
|
||
expect(result?.outcome).toBe('plan_ready');
|
||
});
|
||
|
||
test('silent write to unsanctioned path → returns silent_write', () => {
|
||
const visible = `
|
||
⏺ Write(src/app/dangerous-write.ts)
|
||
⎿ Wrote 42 lines
|
||
`;
|
||
const result = classifyVisible(visible);
|
||
expect(result?.outcome).toBe('silent_write');
|
||
expect(result?.summary).toContain('src/app/dangerous-write.ts');
|
||
});
|
||
|
||
test('write to sanctioned path (.claude/plans) → returns null (allowed)', () => {
|
||
const visible = `
|
||
⏺ Write(/Users/me/.claude/plans/some-plan.md)
|
||
⎿ Wrote 42 lines
|
||
`;
|
||
expect(classifyVisible(visible)).toBeNull();
|
||
});
|
||
|
||
test('write while a permission dialog is on screen → returns null (gated, not silent, not asked)', () => {
|
||
const visible = `
|
||
⏺ Write(src/app/edit-with-permission.ts)
|
||
|
||
Edit to src/app/edit-with-permission.ts
|
||
|
||
Do you want to proceed?
|
||
|
||
❯ 1. Yes
|
||
2. No
|
||
`;
|
||
// The numbered prompt is a permission dialog (Edit to + Do you want to proceed?);
|
||
// silent_write is suppressed because a numbered prompt is visible, AND
|
||
// 'asked' is suppressed because the prompt is a permission dialog.
|
||
expect(classifyVisible(visible)).toBeNull();
|
||
});
|
||
|
||
test('write while a real skill question is on screen → returns asked (write is captured but not silent)', () => {
|
||
const visible = `
|
||
⏺ Write(src/app/foo.ts)
|
||
|
||
D1 — Choose your scope mode
|
||
|
||
❯ 1. HOLD SCOPE
|
||
2. SCOPE EXPANSION
|
||
`;
|
||
// The numbered prompt is a skill question, not a permission dialog;
|
||
// silent_write is suppressed (numbered prompt is visible) and the
|
||
// outcome is 'asked' — Step 0 fired.
|
||
const result = classifyVisible(visible);
|
||
expect(result?.outcome).toBe('asked');
|
||
});
|
||
|
||
test('idle / no signals → returns null', () => {
|
||
const visible = `
|
||
Some prose without any classifier signals.
|
||
`;
|
||
expect(classifyVisible(visible)).toBeNull();
|
||
});
|
||
|
||
test('TAIL_SCAN_BYTES is exported as 1500', () => {
|
||
// Shared between runner and routing test; a regression that desyncs the
|
||
// recent-tail window would surface here.
|
||
expect(TAIL_SCAN_BYTES).toBe(1500);
|
||
});
|
||
|
||
// D4-B: strictPlanWrites detector. Catches the transcript bug where the
|
||
// model writes findings to the plan file before any AskUserQuestion fires.
|
||
test('strictPlanWrites: plan write before any AUQ → wrote_findings_before_asking', () => {
|
||
const visible = `
|
||
⏺ Edit(/Users/me/.claude/plans/some-plan.md)
|
||
⎿ Updated 12 lines
|
||
`;
|
||
const result = classifyVisible(visible, { strictPlanWrites: true });
|
||
expect(result?.outcome).toBe('wrote_findings_before_asking');
|
||
expect(result?.summary).toContain('.claude/plans/some-plan.md');
|
||
});
|
||
|
||
test('strictPlanWrites: plan write AFTER an AUQ render → not flagged', () => {
|
||
// AUQ renders first, then the model writes the plan post-answer. This is
|
||
// the legitimate end-of-workflow flow and must NOT trigger the detector.
|
||
const visible = `
|
||
D1 — Some scope question
|
||
|
||
❯ 1. Option A
|
||
2. Option B
|
||
|
||
⏺ Edit(/Users/me/.claude/plans/some-plan.md)
|
||
⎿ Updated 12 lines
|
||
`;
|
||
const result = classifyVisible(visible, { strictPlanWrites: true });
|
||
// Outcome is 'asked' (the numbered list rendered); the post-AUQ plan
|
||
// write is ignored by the detector.
|
||
expect(result?.outcome).toBe('asked');
|
||
});
|
||
|
||
test('strictPlanWrites: AUQ first then plan write — write_pos > auq_pos → not flagged', () => {
|
||
// Same scenario, more explicit ordering: the regex finds the write at a
|
||
// position AFTER the numbered list. Detector lets it through.
|
||
const visible = [
|
||
'D1 — Choose your approach',
|
||
'',
|
||
'❯ 1. Approach A',
|
||
' 2. Approach B',
|
||
'',
|
||
'⏺ Write(/Users/me/.claude/plans/draft.md)',
|
||
'⎿ Wrote 42 lines',
|
||
].join('\n');
|
||
const result = classifyVisible(visible, { strictPlanWrites: true });
|
||
expect(result?.outcome).toBe('asked');
|
||
});
|
||
|
||
test('strictPlanWrites: only a permission dialog visible → plan write still flagged', () => {
|
||
// A permission dialog ❯ 1./2. is NOT an AUQ; pre-AUQ plan writes still
|
||
// hit the detector even when a permission prompt is on screen.
|
||
const visible = `
|
||
⏺ Edit(/Users/me/.claude/plans/some-plan.md)
|
||
|
||
Edit to /Users/me/.claude/plans/some-plan.md
|
||
|
||
Do you want to proceed?
|
||
|
||
❯ 1. Yes
|
||
2. No
|
||
`;
|
||
const result = classifyVisible(visible, { strictPlanWrites: true });
|
||
expect(result?.outcome).toBe('wrote_findings_before_asking');
|
||
});
|
||
|
||
test('strictPlanWrites OFF: plan write before AUQ → returns null (legacy behavior preserved)', () => {
|
||
const visible = `
|
||
⏺ Edit(/Users/me/.claude/plans/some-plan.md)
|
||
⎿ Updated 12 lines
|
||
`;
|
||
// Without strictPlanWrites, the sanctioned-path list lets this through.
|
||
expect(classifyVisible(visible)).toBeNull();
|
||
});
|
||
});
|
||
|
||
describe('parseNumberedOptions', () => {
|
||
test('does not combine an old AUQ prompt with the later ordinary test-case list', () => {
|
||
// B CEO retry, 2026-09-08: the old prompt cursor slid outside the
|
||
// option parser's 4KB window. Its prose fallback then supplied a new
|
||
// five-item test list while the prompt parser retained the old AUQ.
|
||
const visible = '☐Stripe event types\nWhich event should the handler accept?\n' +
|
||
'❯1.Specify one canonical event\n2.Accept all events\n' + '·'.repeat(4200) + '\n' +
|
||
'Minimum required test cases (all must be specified in the plan):\n' +
|
||
'1.Happypath:validcanonicalevent,knownuser→userupdated,emailsent\n' +
|
||
'2.Email failure:emailthrows→userupdated,errorlogged,HTTP200\n' +
|
||
'3.DB timeout: DB throws onuser update →exceptin ropagates, non-200\n' +
|
||
'4.Unkown event typ: non-canonical event→ HTTP200,nouserupdate\n' +
|
||
'5.Unknown user: valid event, usernotinDB→existingguard→HTTP200\n❯1\n';
|
||
const seen = new Set<string>();
|
||
expect(capturePlanCountQuestion(visible, seen, 0, false)).toBeNull();
|
||
expect(seen.size).toBe(0);
|
||
});
|
||
|
||
test('extracts options from a clean cursor list', () => {
|
||
const visible = `
|
||
❯ 1. HOLD SCOPE
|
||
2. SCOPE EXPANSION
|
||
`;
|
||
const opts = parseNumberedOptions(visible);
|
||
expect(opts).toHaveLength(2);
|
||
expect(opts[0]).toEqual({ index: 1, label: 'HOLD SCOPE' });
|
||
expect(opts[1]).toEqual({ index: 2, label: 'SCOPE EXPANSION' });
|
||
});
|
||
|
||
test('returns empty array on prose-with-numbers (no cursor)', () => {
|
||
expect(parseNumberedOptions('text 1. one 2. two')).toEqual([]);
|
||
});
|
||
|
||
test('extracts options when the cursor is INLINE with prompt header (box-layout)', () => {
|
||
// Real /plan-ceo-review rendering: the TTY's cursor-positioning escapes
|
||
// collapse divider + header + prompt + cursor onto one logical line.
|
||
// Subsequent options (2..7) still start their own lines.
|
||
const visible = [
|
||
'────────────────────────────────────────',
|
||
'☐ Review scope What scope do you want me to CEO-review? ❯ 1. The branch\'s diff vs main',
|
||
' Review the full branch: ~10K LOC.',
|
||
'2. A specific plan file or design doc',
|
||
' You point me at a file (path) and I review that.',
|
||
'3. An idea you\'ll describe inline',
|
||
'4. Cancel — wrong skill',
|
||
'5. Type something.',
|
||
'────────────────────────────────────────',
|
||
'6. Chat about this',
|
||
'7. Skip interview and plan immediately',
|
||
].join('\n');
|
||
const opts = parseNumberedOptions(visible);
|
||
expect(opts).toHaveLength(7);
|
||
expect(opts[0]).toEqual({ index: 1, label: "The branch's diff vs main" });
|
||
expect(opts[1]?.index).toBe(2);
|
||
expect(opts[6]?.index).toBe(7);
|
||
expect(opts[6]?.label).toBe('Skip interview and plan immediately');
|
||
});
|
||
|
||
test('inline-cursor and start-of-line cursor both produce 7 options for the box-layout case', () => {
|
||
// The inline path captures option 1 from the cursor line itself; the
|
||
// subsequent-lines path captures 2..7 with the existing optionRe.
|
||
const inlineLayout = [
|
||
'header text ❯ 1. first option',
|
||
'2. second',
|
||
'3. third',
|
||
].join('\n');
|
||
expect(parseNumberedOptions(inlineLayout)).toEqual([
|
||
{ index: 1, label: 'first option' },
|
||
{ index: 2, label: 'second' },
|
||
{ index: 3, label: 'third' },
|
||
]);
|
||
|
||
const cleanLayout = [
|
||
' ❯ 1. first option',
|
||
' 2. second',
|
||
' 3. third',
|
||
].join('\n');
|
||
expect(parseNumberedOptions(cleanLayout)).toEqual([
|
||
{ index: 1, label: 'first option' },
|
||
{ index: 2, label: 'second' },
|
||
{ index: 3, label: 'third' },
|
||
]);
|
||
});
|
||
});
|
||
|
||
// ────────────────────────────────────────────────────────────────────────────
|
||
// Per-finding count primitives — Section 3 unit tests #1–#5, #7, #12.
|
||
// ────────────────────────────────────────────────────────────────────────────
|
||
|
||
describe('optionsSignature', () => {
|
||
test('returns a "|"-joined `index:label` string for a clean list', () => {
|
||
const sig = optionsSignature([
|
||
{ index: 1, label: 'HOLD SCOPE' },
|
||
{ index: 2, label: 'SCOPE EXPANSION' },
|
||
]);
|
||
expect(sig).toBe('1:HOLD SCOPE|2:SCOPE EXPANSION');
|
||
});
|
||
|
||
test('order-independent: shuffled inputs produce the same signature', () => {
|
||
// parseNumberedOptions already returns sorted, but defensive sort means
|
||
// a future caller that hands us shuffled input still produces a stable
|
||
// dedupe signature.
|
||
const a = optionsSignature([
|
||
{ index: 2, label: 'B' },
|
||
{ index: 1, label: 'A' },
|
||
{ index: 3, label: 'C' },
|
||
]);
|
||
const b = optionsSignature([
|
||
{ index: 1, label: 'A' },
|
||
{ index: 2, label: 'B' },
|
||
{ index: 3, label: 'C' },
|
||
]);
|
||
expect(a).toBe(b);
|
||
});
|
||
|
||
test('empty list returns empty string', () => {
|
||
expect(optionsSignature([])).toBe('');
|
||
});
|
||
|
||
test('single-item list returns just that entry', () => {
|
||
expect(optionsSignature([{ index: 1, label: 'Only' }])).toBe('1:Only');
|
||
});
|
||
});
|
||
|
||
describe('COMPLETION_SUMMARY_RE', () => {
|
||
test('matches GSTACK REVIEW REPORT heading', () => {
|
||
expect(COMPLETION_SUMMARY_RE.test('## GSTACK REVIEW REPORT')).toBe(true);
|
||
});
|
||
|
||
test('matches Completion Summary heading (ceo + eng)', () => {
|
||
expect(COMPLETION_SUMMARY_RE.test('## Completion Summary')).toBe(true);
|
||
expect(COMPLETION_SUMMARY_RE.test('## Completion summary')).toBe(true);
|
||
});
|
||
|
||
test('matches Status: clean (CEO review-log shape)', () => {
|
||
expect(COMPLETION_SUMMARY_RE.test('Status: clean')).toBe(true);
|
||
expect(COMPLETION_SUMMARY_RE.test('Status: issues_open')).toBe(true);
|
||
});
|
||
|
||
test('matches VERDICT: line', () => {
|
||
expect(COMPLETION_SUMMARY_RE.test('VERDICT: CLEARED — Eng Review passed')).toBe(true);
|
||
});
|
||
|
||
test('does NOT match prose mentions of "verdict" mid-line', () => {
|
||
// VERDICT must be at the start of a line to count.
|
||
expect(COMPLETION_SUMMARY_RE.test('the final verdict: undecided')).toBe(false);
|
||
});
|
||
|
||
test('does NOT treat source or proposed diff rows as assistant completion', () => {
|
||
for (const line of [
|
||
'409 +## GSTACK REVIEW REPORT',
|
||
'419 +**VERDICT:** Design Review complete — 8 decisions made.',
|
||
'+## GSTACK REVIEW REPORT',
|
||
'409→## GSTACK REVIEW REPORT',
|
||
'The plan must end with ## GSTACK REVIEW REPORT.',
|
||
]) expect(COMPLETION_SUMMARY_RE.test(line)).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe('classifyPlanCountFrame replay', () => {
|
||
test('waits through proposed Write approval and tool output, then accepts the actual report', () => {
|
||
// Sanitized rows and native prompt from the failed design-count attempt.
|
||
const proposedDiff = [
|
||
'409 +## GSTACK REVIEW REPORT',
|
||
'416 +| Design Review | 1 | issues_open | score: 2/10 → 8/10, 8 decisions |',
|
||
'419 +**VERDICT:** Design Review complete — 8 decisions made.',
|
||
].join('\n');
|
||
const permission = [
|
||
'Doyouwanttooverwritegstack-test-plan-design.md?',
|
||
'❯1.Yes',
|
||
'2.Yes,andswitchtoacceptedits(auto-approvefileeditsandcommonfilecommands)forthissession;Yes,and',
|
||
'alwaysallowaccessto/tmp/fixtureforthissession',
|
||
'3.No',
|
||
'Esctocancel·Tabtoamend',
|
||
].join('\n');
|
||
const frames = [
|
||
`${proposedDiff}\n${permission}`,
|
||
`${proposedDiff}\n⏺ Updated gstack-test-plan-design.md`,
|
||
`${proposedDiff}\n⏺ ## GSTACK REVIEW REPORT\nDesign Review complete — 8 decisions made.`,
|
||
];
|
||
expect(frames.map(classifyPlanCountFrame)).toEqual(['permission', null, 'completion_summary']);
|
||
});
|
||
|
||
test('a pending native permission beats even an unnumbered report heading', () => {
|
||
const visible = '## GSTACK REVIEW REPORT\nDoyouwanttooverwriteplan.md?\n❯1.Yes\n2.No\nEsctocancel·Tabtoamend';
|
||
expect(classifyPlanCountFrame(visible)).toBe('permission');
|
||
});
|
||
|
||
test('a later report supersedes the granted menu still in short scrollback', () => {
|
||
const permission = 'Doyouwanttooverwriteplan.md?\n❯1.Yes\n2.No\nEsctocancel·Tabtoamend';
|
||
expect(classifyPlanCountFrame(permission)).toBe('permission');
|
||
expect(classifyPlanCountFrame(`${permission}\n● ## GSTACK REVIEW REPORT`)).toBe('completion_summary');
|
||
});
|
||
|
||
test('an active question after a prior report keeps the counter running', () => {
|
||
expect(classifyPlanCountFrame('## GSTACK REVIEW REPORT\nOne more choice\n❯1.Add to plan\n2.Defer')).toBeNull();
|
||
});
|
||
|
||
test('an active AUQ supersedes a granted permission menu in short scrollback', () => {
|
||
const permission = 'Doyouwanttooverwriteplan.md?\n❯1.Yes\n2.No\nEsctocancel·Tabtoamend';
|
||
const question = '☐ Error handling\nWhich failure path should we test?\n❯1.Timeout\n2.Refusal';
|
||
expect(classifyPlanCountFrame(`${permission}\n${question}`)).toBeNull();
|
||
});
|
||
|
||
test('preserves actual report variants and the native plan-ready terminal', () => {
|
||
for (const report of [
|
||
'## GSTACK REVIEW REPORT', '⏺##GSTACKREVIEWREPORT', '●GSTACKREVIEWREPORT',
|
||
'## Completion Summary', '● ## Completion Summary', 'Status: clean', 'Status: issues_open',
|
||
'VERDICT: CLEARED — Eng Review passed', '**VERDICT:** Design Review complete.',
|
||
]) expect(classifyPlanCountFrame(report)).toBe('completion_summary');
|
||
expect(classifyPlanCountFrame('Ready to execute the plan?\n❯1.Yes\n2.No, keep planning')).toBe('plan_ready');
|
||
});
|
||
});
|
||
|
||
describe('planCountSubmissionInput replay', () => {
|
||
test('uses the captured DevEx panel anchors when the Submit button label is damaged', () => {
|
||
const captured = [
|
||
'← ☒ Routing setup ☐ Cross-project ✔ Submit →',
|
||
'Review your answers',
|
||
'⚠You have not answere all questions',
|
||
' │ ●D1 — Shouldgstack add skill routingrulestothisproject\'sCLAUDE.md?<gstack-qid:routing-injection>',
|
||
'→dd routing rules (Recmmeded)',
|
||
'Ready to submit your answers?',
|
||
'❯1.Sbmi answers',
|
||
'2Cancel',
|
||
].join('\r\r');
|
||
expect(planCountSubmissionInput(captured)).toBe('\x1b[Z');
|
||
expect(planCountSubmissionInput(captured.replace('☐ Cross-project', '☒ Cross-project'))).toBe('\r');
|
||
expect(planCountSubmissionInput(captured + '\r☐ Retry spec\rRetry once?\r❯1.Yes\r2.No')).toBeNull();
|
||
expect(planCountSubmissionInput(captured + '\r☐ Proposal\rSend this proposal?\r❯1.Submit proposal\r2.Keep editing')).toBeNull();
|
||
expect(planCountSubmissionInput(captured + '\r☐ Retry spec\rRetry once?\r❯2.No\r3.Other')).toBeNull();
|
||
expect(planCountSubmissionInput(captured.replace('Review your answers', 'Review context'))).toBeNull();
|
||
expect(planCountSubmissionInput(captured.replace('Ready to submit your answers?', 'Read the proposed answers.'))).toBeNull();
|
||
});
|
||
|
||
test('the captured mode Submit panel with a damaged caption and dotless cursor returns to its unanswered tab', () => {
|
||
// Exact final active panel from targeted-a's SCOPE EXPANSION retry.
|
||
const captured = [
|
||
'← ☒ Routing rule ☐ Design doc ✔ Submit →',
|
||
'',
|
||
'Review your answrs',
|
||
'⚠ You hvenot answered all questions',
|
||
" ● Add gstack skill routing rules tothisproject'sCLAUDE.md?",
|
||
'→dd routing rues (Recommnded)',
|
||
'',
|
||
'Ready to submit your answers?',
|
||
'',
|
||
'❯1Submit answers',
|
||
' 2. Cancel',
|
||
].join('\r');
|
||
expect(planCountSubmissionInput(captured)).toBe('\x1b[Z');
|
||
const answered = captured.replace('☐ Design doc', '☒ Design doc').replace('⚠ You hvenot answered all questions', '');
|
||
expect(planCountSubmissionInput(answered)).toBe('\r');
|
||
expect(planCountSubmissionInput(captured + '\r☐ Design doc\rRun office hours?\r❯1Run now\r2.Skip')).toBeNull();
|
||
});
|
||
|
||
const incomplete = [
|
||
'← ☒ Learnings scope ☐ Approach ✔ Submit →',
|
||
'Review your answers',
|
||
'⚠You have not answered all questions',
|
||
' │ ●D1 — Cross-project learnings: Enable searching learnings from your other local projects?',
|
||
'→Enable cross-project (Recommended)',
|
||
'Ready t submit your answers?',
|
||
'❯1.Submit aswers',
|
||
'2Cancel',
|
||
].join('\r\r');
|
||
|
||
test('returns to the unanswered tab, then submits only after both answers', () => {
|
||
expect(planCountSubmissionInput(incomplete)).toBe('\x1b[Z');
|
||
const nextQuestion = [
|
||
'← ☒ Learnings scope ☐ Approach ✔ Submit →',
|
||
'│ Which approach should this plan use?',
|
||
'❯1.Extend the existing dispatcher',
|
||
'2.Add a separate handler',
|
||
].join('\r\r');
|
||
expect(planCountSubmissionInput(`${incomplete}\r${nextQuestion}`)).toBeNull();
|
||
const question = capturePlanCountQuestion(nextQuestion, new Set(), 0, true);
|
||
expect(question?.promptSnippet).toContain('Which approach');
|
||
expect(question?.options).toHaveLength(2);
|
||
const answered = incomplete.replace('☐ Approach', '☒ Approach').replace('⚠You have not answered all questions', '');
|
||
expect(planCountSubmissionInput(answered)).toBe('\r');
|
||
});
|
||
|
||
test('navigates to the first unanswered tab when more than one remains', () => {
|
||
const frame = incomplete.replace('☒ Learnings scope ☐ Approach', '☐ Learnings scope ☐ Approach ☒ Mode');
|
||
expect(planCountSubmissionInput(frame)).toBe('\x1b[Z\x1b[Z\x1b[Z');
|
||
});
|
||
|
||
test('does not revisit a stale submit panel when a later single question is active', () => {
|
||
expect(planCountSubmissionInput(`${incomplete}\r☐ Retry spec\rRetry once?\r❯1.Yes\r2.No`)).toBeNull();
|
||
expect(planCountSubmissionInput('Ready to submit the plan?\n❯1.Submit\n2.Cancel')).toBeNull();
|
||
});
|
||
});
|