From c5250dedc1ef9398ff3f10519c17919aaae880dc Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 17 Nov 2026 20:02:11 +0800 Subject: [PATCH] Keep reviewer product challenges open on the approval page (#4431) * Keep reviewer product challenges open on the approval page Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Read the approvals record without writing the slug cache when building the gate Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Keep every reviewer challenge on the approval page, and ask again when the cut list changes A challenge with no change kind and no real owner quote now becomes a proposal instead of vanishing. An ordinary finding that only mentions an earlier challenge no longer closes it. The cut list and confirm-direction items carry their content in their origin, so an earlier answer is not reused for a changed list. Review-Finding: p1/specialist-batched#1 reader=specialist-batched Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p1/red-team#3 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Keep removed owner quotes redacted, and keep High proposals as blocking tasks when declined Public exports now redact the Owner's words from every plan text the run kept, so a quote a revision removed stays hidden in earlier reviewer results. A paired proposal takes the heaviest change either reviewer named, so an ordering-plus-scope pair is re-reviewed instead of settled. A proposal behind a Critical or High finding offers b as keep the draft and carry it into the build as a blocking task, and only a settles it. Review-Finding: p1v/outside-voice#1 reader=outside-voice Review-Finding: p1v/outside-voice#2 reader=outside-voice Review-Finding: p1v/adversarial-native#2 reader=adversarial-native Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Document owner's words, reviewer proposals and day-one items on the approval page Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * chore: changelog and TODOS Co-Authored-By: Claude Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Co-authored-by: Claude --- autoplan/DRIVER.md | 2 +- capy/skill/gstack/captain.md | 3 +- ...-keeps-reviewer-product-challenges-open.md | 1 + docs/troubleshooting.md | 11 +- docs/unattended.md | 37 +- lib/autoplan-confirm.ts | 24 +- lib/autoplan-gate-items.ts | 157 ++++++++ lib/autoplan-gate.ts | 38 +- lib/autoplan-owner-text.ts | 113 ++++++ lib/autoplan-owner-words.ts | 15 +- lib/autoplan-prompts.ts | 2 +- lib/autoplan-reconcile.ts | 8 +- lib/autoplan-revise.ts | 10 +- lib/autoplan-run.ts | 3 +- lib/captain-brief.ts | 8 +- lib/gate-list.ts | 13 +- lib/headless-artifacts.ts | 2 +- lib/owner-brief.ts | 8 + test/autoplan-carry.test.ts | 5 +- test/autoplan-day-one-gate.test.ts | 365 ++++++++++++++++++ test/captain-brief.test.ts | 6 +- test/fixtures/module-size-ratchet.json | 2 + 22 files changed, 792 insertions(+), 41 deletions(-) create mode 100644 changelog.d/approval-page-keeps-reviewer-product-challenges-open.md create mode 100644 lib/autoplan-gate-items.ts create mode 100644 lib/autoplan-owner-text.ts create mode 100644 test/autoplan-day-one-gate.test.ts diff --git a/autoplan/DRIVER.md b/autoplan/DRIVER.md index 81d661433..a117116ed 100644 --- a/autoplan/DRIVER.md +++ b/autoplan/DRIVER.md @@ -102,7 +102,7 @@ RESULT FORMAT (required by gstack-autoplan; the parent binds your file by this c ```gstack-findings {"id":"F1","severity":"High","title":"","file":"","line":12,"fix":""} ``` - severity is Critical | High | Medium | Low | Informational. Add "user_challenge": true only when you recommend changing the plan's stated direction AND the change alters its scope, cost or direction (then also add "changes": "scope" | "cost" | "direction") or only its delivery packaging or ordering, with no Implementation-plan edit (then "changes": "packaging" | "ordering"). Naming and other reversible choices are ordinary findings, not user challenges. Add "urgent": true and "suggested_owner": "" for a security or data-loss finding this plan does not own. An empty fence means no findings; a missing fence is refused. + severity is Critical | High | Medium | Low | Informational. Any finding that recommends changing the plan's scope, cost or direction adds "changes": "scope" | "cost" | "direction", or "packaging" | "ordering" when only its delivery packaging or build order changes, with no Implementation-plan edit; that holds at any severity. Only the owner's own words are the plan's direction: add "user_challenge": true and "owner_quote": only when the change goes against bullet n (from 1) of the plan's "Owner's words" section. Scope, order or features the planning agent wrote are proposals, so a change to them is an ordinary finding with "changes" and no user_challenge. A plan with no "Owner's words" section: add "user_challenge": true (no owner_quote) when you recommend changing its stated direction. Naming and other reversible choices are ordinary findings with no "changes". Add "urgent": true and "suggested_owner": "" for a security or data-loss finding this plan does not own. An empty fence means no findings; a missing fence is refused. 3. Write the whole result to this file: ## Gate replies diff --git a/capy/skill/gstack/captain.md b/capy/skill/gstack/captain.md index d4227c769..7bb28aa7e 100644 --- a/capy/skill/gstack/captain.md +++ b/capy/skill/gstack/captain.md @@ -104,7 +104,8 @@ For an autoplan run, open the plan with `## ELI5` (5-10 plain sentences), then w gstack-owner-brief render --captain --out --captain-name "" ``` -It prints a header line ("Decision needed … Reply **do it** …"), the `### ELI5` summary (on a run whose gate +It prints a header line ("Decision needed … Reply **do it** …"), the plan's `### Day one` table, `### What it won't do yet` +and the owner's words it follows (each when the plan has it), the `### ELI5` summary (on a run whose gate carries `eli5`), the four plan sections (each capped, with a pointer to the plan for the rest), and "What we need from you", one lettered line per choice in the ask format, closed by "do it", then a `### Cost` section (spent so far, worst case, and the estimate for the phases `rec` can reopen). The last line, "For the relaying agent", carries the run, `gate_rev`, `rec_hash` and the exact diff --git a/changelog.d/approval-page-keeps-reviewer-product-challenges-open.md b/changelog.d/approval-page-keeps-reviewer-product-challenges-open.md new file mode 100644 index 000000000..7486b88ad --- /dev/null +++ b/changelog.d/approval-page-keeps-reviewer-product-challenges-open.md @@ -0,0 +1 @@ +- **/autoplan's approval page no longer hides a reviewer's product objection behind "keep your direction".** A plan can now quote its owner under `### Owner's words`, and only those quotes count as the plan's direction. When a reviewer recommends changing anything else the plan says (its scope, build order, direction, cost or packaging), at any severity and even from one reviewer, the approval page shows it as a lettered choice that recommends the reviewer's change, and the cost line says what taking it actually does. A plan with no Owner's words section keeps today's default and gets one question asking the owner to confirm the direction is theirs. A challenge raised in an earlier review round stays on the page until the owner answers it or a later round marks it fixed. App plans with a `### Day one` table (the owner's first actions, how often, the feature, the way in from the first screen, the first build that has it, and how it's checked) show it first on the approval page, turn each guessed row into a question for the owner, and letter every cut that drops a day-one row or a quoted owner line; an app plan without the table gets one item asking for it. Declining a reviewer's change on a High or Critical finding keeps the plan as written and carries the finding into the build as a blocking task. Quoted owner words, including ones a later revision removed, are redacted from public exports. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 8af578794..4c7f040cc 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -5302,8 +5302,9 @@ directory, and this one already holds files. ### `OWNER_REPLY_REQUIRED` **Meaning.** An agent answered the gate (`--by agent:`) without recording -what the owner actually said, or answered a `uc` item (a user challenge or a -round-cap approval, which only the owner settles) in its own words +what the owner actually said, or answered a `uc` item (a user challenge, a +reviewer's proposal, a day-one or cut question, or a round-cap approval, which +only the owner settles) in its own words (`--words-by agent:`). Nothing was applied. **Fix.** Pass the owner's words verbatim: `--owner-reply ""`, @@ -5417,8 +5418,10 @@ errors. **Meaning.** A public copy of an autoplan run still quotes the owner's own words: a gate reply the private run recorded (on a decision row, the gate or -the journal), the words a carried gate reused, or a reason a human gave for -deferring a phase, in prose or in one of gstack's renderings of that reason. +the journal), the words a carried gate reused, a quote under the plan's +`### Owner's words` heading (one a later revision removed included), or a +reason a human gave for deferring a phase, in prose or in one of gstack's +renderings of that reason. Nothing a person wrote leaves without their click. A reply of 3 or more words is a quote wherever it appears whole, and from 8 words any 8 consecutive words are one, compared across punctuation, line breaks, JSON escapes, entities, HTML and diff --git a/docs/unattended.md b/docs/unattended.md index ced169259..d9b41014b 100644 --- a/docs/unattended.md +++ b/docs/unattended.md @@ -306,8 +306,10 @@ owner's own words: nothing a person wrote leaves without their click (GST-1243). - **Whose words.** Every owner reply the private run ever recorded: on decision rows, on `run.json`'s gate, and in the journal (`attempts.jsonl` keeps a reply that a later answer at the same gate replaced), the words a - carried gate reused, and the reason a human gave for `close --deferred --by - human`. A reply that parsed as gate grammar is the decision code, not owner + carried gate reused, each quote under a `### Owner's words` heading in any + plan text the run kept (the active plan, its source copies and each gate's + copy, so a quote a later revision removed stays redacted), and the reason a + human gave for `close --deferred --by human`. A reply that parsed as gate grammar is the decision code, not owner prose. An agent's own words (`answer_words`) and an agent's deferral reason stay. - **Dropped fields.** `owner_reply` anywhere, a carry record's `words`, and a @@ -524,6 +526,17 @@ The example above is the full run. The first `next` also takes `--kind`: `p1b` (approve with the recommended changes) or an explicit `a` applies a fix; a finding carried with `b` stays open, so a rerun that raises it again asks again. + With an `### Owner's words` section in the plan, only a challenge naming + one of its bullets (`owner_quote`) is a user challenge; a reviewer's + `changes` to anything else, at any severity and from one voice, is a + `proposal` approval item recommending the change, whose `b` keeps the draft + (behind a Critical or High finding, as a blocking build task). Without that + section the default stays, plus one `confirm_direction` auto item when a + one-voice challenge keeps it. An earlier round's open challenge stays until + answered or marked fixed (`resolves`). `### Day one` and `### What it won't + do yet` add `day_one` and `cut` approval items (a missing day-one page on a + UI plan, each `assumed` row, each cut that drops a day-one row or quoted + owner line) and one `cuts` auto item for the rest. 4. **Answer the gate** with the reply grammar and the revision you read: ```bash $AP answer --out --gate-rev 1 --reply "rec" --by human # every recommendation, plan changes included (APPLY: ...; amend_pending) @@ -540,7 +553,8 @@ The example above is the full run. The first `next` also takes `--kind`: are then recorded as `answer_words` with `words_by`, never as `owner_reply`; a later gate never carries them (`CARRY: no`), and `gstack-approvals import` lists that row under the agent, not the owner. - They never settle a `uc` item (a user challenge or a round-cap approval): + They never settle a `uc` item (a user challenge, a reviewer's proposal, a + day-one or cut question, or a round-cap approval): a reply in an agent's own words that would choose one, by `rec`, `as-is` or a token, is refused (`OWNER_REPLY_REQUIRED`) and nothing is applied; such a reply may still answer the `d` items and leave the `uc` items to @@ -625,9 +639,13 @@ Each prompt file ends with this contract; `submit` enforces it. 2. The review is prose, then one fenced block of canonical findings, one JSON object per line: `{"id":"F1","severity":"High","title":"...","file":"...","line":12,"fix":"..."}` inside a ```` ```gstack-findings ```` fence. `severity` is Critical | High | - Medium | Low | Informational; `"user_challenge": true` marks a recommended - change to the plan's stated direction and needs `"changes": "scope" | - "cost" | "direction"` (what accepting it changes); `"urgent": true` with + Medium | Low | Informational; a finding that recommends changing the + plan's scope, cost or direction adds `"changes": "scope" | "cost" | + "direction"` (or `"packaging" | "ordering"` when only delivery packaging or + build order changes), at any severity; `"user_challenge": true` with + `"owner_quote": ` marks a change against bullet n of the plan's + `### Owner's words` (on a plan without that section, `"user_challenge": + true` alone marks a change to its stated direction); `"urgent": true` with `"suggested_owner"` marks a security or data-loss finding the plan does not own. An empty fence means no findings; a missing fence is refused. 3. The whole result is written to the printed `result=` path. @@ -861,7 +879,8 @@ predictions with his answers. prospective evidence. - **The record.** `shadow/ceo-only.r.jsonl`, one row per gate item: the frozen item, `item_class` (`challenge2`, `challenge1`, `disagree`, `agent`, - `cap_deferred`, `cap_blocker`, `cap_delta`, `finding`, `p1`), `ceo_eligible` + `cap_deferred`, `cap_blocker`, `cap_delta`, `finding`, `proposal`, + `confirm_direction`, `day_one`, `cut`, `cuts`, `p1`), `ceo_eligible` (false for a `finding` item, which a CEO-only run leaves to the owner), the prediction, `rule_pick` (the driver's keep-direction pick, the free baseline), `rec_hash`, the plan and prompt hashes, the model, the gstack @@ -891,7 +910,9 @@ predictions with his answers. `gstack-owner-brief render --out ` is what the owner sees at the final gate, interactive or unattended: one page built from `gate.json`, `decisions.jsonl` and `findings.jsonl` (`BRIEF_INPUT_MISSING` when one is -absent). It opens with the `URGENT, outside this plan` block, then a +absent). It opens with the `URGENT, outside this plan` block, then the +plan's `### Day one` table, its `### What it won't do yet` cuts and the +owner's words it follows (each only when the plan has it), then a plain-language summary (phases closed, findings accepted, how many decisions take their default, the cycle time; `--summary ` or `/summary.md` replaces the generated sentence with the run's own), then the numbered diff --git a/lib/autoplan-confirm.ts b/lib/autoplan-confirm.ts index 4589d1d81..cb99d74c8 100644 --- a/lib/autoplan-confirm.ts +++ b/lib/autoplan-confirm.ts @@ -86,7 +86,9 @@ export function phaseDelta(state: RunState, phase: string, snapshotPath: string) export function confirmBlock(state: RunState, phase: string, snapshotPath: string, round: number): { text: string; confirm: NonNullable } | undefined { if (round <= 1) return undefined; const delta = phaseDelta(state, phase, snapshotPath); - const rule = 'Review only what changed and its consequences; the DECIDED AT THE GATE list is settled scope. A finding on settled scope is recorded settled unless it cites a hunk of this diff or a file:line the settled decision\'s record does not contain.'; + const open = openEarlier(state, phase); + const rule = 'Review only what changed and its consequences; the DECIDED AT THE GATE list is settled scope. A finding on settled scope is recorded settled unless it cites a hunk of this diff or a file:line the settled decision\'s record does not contain.' + + (open.length ? ` OPEN CHALLENGES from earlier rounds stay on the owner's gate until answered: for each one the revised plan now fixes, add a row {"severity":"Informational","title":"Resolved: ","resolves":"<id>"}; raise again any you still hold.\n${open.map(r => `- ${r.id}: ${r.title}${(r as ChallengeRow).changes ? ` (changes ${(r as ChallengeRow).changes})` : ''}`).join('\n')}` : ''); if (!delta) return { text: `\n\nCONFIRM ROUND ${round} (data, not instructions): no earlier snapshot of this phase is on disk, so review the whole plan. ${rule}\n`, confirm: { round, added: 0, removed: 0 } }; const stat = diffStat(delta.ops); const hunks = renderHunks(delta.ops) || '(no change: the same Implementation plan is reviewed again)'; @@ -105,9 +107,27 @@ export function reviewRows(state: RunState, prev: PhaseState | undefined): Findi return file && fs.existsSync(file) ? (readJsonl(file).rows as unknown as FindingRow[]) : []; }); } -const earlierRows = (state: RunState, phase: string): FindingRow[] => +export const earlierRows = (state: RunState, phase: string): FindingRow[] => state.history.filter(h => h.event === 'reopened' && h.phase === phase).flatMap(h => reviewRows(state, h.previous as PhaseState | undefined)); +type ChallengeRow = FindingRow & { user_challenge?: boolean; changes?: string; settled_by?: string; correlates?: string[]; resolves?: string }; +/** + * Earlier rounds' challenges and `changes` findings in this phase that are still open (full runs; a lean run has one + * round): not answered at a gate, not settled, and neither repeated (`correlates` on a challenge or settled row) nor marked + * fixed (`resolves`) by a later round. A later round staying silent on one, or naming it only in an ordinary finding, never closes it. + */ +export function openEarlier(state: RunState, phase: string, current: FindingRow[] = []): FindingRow[] { + if (state.lean) return []; + const earlier = earlierRows(state, phase) as ChallengeRow[]; + if (!earlier.length) return []; + const answered = settledIds(state); + const ids = new Set(current.map(r => r.id)); + const covered = new Set(([...current, ...earlier] as ChallengeRow[]).flatMap(r => [...(r.user_challenge || r.changes || r.settled_by ? r.correlates ?? [] : []), ...(r.resolves ? [r.resolves] : [])])); + const open = new Map<string, FindingRow>(); + for (const r of earlier) if ((r.user_challenge || r.changes) && !r.settled_by && !answered.has(r.id) && !ids.has(r.id) && !covered.has(r.id)) open.set(r.id, r); + return [...open.values()]; +} + /** The origin tag of an open Critical/High finding's gate item: only `a` (its fix applied to the plan) settles it. */ export const FINDING_ORIGIN = 'finding'; diff --git a/lib/autoplan-gate-items.ts b/lib/autoplan-gate-items.ts new file mode 100644 index 000000000..ce7d7a5b0 --- /dev/null +++ b/lib/autoplan-gate-items.ts @@ -0,0 +1,157 @@ +/** + * autoplan-gate-items — the gate items that keep a product challenge on the + * owner's page (GST-2947). Only the owner's own words are the plan's + * direction (lib/autoplan-owner-text.ts): a reviewer's scope, ordering, + * direction, cost or packaging change to anything else the plan says becomes + * a lettered proposal recommending the reviewer's change, at any severity and + * from one voice; a challenge that names a quoted owner line keeps today's + * keep-direction rules in buildGate (lib/autoplan-gate.ts). A plan with no + * Owner's words section keeps today's defaults and gets one item asking the + * owner to confirm its direction. The day-one items ask about every assumed + * day-one row, a missing day-one page on an app plan, and each cut that drops + * a day-one row or a quoted owner line (the other cuts are one grouped item). + */ +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { branchKey, captainApprovalsDir } from './approval-record'; +import { cutDrops, parseCuts, parseDayOne, parseOwnerWords, wordKey, type DayOneTable, type OwnerQuote, type OwnerWordsSection } from './autoplan-owner-text'; +import { SETTLEABLE_CHANGES } from './autoplan-reconcile'; +import { readDecisions, readJournal, type RunState } from './autoplan-state'; +import { resolveStateRoot } from './state-root'; +import type { GateItem } from './gate-list'; +import type { FindingRow } from './headless-artifacts'; + +export type ChallengeRow = FindingRow & { user_challenge?: boolean; changes?: string; settled_by?: string; owner_quote?: number; resolves?: string }; +export type NewItem = Omit<GateItem, 'id'> & { idKind: 'd' | 'uc'; key: string }; +export interface GateOwnerWords { status: OwnerWordsSection['status']; quotes: Array<OwnerQuote & { verified: boolean }>; reason?: string; fix?: string } +export interface OwnerContext { words: OwnerWordsSection; verified: Set<number>; dayOne: DayOneTable; cuts: string[]; app: boolean; lean: boolean } + +/** + * The owner's words in every approvals record already on disk for the branch checked out at `cwd` (lib/approval-record.ts + * layout: <state root>/projects/<slug>/approvals/<branch key>.jsonl and its mirrors). Read-only: the slug is not resolved, + * because resolving it writes the slug cache, and building a gate must not write outside the run. + */ +export function ledgerWords(cwd: string, env: NodeJS.ProcessEnv = process.env): string[] { + const head = spawnSync('git', ['symbolic-ref', '--short', '-q', 'HEAD'], { cwd, encoding: 'utf8', timeout: 10_000 }); + const branch = head.status === 0 ? head.stdout.trim() : ''; + if (!branch) return []; + const name = `${branchKey(branch)}.jsonl`; + const files: string[] = []; + const under = (root: string, sub: string[]) => { try { for (const d of fs.readdirSync(root)) files.push(path.join(root, d, ...sub, name)); } catch { /* no such root */ } }; + under(path.join(resolveStateRoot(env), 'projects'), ['approvals']); + for (const root of [env.GSTACK_APPROVALS_DIR, captainApprovalsDir(env)]) if (root) under(root, []); + const words: string[] = []; + for (const file of files) { + let text: string; + try { text = fs.readFileSync(file, 'utf8'); } catch { continue; } + for (const line of text.split('\n')) { + try { const row = JSON.parse(line); if (typeof row?.words === 'string' && !row.words_by) words.push(row.words); } catch { /* a torn line */ } + } + } + return words; +} + +/** Every owner reply this run recorded, plus the owner's words in the approvals records for the plan's branch. */ +export function recordedOwnerWords(state: RunState, env: NodeJS.ProcessEnv = process.env): string[] { + const out: string[] = []; + for (const r of readJournal(state.out)) if (typeof r.owner_reply === 'string') out.push(r.owner_reply); + for (const d of readDecisions(state.out)) if (typeof d.owner_reply === 'string') out.push(d.owner_reply); + return [...out, ...ledgerWords(path.dirname(state.plan_input ?? state.plan_source), env)]; +} + +export function ownerContext(state: RunState, recorded: string[] = recordedOwnerWords(state)): OwnerContext { + let text = ''; + try { text = fs.readFileSync(state.active_plan, 'utf8'); } catch { /* no plan text: nothing is quoted */ } + const words = parseOwnerWords(text); + const keys = recorded.map(wordKey); + const verified = new Set(words.quotes.filter(q => keys.some(k => k.includes(wordKey(q.text)))).map(q => q.n)); + return { words, verified, dayOne: parseDayOne(text), cuts: parseCuts(text), app: !!state.scope?.ui, lean: !!state.lean }; +} + +export function gateOwnerWords(ctx: OwnerContext): GateOwnerWords { + return { status: ctx.words.status, quotes: ctx.words.quotes.map(q => ({ ...q, verified: ctx.verified.has(q.n) })), + ...(ctx.words.reason ? { reason: ctx.words.reason, fix: ctx.words.fix } : {}) }; +} + +/** The owner line a challenge names, when the plan quotes one there. */ +export const ownerQuoteOf = (ctx: OwnerContext, f: ChallengeRow | undefined): OwnerQuote | undefined => + f?.owner_quote ? ctx.words.quotes.find(q => q.n === f.owner_quote) : undefined; + +/** Today's keep-direction rules apply: the plan quotes no owner, or the challenge goes against a quoted owner line. */ +export const directionIsOwners = (ctx: OwnerContext, rows: Array<ChallengeRow | undefined>): boolean => + ctx.words.status === 'none' || rows.some(r => !!ownerQuoteOf(ctx, r)); + +/** What choosing the reviewer's change costs, as revise actually discharges it (lib/autoplan-revise.ts). */ +export function proposalCost(ctx: OwnerContext, phase: string, changes: string): string { + if (ctx.lean) return 'a applies without re-review (lean run: one gate revision)'; + if (SETTLEABLE_CHANGES.includes(changes)) return 'a is settled with revise --settle: no plan edit, no re-review'; + return `a reopens ${phase}${phase === 'eng' ? '' : ' and eng'} once the plan is revised`; +} + +/** A proposal behind a Critical or High row keeps the finding path's b: the draft stands and the finding becomes a blocking build task. */ +export const blockingProposal = (rows: ChallengeRow[]): boolean => rows.some(r => r.severity === 'Critical' || r.severity === 'High'); + +/** + * One proposal from one or both voices (a paired twin) against agent-written plan text: a takes the change, b keeps the draft. + * Its `changes` is the heaviest any row names (scope, cost, direction, then packaging or ordering), so a pair never settles a scope change. + */ +export function proposalItem(ctx: OwnerContext, phase: string, rows: ChallengeRow[], o: { carried?: boolean } = {}): NewItem { + const named: string[] = rows.flatMap(r => (r.changes ? [r.changes] : [])); + const changes = ['scope', 'cost', 'direction'].find(c => named.includes(c)) ?? named[0] ?? 'direction'; + const keep = blockingProposal(rows) ? "keep the plan's draft; carry it into the build as a blocking task (no plan change)" : "keep the plan's draft"; + const fixes = [...new Set(rows.map(r => r.resolution).filter((r): r is string => !!r))]; + const voices = rows.map(r => r.voice).join(' + '); + const ids = rows.map(r => r.id).join(' + '); + return { idKind: 'uc', key: rows.map(r => r.id).join('+'), title: `${rows[0]!.title} [${ids}]`, kind: 'approval', recommended: 'a', phase, item_class: 'proposal', changes, + recommended_basis: "the reviewer's change: only the owner's words are direction, and this changes text the planning agent wrote", + why: `${voices} recommend${rows.length > 1 ? '' : 's'} changing the plan's ${changes} (${rows[0]!.severity}); no quoted owner line says otherwise${o.carried ? '; raised in an earlier round and still open' : ''}`, + cost: proposalCost(ctx, phase, changes), + options: [{ key: 'a', text: `take the change: ${fixes.length ? fixes.join('; ') : rows[0]!.title}`, changes_plan: true }, { key: 'b', text: keep, changes_plan: false }] }; +} + +/** + * No Owner's words section: a one-voice challenge keeps the plan's direction by default, so the owner is asked to confirm + * the direction is theirs (auto: today's default stands unanswered). A two-voice challenge already recommends the change + * on a shared proposal (challengeDefault), so it adds no confirm item. + */ +export function confirmDirectionItem(challenges: string[]): NewItem { + return { idKind: 'd', key: 'confirm-direction', kind: 'auto', recommended: 'a', item_class: 'confirm_direction', + title: `Confirm the plan's direction is yours: the plan quotes no owner words, so ${challenges.join(', ')} default to the plan as written`, + recommended_basis: "today's default for a plan with no Owner's words section", + why: "only the owner's words are direction; without an Owner's words section the gate cannot tell your direction from the planning agent's draft", + options: [{ key: 'a', text: 'yes, the plan as written is what I asked for', changes_plan: false }, + { key: 'b', text: "no, it is a draft: quote what I said in an Owner's words section and revise, so the challenges are judged against it", changes_plan: true }] }; +} + +/** The day-one questions: each assumed row, a missing page on an app plan, and the plan's cuts. */ +export function dayOneItems(ctx: OwnerContext): NewItem[] { + const items: NewItem[] = []; + const reopen = ctx.lean ? 'applies without re-review (lean run)' : 'reopens ceo and eng once the plan is revised'; + if (ctx.app && ctx.dayOne.status !== 'ok') { + items.push({ idKind: 'uc', key: 'day-one-page', kind: 'approval', recommended: 'a', item_class: 'day_one', changes: 'scope', cost: `a ${reopen}`, + title: `The plan has no day-one page${ctx.dayOne.reason ? ` (${ctx.dayOne.reason})` : ''}: the first things you will do with it, how often, and which build puts each on your device`, + why: 'an app plan names what its owner does on day one so the most-used thing is built first and every feature has a way in', + options: [{ key: 'a', text: 'add it: a ### Day one table (action, frequency, source, feature, route, first build, check), then revise', changes_plan: true }, { key: 'b', text: 'approve without it', changes_plan: false }] }); + } + for (const row of ctx.dayOne.rows.filter(r => r.assumed)) { + items.push({ idKind: 'uc', key: `day-one:${wordKey(row.action).trim()}`, kind: 'approval', recommended: 'a', item_class: 'day_one', cost: `b ${reopen}`, + title: `Day one: the plan assumes you will do "${row.action.replace(/[.]$/, '')}" (${row.frequency || 'how often unstated'}); is that right?`, + why: `no owner words or owner evidence back this row; feature: ${row.feature || 'none named'}; first build: ${row.first_build || 'none named'}`, + options: [{ key: 'a', text: 'yes, I do that: keep the row', changes_plan: false }, { key: 'b', text: 'no, or not like that: say what you do instead, then revise', changes_plan: true }] }); + } + const targets = [...ctx.dayOne.rows.flatMap(r => [r.action, r.feature]), ...ctx.words.quotes.map(q => q.text)].filter(Boolean); + const named = ctx.cuts.filter(c => targets.some(t => cutDrops(c, t))); + for (const cut of named) { + items.push({ idKind: 'uc', key: `cut:${wordKey(cut).trim()}`, kind: 'approval', recommended: 'a', item_class: 'cut', changes: 'scope', cost: `b ${reopen}`, + title: `Cut: ${cut}`, why: 'this cut drops something on the day-one page or in your own words', + options: [{ key: 'a', text: 'keep the cut: not in the first build', changes_plan: false }, { key: 'b', text: 'put it back in the first build', changes_plan: true }] }); + } + const rest = ctx.cuts.filter(c => !named.includes(c)); + if (rest.length) { + items.push({ idKind: 'd', key: 'cuts', kind: 'auto', recommended: 'a', item_class: 'cuts', changes: 'scope', cost: `b ${reopen}`, + title: `${rest.length} other cut${rest.length === 1 ? '' : 's'}: ${rest.join('; ')}`, why: 'none of these drops a day-one row or a quoted owner line', + options: [{ key: 'a', text: 'keep these cuts', changes_plan: false }, { key: 'b', text: 'put some back: name them, then revise', changes_plan: true }] }); + } + return items; +} diff --git a/lib/autoplan-gate.ts b/lib/autoplan-gate.ts index 3600c6c12..e2f4e33d2 100644 --- a/lib/autoplan-gate.ts +++ b/lib/autoplan-gate.ts @@ -26,7 +26,8 @@ import { FILES, RunError, journal as journalRow, now, readDecisions, voiceRows, import { applyCapChoices, pendingDeltas, releaseUndispatched, roundCap, roundOf } from './autoplan-budget'; import { evaluateCarry, gateEvidence, voidPendingCheck } from './autoplan-carry'; import { buildEli5, capyRelayLine } from './captain-brief'; -import { FINDING_ORIGIN, previousReview, reviewRows, settledIds } from './autoplan-confirm'; +import { FINDING_ORIGIN, openEarlier, previousReview, reviewRows, settledIds } from './autoplan-confirm'; +import { blockingProposal, confirmDirectionItem, dayOneItems, directionIsOwners, gateOwnerWords, ownerContext, ownerQuoteOf, proposalItem, type ChallengeRow, type NewItem } from './autoplan-gate-items'; import { phaseClose } from './autoplan-timing'; import { agentWords, ANSWERED_BY_RE, applyReply, autoDefault, decisionId, decisionRows, keepDirection, legacyRecHash, parseReply, pendingHint, recHash, replyShape, validateGateList, type GateChoice, type GateItem, type GateList, type GateOption, type ParsedReply } from './gate-list'; import type { DecisionRow, FindingRow } from './headless-artifacts'; @@ -196,6 +197,15 @@ function agentDecision(id: string, title: string, phase: string, why: string): G export function buildGate(state: RunState, gateRev: number): GateList { const items: GateItem[] = []; let d = 0, uc = 0; + const owner = ownerContext(state); + const quoted = owner.words.status !== 'none'; + const kept: string[] = []; + const keptIds: string[] = []; + const add = ({ idKind, key, ...item }: NewItem, origin: (options: GateOption[]) => string): string => { + const id = idKind === 'uc' ? `uc${++uc}` : `d${++d}`; + items.push({ id, ...item, origin: origin(item.options) }); + return id; + }; for (const phase of state.phase_order) { const ps = state.phases[phase]; if (!ps?.closed_at || ps.deferred) continue; @@ -208,12 +218,19 @@ export function buildGate(state: RunState, gateRev: number): GateList { const push = (item: GateItem, ids: string, tag?: string) => items.push({ ...item, origin: [origin(ids, item.options), ...(tag ? [tag] : [])].join('|') }); const challenged = new Set<string>(); const twins = new Map(consensus.rows.filter(r => sameProblem(r) && (r.disposition === 'confirmed' || r.disposition === 'unverified')).map(r => [r.native_id!, r.outside_id])); + const carried = openEarlier(state, phase, [...native, ...outside]) as ChallengeRow[]; + for (const f of carried) byId.set(f.id, f); + const propose = (rows: ChallengeRow[], fromEarlier = false) => { + rows.forEach(r => challenged.add(r.id)); + add(proposalItem(owner, phase, rows, { carried: fromEarlier }), options => [origin(rows.map(r => r.id).join('+'), options), ...(blockingProposal(rows) ? [FINDING_ORIGIN] : [])].join('|')); + }; for (const row of consensus.rows) { const o = byId.get(row.outside_id)! as FindingRow & { user_challenge?: boolean; changes?: string; settled_by?: string }; if (o.settled_by) continue; const n = (row.native_id ? byId.get(row.native_id) : undefined) as (FindingRow & { user_challenge?: boolean; changes?: string }) | undefined; const ids = `${row.native_id}+${row.outside_id}`; if (o.user_challenge && n?.user_challenge && row.disposition !== 'new' && row.basis !== 'file') { + if (!directionIsOwners(owner, [n, o])) { propose([n, o]); continue; } challenged.add(o.id); challenged.add(n.id); const title = `${n.title} [${row.native_id} + ${row.outside_id}]`; if (reran && !n.changes && !o.changes) { push(agentDecision(`d${++d}`, title, phase, 'both voices recommend changing your stated direction'), ids); continue; } @@ -230,10 +247,18 @@ export function buildGate(state: RunState, gateRev: number): GateList { options: [{ key: 'a', text: `native position (${row.severity.native})`, changes_plan: false }, { key: 'b', text: `outside position (${row.severity.outside})`, changes_plan: true }] }, ids); } } - for (const f of [...native, ...outside] as Array<FindingRow & { user_challenge?: boolean; changes?: string; settled_by?: string }>) { - if (!f.user_challenge || challenged.has(f.id) || f.settled_by) continue; - const why = `one voice (${f.voice}) recommends changing your stated direction`; + const twinOf = (id: string) => twins.get(id) ?? [...twins].find(([, out]) => out === id)?.[0]; + for (const f of [...native, ...outside, ...carried] as ChallengeRow[]) { + if (challenged.has(f.id) || f.settled_by) continue; + if (quoted && (f.changes || f.user_challenge) && !ownerQuoteOf(owner, f)) { + const twin = twinOf(f.id) ? byId.get(twinOf(f.id)!) as ChallengeRow | undefined : undefined; + propose(twin && !twin.settled_by && !ownerQuoteOf(owner, twin) ? [f, twin] : [f], carried.includes(f)); + continue; + } + if (!f.user_challenge || !directionIsOwners(owner, [f])) continue; + const why = `one voice (${f.voice}) recommends changing your stated direction${carried.includes(f) ? '; raised in an earlier round and still open' : ''}`; if (reran && !f.changes) { push(agentDecision(`d${++d}`, `${f.title} [${f.id}]`, phase, why), f.id); continue; } + if (!quoted) { kept.push(`d${d + 1}`); keptIds.push(f.id); } push({ id: `d${++d}`, title: `${f.title} [${f.id}]`, kind: 'auto', recommended: 'a', phase, item_class: 'challenge1', why, ...(f.changes ? { changes: f.changes } : {}), cost: `b reopens ${phase}${phase === 'eng' ? '' : ' and eng'}`, options: [KEEP('keep your direction'), { key: 'b', text: 'accept the change', changes_plan: true }] }, f.id); } @@ -242,7 +267,7 @@ export function buildGate(state: RunState, gateRev: number): GateList { for (const f of [...native, ...outside] as Array<FindingRow & { user_challenge?: boolean; settled_by?: string }>) { if (f.voice === 'outside' && pairedOutside.has(f.id)) continue; const group = [f, ...(twins.has(f.id) ? [byId.get(twins.get(f.id)!)!] : [])] as Array<FindingRow & { user_challenge?: boolean; settled_by?: string }>; - if (group.some(g => challenged.has(g.id) || g.user_challenge || g.settled_by)) continue; + if (group.some(g => challenged.has(g.id) || (g.user_challenge && directionIsOwners(owner, [g])) || g.settled_by)) continue; const severity = group.some(g => g.severity === 'Critical') ? 'Critical' : group.some(g => g.severity === 'High') ? 'High' : null; if (!severity) continue; const ids = group.map(g => g.id); @@ -253,8 +278,11 @@ export function buildGate(state: RunState, gateRev: number): GateList { } } items.push(...capItems(state, { d: () => `d${++d}`, uc: () => `uc${++uc}` })); + if (!quoted && kept.length) add(confirmDirectionItem(kept), options => ['owner', 'confirm-direction', optionHash(options), keptIds.join('+')].join('|')); + for (const item of dayOneItems(owner)) add(item, options => ['owner', item.key, optionHash(options), createHash('sha256').update(item.title).digest('hex').slice(0, 16)].join('|')); items.push(planApproval(state, items)); const list: GateList = { schema_version: 1, run: state.run, gate_rev: gateRev, items, title: '/autoplan final approval gate', rec_rev: 0, rec_hash_v: 2, + ...(quoted ? { owner_words: gateOwnerWords(owner) } : {}), ...(fs.existsSync(state.active_plan) ? { eli5: buildEli5(fs.readFileSync(state.active_plan, 'utf8'), state.active_plan) } : {}) }; const problems = validateGateList(list); if (problems.length) throw new Error(`gate list invalid: ${problems.join('; ')}`); diff --git a/lib/autoplan-owner-text.ts b/lib/autoplan-owner-text.ts new file mode 100644 index 000000000..05adcce48 --- /dev/null +++ b/lib/autoplan-owner-text.ts @@ -0,0 +1,113 @@ +/** + * autoplan-owner-text — the parts of a plan that say what the owner asked for + * and what they will do on day one (GST-2947). `### Owner's words` quotes the + * owner, one bullet per quote with who and when: only these lines are the + * plan's direction, so a reviewer's challenge to anything else the plan says + * is an ordinary proposal (lib/autoplan-gate-items.ts). `### Day one` is the + * table of the owner's first actions (action, frequency, source, feature, + * route, first build, check); a row whose source is `assumed` becomes an + * owner question at the gate. `### What it won't do yet` lists the plan's + * cuts. Read by the gate builder and the owner and captain briefs. + */ +import { findSection } from './markdown-sections'; + +export const OWNER_WORDS_TITLES = ["Owner's words", 'Owner words']; +export const DAY_ONE_TITLES = ['Day one', 'Day-one page', 'Day one page']; +export const CUTS_TITLES = ["What it won't do yet", 'What it will not do yet', "Won't do yet"]; +export const DAY_ONE_COLUMNS = ['action', 'frequency', 'source', 'feature', 'route', 'first build', 'check'] as const; + +export interface OwnerQuote { n: number; who: string; text: string } +export interface OwnerWordsSection { status: 'none' | 'ok' | 'malformed'; quotes: OwnerQuote[]; reason?: string; fix?: string } +export interface DayOneRow { action: string; frequency: string; source: string; feature: string; route: string; first_build: string; check: string; assumed: boolean } +export interface DayOneTable { status: 'none' | 'ok' | 'malformed'; rows: DayOneRow[]; reason?: string } + +const BULLET = /^\s*[-*+]\s+(.*)$/; +const QUOTED = /[“"](.+)[”"]/; + +/** The quotes under `### Owner's words`; a bullet with no quoted words makes the section malformed (its other quotes still count). */ +export function parseOwnerWords(planText: string): OwnerWordsSection { + const section = findSection(planText, OWNER_WORDS_TITLES); + if (!section) return { status: 'none', quotes: [] }; + const bullets = section.body.split('\n').map(l => BULLET.exec(l)?.[1]?.trim()).filter((b): b is string => !!b); + const fix = 'one bullet per quote: - <who>, <when>: "<their exact words>"'; + if (!bullets.length) return { status: 'malformed', quotes: [], reason: 'the section has no bullet list', fix }; + const quotes: OwnerQuote[] = []; + const bad: number[] = []; + bullets.forEach((b, i) => { + const m = QUOTED.exec(b); + if (!m || !m[1]!.trim()) { bad.push(i + 1); return; } + quotes.push({ n: i + 1, who: b.slice(0, m.index).replace(/[\s:,-]+$/, '').trim() || 'unattributed', text: m[1]!.trim() }); + }); + return bad.length ? { status: 'malformed', quotes, reason: `bullet ${bad.join(', ')} quotes no words`, fix } : { status: 'ok', quotes }; +} + +/** The OWNER_WORDS line `next` and the gate print. */ +export function ownerWordsLine(w: OwnerWordsSection, unverified = 0): string { + if (w.status === 'none') return "OWNER_WORDS: none (no ### Owner's words section: reviewer challenges keep the plan's direction, and the gate asks the owner to confirm it)"; + if (w.status === 'malformed') return `OWNER_WORDS: malformed (${w.reason}; fix: ${w.fix}); ${w.quotes.length} quote${w.quotes.length === 1 ? '' : 's'} read`; + return `OWNER_WORDS: ${w.quotes.length} quote${w.quotes.length === 1 ? '' : 's'}${unverified ? ` (${unverified} unverified: not found in a recorded owner reply)` : ''}`; +} + +const cells = (line: string) => line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(c => c.trim()); +const header = (c: string) => c.toLowerCase().replace(/[*_`]/g, '').replace(/[-\s]+/g, ' ').trim(); + +/** The `### Day one` table: the first table under the heading, with every DAY_ONE_COLUMNS column in any order. */ +export function parseDayOne(planText: string): DayOneTable { + const section = findSection(planText, DAY_ONE_TITLES); + if (!section) return { status: 'none', rows: [] }; + const lines = section.body.split('\n'); + const start = lines.findIndex((l, i) => /^\s*\|/.test(l) && /^\s*\|?\s*:?-{3,}/.test(lines[i + 1] ?? '')); + if (start < 0) return { status: 'malformed', rows: [], reason: `no table (columns: ${DAY_ONE_COLUMNS.join(', ')})` }; + const head = cells(lines[start]!).map(header); + const missing = DAY_ONE_COLUMNS.filter(c => !head.includes(c)); + if (missing.length) return { status: 'malformed', rows: [], reason: `the table has no ${missing.join(', ')} column` }; + const at = (row: string[], c: string) => row[head.indexOf(c)] ?? ''; + const rows: DayOneRow[] = []; + for (let i = start + 2; i < lines.length && /^\s*\|/.test(lines[i]!); i++) { + const row = cells(lines[i]!); + if (!at(row, 'action')) continue; + const source = at(row, 'source'); + rows.push({ action: at(row, 'action'), frequency: at(row, 'frequency'), source, feature: at(row, 'feature'), route: at(row, 'route'), + first_build: at(row, 'first build'), check: at(row, 'check'), assumed: /^\W*assumed\b/i.test(source) }); + } + return rows.length ? { status: 'ok', rows } : { status: 'malformed', rows: [], reason: 'the table has no rows' }; +} + +/** + * What the owner reads first at the gate (lib/captain-brief.ts, lib/owner-brief.ts): the day-one table, what the first + * build won't do yet, and the quoted owner words a reviewer needs the owner's answer to change. Empty when the plan has none. + */ +export function renderDayOne(planText: string, quotes: Array<OwnerQuote & { verified?: boolean }> = []): string[] { + const day = parseDayOne(planText); + const cuts = parseCuts(planText); + const out: string[] = []; + if (day.status === 'ok') { + out.push('### Day one', '', 'What you can do with it on day one:', '', '| What you do | How often | Feature | How you get there | First build with it | How we check it works |', '|---|---|---|---|---|---|', + ...day.rows.map(r => `| ${r.action}${r.assumed ? ' (our guess: asked below)' : ''} | ${r.frequency} | ${r.feature} | ${r.route} | ${r.first_build} | ${r.check} |`), ''); + } + if (cuts.length) out.push("### What it won't do yet", '', ...cuts.map(c => `- ${c}`), ''); + if (quotes.length) out.push('### Your words this plan follows', '', ...quotes.map(q => `- ${q.who}: “${q.text}”${q.verified === false ? ' (not found in your recorded replies)' : ''}`), '', + 'A reviewer who wants to change one of these needs your answer. Anything else in the plan was written by the planning agent, so a reviewer\'s change to it is recommended below.', ''); + return out; +} + +/** The bullets under `### What it won't do yet`. */ +export function parseCuts(planText: string): string[] { + const section = findSection(planText, CUTS_TITLES); + return section ? section.body.split('\n').map(l => BULLET.exec(l)?.[1]?.trim()).filter((b): b is string => !!b) : []; +} + +const STOP = new Set(['the', 'and', 'for', 'with', 'from', 'that', 'this', 'into', 'onto', 'its', 'not', 'yet', 'will', 'won', 'are', 'has', 'have', 'one', 'all', 'any', 'each', 'every', 'day', 'first', 'build', 'v0', 'v1']); +const words = (t: string) => [...new Set((t.toLowerCase().match(/[a-z0-9]+/g) ?? []).filter(w => w.length >= 3 && !STOP.has(w)))]; +const covers = (want: string[], have: Set<string>) => { + const hit = want.filter(w => have.has(w)).length; + return want.length > 0 && hit >= Math.min(2, want.length) && hit / want.length >= 0.6; +}; +/** A cut drops `target` (a feature, an action or a quote) when either names most of the other's words. */ +export function cutDrops(cut: string, target: string): boolean { + const c = words(cut), t = words(target); + return covers(t, new Set(c)) || covers(c, new Set(t)); +} + +/** Text compared as words: case, punctuation and spacing ignored. */ +export const wordKey = (t: string) => ` ${(t.toLowerCase().match(/[a-z0-9]+/g) ?? []).join(' ')} `; diff --git a/lib/autoplan-owner-words.ts b/lib/autoplan-owner-words.ts index 0e19c963b..17614be11 100644 --- a/lib/autoplan-owner-words.ts +++ b/lib/autoplan-owner-words.ts @@ -6,8 +6,10 @@ * What counts. `ownerWords` reads the private run and collects every owner * reply it ever recorded: `owner_reply` on decision rows, on run.json's gate * and on every `answered` journal row (attempts.jsonl keeps replies a later - * answer at the same gate replaced), the words a carried gate reused, and a - * reason a human gave for `close --deferred <reason> --by human`. A reply that + * answer at the same gate replaced), the words a carried gate reused, each + * quote in a `### Owner's words` section of any plan text the run kept (plan-active.md, plan-source*.md, + * plan-at-gate.r*.md, plan-file.*.md; lib/autoplan-owner-text.ts), so a quote a revision removed stays redacted, + * and a reason a human gave for `close --deferred <reason> --by human`. A reply that * parsed as gate grammar (`owner_reply_parsed`) is the decision code and is * not scanned for; `reply` and the agent's own `answer_words` stay. * @@ -52,7 +54,8 @@ */ import * as fs from 'node:fs'; import * as path from 'node:path'; -import { readDecisions, readJournal, type RunState } from './autoplan-state'; +import { parseOwnerWords } from './autoplan-owner-text'; +import { FILES, readDecisions, readJournal, type RunState } from './autoplan-state'; export const OWNER_WORDS_MARK = '[owner words redacted]'; export const MIN_TOKENS = 3; @@ -226,7 +229,7 @@ export function redactOwnerWords(text: string, owner: OwnerWords, keep: Span[] = return { text: out, redacted: spans.length }; } -/** Drop the owner-word fields from a JSON value: `owner_reply`, a carry record's `words`, a human deferral's `reason`. */ +/** Drop the owner-word fields from a JSON value: `owner_reply`, a gate's `owner_words`, a carry record's `words`, a human deferral's `reason`. */ export function dropOwnerFields(value: unknown): { value: unknown; dropped: number } { let dropped = 0; const walk = (v: unknown): unknown => { @@ -234,6 +237,7 @@ export function dropOwnerFields(value: unknown): { value: unknown; dropped: numb if (!v || typeof v !== 'object') return v; const o: Record<string, unknown> = { ...(v as Record<string, unknown>) }; if ('owner_reply' in o) { delete o.owner_reply; dropped++; } + if ('owner_words' in o && 'gate_rev' in o) { delete o.owner_words; dropped++; } if ('verdict' in o && typeof o.words === 'string') { delete o.words; dropped++; } if (o.by === 'human' && typeof o.reason === 'string' && 'cause' in o) { o.reason = OWNER_WORDS_MARK; dropped++; } return Object.fromEntries(Object.entries(o).map(([k, x]) => [k, walk(x)])); @@ -269,6 +273,9 @@ export function ownerWords(state: Pick<RunState, 'out' | 'phases' | 'gate' | 'ca const gate = state.gate as { owner_reply?: unknown; answered_at?: unknown; owner_reply_parsed?: unknown } | undefined; note(gate?.owner_reply, gate?.answered_at, gate?.owner_reply_parsed); note(state.carry?.words, undefined, false); + let names: string[] = []; + try { names = fs.readdirSync(out).filter(f => f === FILES.active || /^plan-source.*\.md$/.test(f) || /^plan-at-gate\.r\d+\.md$/.test(f) || /^plan-file\..+\.md$/.test(f)).sort(); } catch { /* no run directory */ } + for (const text of new Set(names.flatMap(f => parseOwnerWords(read(f) ?? '').quotes.map(q => q.text)))) note(text, undefined, false); const deferred = new Map<string, string | undefined>(); for (const r of journal) if (r.event === 'phase_deferred' && r.by === 'human' && typeof r.reason === 'string') deferred.set(r.reason, deferred.get(r.reason) ?? String(r.ts)); diff --git a/lib/autoplan-prompts.ts b/lib/autoplan-prompts.ts index 87b444f22..fc136627f 100644 --- a/lib/autoplan-prompts.ts +++ b/lib/autoplan-prompts.ts @@ -123,7 +123,7 @@ RESULT FORMAT (required by gstack-autoplan; the parent binds your file by this c \`\`\`gstack-findings {"id":"F1","severity":"High","title":"<one line>","file":"<path or omit>","line":12,"fix":"<the fix>"} \`\`\` - severity is Critical | High | Medium | Low | Informational. Add "user_challenge": true only when you recommend changing the plan's stated direction AND the change alters its scope, cost or direction (then also add "changes": "scope" | "cost" | "direction") or only its delivery packaging or ordering, with no Implementation-plan edit (then "changes": "packaging" | "ordering"). Naming and other reversible choices are ordinary findings, not user challenges. Add "urgent": true and "suggested_owner": "<who>" for a security or data-loss finding this plan does not own. An empty fence means no findings; a missing fence is refused. + severity is Critical | High | Medium | Low | Informational. Any finding that recommends changing the plan's scope, cost or direction adds "changes": "scope" | "cost" | "direction", or "packaging" | "ordering" when only its delivery packaging or build order changes, with no Implementation-plan edit; that holds at any severity. Only the owner's own words are the plan's direction: add "user_challenge": true and "owner_quote": <n> only when the change goes against bullet n (from 1) of the plan's "Owner's words" section. Scope, order or features the planning agent wrote are proposals, so a change to them is an ordinary finding with "changes" and no user_challenge. A plan with no "Owner's words" section: add "user_challenge": true (no owner_quote) when you recommend changing its stated direction. Naming and other reversible choices are ordinary findings with no "changes". Add "urgent": true and "suggested_owner": "<who>" for a security or data-loss finding this plan does not own. An empty fence means no findings; a missing fence is refused. 3. Write the whole result to this file: ${resultPath} `; diff --git a/lib/autoplan-reconcile.ts b/lib/autoplan-reconcile.ts index cda0de854..9a7ed459d 100644 --- a/lib/autoplan-reconcile.ts +++ b/lib/autoplan-reconcile.ts @@ -28,6 +28,10 @@ export interface CanonicalFinding { user_challenge?: boolean; urgent?: boolean; suggested_owner?: string; plan_items?: string[]; dimension?: string; /** What a user challenge changes: scope, cost or direction (plan B2a), or packaging/ordering (settled without a plan edit). */ changes?: Changes; + /** A challenge to the owner's own words: the 1-based bullet of the plan's `### Owner's words` it would change. */ + owner_quote?: number; + /** A confirm round's row naming the earlier challenge id the revised plan now fixes. */ + resolves?: string; } export const CHANGES = ['scope', 'cost', 'direction', 'packaging', 'ordering'] as const; /** Accepted changes of these kinds need no Implementation-plan edit: `revise --settle` records them. */ @@ -90,6 +94,8 @@ function parseFences(text: string, errors: string[]): { findings: CanonicalFindi if (typeof row.suggested_owner === 'string') finding.suggested_owner = row.suggested_owner; if (Array.isArray(row.plan_items)) finding.plan_items = row.plan_items.filter((p: unknown): p is string => typeof p === 'string'); if (typeof row.dimension === 'string') finding.dimension = row.dimension; + if (Number.isInteger(row.owner_quote) && row.owner_quote > 0) finding.owner_quote = row.owner_quote; + if (typeof row.resolves === 'string' && row.resolves.trim()) finding.resolves = row.resolves.trim(); if (row.changes !== undefined) { if (!(CHANGES as readonly unknown[]).includes(row.changes)) { errors.push(`findings row ${i + 1}: changes ${JSON.stringify(row.changes)} is not one of ${CHANGES.join('|')}`); return; } finding.changes = row.changes; @@ -186,7 +192,7 @@ export function canonicalRows(findings: CanonicalFinding[], ctx: { run: string; ...(f.local_id ? { source: f.local_id } : {}), ...(f.user_challenge ? { user_challenge: true } : {}), ...(f.urgent ? { urgent: true } : {}), ...(f.suggested_owner ? { suggested_owner: f.suggested_owner } : {}), ...(f.dimension ? { dimension: f.dimension } : {}), - ...(f.changes ? { changes: f.changes } : {}), + ...(f.changes ? { changes: f.changes } : {}), ...(f.owner_quote ? { owner_quote: f.owner_quote } : {}), ...(f.resolves ? { resolves: f.resolves } : {}), } as FindingRow)); } diff --git a/lib/autoplan-revise.ts b/lib/autoplan-revise.ts index 05be2e50b..5d8846148 100644 --- a/lib/autoplan-revise.ts +++ b/lib/autoplan-revise.ts @@ -24,7 +24,7 @@ import { exportRun } from './autoplan-export'; import { applyRenames, approve, closeDraftDirections, finishGate, planReopen } from './autoplan-gate'; import { carryLines, keepPlanFile, voidPendingCheck } from './autoplan-carry'; import { atCap, pendingDeltas, roundCap, roundOf } from './autoplan-budget'; -import { diffStat, lineDiff } from './autoplan-confirm'; +import { diffStat, earlierRows, lineDiff } from './autoplan-confirm'; import { SETTLEABLE_CHANGES } from './autoplan-reconcile'; import { normalizeRevision, reviewHash, scaffold } from './autoplan-plan-text'; import { parseScopeTokens } from './autoplan-scope'; @@ -90,20 +90,22 @@ function settleEvidence(state: RunState, ids: string[], revised?: string): { pla const SEVERITY_ORDER = ['Informational', 'Low', 'Medium', 'High', 'Critical']; export const BELOW_HIGH = ['Informational', 'Low', 'Medium']; +/** A finding that changes these is re-reviewed whatever its severity: the owner took a reviewer's scope, direction or cost change. */ +const REREVIEWED_CHANGES = ['scope', 'direction', 'cost']; /** * The severity an incorporated decision resolves to: the highest of the findings its gate item named (the * decisions.jsonl origin's ids, looked up in that phase's bound rows). `unknown` when the row, its origin or a - * finding is missing; `challenge` for a user challenge, whose direction change is always re-reviewed. + * finding is missing; `challenge` for a user challenge or a scope, direction or cost change, which is always re-reviewed. */ export function decisionSeverity(state: RunState, decision: string): string { const row = readDecisions(state.out).find(d => d.id === decision); const [phase, ids] = row?.origin?.split('|') ?? []; if (!phase || !ids || !state.phases[phase]?.closed_at) return 'unknown'; - const rows = [...voiceRows(state, phase, 'native'), ...voiceRows(state, phase, 'outside')]; + const rows = [...voiceRows(state, phase, 'native'), ...voiceRows(state, phase, 'outside'), ...earlierRows(state, phase)]; const found = ids.split('+').filter(id => id && id !== 'null').map(id => rows.find(r => r.id === id)); if (!found.length || found.some(f => !f)) return 'unknown'; - if (found.some(f => (f as { user_challenge?: boolean }).user_challenge)) return 'challenge'; + if (found.some(f => (f as { user_challenge?: boolean }).user_challenge || REREVIEWED_CHANGES.includes((f as { changes?: string }).changes ?? ''))) return 'challenge'; return found.map(f => f!.severity).reduce((a, b) => (SEVERITY_ORDER.indexOf(b) > SEVERITY_ORDER.indexOf(a) ? b : a)); } diff --git a/lib/autoplan-run.ts b/lib/autoplan-run.ts index 0e78b501f..1a63fadc5 100644 --- a/lib/autoplan-run.ts +++ b/lib/autoplan-run.ts @@ -35,6 +35,7 @@ import { familyConflict, modelFamily } from './outside-voice-runner'; import { SpendCapExceeded, release, renderSpend, reserve, settle, summarize, readLedger } from './spend-ledger'; import { DEFAULT_MAX_ROUNDS, attemptEstimate, overCap, resumeStop, roundCap, roundOf, roundsLine, stopForBudget, stopLines } from './autoplan-budget'; import { annotateConfirm, confirmBlock } from './autoplan-confirm'; +import { ownerWordsLine, parseOwnerWords } from './autoplan-owner-text'; import { LEAN_SKIPPED, captureDraft, checkDraftReceipt, draftLine, leanLenses, leanLine, leanMode, leanPrompt, type AutoplanKind } from './autoplan-lean'; /** An unreadable run.lock younger than this is a lock some other gstack is still writing, never a stale one. */ @@ -313,7 +314,7 @@ function recordPlanReality(state: RunState): string[] { const verdict = rows.verdict !== 'complete' ? rows.verdict : plan.verdict; state.plan_reality = { plan_sha256: sha, checker: PLAN_REALITY_CHECKER, verdict, line: `${rows.line}; ${plan.line}` }; journal(state.out, { event: 'plan_reality', plan_sha256: sha, checker: PLAN_REALITY_CHECKER, verdict }); - return [`${rows.line} (report only)`, `${plan.line} (report only)`, ...plan.numberLines]; + return [`${rows.line} (report only)`, `${plan.line} (report only)`, ...plan.numberLines, ownerWordsLine(parseOwnerWords(text))]; } function resolveAttempt(v: VoiceState, attempt: string | undefined, phase: string, voice: Voice): AttemptState { diff --git a/lib/captain-brief.ts b/lib/captain-brief.ts index fc3684a1c..fbeac4057 100644 --- a/lib/captain-brief.ts +++ b/lib/captain-brief.ts @@ -1,7 +1,8 @@ /** * captain-brief — the plan-approval ask in the shape Capy Captains relay to * their person (capy/skill/gstack/captain.md): a two-line header with the - * one-word reply, then Before → after, Why it matters, What caused this work, + * one-word reply, then the plan's day-one table, what it won't do yet and the + * owner's words it follows when the plan has them (lib/autoplan-owner-text.ts), then Before → after, Why it matters, What caused this work, * Big decisions (each read from the reviewed plan through the shared heading * parser) and What we need from you: the owner's ask format (crew/docs/captain.md * § The ask format), one lettered line per gate choice with the Captain's name @@ -19,6 +20,7 @@ import * as path from 'node:path'; import { gateCost, gateCostSentence, priorChoices } from './autoplan-gate-cost'; import { parseReply, recHash, type GateEli5, type GateItem } from './gate-list'; import { renderUrgentBlock } from './headless-artifacts'; +import { renderDayOne } from './autoplan-owner-text'; import { findSection, firstTitle } from './markdown-sections'; import type { BriefInputs } from './owner-brief'; @@ -47,6 +49,7 @@ const stripRef = (t: string) => t.replace(/\s*\[[^\]]*\]\s*$/, '').trim(); const OPTION_WORDS: Record<string, string> = { 'keep your direction': 'keep the plan as written (a reviewer suggested changing it)', 'accept the change': "make the reviewer's change", + "keep the plan's draft": 'keep the plan as written (a reviewer suggested changing it)', }; const plainOption = (t: string) => { const s = t.replace(/\s*\([^)]*gstack-autoplan[^)]*\)/g, '').trim(); @@ -139,7 +142,8 @@ export function renderCaptainBrief(inputs: BriefInputs, o: { outDir: string; cap `\`gstack-autoplan answer --out ${o.outDir} --gate-rev ${list.gate_rev} --reply rec --rec-hash ${hash} --by agent:<id> --owner-reply "<their exact words>"\`, then \`gstack-approvals import --autoplan ${o.outDir} --by <name>\`.`; // The price sits above the trailer: the relaying agent sends everything above that line, so the person approving sees it. const cost = inputs.run ? ['### Cost', '', gateCostSentence(gateCost(o.outDir, list, { phase_order: inputs.run.phase_order ?? [], outside_enabled: inputs.run.outside_enabled !== false, spend_cap_usd: inputs.run.spend_cap_usd ?? null, scope_flags: inputs.run.scope_flags, lean: inputs.run.lean })), ''] : []; - const text = [...urgent, ...header, '', ...body, ...need, ...cost, '---', '', trailer, ''].join('\n'); + const dayOne = renderDayOne(plan.text, list.owner_words?.quotes); + const text = [...urgent, ...header, '', ...dayOne, ...body, ...need, ...cost, '---', '', trailer, ''].join('\n'); return { text, missing, pending, recHash: hash }; } diff --git a/lib/gate-list.ts b/lib/gate-list.ts index 72a53cccf..12759f22f 100644 --- a/lib/gate-list.ts +++ b/lib/gate-list.ts @@ -21,6 +21,7 @@ * Rendered by bin/gstack-gate; rows land in decisions.jsonl (lib/headless-artifacts.ts). */ import { createHash } from 'node:crypto'; +import { ownerWordsLine } from './autoplan-owner-text'; import type { DecisionRow } from './headless-artifacts'; /** `changes_plan`: choosing this option is an accepted plan change (reopens its phase plus Eng, prints APPLY:). */ @@ -47,7 +48,8 @@ export interface GateItem { /** An open Critical or High finding (its ids, a paired twin included): `a` applies the reviewer's fix to the plan. */ finding?: string[]; } -export type ItemClass = 'challenge2' | 'challenge1' | 'disagree' | 'agent' | 'cap_deferred' | 'cap_blocker' | 'cap_delta' | 'finding' | 'p1'; +export type ItemClass = 'challenge2' | 'challenge1' | 'disagree' | 'agent' | 'cap_deferred' | 'cap_blocker' | 'cap_delta' | 'finding' | 'p1' + | 'proposal' | 'confirm_direction' | 'day_one' | 'cut' | 'cuts'; export interface GateList { schema_version: 1; run: string; gate_rev: number; items: GateItem[]; title?: string; /** Bumped by every `recommend`, so a `rec` relayed before it no longer matches `recHash`. */ rec_rev?: number; @@ -55,6 +57,8 @@ export interface GateList { schema_version: 1; run: string; gate_rev: number; it rec_hash_v?: 2; /** The plan's plain-language ask, read from the reviewed plan (lib/captain-brief.ts `buildEli5`); printed first. */ eli5?: GateEli5; + /** The plan's `### Owner's words` (lib/autoplan-owner-text.ts): the quotes a challenge must name to keep the plan's direction; `verified` when a recorded owner reply holds it. */ + owner_words?: { status: 'ok' | 'malformed' | 'none'; quotes: Array<{ n: number; who: string; text: string; verified: boolean }>; reason?: string; fix?: string }; /** The one-reviewer check of an unreviewed post-cap delta before a carry (lib/autoplan-carry.ts). */ carry_check?: { attempt: string; model: string; verdict: 'passed' | 'failed' | 'unavailable'; max_severity: string; findings: number; at: string } } /** The captain approvals shape (crew/docs/captain.md § Approvals), section text taken from the reviewed plan; '' when absent. */ @@ -135,6 +139,7 @@ export function renderGate(list: GateList, page = 1, pageSize = PAGE_SIZE): stri lines.push(`GATE: run=${list.run} gate_rev=${list.gate_rev} items=${list.items.length} page=${current}/${pages}${list.title ? ` — ${list.title}` : ''}`); lines.push(''); if (list.eli5 && current === 1) lines.push(...renderEli5(list.eli5), ''); + if (list.owner_words && current === 1) lines.push(...renderOwnerWords(list.owner_words), ''); if (list.carry_check) lines.push(`Carry check ${list.carry_check.attempt}: ${list.carry_check.verdict} (${list.carry_check.model}; ${list.carry_check.findings} finding(s), highest ${list.carry_check.max_severity}).`, ''); list.items.slice(start, start + pageSize).forEach((item, i) => { const n = start + i + 1; @@ -161,6 +166,12 @@ export function renderEli5(e: GateEli5): string[] { return lines; } +/** The OWNER_WORDS line, then each quote a challenge must name to keep the plan's direction, marked when no recorded owner reply holds it. */ +export function renderOwnerWords(w: NonNullable<GateList['owner_words']>): string[] { + return [ownerWordsLine(w, w.quotes.filter(q => !q.verified).length), "Owner's words (a reviewer's challenge to one of these keeps the plan's direction; anything else the plan says is a proposal):", + ...w.quotes.map(q => `${q.n}. ${q.who}: "${q.text}"${q.verified ? '' : ' (unverified: no recorded owner reply holds it)'}`)]; +} + function exampleTokens(list: GateList): string { return list.items.slice(0, 2).map(i => `${i.id}${i.options.find(o => o.key !== i.recommended)?.key ?? i.recommended}`).join(' '); } diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.ts index 6e4c3266b..927970c9a 100644 --- a/lib/headless-artifacts.ts +++ b/lib/headless-artifacts.ts @@ -30,7 +30,7 @@ export type RunStatus = ResultStatus | 'awaiting_result' | 'running'; export interface FindingRow { schema_version: 1; run: string; id: string; phase: string; voice: Voice; severity: Severity; title: string; model?: string; file?: string; line?: number; disposition?: Disposition; resolution?: string; - plan_items?: string[]; native_counterpart?: string | null; source?: string; changes?: 'scope' | 'cost' | 'direction'; + plan_items?: string[]; native_counterpart?: string | null; source?: string; changes?: 'scope' | 'cost' | 'direction' | 'packaging' | 'ordering'; } export interface DecisionRow { schema_version: 1; run: string; id: string; title: string; options: string[]; recommended: string | null; diff --git a/lib/owner-brief.ts b/lib/owner-brief.ts index 618299714..3573527b8 100644 --- a/lib/owner-brief.ts +++ b/lib/owner-brief.ts @@ -13,6 +13,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { gateCost, gateCostSentence } from './autoplan-gate-cost'; +import { renderDayOne } from './autoplan-owner-text'; import { decisionId, PAGE_SIZE, renderGate, type GateList } from './gate-list'; import { readJsonl, renderUrgentBlock, type DecisionRow } from './headless-artifacts'; import type { ResultCodeName } from './result-codes'; @@ -73,6 +74,12 @@ export function renderDecisions(inputs: BriefInputs, page = 1): string { }).join('\n'); } +/** The reviewed plan's text, for the day-one block; '' when the run directory is not known or has no plan. */ +function planText(outDir: string | undefined, run: Record<string, any> | undefined): string { + const file = typeof run?.active_plan === 'string' ? run.active_plan : outDir ? path.join(outDir, 'plan-active.md') : undefined; + try { return file ? fs.readFileSync(file, 'utf8') : ''; } catch { return ''; } +} + export function renderBrief(inputs: BriefInputs, o: { page?: number; summary?: string; outDir?: string } = {}): string { const pages = Math.max(1, Math.ceil(inputs.gate.items.length / PAGE_SIZE)); const page = Math.min(Math.max(1, o.page ?? 1), pages); @@ -83,6 +90,7 @@ export function renderBrief(inputs: BriefInputs, o: { page?: number; summary?: s '', renderUrgentBlock(inputs.findings).trimEnd(), '', + ...renderDayOne(planText(o.outDir, inputs.run), inputs.gate.owner_words?.quotes), '### Summary', '', plainSummary(inputs, o.summary), diff --git a/test/autoplan-carry.test.ts b/test/autoplan-carry.test.ts index 8772eb196..04465bb9f 100644 --- a/test/autoplan-carry.test.ts +++ b/test/autoplan-carry.test.ts @@ -243,12 +243,13 @@ describe('carry-forward', () => { const doIt = answeredAndRevised(); phaseVia(r, doIt.out, 'ceo', NONE); const d = phaseVia(r, doIt.out, 'eng', PKG).outside; - expect(d.stdout).toMatch(/^CARRIED: gate_rev=2 <- gate_rev=1 .*reason="do it" covers \w+; plan unchanged/m); + expect(d.stdout).toMatch(/^CARRIED: gate_rev=2 <- gate_rev=1 .*reason="do it" covers [\w,]+; plan unchanged/m); + expect(d.stdout).toMatch(/^CARRIED_UNDER_DO_IT: \w+ Confirm the plan's direction is yours: .* -> yes, the plan as written is what I asked for/m); expect(d.stdout).toMatch(/^CARRIED_UNDER_DO_IT: \w+ Split the backoff into its own PR .*\(the owner has not seen this item\)$/m); expect(decisions(doIt.out).find(x => x.gate_rev === 2 && /Split the backoff/.test(x.title))).toMatchObject({ carried_under: 'do it' }); const loaded = loadBriefInputs(doIt.out); if ('error' in loaded) throw new Error(String(loaded.error)); - expect(renderCaptainBrief(loaded.inputs, { outDir: doIt.out }).text).toContain('Taken under "do it" without being shown to the owner: Split the backoff into its own PR.'); + expect(renderCaptainBrief(loaded.inputs, { outDir: doIt.out }).text).toContain('Taken under "do it" without being shown to the owner: Split the backoff into its own PR;'); const rec = answeredAndRevised([], 'rec'); phaseVia(r, rec.out, 'ceo', NONE); expect(phaseVia(r, rec.out, 'eng', PKG).outside.stdout).toMatch(/^CARRY: no \(new item \w+: Split the backoff/m); diff --git a/test/autoplan-day-one-gate.test.ts b/test/autoplan-day-one-gate.test.ts new file mode 100644 index 000000000..8f711017f --- /dev/null +++ b/test/autoplan-day-one-gate.test.ts @@ -0,0 +1,365 @@ +/** + * GST-2947 PR 1: the approval page keeps a reviewer's product challenge open. + * A free, deterministic replay of a reviewed app plan's records, rebuilt as a + * synthetic, public-safe fixture (titles and fields only: no owner replies, no + * private content, no real quotes). Round 1's CEO reviewer challenged the build + * order and the promise scope; round 2 never repeated those, and its one + * challenge became "keep your direction" because the planning agent's own draft + * counted as the owner's direction. Now only the plan's `### Owner's words` + * count as direction: the three challenges come out as lettered proposals + * recommending the change. Negative controls: (a) a challenge to a quoted owner + * line keeps the keep-direction default; (b) a plan with no Owner's words + * section keeps today's default and gets one confirm-direction item; (c) a + * round-1 challenge the revision fixed (`resolves`) or the owner answered does + * not resurface. + */ +import { afterAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { applyGuidance, buildGate } from '../lib/autoplan-gate'; +import { branchKey } from '../lib/approval-record'; +import { proposalCost, proposalItem, ownerContext, recordedOwnerWords } from '../lib/autoplan-gate-items'; +import { confirmBlock, openEarlier, settledIds } from '../lib/autoplan-confirm'; +import { buildTasks } from '../lib/autoplan-export'; +import { exportPublic } from '../lib/autoplan-public'; +import * as crypto from 'node:crypto'; +import { cutDrops, parseCuts, parseDayOne, parseOwnerWords, ownerWordsLine } from '../lib/autoplan-owner-text'; +import { ownerWords, redactOwnerWords } from '../lib/autoplan-owner-words'; +import { consensusRecord, parseReviewResult, reconcile } from '../lib/autoplan-reconcile'; +import { decisionSeverity } from '../lib/autoplan-revise'; +import { writeDecisions, type RunState } from '../lib/autoplan-state'; +import { renderCaptainBrief } from '../lib/captain-brief'; +import { decisionRows, parseReply, renderGate, type GateList } from '../lib/gate-list'; +import type { FindingRow } from '../lib/headless-artifacts'; + +const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'autoplan-day-one-')); +afterAll(() => fs.rmSync(TMP, { recursive: true, force: true })); +const RUN = 'replay-20261117'; +const SHA = 'a'.repeat(64); + +const DAY_ONE = `### Day one + +| action | frequency | source | feature | route | first build | check | +|---|---|---|---|---|---|---| +| sees the day's meetings and who is coming | daily | calendar export | Today screen | root screen | build 1 | the owner's real calendar shows on the phone | +| reads the before-meeting card | several times a day | owner words 1 | Before card | Today screen, tap a meeting | build 1 | a card opens for the next meeting | +| reviews the promises made in a meeting | daily | assumed | Promise review | Today screen, Promises | build 2 | a promise from a test meeting appears | + +### What it won't do yet + +- No Today screen in the first build: notifications only +- No Android build +- No shared team calendars +`; +const planText = (o: { owner?: string | null; dayOne?: boolean } = {}) => [ + '# Meeting companion for the phone and watch (synthetic replay)', '', + '## Implementation plan', '', + ...(o.owner === null ? [] : ["### Owner's words", '', o.owner ?? '- The owner, day 0: "I want to remember what I promised people after every meeting"', '']), + ...(o.dayOne === false ? [] : [DAY_ONE]), + '### Units', '', 'U1 the live lane. U2 the transcript. U3 the before-meeting card. U4 the promise review screen.', '', + '## Review record', ''].join('\n'); + +type Row = Partial<FindingRow> & { id: string; severity: FindingRow['severity']; title: string; user_challenge?: boolean; changes?: string; owner_quote?: number; resolves?: string }; +const row = (phase: string, voice: 'native' | 'outside', r: Row): FindingRow => ({ schema_version: 1, run: RUN, phase, voice, disposition: 'open', ...r } as FindingRow); + +/** Round 1 of the CEO phase: the build-order and promise-scope challenges that round 2 never repeated. */ +const ROUND1 = { + native: [ + row('ceo', 'native', { id: `${RUN}-ceo-native-1`, severity: 'Critical', title: 'Watch cue delivery depends on a reachability the OS grants only in the foreground' }), + row('ceo', 'native', { id: `${RUN}-ceo-native-4`, severity: 'High', title: 'Build order puts the riskiest layer (the live lane) before the loop that pays off on day one (before-meeting card, promise review)', user_challenge: true, changes: 'ordering', resolution: 'build the before-meeting card and the promise review first; the live lane after' }), + row('ceo', 'native', { id: `${RUN}-ceo-native-18`, severity: 'Medium', title: 'The promise ledger learns only from in-person meetings, though the meetings archive already holds the rest', user_challenge: true, changes: 'scope', resolution: 'read promises from the meetings archive too' }), + ], + outside: [row('ceo', 'outside', { id: `${RUN}-ceo-outside-1`, severity: 'High', title: 'The scratch-server checks cannot tell client, transport or server slowness apart' })], +}; +/** Round 2: one new challenge (the replay's d1) and an ordinary High finding; nothing repeats round 1. */ +const round2 = (o: { quote?: number; resolved?: boolean } = {}) => ({ + native: [ + row('ceo', 'native', { id: `${RUN}-ceo-r2-native-1`, severity: 'High', title: 'The two checks that can redirect the plan without any build run only after three units are built', user_challenge: true, changes: 'ordering', resolution: 'run both checks before any build unit', ...(o.quote ? { owner_quote: o.quote } : {}) }), + row('ceo', 'native', { id: `${RUN}-ceo-r2-native-2`, severity: 'High', title: 'The relationship-judgment harness has no runtime home' }), + ...(o.resolved ? [row('ceo', 'native', { id: `${RUN}-ceo-r2-native-3`, severity: 'Informational', title: 'Resolved: the build order now ships the day-one loop first', resolves: `${RUN}-ceo-native-4` })] : []), + ], + outside: [row('ceo', 'outside', { id: `${RUN}-ceo-r2-outside-1`, severity: 'Medium', title: 'The upstream-edit list omits the signing settings' })], +}); + +const jsonl = (rows: unknown[]) => rows.map(r => JSON.stringify(r)).join('\n') + (rows.length ? '\n' : ''); +function makeRun(name: string, o: { plan: string; round2: ReturnType<typeof round2>; round1?: boolean; ui?: boolean; lean?: boolean; answered?: string[] }): RunState { + const out = path.join(TMP, name); + fs.mkdirSync(out, { recursive: true }); + const plan = path.join(out, 'plan-active.md'); + fs.writeFileSync(plan, o.plan); + fs.writeFileSync(path.join(out, 'plan.md'), o.plan); + const voice = (output: string) => ({ status: 'completed', output, model: 'fixture' }); + const write = (stem: string, rows: FindingRow[]) => fs.writeFileSync(path.join(out, `${stem}.findings.jsonl`), jsonl(rows)); + write('ceo-native.a3.bound.md', o.round2.native); write('ceo-outside.a4.bound.md', o.round2.outside); + const history: Array<Record<string, unknown>> = []; + if (o.round1 !== false) { + write('ceo-native.a1.bound.md', ROUND1.native); write('ceo-outside.a2.bound.md', ROUND1.outside); + history.push({ event: 'reopened', phase: 'ceo', previous: { snapshot: SHA, closed_at: '2026-11-09T01:00:00Z', native: voice('ceo-native.a1.bound.md'), outside: voice('ceo-outside.a2.bound.md') } }); + } + const rec = reconcile(o.round2.native, o.round2.outside, []); + fs.writeFileSync(path.join(out, 'ceo-consensus.json'), JSON.stringify(consensusRecord('ceo', { rows: o.round2.native, model: 'fixture' }, { rows: o.round2.outside, model: 'fixture' }, rec))); + fs.writeFileSync(path.join(out, 'attempts.jsonl'), ''); + if (o.answered?.length) writeDecisions(out, o.answered.map((id, i) => ({ schema_version: 1, run: RUN, id: `${RUN}-g1-d${i + 1}`, gate_rev: 1, label: `D${i + 1}`, title: id, status: 'overridden', chosen: 'a', origin: `ceo|${id}|2026-11-09T01:00:00Z|${SHA}|0` } as any))); + return { run: RUN, out, revision: 1, plan_source: path.join(out, 'plan.md'), active_plan: plan, restore: path.join(out, 'restore.md'), scope: { ui: o.ui !== false } as any, phase_order: ['ceo'], + phases: { ceo: { snapshot: SHA, closed_at: '2026-11-10T01:00:00Z', native: voice('ceo-native.a3.bound.md') as any, outside: voice('ceo-outside.a4.bound.md') as any } }, + outside_enabled: true, attempt_counter: 4, spend_cap_usd: null, history, created_at: '2026-11-09T00:00:00Z', updated_at: '2026-11-10T00:00:00Z', ...(o.lean ? { lean: 'lean' as any } : {}) } as unknown as RunState; +} +const byClass = (list: GateList, cls: string) => list.items.filter(i => i.item_class === cls); +const lettered = (list: GateList) => list.items.filter(i => i.id !== 'p1').length; +const covering = (list: GateList, id: string) => list.items.find(i => i.title.includes(`[${id}`) || i.title.includes(` ${id}]`) || i.title.includes(`+ ${id}`)); +const rec = (list: GateList) => Object.fromEntries(parseReply('rec', list).choices.map(c => [c.id, c.chosen])); + +describe('replay: a reviewed app plan whose product challenges were hidden', () => { + const state = makeRun('replay', { plan: planText(), round2: round2() }); + const list = buildGate(state, 1); + + test('round-1 build order (F4) and promise scope (F18) come back as lettered proposals recommending the change', () => { + for (const id of [`${RUN}-ceo-native-4`, `${RUN}-ceo-native-18`]) { + const item = covering(list, id)!; + expect(item).toBeDefined(); + expect(item.item_class).toBe('proposal'); + expect(item.kind).toBe('approval'); + expect(item.recommended).toBe('a'); + expect(item.options.find(o => o.key === 'a')!.text).toStartWith('take the change: '); + expect(item.why).toContain('raised in an earlier round and still open'); + } + }); + + test("round 2's one-voice challenge (d1) recommends the reviewer's change, not \"keep your direction\"", () => { + const d1 = covering(list, `${RUN}-ceo-r2-native-1`)!; + expect(d1.item_class).toBe('proposal'); + expect(rec(list)[d1.id]).toBe('a'); + expect(d1.options.find(o => o.key === d1.recommended)!.changes_plan).toBe(true); + expect(list.items.some(i => i.options.some(o => o.text.startsWith('keep your direction')))).toBe(false); + expect(list.items.find(i => i.id === 'p1')!.recommended).toBe('b'); + }); + + test('day one: the assumed row is an owner question, the cut that drops the Today screen is lettered, the rest are one item', () => { + expect(byClass(list, 'day_one').map(i => i.title)).toEqual(['Day one: the plan assumes you will do "reviews the promises made in a meeting" (daily); is that right?']); + expect(byClass(list, 'cut').map(i => i.title)).toEqual(['Cut: No Today screen in the first build: notifications only']); + expect(byClass(list, 'cuts').map(i => i.title)).toEqual(['2 other cuts: No Android build; No shared team calendars']); + expect(list.owner_words).toMatchObject({ status: 'ok', quotes: [{ n: 1, verified: false }] }); + }); + + test('lettered-item counts (recorded for the PR): 3 proposals, 3 day-one items, 1 High finding', () => { + expect(byClass(list, 'proposal').length).toBe(3); + expect(byClass(list, 'finding').length).toBe(1); + expect(lettered(list)).toBe(7); + }); +}); + +describe('negative controls', () => { + test('(a) a challenge to a quoted owner line keeps "keep your direction"', () => { + const owner = '- The owner, day 0: "I want to remember what I promised people after every meeting"\n- The owner, day 0: "build the live lane first, it is the whole point"'; + const list = buildGate(makeRun('control-a', { plan: planText({ owner }), round2: round2({ quote: 2 }) }), 1); + const d1 = covering(list, `${RUN}-ceo-r2-native-1`)!; + expect(d1.item_class).toBe('challenge1'); + expect(d1.recommended).toBe('a'); + expect(d1.options[0]!.text).toBe('keep your direction'); + expect(byClass(list, 'confirm_direction')).toEqual([]); + expect(byClass(list, 'proposal').length).toBe(2); + expect(lettered(list)).toBe(7); + }); + + test("(b) no Owner's words section: today's keep-direction default stays, plus one confirm-direction item", () => { + const list = buildGate(makeRun('control-b', { plan: planText({ owner: null }), round2: round2() }), 1); + expect(byClass(list, 'proposal')).toEqual([]); + const kept = byClass(list, 'challenge1'); + expect(kept.map(i => i.recommended)).toEqual(['a', 'a', 'a']); + expect(kept.every(i => i.options[0]!.text === 'keep your direction')).toBe(true); + const confirm = byClass(list, 'confirm_direction'); + expect(confirm.length).toBe(1); + expect(confirm[0]!.title).toContain(kept.map(i => i.id).join(', ')); + expect(list.owner_words).toBeUndefined(); + expect(lettered(list)).toBe(8); + }); + + test('(c) a round-1 challenge the revision fixed (resolves) or the owner answered does not resurface', () => { + const state = makeRun('control-c', { plan: planText(), round2: round2({ resolved: true }), answered: [`${RUN}-ceo-native-18`] }); + const list = buildGate(state, 2); + expect(covering(list, `${RUN}-ceo-native-4`)).toBeUndefined(); + expect(covering(list, `${RUN}-ceo-native-18`)).toBeUndefined(); + expect(openEarlier(state, 'ceo', [...round2({ resolved: true }).native])).toEqual([]); + expect(byClass(list, 'proposal').length).toBe(1); + expect(lettered(list)).toBe(5); + }); + + test('a later round staying silent never closes a challenge, and a lean run carries nothing', () => { + const state = makeRun('silent', { plan: planText(), round2: round2() }); + expect(openEarlier(state, 'ceo', round2().native).map(r => r.id)).toEqual([`${RUN}-ceo-native-4`, `${RUN}-ceo-native-18`]); + expect(openEarlier({ ...state, lean: 'lean' as any }, 'ceo', round2().native)).toEqual([]); + }); + + test('the confirm round lists the open earlier challenges and asks for resolves', () => { + const state = makeRun('confirm', { plan: planText(), round2: round2() }); + const block = confirmBlock(state, 'ceo', path.join(state.out, 'missing-snapshot.md'), 2)!.text; + expect(block).toContain(`- ${RUN}-ceo-native-4: Build order puts the riskiest layer`); + expect(block).toContain('"resolves":"<id>"'); + }); +}); + +describe('owner_quote downgrade, the day-one page requirement and the cost line', () => { + test('a challenge naming no real owner line is an ordinary proposal', () => { + const list = buildGate(makeRun('bad-quote', { plan: planText(), round2: round2({ quote: 9 }), round1: false }), 1); + expect(covering(list, `${RUN}-ceo-r2-native-1`)!.item_class).toBe('proposal'); + }); + + test('a below-High challenge with no changes and no real owner line still reaches the gate as a proposal', () => { + const native = [row('ceo', 'native', { id: `${RUN}-ceo-r2-native-9`, severity: 'Medium', title: 'Make the summary daily instead of weekly', user_challenge: true, owner_quote: 99 })]; + const list = buildGate(makeRun('challenge-no-changes', { plan: planText(), round2: { native, outside: [] }, round1: false }), 1); + const item = covering(list, `${RUN}-ceo-r2-native-9`)!; + expect(item.item_class).toBe('proposal'); + expect(item.changes).toBe('direction'); + expect(item.recommended).toBe('a'); + }); + + test('an ordinary finding that only correlates with an earlier challenge does not close it', () => { + const state = makeRun('correlated', { plan: planText(), round2: round2() }); + const naming = row('ceo', 'native', { id: `${RUN}-ceo-r2-native-8`, severity: 'Low', title: 'Build order wording', correlates: [`${RUN}-ceo-native-4`] } as Row); + expect(openEarlier(state, 'ceo', [naming]).map(r => r.id)).toContain(`${RUN}-ceo-native-4`); + const repeat = row('ceo', 'native', { id: `${RUN}-ceo-r2-native-7`, severity: 'High', title: 'Build order again', changes: 'ordering', correlates: [`${RUN}-ceo-native-4`] } as Row); + expect(openEarlier(state, 'ceo', [repeat]).map(r => r.id)).not.toContain(`${RUN}-ceo-native-4`); + }); + + test('a paired ordering and scope proposal takes scope: its cost line reopens and applyGuidance does not settle it', () => { + const state = makeRun('pair', { plan: planText(), round2: round2(), round1: false }); + const pair = [row('ceo', 'native', { id: 'n1', severity: 'Medium', title: 'Build the card first', changes: 'ordering' }), row('ceo', 'outside', { id: 'o1', severity: 'Medium', title: 'Build the card first', changes: 'scope' })] as any; + const item = proposalItem(ownerContext(state, []), 'ceo', pair); + expect(item.changes).toBe('scope'); + expect(item.cost).toBe('a reopens ceo and eng once the plan is revised'); + expect(applyGuidance({ changes: item.changes as any, item: 'uc1' })).toBe('edit the plan, then revise'); + }); + + test('a High proposal answered b keeps its finding open as a blocking task; below High keeps the plain draft option', () => { + const state = makeRun('high-b', { plan: planText(), round2: round2(), round1: false }); + const list = buildGate(state, 1); + const high = covering(list, `${RUN}-ceo-r2-native-1`)!; + expect(high.item_class).toBe('proposal'); + expect(high.recommended).toBe('a'); + expect(high.options.find(o => o.key === 'b')!.text).toBe("keep the plan's draft; carry it into the build as a blocking task (no plan change)"); + expect(high.origin).toEndWith('|finding'); + writeDecisions(state.out, [{ schema_version: 1, run: RUN, id: `${RUN}-g1-${high.id}`, gate_rev: 1, label: high.id.toUpperCase(), title: high.title, status: 'overridden', chosen: 'b', origin: high.origin } as any]); + expect(settledIds(state).has(`${RUN}-ceo-r2-native-1`)).toBe(false); + expect(buildTasks(state, round2().native).some(t => t.findings.includes(`${RUN}-ceo-r2-native-1`))).toBe(true); + const medium = buildGate(makeRun('medium-b', { plan: planText(), round2: round2() }), 1); + const scope = covering(medium, `${RUN}-ceo-native-18`)!; + expect(scope.options.find(o => o.key === 'b')!.text).toBe("keep the plan's draft"); + expect(scope.origin).not.toEndWith('|finding'); + }); + + test('a quote a revision removed stays redacted in the public export of an earlier reviewer result', () => { + const quote = 'I want to remember what I promised people after every meeting'; + const state = makeRun('revised-quote', { plan: planText({ owner: null }), round2: round2(), round1: false }); + fs.writeFileSync(path.join(state.out, 'plan-source.md'), planText()); + fs.writeFileSync(path.join(state.out, 'ceo-native.a1.bound.md'), `The owner said "${quote}", so keep the promise review.\n`); + const sha = (f: string) => crypto.createHash('sha256').update(fs.readFileSync(path.join(state.out, f))).digest('hex'); + const run = { ...state, artifacts: { 'ceo-native.a1.bound.md': { path: 'ceo-native.a1.bound.md', sha256: sha('ceo-native.a1.bound.md') } } } as RunState; + fs.writeFileSync(path.join(state.out, 'run.json'), JSON.stringify(run, null, 2)); + const pub = path.join(TMP, 'revised-quote-public'); + exportPublic(run, pub); + const text = fs.readFileSync(path.join(pub, 'ceo-native.a1.bound.md'), 'utf8'); + expect(text).not.toContain(quote); + expect(text).toContain('[owner words redacted]'); + }); + + test('a changed cut list or challenge list gets a new origin, so an earlier answer is asked again instead of carried', () => { + const origin = (list: GateList, cls: string) => byClass(list, cls)[0]!.origin; + const cuts = (extra: string) => planText().replace('- No shared team calendars\n', `- No shared team calendars\n${extra}`); + const before = buildGate(makeRun('cuts-before', { plan: cuts(''), round2: round2(), round1: false }), 1); + const after = buildGate(makeRun('cuts-after', { plan: cuts('- No web dashboard\n'), round2: round2(), round1: false }), 1); + expect(origin(after, 'cuts')).not.toBe(origin(before, 'cuts')); + const confirmOne = buildGate(makeRun('confirm-one', { plan: planText({ owner: null }), round2: round2(), round1: false }), 1); + const confirmTwo = buildGate(makeRun('confirm-two', { plan: planText({ owner: null }), round2: round2() }), 1); + expect(origin(confirmTwo, 'confirm_direction')).not.toBe(origin(confirmOne, 'confirm_direction')); + }); + + test('an app plan with no Day one table gets one item; a backend plan never does', () => { + const app = buildGate(makeRun('no-day-one-app', { plan: planText({ dayOne: false }), round2: round2(), round1: false }), 1); + expect(byClass(app, 'day_one').map(i => [i.title.slice(0, 32), i.recommended])).toEqual([['The plan has no day-one page: th', 'a']]); + const backend = buildGate(makeRun('no-day-one-backend', { plan: planText({ dayOne: false }), round2: round2(), round1: false, ui: false }), 1); + expect(byClass(backend, 'day_one')).toEqual([]); + }); + + test("the cost line states what revise does: full runs re-review scope (even below High), settle ordering, lean applies", () => { + const state = makeRun('cost', { plan: planText(), round2: round2() }); + const list = buildGate(state, 1); + writeDecisions(state.out, decisionRows(list)); + const scope = covering(list, `${RUN}-ceo-native-18`)!; + expect(scope.cost).toBe('a reopens ceo and eng once the plan is revised'); + expect(decisionSeverity(state, decisionRows(list).find(r => r.label?.toLowerCase() === scope.id)!.id)).toBe('challenge'); + const order = covering(list, `${RUN}-ceo-r2-native-1`)!; + expect(order.cost).toBe('a is settled with revise --settle: no plan edit, no re-review'); + expect(applyGuidance({ changes: order.changes, item: order.id })).toBe(`no plan edit needed: revise --settle ${order.id}`); + const lean = ownerContext({ ...state, lean: 'lean' as any }, []); + expect(proposalCost(lean, 'eng', 'scope')).toBe('a applies without re-review (lean run: one gate revision)'); + }); +}); + +describe('parsers, render and redaction', () => { + test("Owner's words: ok, none and malformed, with the OWNER_WORDS line", () => { + expect(parseOwnerWords(planText())).toEqual({ status: 'ok', quotes: [{ n: 1, who: 'The owner, day 0', text: 'I want to remember what I promised people after every meeting' }] }); + expect(ownerWordsLine(parseOwnerWords(planText({ owner: null })))).toStartWith('OWNER_WORDS: none'); + const bad = parseOwnerWords(planText({ owner: '- The owner said to ship it' })); + expect(bad.status).toBe('malformed'); + expect(ownerWordsLine(bad)).toBe('OWNER_WORDS: malformed (bullet 1 quotes no words; fix: one bullet per quote: - <who>, <when>: "<their exact words>"); 0 quotes read'); + expect(ownerWordsLine(parseOwnerWords(planText()), 1)).toBe('OWNER_WORDS: 1 quote (1 unverified: not found in a recorded owner reply)'); + }); + + test('Day one table and cuts', () => { + const day = parseDayOne(planText()); + expect(day.status).toBe('ok'); + expect(day.rows.map(r => [r.feature, r.assumed])).toEqual([['Today screen', false], ['Before card', false], ['Promise review', true]]); + expect(parseDayOne('### Day one\n\n| action | feature |\n|---|---|\n| a | b |\n')).toMatchObject({ status: 'malformed', reason: 'the table has no frequency, source, route, first build, check column' }); + expect(parseCuts(planText())).toEqual(['No Today screen in the first build: notifications only', 'No Android build', 'No shared team calendars']); + expect(cutDrops('No Today screen in the first build', 'Today screen')).toBe(true); + expect(cutDrops('No Android build', 'Today screen')).toBe(false); + }); + + test('reviewer rows carry owner_quote and resolves; bad values are dropped', () => { + const fence = (row: object) => `INPUT: ceo ${SHA}\n\n\`\`\`gstack-findings\n${JSON.stringify(row)}\n\`\`\`\n`; + const ok = parseReviewResult(fence({ severity: 'High', title: 't', user_challenge: true, owner_quote: 2, changes: 'ordering' }), { phase: 'ceo', sha256: SHA }); + expect(ok.findings[0]).toMatchObject({ owner_quote: 2, user_challenge: true, changes: 'ordering' }); + const resolved = parseReviewResult(fence({ severity: 'Informational', title: 'Resolved: t', resolves: ' x-1 ' }), { phase: 'ceo', sha256: SHA }); + expect(resolved.findings[0]!.resolves).toBe('x-1'); + const bad = parseReviewResult(fence({ severity: 'High', title: 't', owner_quote: 0, resolves: '' }), { phase: 'ceo', sha256: SHA }); + expect(bad.findings[0]!.owner_quote).toBeUndefined(); + expect(bad.findings[0]!.resolves).toBeUndefined(); + }); + + test('the gate render and the captain brief open with what the owner can do on day one and the words they are protected by', () => { + const state = makeRun('render', { plan: planText(), round2: round2() }); + const list = buildGate(state, 1); + const rendered = renderGate(list, 1, 50); + expect(rendered).toContain("OWNER_WORDS: 1 quote (1 unverified"); + expect(rendered).toContain('1. The owner, day 0: "I want to remember what I promised people after every meeting" (unverified'); + const brief = renderCaptainBrief({ gate: list, decisions: decisionRows(list), findings: [], run: { status: 'gate_pending', active_plan: state.active_plan } }, { outDir: state.out }).text; + expect(brief.indexOf('### Day one')).toBeGreaterThan(0); + expect(brief.indexOf('### Day one')).toBeLessThan(brief.indexOf("### What it won't do yet")); + expect(brief.indexOf("### What it won't do yet")).toBeLessThan(brief.indexOf('### Before → after')); + expect(brief).toContain('| reviews the promises made in a meeting (our guess: asked below) | daily |'); + }); + + test('a quote found in an approvals record on disk is verified, and reading it writes nothing to the state root', () => { + const state = makeRun('ledger', { plan: planText(), round2: round2(), round1: false }); + const repo = path.dirname(state.plan_source); + expect(spawnSync('git', ['init', '-q', '-b', 'day-one-ledger', repo], { encoding: 'utf8', timeout: 30_000 }).status).toBe(0); + const home = path.join(TMP, 'ledger-home'); + const mirror = path.join(TMP, 'ledger-mirror', 'some-slug'); + fs.mkdirSync(mirror, { recursive: true }); + fs.writeFileSync(path.join(mirror, `${branchKey('day-one-ledger')}.jsonl`), JSON.stringify({ schema_version: 1, id: 'x', words: 'The owner said: I want to remember what I promised people after every meeting' }) + '\n'); + const env = { HOME: home, GSTACK_APPROVALS_DIR: path.dirname(mirror) }; + const words = recordedOwnerWords(state, env); + expect(ownerContext(state, words).verified).toEqual(new Set([1])); + expect(fs.existsSync(home)).toBe(false); + }); + + test('quoted owner words are redacted from public copies', () => { + const state = makeRun('redact', { plan: planText(), round2: round2(), round1: false }); + const words = ownerWords(state); + const out = redactOwnerWords('The plan says: I want to remember what I promised people after every meeting.', words); + expect(out.redacted).toBe(1); + expect(out.text).not.toContain('promised people'); + }); +}); diff --git a/test/captain-brief.test.ts b/test/captain-brief.test.ts index ddbce6b1e..e7f247160 100644 --- a/test/captain-brief.test.ts +++ b/test/captain-brief.test.ts @@ -178,7 +178,7 @@ describe('carried decisions at a cap gate (#3546)', () => { const challenge = (title: string) => ({ severity: 'Medium', title, fix: `change: ${title}`, user_challenge: true, changes: 'scope' }); phaseVia(r, out, 'ceo', { native: [challenge('Use a queue table'), challenge('Add metrics')], outside: [challenge('Drop jitter')] }); phaseVia(r, out, 'eng', { native: [], outside: [] }); - const ds = JSON.parse(fs.readFileSync(path.join(out, 'gate.json'), 'utf8')).items.filter((i: any) => i.id.startsWith('d')); + const ds = JSON.parse(fs.readFileSync(path.join(out, 'gate.json'), 'utf8')).items.filter((i: any) => i.item_class === 'challenge1'); expect(ds.map((i: any) => i.recommended)).toEqual(['a', 'a', 'a']); expect(r.ap(['answer', '--by', 'human', '--out', out, '--gate-rev', '1', '--reply', `${ds.map((i: any) => `${i.id}b`).join(' ')} p1b`]).status).toBe(0); const v2 = path.join(dir, 'plan-v2.md'); @@ -203,7 +203,7 @@ describe('carried decisions at a cap gate (#3546)', () => { const { gate, gateText, briefText, gateRec, briefRec } = renders(out); expect(gate.gate_rev).toBe(2); expect(gate.items.some(i => i.cap?.kind === 'delta')).toBe(true); - const carried = gate.items.filter(i => i.carried); + const carried = gate.items.filter(i => i.carried && i.item_class === 'challenge1'); expect(carried.map(i => [i.recommended, i.carried!.chosen])).toEqual([['a', 'b'], ['a', 'b'], ['a', 'b']]); expect(briefRec).toEqual(gateRec); expect(Object.fromEntries(carried.map(i => [i.id, gateRec[i.id]]))).toEqual({ d1: 'b', d2: 'b', d3: 'b' }); @@ -213,7 +213,7 @@ describe('carried decisions at a cap gate (#3546)', () => { expect(briefText).toContain(`- ${String.fromCharCode(65 + n)}: ${item.title.replace(/\s*\[[^\]]*\]\s*$/, '')}. We could: 1) ${WORDS[text] ?? text};`); }); expect(briefText).toContain("- A: Use a queue table. We could: 1) make the reviewer's change; 2) keep the plan as written (a reviewer suggested changing it). Recommendation: make the reviewer's change (your answer at gate_rev 1, carried forward). A1 to take recommendation."); - expect(briefText).toContain('do it keeps the 3 you already answered and takes the recommendation for the rest.'); + expect(briefText).toContain('do it keeps the 4 you already answered and takes the recommendation for the rest.'); expect(briefText).toContain('Reply **do it** to keep the answers you already gave and take every other recommendation (recommended)'); }); diff --git a/test/fixtures/module-size-ratchet.json b/test/fixtures/module-size-ratchet.json index bf2786bfe..6c062b2e3 100644 --- a/test/fixtures/module-size-ratchet.json +++ b/test/fixtures/module-size-ratchet.json @@ -148,6 +148,8 @@ { "file": "lib/autoplan-export.ts", "movedFrom": "(new: the unattended export file set, B2/B12)" }, { "file": "lib/spec-review-cap.ts", "movedFrom": "(new: the spec-review loop at the cap: numbered gaps and deterministic fix verification, B8)" }, { "file": "bin/gstack-autoplan", "movedFrom": "(new: thin entrypoint over lib/autoplan-run.ts, B2)" }, + { "file": "lib/autoplan-gate-items.ts", "movedFrom": "(new: the gate items that keep reviewer product challenges on the owner's page, GST-2947)" }, + { "file": "lib/autoplan-owner-text.ts", "movedFrom": "(new: the plan's Owner's words, Day one and cuts sections, GST-2947)" }, { "file": "lib/autoplan-plan-text.ts", "movedFrom": "(new: plan wrap, Implementation-plan review hash, scaffold and drift lines, field wave B1c)" }, { "file": "lib/autoplan-admission.ts", "movedFrom": "(new: install verdict and Bun minimum admission for mutating autoplan verbs, field wave B-core)" }, { "file": "lib/autoplan-migrate.ts", "movedFrom": "(new: gstack_version stamp and legacy decision-id migration at load, field wave B1a)" },