mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-04 07:47:27 +01:00
* feat(loadouts): Opus 5.5 lite loadout with explicit model detection (GSTA-161)
modules/loadouts.json gains the lite loadout (eleven coaching preamble
pieces dropped; upgrade-check and brain-sync kept) and a models map that
sends only claude-opus-5-5 (and its dated snapshots) to it. Detection is
explicit: Capy passes --model to the installer, Claude Code opts in with
./setup --loadout lite; anything unmapped, invalid or unreadable serves full.
The checkout always stays the full render.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs(loadouts): Opus 5.5 lite, detection order, Capy SKILL_ROOT, setup --loadout; troubleshooting anchors; changelog fragment (GSTA-161)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(loadouts): claude_loadout read through CONFIG_BIN; capy skill context ceiling for the --model line (GSTA-161)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: pre-landing review fixes (prune keeps a reused loadout folder, GSTACK_LOADOUT_SKILL_ROOT, claude_loadout guard test) (GSTA-161)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: pre-landing review fixes (Capy skill passes the model as GSTACK_MODEL so an older installer ignores it) (GSTA-161)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: pre-landing review fixes (prune only owned, unused folders; full root from the canonical Claude install; fallback reason and source) (GSTA-161)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs: loadout source example, install and resolve commands, Capy launch-file note (GSTA-161)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* feat(autoplan): --ceo-only runs the CEO review alone with zero questions (GST-537)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: pre-landing review fixes
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test: classify autoplan-ceo-only in the Codex host metadata
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: select autoplan-ceo-only on the skills it runs; say it needs Claude Code
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test: run autoplan-ceo-only in the marathon lane
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs: changelog entry for /autoplan --ceo-only
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test: count the autoplan-ceo-only paid file in the shard inventory
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* feat: gstack-autoplan next --ceo-only runs the CEO review alone and ends reviewed (GST-537)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: budget and close recover a budget-stopped CEO-only run; reviewed is at rest for checkpoints
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: CEO-only finish leaves owner-only cap items undecided, refuses marker phase flags and a plan at the report path, and replaces ceo-review.md atomically
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: the CEO-only report-path guard compares real paths and refuses at the finish when the report file is the plan
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs: CEO_ONLY_CONFLICT covers a plan linked to the report path
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(browse): failing-first device and touch tests (GSTA-227 F3, #3058)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: the report-path guard keeps the lexical check, skips safe hard links and compares bigint file ids
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* browse: per-session tabs for parallel agents; tab pins stop moving the shared active tab (#1961)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* browse: keep the server.ts tab-pin anchor comment for source guards
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* feat(browse): per-tab phone emulation and touch input ($B device, tap, swipe, pinch, touch; #3058, GSTA-227 F3)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test: copy lib/result-codes-autoplan.ts into the fixtures that copy the result-code tables, and keep it out of derived closures
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs(qa, aside): touch pointer in /qa, Aside touch recipe verified on Aside 1.26, report Phones row (GSTA-227 F3, #3058)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* browse: drop the sessions paragraph from /browse to stay inside the parity cap
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* changelog: F3 phone emulation and touch entry
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* browse: hide the ps window in the session harness walk
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs: the decisions.jsonl status list names auto_kept
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(browse): session cap, LRU eviction, headed release and scoped auto-session rows
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* browse: sessions keep tab <id> picks, sidebar claude stays on the user's tab, pinned rebuild and state load rebind the scope
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: pre-landing review fixes (touch cancel with no finger held is a no-op)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: Step 11 review fixes (headed tab adoption, pinned viewport reset, CLI retry keeps --session, rebuild id remap, --json notice, evicted-session reset, device kept after annotated captures, render opts out of sessions, session: client ids reserved)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: headed viewport auto keeps the user's active tab; render's closetab opts out of sessions
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs: sessions, phone emulation and touch in BROWSER.md; session: client ids reserved; TODOS #1961/#3058 shipped
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test: copy lib/result-codes-browse.ts into the fixtures that copy the result-code modules
lib/result-codes.ts imports ./result-codes-browse, so fixtures with an explicit
lib list failed with 'Cannot find module'. pr-dependencies lists it with the other
reason-code modules as selection data. GSTA-227
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* feat: gstack-clean reclaims per-repo .gstack scratch and logs, dry run by default (#2627)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* browse: name the Aside touch recipe's coordinates <tap-x>/<tap-y> with a numeric grammar
The generated-bash lint (INV-3) rejected the free-text <x>/<y> placeholders. GSTA-227
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(clean): leave hard-linked and unreadable logs alone; cut through a no-follow descriptor checked against the evaluated inode
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(clean): tests that expect tmp removal see a quiet ps, so a codex elsewhere on the host cannot flake them
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(clean): an unlistable tmp/ skips its group; liveness asked once per group on apply; BROWSER.md says which logs reset at daemon start
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(clean): write output synchronously so --json reaches a pipe whole; test fixes for root, wrapper git and the ps stub
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(clean): every change rechecks the verified folder and the measured file; full writes; EPIPE ends output quietly
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(clean): the early-close test checks the bin's own exit status
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs: list gstack-clean among the standalone CLIs
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(clean): copied-install fixtures and the dependency list carry lib/result-codes-clean.ts
The remote pregate failed 11 cases in gstack-doctor, plan-tune-cathedral and
timeline-stop-hook-slug: each copies an explicit list of lib/result-codes-*.ts
files into a temp install, and lib/result-codes.ts now imports
./result-codes-clean. Same lists GSTA-168 extended for result-codes-eval.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* chore: regenerate gstack-doctor-components.sh for the gstack-clean result codes
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* qa: fold the touch pointer into the Phases sentence to fit the parity size cap after the main merge
qa's union was 95988 bytes (ratio 1.142 > maxSizeRatio 1.142, train 75). Now 95975 (1.1419). GSTA-227
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs: #3058 troubleshooting 'Fixed in' lines name v1.92.10.0 after the main merge
GSTA-227
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(clean): classify gstack-tasks rows files (tasks-*) as kept, after main added the producer
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs: #3058 troubleshooting 'Fixed in' lines name v1.92.20.0 after the main merge
GSTA-227
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: pre-landing review fixes (restore the lib/result-codes-plan.ts ratchet row the base merge dropped)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(clean): the producer scan ends a name at a colon, so prose after a path names the file (train 78)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs: #3058 troubleshooting 'Fixed in' lines name v1.92.30.0 after the main merge
GSTA-227
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* outside-voice-api: caller receipts, stop_reason, OpenAI max_completion_tokens
A caller can write its own egress receipt (sink, consent, payload class);
the default stays the outside-voice receipt, so existing callers send and
record the same bytes. The result carries the provider's stop reason, and
an OpenAI request gets max_completion_tokens only when the caller sets an
output limit (GST-537 PR 3).
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* autoplan gate: item classes and the owner's answer provenance
Gate items carry item_class, ruleKept() names the keep-direction pick, and
answered decision rows record owner_mode, owner_named, rec_hash and
answered_role parsed from the owner's own words (GST-537 PR 3).
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* autoplan: shadow-mode decider module, frozen prompt and spend accounting
The switch (off by default, fixed at init), the lease, one model call per
gate with a page retry and a truncation retry under one deadline, the
once-per-revision record with its journaled sha256, the 10% audit mark,
and shadow-labeled ledger rows that count against the cap, show as
shadow= on GATE_SPEND and stay out of the per-voice price (GST-537 PR 3).
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* gstack-autoplan: shadow every published gate, the shadow export, config and docs
Every driver command that prints a gate records the shadow first and
checkpoints after it; answer waits for a live lease and records a dead
one retrospectively; gstack-autoplan shadow exports answered revisions
for taste-replay R2 (SHADOW_BEFORE_ANSWER otherwise); gstack-config
autoplan_shadow / autoplan_shadow_model; gstack-artifact validate checks
the record's hash (GST-537 PR 3).
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* changelog: shadow mode for the CEO-only decider (GST-537 PR 3)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* autoplan shadow: /ship review fixes
- register test/fixtures/shadow-fake-model.ts in FREE_FIXTURES (free-fixtures inventory failed)
- withRunLock: count dead-owner reclaims apart from waitMs iterations, so a long wait can still reclaim
- buildPage: fill the decider template in one pass, so slot names inside the plan stay plan text
- revise regate: the shared publish step prints the GATE and ESCALATE lines once
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* autoplan shadow: reply files never follow a link; the retry reserves against the current cap
- a model reply is written by temp file and rename, so a link at the reply path is replaced, not written through
- each shadow reservation reads the run's current spend cap, so a budget change during the call is not undone
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* outside-voice-api: write the egress receipt under the caller's env
callModel resolved the receipt's state root from process.env even when the caller passed env, so the shadow
tests wrote to the real ~/.gstack (the free-suite home-containment guard caught it). The receipt now uses
req.env; the shadow tests give the fake model a private HOME, GSTACK_HOME and GSTACK_STATE_ROOT, and the receipt
test no longer sets process.env to pass.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(autoplan): CEO-only runs leave main's open Critical/High finding items to the owner (no decision row)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(autoplan): shadow pages carry main's finding items; a finding item is never ceo_eligible
After merging #3767 (main 90a170c), open Critical/High findings are gate items
(item_class finding). The shadow records one row per gate item, so its pages now
include them. A CEO-only run leaves those items to the owner, so their rows are
ceo_eligible false (rule_pick was already null). The shadow fixtures follow
main's gate (items, counts, "Do it" tokens); the two merge adapters follow
main's doNext(out, rest, price) and its per-voice reservation (--estimate-usd).
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs: #3058 troubleshooting 'Fixed in' lines name v1.92.61.0 after the main merge
GSTA-227
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(investigate): drop the five-phase step procedure (GST-938)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* changelog: GST-938 fragment wording
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(investigate): keep the web-search sanitize guard; update BROWSER.md and docs/skills.md (review pass 1)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* changelog: GST-938 wording
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(investigate): pin the web-search guard; changelog size (adversarial review)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(clean): classify restamp-staging.json, the restamp producer main gained after #3779's base (wave browse)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: pre-landing review fixes (wave browse): scoped newtab keeps a concurrent tab switch; shadow validate catches a deleted record; a failed shadow publish is journaled
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: a failed shadow publish journals under the run lock and never throws (wave browse review pass 2)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs(unattended): shadow publish failures and the missing-record validate check (wave browse docs audit)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* changelog: wave browse integrator fixes fragment
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix: shadow reader dedupes by run folder, so two runs started in the same second both count (wave browse CI free-suite 16)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* chore: regenerate doctor result anchors in generator order (wave browse rebuild without #3818)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* changelog: name the wave fragment after the rebuilt wave
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>
199 lines
12 KiB
TypeScript
199 lines
12 KiB
TypeScript
/**
|
|
* autoplan-budget — the run budget of the unattended runner (field list 2,
|
|
* W5). Review rounds are counted per phase from `state.history` reopen events
|
|
* and capped by `run.json.max_rounds` (default 2 for new unattended runs; a
|
|
* resumed run keeps the value it persisted) plus the
|
|
* owner's per-phase grants at the gate. Unattended runs on Capy reserve a
|
|
* default per-voice estimate for unestimated host attempts, so `--spend-cap`
|
|
* binds. A dispatch the cap refuses stops the run at the terminal `incomplete`
|
|
* status with a structured `stop` object (`reason: budget_exhausted`) and
|
|
* printed recovery commands; `gstack-autoplan budget` journals the owner's cap
|
|
* change and `resume` lifts the stop only after one. Phase close at the cap
|
|
* lives in lib/autoplan-gate.ts (`closeDeferred`); `escalateLine` names the
|
|
* capped phases still holding High or Critical findings.
|
|
*/
|
|
import * as fs from 'node:fs';
|
|
import * as path from 'node:path';
|
|
import { 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 { readLedger, release, setCap, summarize } from './spend-ledger';
|
|
|
|
export const DEFAULT_MAX_ROUNDS = 2;
|
|
/** Reserved per voice for a host-subagent attempt with no `--estimate-usd` in an unattended run with a spend cap or on Capy. */
|
|
export const DEFAULT_HOST_ESTIMATE_USD = 5;
|
|
|
|
/** Round r of a phase: 1 plus the times it was reopened. */
|
|
export const roundOf = (state: RunState, phase: string): number => 1 + state.history.filter(h => h.event === 'reopened' && h.phase === phase).length;
|
|
/** The phase's round cap: max_rounds plus the owner's grants; null when the run is uncapped. */
|
|
export function roundCap(state: RunState, phase: string): number | null {
|
|
return state.max_rounds == null ? null : state.max_rounds + (state.round_grants?.[phase] ?? 0);
|
|
}
|
|
/** Reopening would pass the cap: the phase has used its last round. */
|
|
export const atCap = (state: RunState, phase: string): boolean => { const cap = roundCap(state, phase); return cap !== null && roundOf(state, phase) >= cap; };
|
|
/** The phase is about to open past its cap (a rerun-all reply reopened it). */
|
|
export const overCap = (state: RunState, phase: string): boolean => { const cap = roundCap(state, phase); return cap !== null && roundOf(state, phase) > cap; };
|
|
|
|
/** Open High or Critical findings of a closed phase: the deferred counts, else bound rows not settled or answered, an outside row naming the same problem (`sameProblem`) as a High or Critical native one counted once. */
|
|
function openHigh(state: RunState, phase: string): number {
|
|
const ps = state.phases[phase];
|
|
if (ps?.deferred) return (ps.deferred.counts.High ?? 0) + (ps.deferred.counts.Critical ?? 0);
|
|
const file = path.join(state.out, `${phase}-consensus.json`);
|
|
let rows: ConsensusRecord['rows'] = [];
|
|
try { rows = fs.existsSync(file) ? (JSON.parse(fs.readFileSync(file, 'utf8')) as ConsensusRecord).rows : []; } catch {}
|
|
const high = (s: string | undefined) => s === 'High' || s === 'Critical';
|
|
const native = voiceRows(state, phase, 'native');
|
|
const nativeHigh = new Set(native.filter(r => high(r.severity)).map(r => r.id));
|
|
const paired = new Set(rows.filter(r => r.native_id && sameProblem(r) && nativeHigh.has(r.native_id)).map(r => r.outside_id));
|
|
const answered = settledIds(state);
|
|
return [...native, ...voiceRows(state, phase, 'outside')]
|
|
.filter(r => !paired.has(r.id) && !(r as { settled_by?: string }).settled_by && !answered.has(r.id) && high(r.severity)).length;
|
|
}
|
|
|
|
/** At the round cap with High or Critical findings still open, more rounds buy nothing: the owner decides. */
|
|
export function escalateLine(state: RunState): string | undefined {
|
|
const held = state.phase_order.filter(p => state.phases[p]?.closed_at && atCap(state, p)).map(p => [p, openHigh(state, p)] as const).filter(([, n]) => n > 0);
|
|
return held.length ? `ESCALATE: evidence sufficient, decision needed (${held.map(([p, n]) => `${p}: ${n} High open`).join('; ')})` : undefined;
|
|
}
|
|
|
|
export function roundsLine(state: RunState): string {
|
|
const cell = (p: string) => `${p}=${roundOf(state, p)}/${roundCap(state, p) ?? 'none'}`;
|
|
return `ROUNDS: ${state.phase_order.map(cell).join(' ')} max_rounds=${state.max_rounds ?? 'none'} host_spend=unknown`;
|
|
}
|
|
|
|
/**
|
|
* The estimate one new attempt reserves: the flag, else the run's persisted `--estimate-usd`, else the default whenever
|
|
* the run has a spend cap (any session kind) or an unattended run is on Capy, else 0 (host spend unknown, not admitted).
|
|
* `run` prices its api attempts from the price table instead (NextOptions.price); an unpriced model falls back to this.
|
|
*/
|
|
export function attemptEstimate(state: RunState, flag: number | undefined, env: NodeJS.ProcessEnv): { usd: number; line?: string } {
|
|
const set = flag ?? state.estimate_usd;
|
|
if (set !== undefined) return { usd: set };
|
|
if (state.spend_cap_usd === null && (state.session_kind !== 'unattended' || env.GSTACK_CAPY !== '1')) return { usd: 0 };
|
|
return { usd: DEFAULT_HOST_ESTIMATE_USD, line: `ESTIMATE: ${DEFAULT_HOST_ESTIMATE_USD.toFixed(2)} per voice reserved for each host-subagent attempt (default under a spend cap, or unattended on Capy; --estimate-usd <n> sets it for the rest of the run); actual host spend stays unknown` };
|
|
}
|
|
|
|
/** Stop the run: terminal `incomplete` with the structured budget_exhausted stop, journaled. Returns the STOP and RECOVER lines. */
|
|
export function stopForBudget(state: RunState, phase: string, nextEstimate: number): string[] {
|
|
const s = summarize(readLedger(path.join(state.out, FILES.spend), state.spend_cap_usd));
|
|
const stop: RunStop = {
|
|
reason: 'budget_exhausted', phase, cap_usd: state.spend_cap_usd, max_rounds: state.max_rounds ?? null,
|
|
rounds: Object.fromEntries(state.phase_order.map(p => [p, roundOf(state, p)])), spent: s.spent_usd, reserved: s.reserved_usd,
|
|
unknown: s.unknown_usd, unknown_count: s.unknown_count, next_estimate_usd: nextEstimate, at: now(),
|
|
};
|
|
state.stop = stop;
|
|
state.status = 'incomplete';
|
|
journal(state.out, { event: 'stopped', ...stop });
|
|
return stopLines(state);
|
|
}
|
|
|
|
export function stopLines(state: RunState): string[] {
|
|
const s = state.stop;
|
|
if (!s) return [];
|
|
const rounds = Object.entries(s.rounds).map(([p, r]) => `${p}:${r}/${roundCap(state, p) ?? 'none'}`).join(',');
|
|
return [
|
|
`STOP: reason=${s.reason} phase=${s.phase ?? 'none'} cap=${s.cap_usd === null ? 'none' : s.cap_usd.toFixed(2)} spent=${s.spent.toFixed(2)} reserved=${s.reserved.toFixed(2)} unknown=${s.unknown_count}(${s.unknown.toFixed(2)}) next_estimate=${s.next_estimate_usd.toFixed(2)} rounds=${rounds}`,
|
|
...recoveryLines(state),
|
|
];
|
|
}
|
|
|
|
export function recoveryLines(state: RunState): string[] {
|
|
const phase = state.stop?.phase ?? '<phase>';
|
|
return [
|
|
`RECOVER: gstack-autoplan close --out ${state.out} --phase ${phase} --deferred "<reason>" --by <human|agent:<id>> (close ${phase} accepted-with-findings, deferred to the build)`,
|
|
`RECOVER: gstack-autoplan budget --out ${state.out} --spend-cap <usd> [--max-rounds <n>] --by <human|agent:<id>>, then gstack-autoplan resume --out ${state.out} (an owner-authorized cap raise)`,
|
|
];
|
|
}
|
|
|
|
/** Clear the stop into `stops` (its history) and leave the run resumable. */
|
|
export function liftStop(state: RunState, why: string): string[] {
|
|
if (!state.stop) return [];
|
|
(state.stops ??= []).push(state.stop);
|
|
delete state.stop;
|
|
state.status = 'running';
|
|
journal(state.out, { event: 'stop_lifted', why });
|
|
return [`STOP_LIFTED: ${why}`];
|
|
}
|
|
|
|
/** `resume` on a budget-stopped run: lifts the stop only when a budget change was journaled after it. */
|
|
export function resumeStop(state: RunState): string[] {
|
|
if (state.status !== 'incomplete' || state.stop?.reason !== 'budget_exhausted') return [];
|
|
const at = state.stop.at;
|
|
const raised = readJournal(state.out).some(r => r.event === 'budget_changed' && String(r.ts) >= at);
|
|
if (!raised) return [`STOPPED: budget_exhausted at ${at}; nothing changed the budget since`, ...recoveryLines(state)];
|
|
return liftStop(state, 'budget raised after budget_exhausted');
|
|
}
|
|
|
|
export interface BudgetChange { spendCap?: number; maxRounds?: number; by?: string }
|
|
|
|
/** `gstack-autoplan budget`: the owner's journaled change of the spend cap and/or the round cap. */
|
|
export function changeBudget(state: RunState, o: BudgetChange): string[] {
|
|
if (o.by === undefined || !ANSWERED_BY_RE.test(o.by)) throw new RunError('ANSWER_BY_REQUIRED', `budget records who authorized the change: pass --by human or --by agent:<id> (got ${JSON.stringify(o.by ?? null)})`, 3);
|
|
if (o.spendCap === undefined && o.maxRounds === undefined) throw new RunError('ARTIFACT_SCHEMA', 'budget needs --spend-cap <usd> and/or --max-rounds <n>', 1);
|
|
if (o.maxRounds !== undefined && (!Number.isInteger(o.maxRounds) || o.maxRounds < 1)) throw new RunError('ARTIFACT_SCHEMA', '--max-rounds needs an integer >= 1', 1);
|
|
const change: Record<string, unknown> = { event: 'budget_changed', by: o.by };
|
|
const parts: string[] = [];
|
|
if (o.spendCap !== undefined) {
|
|
change.spend_cap = { from: state.spend_cap_usd, to: o.spendCap };
|
|
parts.push(`spend_cap=${state.spend_cap_usd ?? 'none'}->${o.spendCap}`);
|
|
state.spend_cap_usd = o.spendCap;
|
|
setCap(path.join(state.out, FILES.spend), o.spendCap);
|
|
}
|
|
if (o.maxRounds !== undefined) {
|
|
change.max_rounds = { from: state.max_rounds ?? null, to: o.maxRounds };
|
|
parts.push(`max_rounds=${state.max_rounds ?? 'none'}->${o.maxRounds}`);
|
|
state.max_rounds = o.maxRounds;
|
|
}
|
|
journal(state.out, change);
|
|
const lines = [`BUDGET: ${parts.join(' ')} by=${o.by}`];
|
|
if (state.stop) lines.push(`NEXT: gstack-autoplan resume --out ${state.out}`);
|
|
return lines;
|
|
}
|
|
|
|
/**
|
|
* Reservations with no dispatch journaled (a crash between reserve and journal) are proven never dispatched, so released.
|
|
* A shadow call journals `shadow_dispatched` before its send: it counts as dispatched and is never released here.
|
|
*/
|
|
export function releaseUndispatched(state: RunState): string[] {
|
|
const file = path.join(state.out, FILES.spend);
|
|
const dispatched = new Set(readJournal(state.out).filter(r => r.event === 'dispatched' || r.event === 'shadow_dispatched').map(r => r.attempt));
|
|
return readLedger(file).reserved.filter(r => !dispatched.has(r.attempt)).map(r => {
|
|
release(file, r.attempt);
|
|
journal(state.out, { event: 'released_undispatched', attempt: r.attempt, estimate_usd: r.estimate_usd });
|
|
return `RELEASED: ${r.attempt} (never dispatched)`;
|
|
});
|
|
}
|
|
|
|
export const pendingDeltas = (state: RunState) => (state.capped_deltas ?? []).filter(d => d.status === 'pending');
|
|
|
|
/**
|
|
* The owner's answers to cap items (deferred closes, deferred blockers, capped deltas) once the plan proceeds:
|
|
* `b` grants that phase one more round, journaled as a budget change, and adds it to the reopen set; Eng, which
|
|
* reruns last, gets its own grant unless it already has one;
|
|
* `a` accepts. Capped deltas record which.
|
|
*/
|
|
export function applyCapChoices(state: RunState, choices: Array<{ item: GateItem; chosen: string }>, reopen: Set<string>, by: string | undefined): string[] {
|
|
const lines: string[] = [];
|
|
const granted = new Set<string>();
|
|
for (const { item, chosen } of choices) {
|
|
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'})`);
|
|
}
|
|
return lines;
|
|
}
|