mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-26 22:51:47 +02:00
* fix: acknowledge seeded plans before invoking review skills * fix: distinguish current plan input from conversation history * fix: keep hermetic plan reviews on manual permissions * fix: distinguish tool discovery from file permission ownership * fix: preserve initial plan mode in observation tests * fix: wait for scope decisions before writing review findings * fix: carry autoplan decisions consistently into review artifacts * test: retain native failure context in periodic assertions * fix: advance active file permissions before queued questions * fix: finish red-team attempts before retry and cleanup * fix: finalize plan format captures and judges before retry * fix: cancel setup-gbrain SDK attempts before fixture cleanup * test: select periodic consumers of the bounded attempt helper * fix native Bash permission cards and queued questions * fix: preserve independent decisions and review scope Keep CEO approach, engineering scope and outside-review choices from approving independent remedies together. Carry declared contracts through DX polish and resolve new gaps before editing the plan. Regenerate every host and retain existing stop boundaries. Validation: 654 focused tests passed across nine files; all-host generation passed. Full free and periodic validation pending. Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix: require approval before design plan amendments Align the Design review philosophy and rating recipe with its section protocol: resolve one proposed fix, then apply only that approved decision and retain honest scores for declined fixes. Validation: 469 focused tests passed across four files; all-host generation passed. Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix: observe native question completion before transcript persistence Match owned completion hooks to submitted choices, reject conflicting or late answers, and retain bounded failure evidence. * test: recognize review posture in acknowledged native questions Require the selected mode acknowledgement, a completed follow-up question, and its current decoded display while preserving existing posture assertions. * fix: preserve settled CEO choices and isolate pending remedies Resolve established approach gates with cited authority and keep independent fixes out of unrelated option commitments and plan amendments. * fix: carry approved DX choices through later review steps Choose documentation approaches within the accepted scope and map resolved confusion points without reopening them through a bulk menu. * test: handle native settings-file edit prompts Keep one-time owned-file approvals and retain the actual sampled Autoplan permission frame with its matching barrier state. * test: accept standard CEO reply directives with tuning footers Recognize the exact trailing preference footer and letter-list directive while preserving current-display and exact acknowledgement checks. * test: scope split reviewers to their generated plan artifacts * test: observe native Bash permissions and invocation results * test: handle owned Bash prompts during mode preference checks * test: preserve synchronous subprocess rejection in Codex fixture * Fix periodic review handoff navigation Recognize review-first and explicit manual-next-step labels while preserving exact action families, manual preference, and ambiguous-menu rejection. Co-authored-by: OpenAI Codex <noreply@openai.com> * Bind pending file permissions to distinct current targets Allow one captured file request to own the complete current dialog while unrelated file work is pending. Preserve same-path ambiguity, exact input ownership, and one-time grant checks. Co-authored-by: OpenAI Codex <noreply@openai.com> * Make paired CEO verification choices genuinely unresolved Start the positive control with proposed manual checks so its unchanged oracle measures two new coverage decisions. Preserve runtime contracts, targets, count bounds, and all assertions. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep CEO review options and verification within approved scope Audit every offered option for independent add-ons and keep new verification depth pending until accepted. Preserve already requested coverage and trace plan changes to the actual decision. Co-authored-by: OpenAI Codex <noreply@openai.com> * Assemble DX review artifacts before appending the final report Keep early DX evidence above decisions, update artifact sections in place, and append the report using the actual current file suffix. Re-read after deleting an existing report before choosing the append anchor. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep outside plan reviews exclusive and invocation-owned Follow one preflight-selected backend, terminate failed Codex work before fallback, and allocate extra prompt/output files uniquely. Consume only the current invocation’s completed output. Co-authored-by: OpenAI Codex <noreply@openai.com> * Select periodic completion evaluations for report writer changes Register the shared review resolver for eight missing consumers and regress selection for all nine completion cases without changing their IDs or tiers. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep permission ambiguity fixtures on the same normalized target Use distinct raw spellings of one target in the four negative fixtures so they exercise the normalized duplicate-owner guard after exact current-file disambiguation. Preserve the existing exception, no-input, diagnostic and cleanup assertions. Co-authored-by: OpenAI Codex <noreply@openai.com> * Clarify preserved contracts in engineering review fixture Co-authored-by: OpenAI Codex <noreply@openai.com> * Recognize the offered DX follow-up handoff Co-authored-by: OpenAI Codex <noreply@openai.com> * Check independent commitments before presenting review options Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep Codex review output and status in one shell invocation Co-authored-by: OpenAI Codex <noreply@openai.com> * Distinguish seeded plans from reports written by a test attempt Co-authored-by: OpenAI Codex <noreply@openai.com> * Recover clipped Autoplan file approvals with bounded viewport resizing Co-authored-by: OpenAI Codex <noreply@openai.com> * Recover clipped Bash approvals before binding the complete command Co-authored-by: OpenAI Codex <noreply@openai.com> * Isolate setup message tests from the shared checkout Run the real installer in a temporary payload with private config, require successful completion, and guard source and binary contents and mtimes. Co-authored-by: OpenAI Codex <noreply@openai.com> * Fix periodic native permission and report completion handling Match the pinned CLI's soft wraps and clipped headings without granting from incomplete frames. Retire completed file requests, retain mode annotations, and ask section captures for a short final acknowledgement after their full report is saved. Co-authored-by: OpenAI Codex <noreply@openai.com> * Preserve review approvals and validate DX comparison artifacts Keep independent remedies and approved amendments explicit. Give the synthetic DX review its existing documentation and validate peer comparison as required analysis alongside four native decisions. Add positive and negative semantic calibrations while preserving review counts, model budgets and prompt size limits. Co-authored-by: OpenAI Codex <noreply@openai.com> * Make the five-finding CEO fixture's application boundary explicit Materialize the request adapter and service composition used by the synthetic payment application. Explicitly declare the revised unregistered-event and mail-telemetry assumptions while preserving uncaught handler errors, the original invoice path and all five unresolved findings. Co-authored-by: OpenAI Codex <noreply@openai.com> * Keep CEO state-path checks scoped to directory preparation Co-authored-by: OpenAI Codex <noreply@openai.com> * Use checked ports and bounded cleanup in pair-agent tests Discover the daemon port from its owned state file, retain startup diagnostics, and await failed-start cleanup. Add occupied-port, early-exit, deadline, and foreign-state regressions while preserving the existing HTTP assertions and hook budgets. Co-authored-by: Codex <noreply@openai.com> * Preserve queued edit identity and recover clipped Bash permissions Distinguish separately queued unfinished edits from mutation of one native tool ID. Keep grants bound to an exact owned request and reject reused IDs, ambiguous inputs, and competing owners. Support the pinned renderer's literal em dash and request a repaint when only the Bash card's top rule is clipped. Grants still require the complete fresh card and an exact native acknowledgment. Validation: 413 integrated parser/event tests passed; private repaint controls and joint source review passed. Full canonical suite and native periodic rerun remain pending. Co-authored-by: Codex <noreply@openai.com> * Keep periodic reviews within their approved contracts and deliverables Carry exact approvals through engineering review, preserve declared contracts when amending CEO plans, and keep prioritization at the requested decision level. Materialize the revised synthetic SDK reference contract while retaining the five original documentation gaps. Accept the observed semicolon in the finite DX handoff menu and register the direct source dependencies used by the engineering cases. Regenerate canonical review documents without changing model budgets, retries, count bands, or native completion assertions. Validation: all-host generation and 275 review, fixture, selection and parity tests passed. Full free-suite and native periodic validation remain pending. Co-authored-by: Codex <noreply@openai.com> * Keep Eng approval cadence and independence guards explicit * Accept ordinary punctuation in manual review handoffs * Recover file permissions alongside queued Bash calls * Carry approved DX work through later review findings * Clarify the synthetic auth internal failure decision * Bound the periodic DX fixture to onboarding changes * Recognize native Design review handoff labels * Hold scope in the integration-choice review fixture * Carry approved Design decisions through review evidence * Capture listener state when feedback reload fails * Exclude workspace caches before checking deprecated flags * Verify Design UI scope against a seeded review plan * Clarify plan review decisions and outside-voice approval flow * Reject setup menus in the Design UI gate * docs: require focused repair validation before final acceptance * fix: separate review commitments within existing prompt budgets * docs: align generation and contributor validation guidance * fix: advance native review prompts and count acknowledged findings * chore: bump version and changelog (v1.87.1.0) Co-Authored-By: OpenAI Codex <noreply@openai.com> * chore: enforce cheap checks and side-effect-free validation previews * fix: handle owned Fetch permissions and oversized native cards * test: ground review fixtures in independent executable contracts * fix: preserve review decisions and verify reports before completion * test: construct the synthetic credential URL without a scanner false positive * test: materialize DX examples and verify their actual local behavior * fix: clarify CEO review decisions and execution order * fix: clarify review workflow ordering and select Design quality checks * Fix review decision gates and incomplete evaluation fixtures Persist CEO and engineering commitment ledgers before menus, preserve exact approvals, and distinguish implementation structure from feature scope. Route Autoplan through the canonical CEO Step 0 ordering. Classify DX findings before requesting approval and ground runtime claims in actual evidence. Complete neutral non-target fixture contracts and accept the captured Design handoff purpose without relaxing its ownership or acknowledgment checks. Record runtime-capability verification in AGENTS.md validation discipline. Validation: 1,335 focused tests passed across 21 files; build, all-host freshness, skill validation (647 artifacts / 107 tracked), and credential checks passed. Prior paid failures are preserved; behavioral acceptance remains pending. * Fix review decision boundaries and owned Read prompts Preserve exact approvals across review options, compare consistent DX milestones, and keep proposed implementation separate from review evidence. Bind modern Read prompts to one immutable native request and wait for its result. Retain captured regression verdicts, correct fixture error names, improve import probe diagnostics, and record focused-first validation discipline in AGENTS.md. * Clarify CEO and engineering review decisions Use explicit decision steps, one engineering ledger, and clear scope/write transitions. Preserve exact approvals and distinguish pending test requirements. Keep unrelated generated content unchanged. * Fix review decision ordering and native evaluation interactions * Clarify engineering decisions and test artifact order * Clarify pending choices and approvals in CEO reviews * Make CEO review phases sequential and clarify completion * Fix Design board submission intent matching * Seed an existing browser test baseline for Autoplan * Document decision-log payloads before state initialization * Preserve exact review scope and decide one change before drafting options * Require input identity before repeating passing model judges * Honor permitted storage throughout CEO review completion * Match complete native permission text within the pinned renderer contract * Align review approvals, independent choices, and bounded validation * fix: preserve reopened approvals and declare fixture interfaces * fix: isolate review artifacts and audit complete questions * fix: match detector artifact permissions to configured storage * fix: complete native permissions and review fixture workflows * fix: order CEO review work and separate engineering guarantees * fix: preserve native validation and separate review choices * fix: clarify review decisions and judge complete report context * fix: constrain review judgments and retain parse failures * fix: compare each affected value before review decisions * fix: make engineering review decisions and completion order explicit * fix: give the complete Autoplan evaluation a bounded chain budget * fix(cso): diagnose forbidden Docker endpoints before tool lookup * fix(reviews): reconcile workflow contracts and generated artifacts after main integration * fix(evals): migrate retained regressions to the native review harness * fix(tests): close native harness and workflow integration regressions * fix(evals): preserve complete permission context and native menu contracts * fix(tests): capture synchronous command output without pipe drain stalls * fix(reviews): clarify decision and completion ordering * fix(reviews): separate decision readiness from final completion checks * refactor(reviews): consolidate decision rules and completion branches * fix(plan-eng-review): order preparation and clarify decision routing * fix(plan-eng-review): restore size and question-format guard parity * fix(plan-eng-review): clarify scope phases and blocked completion * fix(plan-eng-review): unify review flow and report destination * fix(plan-eng-review): define bootstrap and question stage ownership * fix(plan-eng-review): clarify review structure and design lookup * fix(plan-eng-review): render report examples and show saved decisions * fix: consolidate Eng review decisions and select their evaluations * test: cover overlapping terminal attachments and clean merged runner type * fix: preserve Office Hours relationship closings during review updates * fix: retain pasted review targets across slash invocations * docs: preserve validation traces and correct release scope * test: cover pasted targets in both review skills * fix: validate report artifacts before recording success * fix: redact source roots at CSO report boundaries * fix: bind native Design questions before answering * test: select report privacy and native recovery regressions * test: bind rejection predicate in extracted observers * fix: bind complete boxed native questions * test: keep the Design UI fixture on native review * fix: preserve review decisions and evaluation completion outcomes * fix: clarify CEO approval and report completion order * fix: align native review evaluation ownership and completion * fix: bind review evaluators to native decisions and owned artifacts * fix: validate review decisions against native outcomes * fix: preserve review evidence and Autoplan phase handoffs * test: bind review evidence to owned decisions and completion * fix: retain owned native history across compaction * fix(evals): validate current review decisions and setup choices * fix: bind Autoplan reviews and phase completion to current amended input * fix: reconcile native review evidence and close Autoplan phases * test: recognize owned whole-candidate complexity decisions * test: preserve report freshness for approved investigation handoffs * fix: recognize scoped review findings and isolate dual voice fixtures * fix: make review handoffs and question dispatch self-contained * test: recognize complete CEO decisions and procedural pauses * fix: bind current CEO comparison options and risk intervals * test: bind engineering decisions and completion to owned evidence * fix: publish Autoplan phase reports before continuing tools * test: verify actual Autoplan dual-review dispatch evidence * test: select dual review when shared evidence fixtures change * fix: clarify plan review decisions and completion gates * fix: make CEO review decisions and return paths explicit * test: keep Autoplan prompt files inside attempt state * test: preserve source whitespace across permission dialog wraps * fix: publish Autoplan phase reports before continuing * test: recognize current CEO comparisons and reject inactive records * fix: reconcile engineering decision states before completion * test: recognize complete Design decisions and reports * test: verify current engineering decisions before navigation * Recognize source-owned component reduction choices * fix: recognize current CEO ledger and commitment grids * test: supply RequestPolicy context to Eng count fixture * fix: save complete engineering decisions before asking * fix: bind Autoplan publication to the complete phase readback * chore: prepare 1.87.5.0 reliability release * fix: clarify engineering review completion and preserve log failures * fix: bind CEO saved choices and current section ancestry * fix(evals): bind review execution and completion evidence * fix(plan-ceo-review): verify complete decisions before asking * fix(evals): preserve complete engineering choice records * fix(evals): preserve complete review outcomes and bounded fixtures * fix(autoplan): publish phase reports before advancing * fix(plan-ceo-review): validate option fields before asking * fix(plan-eng-review): verify current decisions after answers * fix(evals): bind review decisions and bound fixture scope * fix(plan-ceo-review): verify decision rows and edit saved checkpoints * fix(evals): bind review evidence and scope document lookup * fix(plan-eng-review): update resolution state with its answer * fix(reviews): preserve complete questions through dispatch * fix(evals): recognize completed mode declarations * fix(evals): define cache consistency at wrapper completion * fix(evals): validate owned initial scope and completed review handoffs * fix: assemble complete CEO decision fields before saving * fix: authenticate automatic mode decisions without guessing selectors * fix: bind engineering coverage to approved regression contracts * fix(evals): supply review helpers to native Eng capture * fix(plan-eng-review): preserve the full selected option scope * fix(evals): recognize owned engineering seed and regression evidence * fix(evals): bind engineering retry reports to native approvals * docs: clarify release guarantees (v1.87.5.0) Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix(evals): recognize owned engineering decisions and handoffs * fix(evals): bind engineering decisions and completion evidence * fix(tests): align review contracts and selection fixtures * fix(skills): restore review prompt size limits * fix(plan-eng-review): clarify review execution and completion * fix(evals): preserve configured retries through all supervision layers * Clarify Engineering decisions and report completion * Keep native decision assertions within their source boundary * fix: recognize owned engineering decisions and completed navigation * fix: bind completed auto decisions to their current review * fix: recognize explicit CEO source attribution * fix: dispatch verified CEO decisions without recomposing fields * test: expose existing execution deadlines to review actors * fix: distinguish CEO decision records from incidental headings * test: bind split-scope choices to the registered native actor * test: connect reviewed regressions to required evaluation coverage * Clarify CEO decision routing and completion stages * test: expose existing section review deadlines to fixture actors * test: recognize complete native CEO pacing inventories * test: exclude answered history from current CEO payloads * test: detect phase entry through owned skill HOME aliases * test: validate native review completion and owned report permissions * fix: make Autoplan close packets carry the parent handoff steps * test: assess source-bound HOLD decisions within the existing deadline * fix: keep CEO native decision fields under one formatting authority * test: register integrated review and permission dependencies * test: align native review adapters and finding coverage Preserve explicit AUTO decisions, apply native single-select defaults, and bind complete cropped questions and report permissions to their owned requests. Require seeded review findings instead of crediting setup menus. Keep captured failure controls and additive selection dependencies. The integrated candidate passed 3,099 focused tests across 65 files; affected paid validation remains required before publication. * fix(autoplan): require phase reports before advancing * fix(evals): bind setup and evidence to complete attempts * fix(evals): bind native answers and pending writes to fixture scope Preserve complete option rows when native descriptions wrap, retain current owned Write arguments before journal publication, and keep engineering and DX answers within their declared fixture interfaces. Add captured free regressions without increasing model budgets or relaxing completion checks. * fix(autoplan): verify phase reports across native tool paths Guard owned methodology reads and reviewer dispatches, detect complete driver loads through Bash, and distinguish report-only edits from implementation changes. Follow authenticated native UUID ancestry when journal writes arrive out of order and verify earlier native content for cached phase reads. Keep current close acknowledgment and parent publication in order, require CEO entry before later phases, and register captured failure regressions. * fix(evals): honor native input and collection lifecycles Match complete native Edit panes and truncated question borders, reject stderr close before EOF, and stop the CEO split fixture once its acknowledged scope decisions are collected. Keep semantic validation, process failures, report requirements, and absolute deadlines authoritative. Add captured-event and real-process regressions with selection dependencies. Focused checks pass; final integrated paid and full-suite acceptance remain pending. * fix(autoplan): retain native session ownership across directory changes Recover missed native UUID ancestry through the existing strict graph while preserving ordinary event order and legacy scoping. Bind publication hooks to Claude's original project directory while retaining current cwd for requested file paths. Captured public-event regressions, existing caller checks, and a pinned native CLI loopback verify both fixes. Preserve failed attempts and require fresh paid and final full-suite acceptance. * docs: align evaluation limits and completion version * fix(autoplan): allow authenticated phase reads during journal streaming * fix(evals): bind clipped native questions and owned edit dialogs * fix: preserve overlay retries and bounded cleanup * fix: recognize owned planning preludes in native questions * docs: explain overlay scheduling and cleanup guarantees * fix: require fresh publication after Autoplan phase reruns * Release gstack 1.87.6 * fix: preserve CI paths, process identity, and test deadlines * fix: keep informational setup commands independent of install probes * fix: clarify plan review decisions and bound source audit reports * Fix remaining Windows identity and native path CI failures * Clarify CEO review decision and reviewer-result routing * test: accept no-install planner in retry supervision * fix(ceo-review): make review decisions and report completion explicit * perf(test): add fast PR gates, input-keyed judge reuse and isolated free shards * fix(test): start isolated CEO smoke from its existing project plan * fix(test): repair CI fixture races and preserve retry evidence * fix(ceo-review): clarify approvals, depth and saved completion --------- Co-authored-by: OpenAI Codex <noreply@openai.com>
374 lines
29 KiB
TypeScript
374 lines
29 KiB
TypeScript
import { expect, test } from 'bun:test';
|
||
import fs from 'node:fs';
|
||
import os from 'node:os';
|
||
import path from 'node:path';
|
||
import actual from './fixtures/eng-next-handoff-ah.json';
|
||
import { isEngCompletionHandoff } from './helpers/eng-completion-handoff';
|
||
import { hasNativePlanTerminal, nativePlanCallFingerprint, planCountQuestionPhase } from './helpers/claude-pty-runner';
|
||
import type { NativePlanQuestionCall, PlanCountTranscript } from './helpers/plan-count-transcript';
|
||
import { readPlanCountTranscript } from './helpers/plan-count-transcript';
|
||
import { isCurrentPlanApprovalScreen } from './helpers/plan-count-pending-exit';
|
||
import { E2E_TOUCHFILES, matchGlob } from './helpers/touchfiles';
|
||
|
||
const call = () => structuredClone(actual.fingerprint.nativeCall) as NativePlanQuestionCall;
|
||
const fp = (c = call()) => nativePlanCallFingerprint(c, 0, false);
|
||
const accepts = (c = call(), plan = actual.plan) => isEngCompletionHandoff(fp(c), plan);
|
||
|
||
function maintenanceRecap() {
|
||
const make = (id: string, header: string, text: string, selected: string, description: string): NativePlanQuestionCall => ({
|
||
sessionId:'maintenance-session', toolUseId:id, questions:[{header,question:text,multiSelect:false,
|
||
options:[{label:selected,description},{label:'Skip',description:'Do not approve this action.'}]}],
|
||
answered:true, failed:false, answers:{[text]:selected}, unansweredQuestionIndices:[], answeredAt:'2026-09-11T00:00:01Z',
|
||
});
|
||
const routing = make('routing','Routing',"Add gstack skill routing rules to CLAUDE.md?",'Add routing rules to CLAUDE.md (recommended)','Append the routing rules after review.');
|
||
const policy = make('policy','TODO 1','D7 — TODO 1: RetryPolicy needs a follow-up.','7A) Add to TODOS.md (recommended)',"Captured in the plan's TODOS section now; write it after exit.");
|
||
const cleanup = make('cleanup','TODO 2','D8 — TODO 2: Remove LegacyBridge after rollout.','8A) Add to TODOS.md (recommended)',"Captured in the plan's TODOS section now; write it after exit.");
|
||
const next = make('next','Next step','D9 — Next steps. Eng review is CLEARED. There is no UI scope. CEO review is optional. What next?',
|
||
'Ready to implement — run /ship when done (recommended)','Exit plan mode with the reviewed plan. Post-exit: append routing rules to CLAUDE.md and create TODOS.md with the two accepted items.');
|
||
next.answeredAt='2026-09-11T00:00:02Z'; next.questions[0]!.options[1]={label:'Run /plan-ceo-review',description:'Optional strategy review.'};
|
||
return {next, prior:[routing,policy,cleanup], plan:'## TODOS\n### Revisit RetryPolicy\nAn approved follow-up.\n### Remove LegacyBridge\nAfter rollout.\n## Implementation Tasks\n'};
|
||
}
|
||
test('completed navigation can recap earlier approved routing and published TODOs', () => {
|
||
const a=maintenanceRecap(), check=(x= a)=>isEngCompletionHandoff(fp(x.next),x.plan,x.prior);
|
||
expect(check()).toBe(true);
|
||
const renamed=structuredClone(a); renamed.plan=renamed.plan.replaceAll('RetryPolicy','TenantPolicy');
|
||
question(renamed.prior[1]!,s=>s.replaceAll('RetryPolicy','TenantPolicy')); expect(check(renamed)).toBe(true);
|
||
const reworded=structuredClone(a);question(reworded.next,s=>s.replace('D9 — Next steps. Eng review is CLEARED','D14: Next step: Engineering review is complete'));
|
||
reworded.next.questions[0]!.header='Next steps';reworded.next.questions[0]!.options[0]!.description='Exit plan mode with the reviewed plan. After exiting: write TODOS.md with 2 accepted items; add gstack routing rules to CLAUDE.md.';
|
||
expect(check(reworded)).toBe(true);
|
||
const batched=structuredClone(a);batched.prior[1]!.questions.push(...batched.prior[2]!.questions);
|
||
Object.assign(batched.prior[1]!.answers,batched.prior[2]!.answers);batched.prior.pop();expect(check(batched)).toBe(true);
|
||
for(const mutate of [
|
||
(x:typeof a)=>{x.prior.shift();},
|
||
(x:typeof a)=>{x.prior[0]!.sessionId='foreign';},
|
||
(x:typeof a)=>{x.prior[0]!.failed=true;},
|
||
(x:typeof a)=>{x.prior[0]!.answeredAt=x.next.answeredAt;},
|
||
(x:typeof a)=>{x.prior[0]!.unansweredQuestionIndices=[0];},
|
||
(x:typeof a)=>{x.prior.push(structuredClone(x.prior[0]!));},
|
||
(x:typeof a)=>{x.prior[0]!.questions[0]!.options[1]=structuredClone(x.prior[0]!.questions[0]!.options[0]!);},
|
||
(x:typeof a)=>{const revoked=structuredClone(x.prior[0]!);revoked.toolUseId='revoked';revoked.answers![revoked.questions[0]!.question]='Skip';x.prior.push(revoked);},
|
||
(x:typeof a)=>{x.prior[1]!.answers![x.prior[1]!.questions[0]!.question]='Skip';},
|
||
(x:typeof a)=>{x.prior[1]!.questions[0]!.options[0]!.description='A new proposed TODO.';},
|
||
(x:typeof a)=>{question(x.prior[1]!,s=>s+' This approval is withdrawn.');},
|
||
(x:typeof a)=>{question(x.next,s=>'Example: '+s);},
|
||
(x:typeof a)=>{question(x.next,s=>s+' This review is cancelled.');},
|
||
(x:typeof a)=>{question(x.next,s=>s.replace('is CLEARED','will be CLEARED'));},
|
||
(x:typeof a)=>{question(x.next,s=>s+' Only if more tests pass.');},
|
||
(x:typeof a)=>{x.next.questions[0]!.options[0]!.description+=' Add another requirement.';},
|
||
(x:typeof a)=>{x.next.questions[0]!.options[0]!.description=x.next.questions[0]!.options[0]!.description!.replace('two','three');},
|
||
(x:typeof a)=>{x.plan=x.plan.replace('## TODOS','## Historical TODOs');},
|
||
(x:typeof a)=>{x.plan=x.plan.replace('RetryPolicy','OtherPolicy');},
|
||
(x:typeof a)=>{x.plan=x.plan.replace('An approved follow-up.','This TODO is withdrawn.');},
|
||
(x:typeof a)=>{x.plan='```md\n'+x.plan+'\n```';},
|
||
]){const x=structuredClone(a);mutate(x);expect(check(x)).toBe(false);}
|
||
expect(isEngCompletionHandoff(fp(a.next),a.plan)).toBe(false);
|
||
});
|
||
function question(c: NativePlanQuestionCall, f: (s: string) => string) {
|
||
const q = c.questions[0]!, answer = c.answers![q.question];
|
||
q.question = f(q.question); c.answers = { [q.question]: answer! }; return c;
|
||
}
|
||
|
||
test('actual completed Next navigation is administrative and never starts review', () => {
|
||
expect(accepts()).toBe(true);
|
||
for (const started of [false, true]) {
|
||
expect(planCountQuestionPhase(fp(), started, () => false, undefined, undefined,
|
||
f => isEngCompletionHandoff(f, actual.plan))).toEqual({ preReview: false, reviewStarted: started, administrative: 'completion-handoff' });
|
||
}
|
||
});
|
||
|
||
test('published confirmation and characterization references do not introduce work', () => {
|
||
expect(actual.source.stat.mtimeMs).toBeLessThan(Date.parse(call().answeredAt!));
|
||
expect(accepts(call(), actual.plan.replaceAll('P0', 'P7'))).toBe(true);
|
||
const c = call(); c.questions[0]!.options.reverse();
|
||
expect(accepts(c)).toBe(true);
|
||
c.answers![c.questions[0]!.question] = c.questions[0]!.options[0]!.label;
|
||
expect(accepts(c)).toBe(true);
|
||
expect(accepts(call(), actual.plan.replace(' - Surfaced by: Architecture issue 3 (D7)', ' - Correction: T2 is cancelled.\n - Surfaced by: Architecture issue 3 (D7)'))).toBe(true);
|
||
expect(accepts(call(), actual.plan.replace('Write characterization tests for `legacyAuthFlow()` before any rewrite', 'Write characterization tests for `legacyAuthFlow()` before any rewrite\nVerify expired and revoked tokens are rejected.'))).toBe(true);
|
||
expect(accepts(call(), actual.plan.replace('Invariants and Latency target above.', 'Invariants and Latency target above.\nKeep a record of rejected alternatives after the author confirms Context.'))).toBe(true);
|
||
});
|
||
|
||
test('incomplete, foreign, ambiguous and changed choices cannot be administrative', () => {
|
||
for (const mutate of [
|
||
(c: NativePlanQuestionCall) => { c.answered = false; },
|
||
(c: NativePlanQuestionCall) => { c.failed = true; },
|
||
(c: NativePlanQuestionCall) => { c.answeredAt = 'invalid'; },
|
||
(c: NativePlanQuestionCall) => { c.unansweredQuestionIndices = [0]; },
|
||
(c: NativePlanQuestionCall) => { c.answers = {}; },
|
||
(c: NativePlanQuestionCall) => { c.answers![c.questions[0]!.question] = 'unoffered'; },
|
||
(c: NativePlanQuestionCall) => { c.questions[0]!.multiSelect = true; },
|
||
(c: NativePlanQuestionCall) => { c.questions.push(structuredClone(c.questions[0]!)); },
|
||
(c: NativePlanQuestionCall) => { c.questions[0]!.options.push({ label: 'Add another requirement' }); },
|
||
(c: NativePlanQuestionCall) => { c.questions[0]!.options[0]!.description += ' Add a new datastore first.'; },
|
||
(c: NativePlanQuestionCall) => { c.questions[0]!.options[1]!.description = 'Change the implementation architecture first.'; },
|
||
(c: NativePlanQuestionCall) => { c.questions[0]!.options[0]!.description = c.questions[0]!.options[0]!.description!.replace('T1', 'T99'); },
|
||
]) { const c = call(); mutate(c); expect(accepts(c)).toBe(false); }
|
||
expect(isEngCompletionHandoff({ ...fp(), signature: 'foreign:call' }, actual.plan)).toBe(false);
|
||
expect(isEngCompletionHandoff({ ...fp(), nativeQuestionIndex: 1 }, actual.plan)).toBe(false);
|
||
expect(isEngCompletionHandoff({ ...fp(), options: [] }, actual.plan)).toBe(false);
|
||
});
|
||
|
||
test('nonasserted, prospective, conditional and reopened navigation stays substantive', () => {
|
||
for (const text of [
|
||
'> ', 'Example: ', 'An unproven hypothesis. ', '```text\n',
|
||
]) expect(accepts(question(call(), s => text + s))).toBe(false);
|
||
for (const change of [
|
||
(s: string) => s.replace('all required reviews are complete', 'all required reviews will be complete'),
|
||
(s: string) => s.replace('all required reviews are complete', 'all required reviews are not complete'),
|
||
(s: string) => s.replace('all required reviews are complete', 'all required reviews are complete if more tests pass'),
|
||
(s: string) => s + '\nA new implementation prerequisite is required.',
|
||
(s: string) => s.replace('Recommendation: A', 'Recommendation: C'),
|
||
]) expect(accepts(question(call(), change))).toBe(false);
|
||
});
|
||
|
||
test('missing, refuted or quoted published prerequisites/tasks cannot be borrowed', () => {
|
||
for (const plan of [
|
||
'', '```markdown\n' + actual.plan + '\n```', actual.plan.split('\n').map(s => '> ' + s).join('\n'),
|
||
actual.plan.replace('## Context', '## Example context'),
|
||
actual.plan.replace('Implementation does not start until the author confirms', 'Implementation starts without the author confirming'),
|
||
actual.plan.replace('### Prerequisite P0', '### Example prerequisite P0'),
|
||
actual.plan.replace('## Implementation Tasks', '## Historical Tasks'),
|
||
actual.plan.replace('Write characterization tests for `legacyAuthFlow()` before any rewrite', 'Write characterization tests after rewriting `legacyAuthFlow()`'),
|
||
actual.plan.replace('**T1 (P1', '**T99 (P1'),
|
||
actual.plan.replace('## Context', 'Example only:\n## Context'),
|
||
actual.plan.replace('## Implementation Tasks', 'Example only:\n## Implementation Tasks'),
|
||
actual.plan.replace('Invariants and Latency target above.', 'Invariants and Latency target above.\nCorrection: Prerequisite P0 is cancelled; the author no longer needs to confirm Context.'),
|
||
actual.plan.replace('Write characterization tests for `legacyAuthFlow()` before any rewrite', 'Write characterization tests for `legacyAuthFlow()` before any rewrite\nCorrection: T1 is cancelled; no characterization tests are required.'),
|
||
]) expect(accepts(call(), plan)).toBe(false);
|
||
});
|
||
|
||
test('exact final exit/report replay retains all freshness, identity and answer gates', () => {
|
||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-eng-next-ah-'));
|
||
const file = path.join(dir, 'reviewed.md');
|
||
const now = Date.now;
|
||
try {
|
||
fs.writeFileSync(file, actual.plan);
|
||
fs.utimesSync(file, actual.source.stat.mtimeMs / 1000, actual.source.stat.mtimeMs / 1000);
|
||
Date.now = () => Date.parse(actual.captureAt);
|
||
const t = structuredClone(actual.transcript) as PlanCountTranscript;
|
||
const id = actual.fingerprint.signature;
|
||
const admin = new Set(accepts() ? [id] : []);
|
||
const check = (v = t, a = admin) => hasNativePlanTerminal(v, file, actual.startedAt, 'plan_ready', a);
|
||
expect(isCurrentPlanApprovalScreen(actual.screen)).toBe(true);
|
||
expect(check()).toBe(true);
|
||
expect(check(t, new Set())).toBe(false);
|
||
expect(check(t, new Set(['foreign:call']))).toBe(false);
|
||
for (const mutate of [
|
||
(v: PlanCountTranscript) => { v.planReadyRequests = []; },
|
||
(v: PlanCountTranscript) => { v.planReadyRequests!.at(-1)!.failed = true; },
|
||
(v: PlanCountTranscript) => { v.planReadyRequests!.at(-1)!.sessionId = 'foreign'; },
|
||
(v: PlanCountTranscript) => { v.planReadyRequests!.at(-1)!.timestamp = '2026-09-10T03:29:40.000Z'; },
|
||
(v: PlanCountTranscript) => { v.planReadyRequests!.at(-1)!.timestamp = new Date(Date.now() + 1).toISOString(); },
|
||
(v: PlanCountTranscript) => { v.calls.at(-1)!.answered = false; },
|
||
(v: PlanCountTranscript) => { v.calls.at(-2)!.answeredAt = '2026-09-10T03:29:00.000Z'; },
|
||
]) { const v = structuredClone(t); mutate(v); expect(check(v)).toBe(false); }
|
||
fs.writeFileSync(file, actual.plan.replace('NO UNRESOLVED DECISIONS', 'Report still pending'));
|
||
fs.utimesSync(file, actual.source.stat.mtimeMs / 1000, actual.source.stat.mtimeMs / 1000);
|
||
expect(check()).toBe(false);
|
||
} finally { Date.now = now; fs.rmSync(dir, { recursive: true, force: true }); }
|
||
});
|
||
|
||
test('new handoff evidence belongs to its existing paid caller', () => {
|
||
for (const file of ['test/eng-next-handoff-ah.test.ts', 'test/fixtures/eng-next-handoff-ah.json']) {
|
||
const owners = Object.entries(E2E_TOUCHFILES).filter(([, globs]) => globs.some(glob => matchGlob(file, glob))).map(([name]) => name);
|
||
expect(owners).toEqual(['plan-eng-finding-count']);
|
||
}
|
||
});
|
||
|
||
const b176 = actual.sourceBoundB176;
|
||
const recorded = () => structuredClone(b176.transcript) as PlanCountTranscript;
|
||
const recordedCall = () => recorded().calls.at(-1)!;
|
||
const recordedPrior = () => recorded().calls.slice(0,-1);
|
||
const recordedCheck = (c=recordedCall(),plan=b176.plan,prior=recordedPrior()) =>
|
||
isEngCompletionHandoff(nativePlanCallFingerprint(c,Date.parse(b176.capturedAt),true),plan,prior);
|
||
const changedApproval = [
|
||
'D1 approval is revoked.',
|
||
'This decision is reopened.',
|
||
'Routing rules: pending approval.',
|
||
];
|
||
test.each(changedApproval)('current navigation cannot withdraw its referenced approval: %s',text=>{
|
||
const c=recordedCall();question(c,s=>s+'\n'+text);expect(recordedCheck(c)).toBe(false);
|
||
const option=recordedCall();option.questions[0]!.options[1]!.description+=' '+text;expect(recordedCheck(option)).toBe(false);
|
||
const prior=recordedPrior();question(prior[0]!,s=>s+'\n'+text);expect(recordedCheck(recordedCall(),b176.plan,prior)).toBe(false);
|
||
expect(recordedCheck(recordedCall(),b176.plan+'\n'+text)).toBe(false);
|
||
});
|
||
test.each([
|
||
'The implementation now requires a production deployment before fixtures.',
|
||
'Implementation needs a production deployment before fixtures.',
|
||
'A production deployment is now required before fixtures.',
|
||
'T2 depends on a production deployment before fixtures.',
|
||
])('current navigation cannot add an unbound declarative obligation: %s',text=>{
|
||
const c=recordedCall();question(c,s=>s+'\n'+text);expect(recordedCheck(c)).toBe(false);
|
||
const option=recordedCall();option.questions[0]!.options[1]!.description+=' '+text;expect(recordedCheck(option)).toBe(false);
|
||
});
|
||
test.each(['Example only:','Sample plan:','Hypothetical:','Source excerpt:'])('report evidence cannot borrow a source-introduced owner: %s',prefix=>{
|
||
for(const heading of ['# Plan:','## GSTACK REVIEW REPORT','## Decision ledger','## Implementation Tasks','## Accepted TODOs','## Implementation order']){
|
||
expect(b176.plan.includes(heading),heading).toBe(true);
|
||
expect(recordedCheck(recordedCall(),b176.plan.replace(heading,prefix+'\n'+heading)),heading).toBe(false);
|
||
}
|
||
});
|
||
test('an inactive source section cannot own or invalidate the next current sibling',()=>{
|
||
const sample='Source excerpt:\n## Old task illustration\nD1 approval is revoked.\nT99 is an illustration.\n\n';
|
||
expect(recordedCheck(recordedCall(),b176.plan.replace('## Implementation Tasks',sample+'## Implementation Tasks'))).toBe(true);
|
||
});
|
||
test('both maintenance forms retain the earlier native-answer cardinality and uniqueness checks',()=>{
|
||
for(const mutate of [
|
||
(c:NativePlanQuestionCall)=>{for(let n=0;n<5;n++){const q=structuredClone(c.questions[0]!);q.question+=' extra '+n;c.questions.push(q);c.answers![q.question]=q.options[0]!.label;}},
|
||
(c:NativePlanQuestionCall)=>{for(let n=0;n<4;n++)c.questions[0]!.options.push({label:'Other '+n});},
|
||
(c:NativePlanQuestionCall)=>{c.questions.push(structuredClone(c.questions[0]!));c.answers!['unowned-key']='unused';},
|
||
]){
|
||
const prior=recordedPrior();mutate(prior[0]!);expect(recordedCheck(recordedCall(),b176.plan,prior)).toBe(false);
|
||
const old=maintenanceRecap();mutate(old.prior[0]!);expect(isEngCompletionHandoff(fp(old.next),old.plan,old.prior)).toBe(false);
|
||
}
|
||
});
|
||
test('review-discovered current changes and example evidence cannot release the pending exit',()=>{
|
||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'eng-b176-review-')),file=path.join(dir,'report.md'),now=Date.now;
|
||
try{
|
||
Date.now=()=>Date.parse(b176.capturedAt);
|
||
const examples=[
|
||
{plan:b176.plan,addition:undefined,expected:true},
|
||
{plan:b176.plan,addition:'D1 approval is revoked.',expected:false},
|
||
{plan:b176.plan,addition:'The implementation now requires a production deployment before fixtures.',expected:false},
|
||
{plan:'Example only:\n'+b176.plan,addition:undefined,expected:false},
|
||
{plan:b176.plan.replace('## Implementation Tasks','Example only:\n## Implementation Tasks'),addition:undefined,expected:false},
|
||
];
|
||
for(const {plan,addition,expected} of examples){
|
||
const t=recorded(),c=t.calls.at(-1)!;if(addition)question(c,s=>s+'\n'+addition);
|
||
const f=nativePlanCallFingerprint(c,Date.parse(b176.capturedAt),true);
|
||
const administrative=new Set(isEngCompletionHandoff(f,plan,t.calls.slice(0,-1))?[f.signature]:[]);
|
||
fs.writeFileSync(file,plan);fs.utimesSync(file,b176.sourceReport.mtimeMs/1000,b176.sourceReport.mtimeMs/1000);
|
||
expect(hasNativePlanTerminal(t,file,b176.startedAt,'plan_ready',administrative)).toBe(expected);
|
||
}
|
||
}finally{Date.now=now;fs.rmSync(dir,{recursive:true,force:true});}
|
||
});
|
||
test('actual b176 answered navigation recaps owned prior maintenance and the published first task',()=>{
|
||
expect(recordedCheck()).toBe(true);
|
||
expect(b176.originalOutcome).toBe('CANCELLED');
|
||
expect(b176.originalD12PreReview).toBe(true);
|
||
expect(b176.originalNativeTerminal).toBe(false);
|
||
for(const started of [true,false])expect(planCountQuestionPhase(nativePlanCallFingerprint(recordedCall(),Date.parse(b176.capturedAt),true),started,()=>false,undefined,undefined,
|
||
f=>isEngCompletionHandoff(f,b176.plan,recordedPrior()))).toEqual({preReview:false,reviewStarted:started,administrative:'completion-handoff'});
|
||
});
|
||
test('recorded navigation is keyed by current references, not the observed numbering or optional label',()=>{
|
||
const c=recordedCall();c.questions[0]!.options[1]!.label='Run /plan-ceo-review (optional)';expect(recordedCheck(c)).toBe(true);
|
||
const renamed=JSON.parse(JSON.stringify({c:recordedCall(),plan:b176.plan,prior:recordedPrior()}).replaceAll('D10','D20').replaceAll('D11','D21'));
|
||
expect(recordedCheck(renamed.c,renamed.plan,renamed.prior)).toBe(true);
|
||
const wording=recordedCall();question(wording,s=>s.replace('engineering review is done','engineering review is complete').replace('every finding has an approved fix','all decisions are settled'));
|
||
wording.questions[0]!.options[0]!.description=wording.questions[0]!.options[0]!.description!.replace('start with','begin with').replace('then write','then create');
|
||
expect(recordedCheck(wording)).toBe(true);
|
||
});
|
||
test.each(['missing-answer','failed','pending-tab','unoffered','future','bad-clock','wrong-fingerprint','wrong-option','extra-question','extra-option','ceo-selected'])('recorded handoff rejects incomplete or conflicting native state: %s',kind=>{
|
||
const c=recordedCall();
|
||
if(kind==='missing-answer'){c.answered=false;c.answers={};}
|
||
if(kind==='failed')c.failed=true;
|
||
if(kind==='pending-tab')c.unansweredQuestionIndices=[0];
|
||
if(kind==='unoffered')c.answers![c.questions[0]!.question]='Unstated route';
|
||
if(kind==='future')c.answeredAt=new Date(Date.now()+60_000).toISOString();
|
||
if(kind==='bad-clock')c.answeredAt='invalid';
|
||
if(kind==='extra-question')c.questions.push(structuredClone(c.questions[0]!));
|
||
if(kind==='extra-option')c.questions[0]!.options.push({label:'Add Redis',description:'New work.'});
|
||
if(kind==='ceo-selected')c.answers![c.questions[0]!.question]=c.questions[0]!.options[1]!.label;
|
||
const f=nativePlanCallFingerprint(c,Date.parse(b176.capturedAt),true);
|
||
if(kind==='wrong-fingerprint')f.signature='foreign:call';
|
||
if(kind==='wrong-option')f.options[0]!.label='Other route';
|
||
expect(isEngCompletionHandoff(f,b176.plan,recordedPrior())).toBe(false);
|
||
});
|
||
test.each(['future-review','negative-review','conditional-review','historical','quoted','revoked-review','unapproved-finding','new-command','quoted-command','new-prerequisite','unknown-task','wrong-first-task','unapproved-routing','unapproved-todo'])('recorded next-step content cannot hide new or incomplete work: %s',kind=>{
|
||
const c=recordedCall();
|
||
if(kind==='future-review')question(c,s=>s.replace('engineering review is done','engineering review will be done'));
|
||
if(kind==='negative-review')question(c,s=>s.replace('engineering review is done','engineering review is not done'));
|
||
if(kind==='conditional-review')question(c,s=>s.replace('engineering review is done','engineering review is done if new tests pass'));
|
||
if(kind==='historical')question(c,s=>'Historical: '+s);
|
||
if(kind==='quoted')question(c,s=>'> '+s);
|
||
if(kind==='revoked-review')question(c,s=>s+'\nThe engineering review is reopened.');
|
||
if(kind==='unapproved-finding')question(c,s=>s.replace('every finding has an approved fix','not every finding has an approved fix'));
|
||
if(kind==='new-command')question(c,s=>s+'\nThen add a new datastore.');
|
||
if(kind==='quoted-command')c.questions[0]!.options[1]!.description+=' Also "deploy production now".';
|
||
if(kind==='new-prerequisite')question(c,s=>s+'\nA new prerequisite is required before implementation.');
|
||
if(kind==='unknown-task')question(c,s=>s.replace('T1–T9','T1–T99'));
|
||
if(kind==='wrong-first-task')c.questions[0]!.options[0]!.description=c.questions[0]!.options[0]!.description!.replace('T1 fixtures','T2 fixtures');
|
||
if(kind==='unapproved-routing')c.questions[0]!.options[0]!.description=c.questions[0]!.options[0]!.description!.replace('(D1)','(D2)');
|
||
if(kind==='unapproved-todo')c.questions[0]!.options[0]!.description=c.questions[0]!.options[0]!.description!.replace('D10/D11','D10/D99');
|
||
expect(recordedCheck(c),kind).toBe(false);
|
||
});
|
||
test.each(['missing-routing','missing-todo','failed-answer','foreign-session','future-answer','duplicate-answer','declined-todo','declined-routing','foreign-source','changed-remedy','withdrawn'])('recorded maintenance remains bound to complete earlier approvals: %s',kind=>{
|
||
const prior=recordedPrior();
|
||
if(kind==='missing-routing')prior.shift();
|
||
if(kind==='missing-todo')prior.pop();
|
||
if(kind==='failed-answer')prior.at(-1)!.failed=true;
|
||
if(kind==='foreign-session')prior.at(-1)!.sessionId='foreign';
|
||
if(kind==='future-answer')prior.at(-1)!.answeredAt=recordedCall().answeredAt;
|
||
if(kind==='duplicate-answer')prior.push(structuredClone(prior[0]!));
|
||
if(kind==='declined-todo')prior.at(-1)!.answers![prior.at(-1)!.questions[0]!.question]='Skip — not valuable enough';
|
||
if(kind==='declined-routing')prior[0]!.answers![prior[0]!.questions[0]!.question]="No thanks, I'll invoke skills manually";
|
||
if(kind==='foreign-source')question(prior.at(-1)!,s=>s.replace('PLAN.md','FOREIGN.md'));
|
||
if(kind==='changed-remedy'){const c=prior.find(c=>c.questions[0]!.header==='Wiring')!;c.answers![c.questions[0]!.question]=c.questions[0]!.options[1]!.label;}
|
||
if(kind==='withdrawn')question(prior.at(-1)!,s=>s+'\nThis decision is withdrawn.');
|
||
expect(recordedCheck(recordedCall(),b176.plan,prior),kind).toBe(false);
|
||
});
|
||
test.each(['foreign-title','foreign-project','foreign-branch','foreign-source','archived','quoted','fenced','duplicate-owner','pending-remedy','changed-answer','missing-todo','wrong-todo-count','missing-task','changed-first-task','late-first-task','incomplete-report','negative-report'])('recorded handoff cannot borrow a foreign or incomplete report: %s',kind=>{
|
||
let plan=b176.plan;
|
||
if(kind==='foreign-title')plan=plan.replaceAll('Multi-tenant Auth Refactor','Different refactor');
|
||
if(kind==='foreign-project')plan=plan.replace('gstack-plan-count-G18mVB','foreign-project');
|
||
if(kind==='foreign-branch')plan=plan.replace('branch main,','branch foreign,');
|
||
if(kind==='foreign-source')plan=plan.replace('Reviewed target: PLAN.md','Reviewed target: FOREIGN.md');
|
||
if(kind==='archived')plan='# Archived\n'+plan.replace(/^# /gm,'## ').replace(/^## /gm,'### ');
|
||
if(kind==='quoted')plan=plan.split('\n').map(line=>'> '+line).join('\n');
|
||
if(kind==='fenced')plan='```md\n'+plan+'\n```';
|
||
if(kind==='duplicate-owner')plan+=plan.split('\n').find(line=>line.startsWith('<!-- Reviewed target:'));
|
||
if(kind==='pending-remedy')plan=plan.replace('State: approved','State: pending');
|
||
if(kind==='changed-answer')plan=plan.replace('Actual answer: A — D7','Actual answer: B — D7');
|
||
if(kind==='missing-todo')plan=plan.replace('### TODO 2:','### Removed 2:');
|
||
if(kind==='wrong-todo-count')plan=plan.replace('### TODO 2:','### TODO 3:');
|
||
if(kind==='missing-task')plan=plan.replace('**T9 (','**T99 (');
|
||
if(kind==='changed-first-task')plan=plan.replace('characterization fixtures for the full R6 input matrix before any rewrite','characterization fixtures after the rewrite');
|
||
if(kind==='late-first-task')plan=plan.replace('1. Record characterization fixtures','2. Record characterization fixtures');
|
||
if(kind==='incomplete-report')plan=plan.replace('NO UNRESOLVED DECISIONS','PENDING DECISIONS');
|
||
if(kind==='negative-report')plan+='\nThe engineering review is not complete.';
|
||
expect(recordedCheck(recordedCall(),plan),kind).toBe(false);
|
||
});
|
||
test('actual D12 native answer survives parser replay; foreign, missing and failed ACKs do not',()=>{
|
||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'eng-b176-ack-')), cwd=path.join(dir,'repo'), config=path.join(dir,'config');
|
||
const c=recordedCall(), [use,result]=b176.nativeD12Tools, project=path.join(config,'projects','owned');
|
||
fs.mkdirSync(cwd);fs.mkdirSync(project,{recursive:true});
|
||
const records:any[]=[{sessionId:c.sessionId,cwd,isSidechain:false,timestamp:use!.timestamp,message:{role:'assistant',content:[{type:'tool_use',id:c.toolUseId,name:'AskUserQuestion',input:use!.input}]}},
|
||
{sessionId:c.sessionId,cwd,isSidechain:false,timestamp:result!.timestamp,message:{role:'user',content:[{type:'tool_result',tool_use_id:c.toolUseId,is_error:false,content:result!.content}]},toolUseResult:{answers:c.answers}}];
|
||
try{
|
||
for(const kind of ['actual','missing','foreign','failed','wrong-id','missing-answers','unoffered']){
|
||
const rows=structuredClone(records);
|
||
if(kind==='missing')rows.pop();
|
||
if(kind==='foreign')rows[1].sessionId='foreign';
|
||
if(kind==='failed')rows[1].message.content[0].is_error=true;
|
||
if(kind==='wrong-id')rows[1].message.content[0].tool_use_id='other';
|
||
if(kind==='missing-answers')delete rows[1].toolUseResult;
|
||
if(kind==='unoffered')rows[1].toolUseResult.answers[c.questions[0]!.question]='Unstated route';
|
||
fs.writeFileSync(path.join(project,c.sessionId+'.jsonl'),rows.map(r=>JSON.stringify(r)).join('\n')+'\n');
|
||
const parsed=readPlanCountTranscript(config,cwd), parsedCall=parsed.calls[0]!;
|
||
if(kind==='actual')expect(parsedCall).toEqual(c);
|
||
expect(recordedCheck(parsedCall),kind).toBe(kind==='actual');
|
||
}
|
||
}finally{fs.rmSync(dir,{recursive:true,force:true});}
|
||
});
|
||
test('actual pending ExitPlanMode needs the classified recap plus the unchanged fresh report and native gates',()=>{
|
||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'eng-b176-terminal-')),file=path.join(dir,'report.md'),now=Date.now;
|
||
try{
|
||
Date.now=()=>Date.parse(b176.capturedAt);fs.writeFileSync(file,b176.plan);fs.utimesSync(file,b176.sourceReport.mtimeMs/1000,b176.sourceReport.mtimeMs/1000);
|
||
const t=recorded(),signature=b176.fingerprint.signature;
|
||
const admin=new Set(recordedCheck()?[signature]:[]);
|
||
const check=(transcript=t,administrative=admin)=>hasNativePlanTerminal(transcript,file,b176.startedAt,'plan_ready',administrative);
|
||
expect(isCurrentPlanApprovalScreen(b176.screen)).toBe(true);
|
||
expect(check()).toBe(true);expect(check(t,new Set())).toBe(false);expect(check(t,new Set(['foreign:call']))).toBe(false);
|
||
for(const mutate of [
|
||
(v:PlanCountTranscript)=>{v.planReadyRequests=[];},
|
||
(v:PlanCountTranscript)=>{v.planReadyRequests![0]!.failed=true;},
|
||
(v:PlanCountTranscript)=>{v.planReadyRequests![0]!.sessionId='foreign';},
|
||
(v:PlanCountTranscript)=>{v.planReadyRequests![0]!.timestamp=new Date(Date.now()+1).toISOString();},
|
||
(v:PlanCountTranscript)=>{v.planReadyRequests![0]!.timestamp=v.calls.at(-1)!.answeredAt!;},
|
||
(v:PlanCountTranscript)=>{v.calls.at(-1)!.answered=false;},
|
||
(v:PlanCountTranscript)=>{v.calls.at(-2)!.answeredAt=new Date(b176.sourceReport.mtimeMs+1).toISOString();},
|
||
]){const v=recorded();mutate(v);expect(check(v)).toBe(false);}
|
||
fs.utimesSync(file,(b176.startedAt-1)/1000,(b176.startedAt-1)/1000);expect(check()).toBe(false);
|
||
fs.writeFileSync(file,b176.plan.replace('NO UNRESOLVED DECISIONS','PENDING'));fs.utimesSync(file,b176.sourceReport.mtimeMs/1000,b176.sourceReport.mtimeMs/1000);expect(check()).toBe(false);
|
||
}finally{Date.now=now;fs.rmSync(dir,{recursive:true,force:true});}
|
||
});
|