diff --git a/bin/gstack-autoplan b/bin/gstack-autoplan index 51312da2b..e35fd6343 100755 --- a/bin/gstack-autoplan +++ b/bin/gstack-autoplan @@ -20,6 +20,7 @@ * gstack-autoplan release --out --attempt drop a reservation for an attempt that never ran * gstack-autoplan close --out --phase

--deferred "" --by > close a phase accepted-with-findings * gstack-autoplan budget --out

[--spend-cap ] [--max-rounds ] --by > the owner's journaled cap change + * gstack-autoplan rule --out --revision --by --reason "" [--owner-ref ] close an UNREVIEWED note * gstack-autoplan check --out --attempt --result --model | --unavailable the delta check before a carry * gstack-autoplan checkpoints --from list checkpoint generations, newest first, with hash ok|bad * gstack-autoplan shadow --out | --runs [--json] export answered gates beside their shadow predictions (read-only) @@ -28,7 +29,7 @@ * Logic: lib/autoplan-run.ts (next/submit/resume), lib/autoplan-gate.ts (close, gate, answer), * lib/autoplan-export.ts, lib/autoplan-prompts.ts, lib/spend-ledger.ts. Codes: lib/result-codes.ts. * Workflow commands end with GSTACK_RESULT: skill=autoplan status= run=; the run is never approved here. - * Mutating verbs (next, submit, answer, recommend, revise, close, budget, check, export, run) pass admission first (lib/autoplan-admission.ts) + * Mutating verbs (next, submit, answer, recommend, revise, close, budget, rule, check, export, run) pass admission first (lib/autoplan-admission.ts) * and bring an older run directory forward (lib/autoplan-migrate.ts) under the run lock. */ import * as fs from 'node:fs'; @@ -45,7 +46,7 @@ import { dispatchLine, exportRun } from '../lib/autoplan-export'; import { capyRelayLine } from '../lib/captain-brief'; import { exportPublic } from '../lib/autoplan-public'; import { migrateRun } from '../lib/autoplan-migrate'; -import { reviseRun } from '../lib/autoplan-revise'; +import { reviseRun, ruleUnreviewed } from '../lib/autoplan-revise'; import { FIX_LINES, KINDS, type AutoplanKind } from '../lib/autoplan-lean'; import { pendingAmendments, type RunState, type Voice } from '../lib/autoplan-state'; import { FILES, RunError, currentPhase, fitReservation, initRun, markOutside, markSent, nextStep, readState, resumeRun, retireAttempt, statusLines, submitResult, withRunLock, writeState, type NextOptions } from '../lib/autoplan-run'; @@ -127,6 +128,9 @@ DRIVER: ${driverFile()} reservation), open findings into tasks.jsonl; Critical, urgent and user-challenge findings become gate items budget --out [--spend-cap ] [--max-rounds ] --by > the owner's cap change, journaled; a run stopped incomplete (budget_exhausted) resumes with resume afterwards + rule --out --revision --by --reason "" [--owner-ref :] + close the open note an UNREVIEWED: line left (a revise at the round cap that only took the owner's approved + recommendations, accepted with no gate and read by no reviewer), as a ruled note closes a /ship finding after round two export --out --public write a machine-path-free copy (recorded roots rewritten, plan.md code kept) with provenance digests; the private run is not touched; refused (ARTIFACT_MACHINE_PATH) when a recorded root would remain. The owner's own words never @@ -355,6 +359,15 @@ function doBudget(out: string, rest: string[], json: boolean): number { return EXIT.ok; } +function doRule(out: string, rest: string[], json: boolean): number { + const state = readState(out); + const lines = ruleUnreviewed(state, { revision: num(rest, '--revision'), by: flag(rest, '--by'), reason: flag(rest, '--reason'), ownerRef: flag(rest, '--owner-ref') }); + exportRun(state); + writeState(state); + emit(json, [...lines, resultLineFor(state.status, out)], { run: state.run, status: state.status, capped_deltas: state.capped_deltas ?? [], out }); + return EXIT.ok; +} + async function doRun(out: string, args: string[], json: boolean): Promise { // run pays for both voices, so it starts the full run unless --kind feature asks for the lean one (R65). const rest = args.includes('--kind') ? args : [...args, '--full']; @@ -479,6 +492,7 @@ async function main(argv: string[]): Promise { if (cmd === 'revise') return await publish(out, json, mutating(out, json, () => doRevise(out, rest))); if (cmd === 'close') return await publish(out, json, mutating(out, json, () => doClose(out, rest))); if (cmd === 'budget') return await publish(out, json, mutating(out, json, () => doBudget(out, rest, json))); + if (cmd === 'rule') return await publish(out, json, mutating(out, json, () => doRule(out, rest, json))); if (cmd === 'check') return await publish(out, json, mutating(out, json, () => doCheck(out, rest))); if (cmd === 'run') { const admission = admit(process.env); if (admission.lines.length) process.stdout.write(admission.lines.join('\n') + '\n'); return await doRun(out, rest, json); } if (cmd === 'status') { diff --git a/capy/skill/gstack/captain.md b/capy/skill/gstack/captain.md index 4c0ad5948..b9db3e58d 100644 --- a/capy/skill/gstack/captain.md +++ b/capy/skill/gstack/captain.md @@ -124,8 +124,9 @@ gstack-approvals import --autoplan --by A later gate that asks nothing new is answered for you with the words you recorded (`CARRIED:`, then `APPROVED:`); the brief says "Nothing pending. Carried forward", so import and build without a second ask. `CARRY_CHECK:` means -one reviewer from another model family reads the unreviewed delta first (`gstack-autoplan check`). Anything -else prints `CARRY: no ()` and goes to the person as today (`docs/unattended.md#carry-forward`). +one reviewer from another model family reads the unreviewed delta first (`gstack-autoplan check`). `UNREVIEWED:` +means a revise at the round cap only took recommendations the person approved, so the run finished with no gate; +rule on that note with `gstack-autoplan rule` when you accept it. Anything else prints `CARRY: no ()` and goes to the person as today (`docs/unattended.md#carry-forward`). If the person answers in words ("split it into two PRs"), map the words to tokens, answer, and confirm in one line what you recorded ("Recorded: split into two PRs; everything else as recommended"). A named option ("B2") diff --git a/changelog.d/autoplan-cap-do-it-no-third-gate.md b/changelog.d/autoplan-cap-do-it-no-third-gate.md new file mode 100644 index 000000000..f19b40067 --- /dev/null +++ b/changelog.d/autoplan-cap-do-it-no-third-gate.md @@ -0,0 +1,4 @@ +--- +important: blocker +--- +**/autoplan no longer asks the owner a third time for changes his "do it" already approved.** When the review rounds run out and the only plan edit since the last gate is the recommendations the owner took in his own words, the run now finishes with no new gate. It prints one `UNREVIEWED:` note saying which revision no reviewer read and why, and `gstack-autoplan rule` records a Captain's or the owner's ruling that closes it, the way /ship ships after its second review round. A change the owner didn't approve still goes to him, now as one item for every phase that hit the cap instead of one item per phase, and a phase that does review the revision still raises its findings. `gstack-autoplan status` shows whether that note is still open. (GST-3753) diff --git a/docs/unattended.md b/docs/unattended.md index e42e5e8b5..b5c45d021 100644 --- a/docs/unattended.md +++ b/docs/unattended.md @@ -824,8 +824,8 @@ item, "do it" cases included, goes to the owner. decision row gets `carried_under: do it`, the output prints `CARRIED_UNDER_DO_IT:` per item, and the approval record lists them as "taken under "do it", not seen by the owner". `rec` carries no new item. -- **Unreviewed post-cap delta.** A "plan changed after cap" item - recommending `a` (accept) is read by one reviewer before it carries. `CARRY_CHECK:` names the attempt and +- **Unreviewed post-cap delta.** A "plan changed after the cap" item + (one per revise, naming every capped phase) recommending `a` (accept) is read by one reviewer before it carries. `CARRY_CHECK:` names the attempt and the prompt (the delta against `plan-at-gate.r.md`, the accepted changes, the full plan); the run reserves the estimate in `spend.json` and refuses when it is over `--carry-check-cap ` (default 5) or the run's cap. @@ -839,6 +839,30 @@ item, "do it" cases included, goes to the owner. when the owner answers the gate, the plan is revised, a new gate is written, or the delta changed after dispatch. +At the round cap, a `revise` that only incorporates recommendations the owner +took in his own words (each decision approved as recommended, none in an +agent's own words) raises no gate at all: the owner already approved exactly +those changes. The capped phases' deltas are recorded `accepted` with +`basis: applied owner-approved recommendations at the round cap`, the journal +gets `unreviewed_at_cap`, and `revise` prints one `UNREVIEWED:` line naming +the revision, the phases that never read it, the decisions and the owner's +words, then `APPROVED:`. That line is an open note, as a finding /ship ships +with after round two is: `gstack-autoplan rule --out --revision --by + --reason "" [--owner-ref :]` records a Captain's +or the owner's ruling on it (`unreviewed_ruled`; gstack cannot rule on its +own note, an agent rules only by relaying one with `--owner-ref`, and a +ruling stands once recorded; a retry of the same ruling is safe). The exported +record names who ruled and the owner ref, never the reason text. `gstack-autoplan status` shows each such +change as `unreviewed open` or `unreviewed ruled by `. A phase that does review the revision (one newly in scope) still +raises its findings at a gate, and a revise that takes anything else (an +override, an agent's own words, an edit with no `--incorporates`) keeps the +one cap item above. + +A cut under `### What it won't do yet` carries its answer to the next gate only +while its words are unchanged (case and punctuation aside). Any reworded cut, a +renamed command included, is a new item and the owner is asked about it once: +a wrong carry would hide a scope cut from him, while a re-ask costs one question. + Carried rows keep `answered_by: agent:gstack-autoplan` and name their source (`carried_gate_from`, `carried_gate_rev`, `carried_answered_by`); `gstack-approvals import --autoplan` writes the carried gate as its own row, diff --git a/lib/autoplan-budget.ts b/lib/autoplan-budget.ts index df83ca925..36589d67d 100644 --- a/lib/autoplan-budget.ts +++ b/lib/autoplan-budget.ts @@ -14,10 +14,10 @@ */ import * as fs from 'node:fs'; import * as path from 'node:path'; -import { ANSWERED_BY_RE, type GateItem } from './gate-list'; +import { agentWords, ANSWERED_BY_RE, type GateItem } from './gate-list'; import { settledIds } from './autoplan-confirm'; import { sameProblem, type ConsensusRecord } from './autoplan-reconcile'; -import { FILES, RunError, journal, now, readJournal, voiceRows, type RunState, type RunStop } from './autoplan-state'; +import { FILES, RunError, journal, now, readDecisions, readJournal, voiceRows, type CappedDelta, type RunState, type RunStop } from './autoplan-state'; import { readLedger, release, setCap, summarize } from './spend-ledger'; export const DEFAULT_MAX_ROUNDS = 2; @@ -180,19 +180,61 @@ export function applyCapChoices(state: RunState, choices: Array<{ item: GateItem const cap = item.cap; if (!cap) continue; const reopens = chosen === 'b'; - for (const d of pendingDeltas(state)) if (d.phase === cap.phase && (cap.kind !== 'delta' || String(d.k) === cap.ref)) { d.status = reopens ? 'reopened' : 'accepted'; d.decided_at = now(); } - if (!reopens || granted.has(cap.phase)) continue; - granted.add(cap.phase); - (state.round_grants ??= {})[cap.phase] = (state.round_grants[cap.phase] ?? 0) + 1; - journal(state.out, { event: 'budget_changed', by: by ?? 'gate', round_grant: { phase: cap.phase, cap: roundCap(state, cap.phase) }, item: item.id }); - reopen.add(cap.phase); - lines.push(`ROUND_GRANTED: ${cap.phase} cap=${roundCap(state, cap.phase)} (${item.id}b by ${by ?? 'gate'})`); - if (cap.phase === 'eng' || !state.phase_order.includes('eng') || granted.has('eng')) continue; - granted.add('eng'); - state.round_grants.eng = (state.round_grants.eng ?? 0) + 1; - journal(state.out, { event: 'budget_changed', by: by ?? 'gate', round_grant: { phase: 'eng', cap: roundCap(state, 'eng') }, item: item.id, reason: `eng reruns after ${cap.phase}` }); - reopen.add('eng'); - lines.push(`ROUND_GRANTED: eng cap=${roundCap(state, 'eng')} (reruns after ${cap.phase}; ${item.id}b by ${by ?? 'gate'})`); + const matched = pendingDeltas(state).filter(d => (cap.kind === 'delta' ? String(d.k) === cap.ref && (cap.phases ?? [cap.phase]).includes(d.phase) : d.phase === cap.phase)); + for (const d of matched) { d.status = reopens ? 'reopened' : 'accepted'; d.decided_at = now(); } + if (!reopens) continue; + const phases = cap.phases ? state.phase_order.filter(p => cap.phases!.includes(p)) : [cap.phase]; + for (const phase of phases) { + if (granted.has(phase)) continue; + granted.add(phase); + (state.round_grants ??= {})[phase] = (state.round_grants[phase] ?? 0) + 1; + journal(state.out, { event: 'budget_changed', by: by ?? 'gate', round_grant: { phase, cap: roundCap(state, phase) }, item: item.id }); + reopen.add(phase); + lines.push(`ROUND_GRANTED: ${phase} cap=${roundCap(state, phase)} (${item.id}b by ${by ?? 'gate'})`); + if (phase === 'eng' || !state.phase_order.includes('eng') || granted.has('eng')) continue; + granted.add('eng'); + state.round_grants.eng = (state.round_grants.eng ?? 0) + 1; + journal(state.out, { event: 'budget_changed', by: by ?? 'gate', round_grant: { phase: 'eng', cap: roundCap(state, 'eng') }, item: item.id, reason: `eng reruns after ${phase}` }); + reopen.add('eng'); + lines.push(`ROUND_GRANTED: eng cap=${roundCap(state, 'eng')} (reruns after ${phase}; ${item.id}b by ${by ?? 'gate'})`); + } } return lines; } + +export const OWNER_RECS_AT_CAP = 'applied owner-approved recommendations at the round cap'; + +/** + * The owner's words when every decision a revise incorporates is a recommendation the owner took in his own words (an + * approved row, chosen = recommended, no agent's own words, none taken under "do it" without being shown to him); undefined otherwise. At the round cap such a revise needs no + * gate: the owner already approved exactly these changes, so the unreviewed revision is recorded instead (GST-3753). + */ +export function ownerTookRecs(state: RunState, ids: string[]): string | undefined { + if (!ids.length) return undefined; + const rows = readDecisions(state.out); + const words: string[] = []; + for (const id of ids) { + const r = rows.find(d => d.id === id); + if (!r || r.status !== 'approved' || r.chosen !== r.recommended || agentWords(r) || (r as { carried_under?: string }).carried_under) return undefined; + const said = r.owner_reply ?? (r.answered_by === 'human' ? r.reply : undefined); + if (!said?.trim()) return undefined; + words.push(said.trim()); + } + return [...new Set(words)].join(' / '); +} + +/** Revisions accepted at the cap with no re-review, by revise number: the open notes `rule` closes. */ +export function unreviewedRevisions(state: RunState): Map { + const out = new Map(); + for (const d of state.capped_deltas ?? []) if (d.basis === OWNER_RECS_AT_CAP) out.set(d.k, [...(out.get(d.k) ?? []), d]); + return out; +} + +/** The one line naming an unreviewed revision and how it closes (or who closed it). */ +export function unreviewedLine(state: RunState, k: number): string { + const ds = unreviewedRevisions(state).get(k) ?? []; + const d = ds[0]!; + const head = `UNREVIEWED: revise v${k} (+${d.added} -${d.removed} lines) changed the plan after ${ds.map(x => x.phase).join(',')} used their last round, so no reviewer read it; accepted without a gate: ${OWNER_RECS_AT_CAP} (${(d.decisions ?? []).join(',')}, answered in the owner's words ${JSON.stringify(ownerTookRecs(state, d.decisions ?? []) ?? '')})`; + return d.ruling ? `${head}; closed by ${d.ruling.by}${d.ruling.owner_ref ? ` (relayed from ${d.ruling.owner_ref})` : ''}: ${d.ruling.reason}` + : `${head}; open note: gstack-autoplan rule --out ${state.out} --revision ${k} --by --reason "" closes it`; +} diff --git a/lib/autoplan-export.ts b/lib/autoplan-export.ts index 212f6e92a..724a7af8e 100644 --- a/lib/autoplan-export.ts +++ b/lib/autoplan-export.ts @@ -99,7 +99,7 @@ function runLog(state: RunState, findings: number, tasks: number, decisions: { t if (state.history.length) lines.push(''); const budget = [ ...state.phase_order.flatMap(p => { const d = state.phases[p]?.deferred; return d ? [`Deferred ${p} at round ${d.round} (${d.cause}, by ${d.by}): ${d.reason}; ${d.open} open finding(s) carried into tasks.jsonl; owner items: ${d.blockers.join(', ') || 'none'}`] : []; }), - ...(state.capped_deltas ?? []).map(d => `Plan changed after the ${d.phase} cap (revise v${d.k}, round ${d.round} of ${d.cap}): +${d.added} -${d.removed} lines unreviewed; ${d.status}`), + ...(state.capped_deltas ?? []).map(d => `Plan changed after the ${d.phase} cap (revise v${d.k}, round ${d.round} of ${d.cap}): +${d.added} -${d.removed} lines unreviewed; ${d.status}${d.basis ? ` without a gate (${d.basis}: ${(d.decisions ?? []).join(',')}); ${d.ruling ? `closed by ${d.ruling.by}${d.ruling.owner_ref ? ` (relayed from ${d.ruling.owner_ref})` : ''}` : 'open note until a ruling (gstack-autoplan rule)'}` : ''}`), ...[...(state.stops ?? []), ...(state.stop ? [state.stop] : [])].map(s => `Stopped ${s.reason} at ${s.at}: cap ${s.cap_usd ?? 'none'}, spent ${s.spent}, reserved ${s.reserved}, unknown ${s.unknown}${s === state.stop ? '' : ' (lifted)'}`), ]; if (budget.length) lines.push(`Budget: max_rounds ${state.max_rounds ?? 'none'}${state.round_grants ? `, grants ${JSON.stringify(state.round_grants)}` : ''}.`, ...budget, ''); diff --git a/lib/autoplan-gate-cost.ts b/lib/autoplan-gate-cost.ts index 715faec1f..3a0dde8e8 100644 --- a/lib/autoplan-gate-cost.ts +++ b/lib/autoplan-gate-cost.ts @@ -62,7 +62,7 @@ export function recReopens(list: GateList, run: Pick o.key === choice)?.changes_plan ?? choice !== item.recommended) for (const p of bound) named.add(p); } diff --git a/lib/autoplan-gate.ts b/lib/autoplan-gate.ts index 8daf50798..5f0ef66ba 100644 --- a/lib/autoplan-gate.ts +++ b/lib/autoplan-gate.ts @@ -124,7 +124,7 @@ export function closeDeferred(state: RunState, phase: Phase, o: { reason: string return { lines, blockers }; } -/** The round-cap items: one per deferred phase, one per deferred blocker, one per capped plan delta. */ +/** The round-cap items: one per deferred phase, one per deferred blocker, one per revise that changed the plan after capped phases (not one per phase). */ function capItems(state: RunState, next: { d: () => string; uc: () => string }): GateItem[] { const items: GateItem[] = []; const push = (item: GateItem, ids: string) => items.push({ ...item, origin: ['cap', ids, optionHash(item.options)].join('|') }); @@ -147,11 +147,16 @@ function capItems(state: RunState, next: { d: () => string; uc: () => string }): options: [{ key: 'a', text: 'carry it into the build as a blocking task (you accept the risk)', changes_plan: false }, reopen(phase)] }, id); } } - for (const delta of pendingDeltas(state)) { - push({ id: next.uc(), title: `plan changed after ${delta.phase} cap: unreviewed delta (+${delta.added} -${delta.removed} lines, ${delta.old_plan_sha256.slice(0, 12)} -> ${delta.new_plan_sha256.slice(0, 12)})`, - kind: 'approval', recommended: 'a', recommended_basis: 'the run budget; the delta is reviewed during the build', phase: delta.phase, cap: { phase: delta.phase, kind: 'delta', ref: String(delta.k) }, item_class: 'cap_delta', - why: `revise v${delta.k} changed the plan after ${delta.phase} used round ${delta.round} of ${delta.cap}, so ${delta.phase} never reviewed it`, - options: [{ key: 'a', text: 'accept the unreviewed delta into the approved plan', changes_plan: false }, reopen(delta.phase)] }, `delta-${delta.k}`); + const byRevise = new Map>(); + for (const d of pendingDeltas(state)) byRevise.set(d.k, [...(byRevise.get(d.k) ?? []), d]); + for (const [k, deltas] of byRevise) { + const delta = deltas[0]!; + const phases = deltas.map(d => d.phase).join(' and '); + push({ id: next.uc(), title: `plan changed after the ${phases} cap: unreviewed delta (+${delta.added} -${delta.removed} lines, ${delta.old_plan_sha256.slice(0, 12)} -> ${delta.new_plan_sha256.slice(0, 12)})`, + kind: 'approval', recommended: 'a', recommended_basis: 'the run budget; the delta is reviewed during the build', phase: delta.phase, cap: { phase: delta.phase, kind: 'delta', ref: String(k), phases: deltas.map(d => d.phase) }, item_class: 'cap_delta', + why: `revise v${k} changed the plan after ${deltas.map(d => `${d.phase} used round ${d.round} of ${d.cap}`).join(' and ')}, so no phase reviewed it`, + options: [{ key: 'a', text: 'accept the unreviewed delta into the approved plan', changes_plan: false }, + { key: 'b', text: `reopen ${phases} for one more round (an owner budget raise${deltas.every(d => d.phase === 'eng') ? '' : '; Eng reruns last'})`, changes_plan: false }] }, `delta-${k}`); } return items; } diff --git a/lib/autoplan-owner-words.ts b/lib/autoplan-owner-words.ts index d80dd3f85..7bdb5c802 100644 --- a/lib/autoplan-owner-words.ts +++ b/lib/autoplan-owner-words.ts @@ -257,6 +257,7 @@ export function dropOwnerFields(value: unknown): { value: unknown; dropped: numb 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++; } + if (o.ruling && typeof o.ruling === 'object' && 'reason' in o.ruling) { const { reason: _reason, ...rest } = o.ruling as Record; o.ruling = rest; dropped++; } return Object.fromEntries(Object.entries(o).map(([k, x]) => [k, walk(x)])); }; return { value: walk(value), dropped }; diff --git a/lib/autoplan-revise.ts b/lib/autoplan-revise.ts index beaa95151..9652da699 100644 --- a/lib/autoplan-revise.ts +++ b/lib/autoplan-revise.ts @@ -13,7 +13,10 @@ * are all below High (no user challenge, no newly in-scope phase) applies * without re-review: the touched phases' reviewed hash is rebound to the * revision and `applied_without_rereview` is journaled; anything unsure - * reopens. One recoverable transaction: the staged plan and state are + * reopens. A phase at its round cap is not reopened: an edit that only + * takes recommendations the owner approved in his own words is accepted + * with one UNREVIEWED note (`ownerTookRecs`, GST-3753); any other edit + * becomes one gate item for all the capped phases. One recoverable transaction: the staged plan and state are * written and `revise_intent` journaled before anything moves; `resume` * (recoverRevise) completes an interrupted revise from the stage. */ @@ -23,7 +26,8 @@ import * as path from 'node:path'; 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 { atCap, OWNER_RECS_AT_CAP, ownerTookRecs, pendingDeltas, roundCap, roundOf, unreviewedLine, unreviewedRevisions } from './autoplan-budget'; +import { isGstackActor, OWNER_REF, OWNER_REF_SHAPE } from './ruled-notes'; import { diffStat, earlierRows, lineDiff } from './autoplan-confirm'; import { SETTLEABLE_CHANGES } from './autoplan-reconcile'; import { sectionHeadings } from '../bin/gstack-autoplan-snapshot'; @@ -196,10 +200,13 @@ export function reviseRun(o: ReviseOptions): ReviseResult { voidPendingCheck(state, 'the plan was revised'); const renames = reopen.length ? planReopen(state, reopen, state.gate_rev ?? 0, `revise v${k}`) : []; + const words = capped.length ? ownerTookRecs(state, [...incorporates, ...settle]) : undefined; + const approved = words ? { decided_at: at, basis: OWNER_RECS_AT_CAP, decisions: [...incorporates, ...settle] } : {}; for (const phase of capped) { - (state.capped_deltas ??= []).push({ k, phase, round: roundOf(state, phase), cap: roundCap(state, phase)!, old_plan_sha256: oldHash, new_plan_sha256: newHash, ...delta, status: 'pending', at }); - journal(out, { event: 'cap_delta', k, phase, round: roundOf(state, phase), cap: roundCap(state, phase), old_plan_sha256: oldHash, new_plan_sha256: newHash, ...delta }); + (state.capped_deltas ??= []).push({ k, phase, round: roundOf(state, phase), cap: roundCap(state, phase)!, old_plan_sha256: oldHash, new_plan_sha256: newHash, ...delta, status: words ? 'accepted' : 'pending', at, ...approved }); + journal(out, { event: 'cap_delta', k, phase, round: roundOf(state, phase), cap: roundCap(state, phase), old_plan_sha256: oldHash, new_plan_sha256: newHash, ...delta, ...(words ? { accepted: OWNER_RECS_AT_CAP } : {}) }); } + if (words) journal(out, { event: 'unreviewed_at_cap', k, phases: capped, reason: OWNER_RECS_AT_CAP, decisions: [...incorporates, ...settle], old_plan_sha256: oldHash, new_plan_sha256: newHash }); for (const p of quiet ? touched : []) { const ps = state.phases[p]!; (ps.rebound ??= []).push({ k, from: ps.snapshot!, to: newHash, decisions: incorporates, at }); @@ -226,7 +233,8 @@ export function reviseRun(o: ReviseOptions): ReviseResult { ...(scaffoldedHeading ? [`SCAFFOLDED: added "${scaffoldedHeading}" (${state.scaffolded ? 'the run was scaffolded' : "the run's first plan had no section headings"}; copy at ${state.plan_source}; ${file} unchanged)`] : []), ...(inputFrom ? [`PLAN_INPUT: ${inputFrom} -> ${file} (drift checks and later revises read ${file}; pass --plan ${inputFrom} to go back)`] : []), ...(quiet ? [`APPLIED: ${incorporates.join(',')} without re-review (${state.lean ? 'lean run: one gate revision' : 'below High'}; plan +${delta.added} -${delta.removed} lines)`] : []), amendmentLine(state)]; - for (const phase of capped) lines.push(`CAPPED: ${phase} used round ${roundOf(state, phase)} of ${roundCap(state, phase)}: not reopened; the gate asks the owner about the unreviewed delta (+${delta.added} -${delta.removed} lines)`); + for (const phase of capped) lines.push(`CAPPED: ${phase} used round ${roundOf(state, phase)} of ${roundCap(state, phase)}: not reopened; ${words ? 'the owner already approved this delta (UNREVIEWED below)' : 'the gate asks the owner about the unreviewed delta'} (+${delta.added} -${delta.removed} lines)`); + if (words) lines.push(unreviewedLine(state, k)); if (regate) { lines.push(...approveOrRegate(state, at)); writeState(state); @@ -272,3 +280,23 @@ export function recoverRevise(out: string): string[] { publish(state, staging, stage.renames, { ...stage.committed, recovered: true }, stage.settled); return [`REVISE_RECOVERED: v${intent.k} completed (reopened=${(stage.committed.reopened as string[]).join(',') || 'none'})`]; } + +export interface RuleOptions { revision?: number; by?: string; reason?: string; ownerRef?: string } + +/** `gstack-autoplan rule`: a Captain's (or the owner's) ruling on an unreviewed revision, closing the open note as /ship's ruled notes do after round two. */ +export function ruleUnreviewed(state: RunState, o: RuleOptions): string[] { + const ds = o.revision === undefined ? undefined : unreviewedRevisions(state).get(o.revision); + if (!ds) throw new RunError('ARTIFACT_SCHEMA', `--revision ${o.revision ?? ''} names no revision accepted unreviewed at the round cap (unreviewed: ${[...unreviewedRevisions(state).keys()].map(k => `v${k}`).join(', ') || 'none'})`, 3); + const by = o.by?.trim(); + if (!by || by.startsWith('--') || isGstackActor(by)) throw new RunError('ANSWER_BY_REQUIRED', 'rule records who ruled: pass --by (gstack cannot rule on its own note)', 3); + if (!o.reason?.trim() || o.reason.trim().startsWith('--')) throw new RunError('ARTIFACT_SCHEMA', 'rule needs --reason ""', 3); + if (o.ownerRef !== undefined && !OWNER_REF.test(o.ownerRef)) throw new RunError('ARTIFACT_SCHEMA', `--owner-ref must be ${OWNER_REF_SHAPE}`, 3); + if (by.startsWith('agent:') && !o.ownerRef) throw new RunError('ANSWER_BY_REQUIRED', `${by} is an agent: an agent rules only by relaying the Captain's or owner's ruling, with --owner-ref ${OWNER_REF_SHAPE}`, 3); + const journaled = readJournal(state.out).filter(e => e.event === 'unreviewed_ruled' && e.k === o.revision).at(-1); + const ruled = ds.find(d => d.ruling)?.ruling ?? (journaled && { by: journaled.by, reason: journaled.reason, ...(journaled.owner_ref ? { owner_ref: journaled.owner_ref } : {}), at: journaled.at }); + if (ruled && (ruled.by !== by || ruled.reason !== o.reason.trim() || ruled.owner_ref !== o.ownerRef)) throw new RunError('ARTIFACT_SCHEMA', `revise v${o.revision} is already ruled by ${ruled.by} (${ruled.at}); a ruling stands once recorded`, 3); + const ruling = ruled ?? { by, reason: o.reason.trim(), ...(o.ownerRef ? { owner_ref: o.ownerRef } : {}), at: now() }; + for (const d of ds) d.ruling = ruling; + if (!journaled) journal(state.out, { event: 'unreviewed_ruled', k: o.revision, phases: ds.map(d => d.phase), ...ruling }); + return [unreviewedLine(state, o.revision!)]; +} diff --git a/lib/autoplan-run.ts b/lib/autoplan-run.ts index eb7d74018..76a7d458d 100644 --- a/lib/autoplan-run.ts +++ b/lib/autoplan-run.ts @@ -565,7 +565,7 @@ export function statusLines(state: RunState): string[] { } if (fs.existsSync(path.join(state.out, FILES.spend))) lines.push(renderSpend(summarize(readLedger(path.join(state.out, FILES.spend))))); lines.push(roundsLine(state), ...stopLines(state)); - for (const d of state.capped_deltas ?? []) lines.push(`CAPPED_DELTA: v${d.k} ${d.phase} +${d.added} -${d.removed} ${d.status}`); + for (const d of state.capped_deltas ?? []) lines.push(`CAPPED_DELTA: v${d.k} ${d.phase} +${d.added} -${d.removed} ${d.status}${d.basis ? ` unreviewed ${d.ruling ? `ruled by ${d.ruling.by}` : 'open: needs gstack-autoplan rule'}` : ''}`); return lines; } export const TERMINAL: readonly RunStatus[] = ['complete', 'reviewed', 'gate_pending', 'amend_pending', 'incomplete', 'refused', 'interrupted']; diff --git a/lib/autoplan-state.ts b/lib/autoplan-state.ts index be6606902..c35035cf0 100644 --- a/lib/autoplan-state.ts +++ b/lib/autoplan-state.ts @@ -31,6 +31,10 @@ export interface Amendment { export interface CappedDelta { k: number; phase: string; round: number; cap: number; old_plan_sha256: string; new_plan_sha256: string; added: number; removed: number; status: 'pending' | 'accepted' | 'reopened'; at: string; decided_at?: string; + /** Accepted with no gate item: the revise only incorporated `decisions`, recommendations the owner took in his own words (kept on those decision rows), so nobody re-reviewed it (OWNER_RECS_AT_CAP). */ + basis?: string; decisions?: string[]; + /** A ruling that closes that open note (`gstack-autoplan rule`), as a ruled note closes a finding /ship leaves open after round two. */ + ruling?: { by: string; reason: string; owner_ref?: string; at: string }; } /** Why a run stopped `incomplete` with work left: the structured budget_exhausted stop `resume` lifts after a budget raise. */ export interface RunStop { diff --git a/lib/gate-list.ts b/lib/gate-list.ts index 56e93409c..e62b3dfe8 100644 --- a/lib/gate-list.ts +++ b/lib/gate-list.ts @@ -42,7 +42,7 @@ export interface GateItem { /** Answered at an earlier revision on an unchanged proposal from a phase that did not rerun. */ carried?: { from: string; chosen: string; gate_rev: number }; /** A round-cap item (lib/autoplan-budget.ts): `b` grants the phase one more round and reopens it. */ - cap?: { phase: string; kind: 'deferred' | 'blocker' | 'delta'; ref?: string }; + cap?: { phase: string; kind: 'deferred' | 'blocker' | 'delta'; ref?: string; /** A delta item for every phase revise `ref` passed at its cap; absent on a gate written with one delta item per phase. */ phases?: string[] }; /** The buildGate branch that wrote it (lib/autoplan-gate.ts); `kind` alone mislabels disagreements and single-voice challenges. */ item_class?: ItemClass; /** An open Critical or High finding (its ids, a paired twin included): `a` applies the reviewer's fix to the plan. */ diff --git a/test/autoplan-budget.test.ts b/test/autoplan-budget.test.ts index 56e6a8ad4..9957489f8 100644 --- a/test/autoplan-budget.test.ts +++ b/test/autoplan-budget.test.ts @@ -147,7 +147,7 @@ describe('the round cap', () => { expect(run.status).toBe('gate_pending'); expect(run.capped_deltas.map((d: any) => [d.phase, d.status])).toEqual([['ceo', 'pending'], ['eng', 'pending']]); const deltas = gate(s.out).items.filter((i: any) => i.cap?.kind === 'delta'); - expect(deltas.map((i: any) => i.title.replace(/\(.*/, '').trim())).toEqual(['plan changed after ceo cap: unreviewed delta', 'plan changed after eng cap: unreviewed delta']); + expect(deltas.map((i: any) => i.title.replace(/\(.*/, '').trim())).toEqual(['plan changed after the ceo and eng cap: unreviewed delta']); expect(deltas.every((i: any) => i.kind === 'approval')).toBe(true); const partial = answer(s.out, 2, 'p1a'); expect(partial.stdout).toMatch(/^GATE_PENDING: /m); @@ -205,9 +205,8 @@ describe('deferred close keeps earlier open findings; a reopened phase reruns En phaseVia(r, s.out, 'eng', NONE); expect(r.ap(['revise', '--out', s.out, '--plan', v2File(s.dir)]).status).toBe(0); const items = gate(s.out).items; - const ceo = items.find((i: any) => i.cap?.kind === 'delta' && i.phase === 'ceo'); - const eng = items.find((i: any) => i.cap?.kind === 'delta' && i.phase === 'eng'); - const replied = answer(s.out, readRunJson(s.out).gate_rev, `${ceo.id}b ${eng.id}a p1a`); + const delta = items.find((i: any) => i.cap?.kind === 'delta' && i.phase === 'ceo'); + const replied = answer(s.out, readRunJson(s.out).gate_rev, `${delta.id}b p1a`); expect(replied.status, replied.stderr).toBe(0); expect(replied.stdout).toMatch(/^ROUND_GRANTED: eng cap=2 \(reruns after ceo; /m); phaseVia(r, s.out, 'ceo', NONE); diff --git a/test/autoplan-carry.test.ts b/test/autoplan-carry.test.ts index 04465bb9f..b9f248af5 100644 --- a/test/autoplan-carry.test.ts +++ b/test/autoplan-carry.test.ts @@ -2,7 +2,7 @@ * Carry-forward (GSTA-155, lib/autoplan-carry.ts): a later gate revision that asks nothing new is answered with the * owner's recorded words from the revision before it, and recorded as a carry; every other case prints why not and * stays at the gate. A "do it" also covers new auto items that change no scope, cost or direction. A capped, - * unreviewed delta gets one reviewer on the delta first (CARRY_CHECK, gstack-autoplan check): High or above means no + * unreviewed delta the owner did not take as a recommendation gets one reviewer on the delta first (CARRY_CHECK, gstack-autoplan check): High or above means no * carry. Runs on the simulated Capy host. */ import { afterAll, describe, expect, setDefaultTimeout, test } from 'bun:test'; @@ -51,6 +51,27 @@ function answeredAndRevised(args: string[] = [], words = 'Garry: Do it', ceo: { } const recHashOf = (out: string) => recHash(gateOf(out)); +/** + * Gate 1 answered item by item in the owner's words, taking a change the gate did not recommend (d1b), then revised to take + * it. At the round cap that is an unreviewed change the owner did not take as a recommendation, so it keeps its gate item + * and the delta check (a revise that only takes recommendations he approved needs neither, GST-3753). + */ +function overriddenAndRevised(args: string[] = []) { + const dir = path.join(r.host.base, `carry${++n}`); + const out = path.join(dir, 'run'); + expect(r.ap(['next', '--out', out, '--plan', writePlan(dir), '--no-ui', ...args]).status).toBe(0); + phaseVia(r, out, 'ceo', ONE_VOICE); + expect(phaseVia(r, out, 'eng', NONE).outside.stdout).toContain('status=gate_pending'); + const ans = r.ap(['answer', '--out', out, '--gate-rev', '1', '--reply', 'd1b p1b', '--by', 'agent:gstack-minder', '--owner-reply', 'd1b p1b']); + expect(ans.status, ans.stderr).toBe(0); + expect(ans.stdout).toMatch(/^APPLY: /m); + const v2 = path.join(dir, 'plan-v2.md'); + fs.writeFileSync(v2, V2); + const rev = r.ap(['revise', '--out', out, '--plan', v2, '--incorporates', 'd1']); + expect(rev.status, rev.stderr).toBe(0); + return { dir, out, v2, rev }; +} + describe('whose words answered the gate (GEVA-2, P7)', () => { test("an agent's own words are recorded as its own, never as the owner's, never carried, and imported under the agent", () => { const dir = path.join(r.host.base, `carry${++n}`); @@ -312,9 +333,9 @@ describe('carry-forward', () => { describe('the delta check before a carry', () => { function capped() { - const s = answeredAndRevised(['--max-rounds', '1']); + const s = overriddenAndRevised(['--max-rounds', '1']); expect(s.rev.stdout).toMatch(/^CAPPED: ceo used round 1 of 1/m); - expect(s.rev.stdout).toMatch(/^CARRY_CHECK: attempt=\S+-c2 items=uc\d+,uc\d+ prompt=\S+ result=\S+ model_family=not anthropic estimate=5\.00 cap=5\.00$/m); + expect(s.rev.stdout).toMatch(/^CARRY_CHECK: attempt=\S+-c2 items=uc\d+ prompt=\S+ result=\S+ model_family=not anthropic estimate=5\.00 cap=5\.00$/m); expect(s.rev.stdout).toMatch(/^GATE: gate_rev=2 /m); const run = readRunJson(s.out); expect(run.status).toBe('gate_pending'); @@ -335,10 +356,10 @@ describe('the delta check before a carry', () => { const ok = r.ap(['check', '--out', s.out, '--attempt', s.check.attempt, '--result', s.check.result, '--model', 'openai/gpt-6.1-sol']); expect(ok.status, ok.stderr).toBe(0); expect(ok.stdout).toMatch(/^CARRY_CHECK: passed attempt=\S+ model=openai\/gpt-6\.1-sol findings=1 highest=Low$/m); - expect(ok.stdout).toMatch(/^CARRIED: gate_rev=2 <- gate_rev=1 .*reason=delta check passed on uc\d+,uc\d+; plan unchanged/m); + expect(ok.stdout).toMatch(/^CARRIED: gate_rev=2 <- gate_rev=1 .*reason=delta check passed on uc\d+; plan unchanged/m); expect(ok.stdout).toContain('status=complete'); expect(gateOf(s.out).carry_check).toMatchObject({ verdict: 'passed', model: 'openai/gpt-6.1-sol', max_severity: 'Low', findings: 1 }); - expect(decisions(s.out).filter(x => x.gate_rev === 2 && x.carry_check).length).toBe(2); + expect(decisions(s.out).filter(x => x.gate_rev === 2 && x.carry_check).length).toBe(1); expect(fs.readFileSync(path.join(s.out, 'decisions.tsv'), 'utf8')).toContain('delta check before carrying gate_rev 2'); expect(r.ap(['export', '--out', s.out]).status).toBe(0); expect(r.validate(s.out).status).toBe(0); @@ -367,7 +388,7 @@ describe('the delta check before a carry', () => { // fails_when=the cap comparison or the attempt guard is dropped or inverted; why_new=tests above run at the default cap // with the right attempt only; seam=none; no_claim=real reviewer dispatch (simulated Capy host) test('a check over --carry-check-cap refuses the carry; a wrong --attempt is refused', () => { - const over = answeredAndRevised(['--max-rounds', '1', '--carry-check-cap', '1']); + const over = overriddenAndRevised(['--max-rounds', '1', '--carry-check-cap', '1']); expect(over.rev.stdout).toMatch(/^CARRY: no \(delta check estimate 5\.00 is over the per-gate cap 1\.00 \(--carry-check-cap\)\)$/m); expect(over.rev.stdout).not.toMatch(/^CARRY_CHECK:/m); expect(readRunJson(over.out).status).toBe('gate_pending'); diff --git a/test/autoplan-do-it-at-cap.test.ts b/test/autoplan-do-it-at-cap.test.ts new file mode 100644 index 000000000..df24aed4e --- /dev/null +++ b/test/autoplan-do-it-at-cap.test.ts @@ -0,0 +1,233 @@ +/** + * GST-3753: the owner's "do it" is carried through the round cap. Replays the shape of run autoplan-embftp-20261124162738 + * (gstack v1.103.1.0) on the simulated Capy host: gate 1 answered "do it", a revise and re-review, gate 2 answered "do it", + * then a revise at the round cap that only takes those recommendations. Before the fix that revise raised gate 3 with one + * "accept the unreviewed delta" approval per capped phase, which a relaying agent could not settle (OWNER_REPLY_REQUIRED), + * and a cut whose command was renamed counted as a new item. Now the run finishes with an UNREVIEWED note a ruling closes; + * a change the owner did not approve still raises one item for all capped phases; a phase that does review the revision + * still raises its finding; and a cut carries its answer only while its words are unchanged. + */ +import { afterAll, describe, expect, setDefaultTimeout, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { OWNER_RECS_AT_CAP, ownerTookRecs } from '../lib/autoplan-budget'; +import type { RunState } from '../lib/autoplan-state'; +import { recReopens } from '../lib/autoplan-gate-cost'; +import { recHash } from '../lib/gate-list'; +import { SMALL_PLAN } from './helpers/autoplan-run-fixture'; +import { capyRunner, phaseVia, readJsonl, readRunJson, writePlan } from './helpers/autoplan-capy'; + +setDefaultTimeout(60_000); +const r = capyRunner(); +afterAll(() => r.cleanup()); +let n = 0; +const NONE = { native: [], outside: [] }; +const DO_IT = 'Garry: Do it'; +const both = (id: string, title: string, fix: string) => ({ + native: [{ id: `N${id}`, severity: 'High', title, user_challenge: true, changes: 'scope', fix }], + outside: [{ id: `O${id}`, severity: 'High', title, user_challenge: true, changes: 'scope', fix }], +}); +const FLAG = both('1', 'Ship the backoff behind a flag first', 'gate the change behind RETRY_BACKOFF=1'); +const DEAD = both('2', 'Dead-letter jobs after the last retry', 'move a job to the dead-letter table after 8 attempts'); +const V2 = SMALL_PLAN.replace('cap 30 s', 'cap 30 s, behind RETRY_BACKOFF=1'); +const V3 = V2.replace('jitter 10%.', 'jitter 10%; a job moves to the dead-letter table after 8 attempts.'); +const gateOf = (out: string) => JSON.parse(fs.readFileSync(path.join(out, 'gate.json'), 'utf8')); +const pending = (out: string) => readRunJson(out).amendments.filter((a: any) => a.status === 'pending').map((a: any) => a.decision).join(','); +const file = (dir: string, text: string) => { const f = path.join(dir, `plan-${++n}.md`); fs.writeFileSync(f, text); return f; }; + +function answer(out: string, rev: number, reply: string, words: string, extra: string[] = []) { + return r.ap(['answer', '--out', out, '--gate-rev', String(rev), '--reply', reply, '--rec-hash', recHash(gateOf(out)), '--by', 'agent:gstack-minder', '--owner-reply', words, ...extra]); +} + +/** Gate 1 "do it", revise, round 2 with a new challenge, gate 2 answered with `gate2` in the owner's words: the revise at the cap comes next. */ +function toTheCap(o: { first?: string[]; round2?: { native?: unknown[]; outside?: unknown[] }; gate2?: string; words2?: string } = {}) { + const dir = path.join(r.host.base, `cap${++n}`); + const out = path.join(dir, 'run'); + expect(r.ap(['next', '--out', out, '--plan', writePlan(dir), ...(o.first ?? ['--no-ui'])]).status).toBe(0); + phaseVia(r, out, 'ceo', FLAG); + expect(phaseVia(r, out, 'eng', NONE).outside.stdout).toMatch(/^GATE: gate_rev=1 /m); + const a1 = answer(out, 1, 'rec', DO_IT); + expect(a1.status, a1.stderr).toBe(0); + const v2 = r.ap(['revise', '--out', out, '--plan', file(dir, V2), '--incorporates', pending(out)]); + expect(v2.stdout).toMatch(/^REVISED: plan=\S+ reopened=ceo,eng$/m); + phaseVia(r, out, 'ceo', o.round2 ?? DEAD); + expect(phaseVia(r, out, 'eng', NONE).outside.stdout).toMatch(/^GATE: gate_rev=2 /m); + const a2 = answer(out, 2, o.gate2 ?? 'rec', o.words2 ?? DO_IT); + expect(a2.status, a2.stderr).toBe(0); + expect(a2.stdout).toMatch(/^APPLY: /m); + return { dir, out }; +} + +describe('two "do it" answers, then the round cap', () => { + test("ownerTookRecs counts only recommendations the owner answered in his own words, not ones taken under \"do it\" unseen", () => { + const out = path.join(r.host.base, `took${++n}`); + fs.mkdirSync(out, { recursive: true }); + const row = (id: string, extra: Record) => JSON.stringify({ id, status: 'approved', chosen: 'a', recommended: 'a', owner_reply: DO_IT, ...extra }); + fs.writeFileSync(path.join(out, 'decisions.jsonl'), [row('seen', {}), row('unseen', { carried_under: 'do it' }), row('own', { owner_reply: undefined, answer_words: 'ok', words_by: 'agent:x' }), row('over', { chosen: 'b', status: 'overridden' })].join('\n') + '\n'); + const state = { out } as RunState; + expect(ownerTookRecs(state, ['seen'])).toBe(DO_IT); + for (const id of ['unseen', 'own', 'over']) expect(ownerTookRecs(state, ['seen', id])).toBeUndefined(); + }); + + test('the revise that only takes the approved recommendations finishes the run: no third gate, one UNREVIEWED note', () => { + const s = toTheCap(); + const rev = r.ap(['revise', '--out', s.out, '--plan', file(s.dir, V3), '--incorporates', pending(s.out)]); + expect(rev.status, rev.stderr).toBe(0); + expect(rev.stdout).toMatch(/^REVISED: plan=\S+ reopened=none capped=ceo,eng$/m); + expect(rev.stdout).not.toMatch(/^GATE: gate_rev=3/m); + expect(rev.stdout).toMatch(/^APPROVED: gate_rev=2 /m); + const note = rev.stdout.split('\n').filter(l => l.startsWith('UNREVIEWED:')); + expect(note).toHaveLength(1); + expect(note[0]).toContain(`changed the plan after ceo,eng used their last round, so no reviewer read it; accepted without a gate: ${OWNER_RECS_AT_CAP}`); + expect(note[0]).toContain(`answered in the owner's words ${JSON.stringify(DO_IT)}`); + expect(note[0]).toMatch(/open note: gstack-autoplan rule --out \S+ --revision 2 /); + const run = readRunJson(s.out); + expect(run.status).toBe('complete'); + expect(run.gate_rev).toBe(2); + expect(run.capped_deltas.map((d: any) => [d.phase, d.status, d.basis])).toEqual([['ceo', 'accepted', OWNER_RECS_AT_CAP], ['eng', 'accepted', OWNER_RECS_AT_CAP]]); + expect(readJsonl(path.join(s.out, 'attempts.jsonl')).filter((j: any) => j.event === 'unreviewed_at_cap')).toMatchObject([{ k: 2, phases: ['ceo', 'eng'], reason: OWNER_RECS_AT_CAP }]); + expect(r.validate(s.out).status).toBe(0); + expect(fs.readFileSync(path.join(s.out, 'review-record.md'), 'utf8')).toContain(`accepted without a gate (${OWNER_RECS_AT_CAP}`); + }); + + test("a ruling closes the note, as a ruled note closes a /ship finding after round two; gstack can't rule on its own", () => { + const s = toTheCap(); + expect(r.ap(['revise', '--out', s.out, '--plan', file(s.dir, V3), '--incorporates', pending(s.out)]).status).toBe(0); + for (const bad of [['--revision', '1', '--by', 'GStack Minder (GSTA-36)', '--reason', 'x'], ['--revision', '2', '--by', 'gstack', '--reason', 'x'], ['--revision', '2', '--by', 'agent:lane', '--reason', 'x'], ['--revision', '2', '--by', '--reason', 'x'], ['--revision', '2', '--by', 'GStack Minder (GSTA-36)'], + ['--revision', '2', '--by', 'GStack Minder (GSTA-36)', '--reason', 'x', '--owner-ref', 'not a ref']]) { + const res = r.ap(['rule', '--out', s.out, ...bad]); + expect(res.status, res.stdout).toBe(3); + } + expect(r.ap(['status', '--out', s.out]).stdout).toMatch(/^CAPPED_DELTA: v2 \S+ .* accepted unreviewed open: needs gstack-autoplan rule$/m); + const ok = r.ap(['rule', '--out', s.out, '--revision', '2', '--by', 'GStack Minder (GSTA-36)', '--owner-ref', 'GSTA-36:2026-11-24T16:00:00Z', '--reason', "the owner's standing do it covers the applied changes"]); + expect(ok.status, ok.stderr).toBe(0); + expect(ok.stdout).toMatch(/^UNREVIEWED: revise v2 .*; closed by GStack Minder \(GSTA-36\) \(relayed from GSTA-36:2026-11-24T16:00:00Z\): the owner's standing do it covers the applied changes$/m); + expect(readRunJson(s.out).capped_deltas.every((d: any) => d.ruling?.by === 'GStack Minder (GSTA-36)')).toBe(true); + expect(fs.readFileSync(path.join(s.out, 'review-record.md'), 'utf8')).toContain('closed by GStack Minder (GSTA-36)'); + expect(r.ap(['status', '--out', s.out]).stdout).toMatch(/^CAPPED_DELTA: v2 \S+ .* accepted unreviewed ruled by GStack Minder \(GSTA-36\)$/m); + const reason = "the owner's standing do it covers the applied changes"; + expect(fs.readFileSync(path.join(s.out, 'review-record.md'), 'utf8')).not.toContain(reason); + const pub = path.join(s.dir, 'public'); + expect(r.ap(['export', '--out', s.out, '--public', pub]).status).toBe(0); + expect(fs.readFileSync(path.join(pub, 'run.json'), 'utf8')).not.toContain(reason); + expect(readRunJson(pub).capped_deltas[0].ruling).toMatchObject({ by: 'GStack Minder (GSTA-36)', owner_ref: 'GSTA-36:2026-11-24T16:00:00Z' }); + const again = r.ap(['rule', '--out', s.out, '--revision', '2', '--by', 'Garry', '--reason', 'second thoughts']); + expect(again.status).toBe(3); + expect(again.stderr).toContain('already ruled by GStack Minder (GSTA-36)'); + expect(r.validate(s.out).status).toBe(0); + }); + + test('a settled change the owner did not take in his own words keeps the cap item, even beside an approved one', () => { + const PACK = { native: [...DEAD.native, { id: 'N5', severity: 'Medium', title: 'Split the backoff into its own PR', user_challenge: true, changes: 'packaging', fix: 'land the schedule change as its own PR' }], outside: [...DEAD.outside, { id: 'O5', severity: 'Medium', title: 'Split the backoff into its own PR', user_challenge: true, changes: 'packaging', fix: 'Land the schedule change as its own PR.' }] }; + const s = toTheCap({ round2: PACK }); + const open = readRunJson(s.out).amendments.filter((a: any) => a.status === 'pending'); + const settle = open.find((a: any) => a.changes === 'packaging').decision, inc = open.find((a: any) => a.changes === 'scope').decision; + const rows = readJsonl(path.join(s.out, 'decisions.jsonl')); + fs.writeFileSync(path.join(s.out, 'decisions.jsonl'), rows.map((d: any) => JSON.stringify(d.id === settle ? { ...d, carried_under: 'do it' } : d)).join('\n') + '\n'); + const rev = r.ap(['revise', '--out', s.out, '--plan', file(s.dir, V3), '--incorporates', inc, '--settle', settle]); + expect(rev.status, rev.stderr).toBe(0); + expect(rev.stdout).toMatch(/^GATE: gate_rev=3 /m); + expect(rev.stdout).not.toMatch(/^(APPROVED|UNREVIEWED):/m); + expect(readRunJson(s.out).capped_deltas.every((d: any) => d.status === 'pending' && !d.basis)).toBe(true); + }); + + test('a rule interrupted after its journal row is retried to the same ruling, never a second one', () => { + const s = toTheCap(); + expect(r.ap(['revise', '--out', s.out, '--plan', file(s.dir, V3), '--incorporates', pending(s.out)]).status).toBe(0); + const args = ['rule', '--out', s.out, '--revision', '2', '--by', 'GStack Minder (GSTA-36)', '--reason', 'covered by do it']; + expect(r.ap(args).status).toBe(0); + const run = readRunJson(s.out); + for (const d of run.capped_deltas) delete d.ruling; + fs.writeFileSync(path.join(s.out, 'run.json'), JSON.stringify(run, null, 2)); + const other = r.ap(['rule', '--out', s.out, '--revision', '2', '--by', 'Garry', '--reason', 'something else']); + expect(other.status).toBe(3); + expect(other.stderr).toContain('already ruled by GStack Minder (GSTA-36)'); + const retry = r.ap(args); + expect(retry.status, retry.stderr).toBe(0); + expect(readRunJson(s.out).capped_deltas.every((d: any) => d.ruling?.reason === 'covered by do it')).toBe(true); + expect(readJsonl(path.join(s.out, 'attempts.jsonl')).filter((j: any) => j.event === 'unreviewed_ruled')).toHaveLength(1); + }); + + test('a change the owner did not approve still raises a gate, with one item for every capped phase', () => { + const s = toTheCap({ round2: { native: [{ id: 'N2', severity: 'High', title: 'Dead-letter jobs after the last retry', user_challenge: true, changes: 'scope', fix: 'dead-letter after 8 attempts' }], outside: [] }, gate2: 'd1b p1b', words2: 'd1b p1b' }); + const rev = r.ap(['revise', '--out', s.out, '--plan', file(s.dir, V3), '--incorporates', pending(s.out)]); + expect(rev.status, rev.stderr).toBe(0); + expect(rev.stdout).not.toMatch(/^UNREVIEWED:/m); + expect(rev.stdout).toMatch(/^GATE: gate_rev=3 /m); + const deltas = gateOf(s.out).items.filter((i: any) => i.cap?.kind === 'delta'); + expect(deltas).toHaveLength(1); + expect(deltas[0].title).toStartWith('plan changed after the ceo and eng cap: unreviewed delta'); + const own = answer(s.out, 3, 'rec', 'Accepted on the standing approval', ['--words-by', 'agent:gstack-minder']); + expect(own.status).toBe(3); + expect(own.stderr).toContain(`(${deltas[0].id} is a round-cap approval only the owner can settle, and this reply`); + expect(own.stderr).toContain('(OWNER_REPLY_REQUIRED)'); + const reopen = r.ap(['answer', '--out', s.out, '--gate-rev', '3', '--reply', `${deltas[0].id}b p1a`, '--by', 'human']); + expect(reopen.status, reopen.stderr).toBe(0); + expect(reopen.stdout).toMatch(/^ROUND_GRANTED: ceo cap=3 /m); + expect(reopen.stdout).toMatch(/^ROUND_GRANTED: eng cap=3 \(reruns after ceo; /m); + expect(readRunJson(s.out).capped_deltas.filter((d: any) => d.k === 2).map((d: any) => d.status)).toEqual(['reopened', 'reopened']); + }); + + test('a gate written before this change, with one delta item per phase, still settles each phase on its own', () => { + const s = toTheCap({ round2: { native: [{ id: 'N2', severity: 'High', title: 'Dead-letter jobs after the last retry', user_challenge: true, changes: 'scope', fix: 'dead-letter after 8 attempts' }], outside: [] }, gate2: 'd1b p1b', words2: 'd1b p1b' }); + expect(r.ap(['revise', '--out', s.out, '--plan', file(s.dir, V3), '--incorporates', pending(s.out)]).stdout).toMatch(/^GATE: gate_rev=3 /m); + const g = gateOf(s.out); + const one = g.items.find((i: any) => i.cap?.kind === 'delta'); + const { phases: _phases, ...cap } = one.cap; + const id2 = `uc${g.items.filter((i: any) => i.id.startsWith('uc')).length + 1}`; + g.items.splice(g.items.indexOf(one), 1, { ...one, cap: { ...cap, phase: 'ceo' } }, { ...one, id: id2, origin: `${one.origin}|eng`, cap: { ...cap, phase: 'eng' } }); + fs.writeFileSync(path.join(s.out, 'gate.json'), JSON.stringify(g, null, 2)); + const res = r.ap(['answer', '--out', s.out, '--gate-rev', '3', '--reply', `${one.id}b ${id2}a p1a`, '--by', 'human']); + expect(res.status, res.stderr).toBe(0); + expect(res.stdout).toMatch(/^ROUND_GRANTED: ceo cap=3 /m); + expect(readRunJson(s.out).capped_deltas.filter((d: any) => d.k === 2).map((d: any) => [d.phase, d.status])).toEqual([['ceo', 'reopened'], ['eng', 'accepted']]); + }); + + test('a phase that does review the revision still raises its new finding at a gate', () => { + const s = toTheCap({ first: [] }); + const rev = r.ap(['revise', '--out', s.out, '--plan', file(s.dir, `\n${V3}`), '--incorporates', pending(s.out)]); + expect(rev.status, rev.stderr).toBe(0); + expect(rev.stdout).toMatch(/^REVISED: plan=\S+ reopened=none added=design capped=ceo,eng$/m); + const design = phaseVia(r, s.out, 'design', { native: [{ id: 'D1', severity: 'High', title: 'The retry status has no screen' }], outside: [] }); + expect(design.outside.stdout).toMatch(/^GATE: gate_rev=3 /m); + const items = gateOf(s.out).items; + expect(items.filter((i: any) => i.item_class === 'finding').map((i: any) => i.title)).toEqual([expect.stringContaining('The retry status has no screen')]); + expect(items.some((i: any) => i.cap?.kind === 'delta')).toBe(false); + }); +}); + +describe('the grant cost line, and cuts that carry only on unchanged words', () => { + const plan = (button: string, extra = '') => [`# Plantpal watering coach (synthetic)`, '', '## Implementation plan', '', "### Owner's words", '', + '- Ada Example, day 0: "I keep forgetting which plant needs water" → does it', '', '### Day one', '', + '| action | frequency | source | feature | route | first build | check |', '|---|---|---|---|---|---|---|', + '| sees which plant needs water today | daily | owner words 1 | Today list | root screen | build 1 | the plant due today is at the top |', '', + "### What it won't do yet", '', `- No \`${button}\` command for shared households`, '- No Android build', '', + `### Units`, '', `U1 the Today list${extra}. U2 the watering reminder.`, '', '## Review record', ''].join('\n'); + + test('the cost line for granting rounds counts every phase the one cap item reopens', () => { + const opt = (key: string) => ({ key, text: key, changes_plan: key === 'b' }); + const list = { schema_version: 1, run: 'r', gate_rev: 3, items: [{ id: 'uc1', title: 'cap', options: [opt('a'), opt('b')], recommended: 'b', kind: 'approval', cap: { phase: 'ceo', kind: 'delta', ref: '2', phases: ['ceo', 'design'] } }] } as any; + expect(recReopens(list, { phase_order: ['ceo', 'design', 'eng'] })).toEqual(['ceo', 'design', 'eng']); + }); + + test('a cut whose words changed, a renamed command included, is asked again; an unchanged cut carries its answer', () => { + const dir = path.join(r.host.base, `cuts${++n}`); + const out = path.join(dir, 'run'); + expect(r.ap(['next', '--out', out, '--plan', writePlan(dir, plan('share')), '--no-ui', '--no-dx']).status).toBe(0); + phaseVia(r, out, 'ceo', FLAG); + expect(phaseVia(r, out, 'eng', NONE).outside.stdout).toMatch(/^GATE: gate_rev=1 /m); + const cut1 = gateOf(out).items.find((i: any) => i.item_class === 'cut' && i.title.includes('share')); + expect(cut1).toBeDefined(); + expect(answer(out, 1, 'rec', DO_IT).status).toBe(0); + const rev = r.ap(['revise', '--out', out, '--plan', file(dir, plan('invite', ', behind RETRY_BACKOFF=1')), '--incorporates', pending(out)]); + expect(rev.stdout).toMatch(/^REVISED: plan=\S+ reopened=ceo,eng$/m); + phaseVia(r, out, 'ceo', NONE); + const eng = phaseVia(r, out, 'eng', NONE).outside; + const gate = gateOf(out); + const cut2 = gate.items.find((i: any) => i.item_class === 'cut' && i.title.includes('invite')); + expect(cut2.origin).not.toBe(cut1.origin); + expect(cut2.carried).toBeUndefined(); + expect(gate.items.find((i: any) => i.item_class === 'cut' && i.title.includes('Android')).carried).toMatchObject({ chosen: 'a', gate_rev: 1 }); + expect(eng.stdout).toMatch(new RegExp(`^CARRY: no \\(new item ${cut2.id}: Cut: No \`invite\` command`, 'm')); + }); +});