mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-03 07:18:03 +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>
549 lines
44 KiB
TypeScript
Executable File
549 lines
44 KiB
TypeScript
Executable File
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
/**
|
|
* gstack-autoplan — the unattended /autoplan runner as an explicit, durable state machine (plan B2).
|
|
*
|
|
* gstack-autoplan next --out <dir> [--plan <file>] [--plan-heading <text>] [--ui|--no-ui] [--developer-tool] [--agent-primary] [--docs-only] [--ceo-only]
|
|
* [--no-outside] [--light] [--spend-cap <usd>] [--estimate-usd <n>] [--deadline <min>] [--redispatch <attempt>] [--json]
|
|
* gstack-autoplan submit --out <dir> --phase <p> --voice native|outside --result <file> | --record <file> [--attest <reason>]
|
|
* --model <id> [--attempt <id>] [--runner <r>] [--usage-usd <n>] [--reconcile <jsonl>] [--json]
|
|
* gstack-autoplan submit --out <dir> --phase <p> --voice outside --unavailable <reason> | --failed <reason> [--json]
|
|
* gstack-autoplan revise --out <dir> --plan <file> [--incorporates <id,...>] [--withdraw <id>] [--settle <id>] [--json] review a revised plan in this run
|
|
* gstack-autoplan run --out <dir> --plan <file> --native-model <id> --outside-model <id> [--runner codex-cli|api] [--native-runner api]
|
|
* [--deadline <min>] [--spend-cap <usd>] [--estimate-usd <n>] [--max-tokens <n>] [--json] next in a loop; needs runners for both voices
|
|
* gstack-autoplan answer --out <dir> --gate-rev <rev> --reply "<grammar>" --by <human|agent:<id>> [--owner-reply <text>|-] [--words-by owner|agent:<id>] [--rec-hash <h>] [--json]
|
|
* gstack-autoplan recommend --out <dir> --gate-rev <n> --item <id> --option <k> --basis "<why>" [--by <who>]
|
|
* gstack-autoplan resume --out <dir> [--from <checkpoint>] [--json] take ownership; intent without a terminal record becomes EXECUTION_UNKNOWN
|
|
* gstack-autoplan status --out <dir> [--json] query: the manifest, no GSTACK_RESULT line
|
|
* gstack-autoplan export --out <dir> [--json] rewrite plan.md, review-record.md, findings/tasks.jsonl and run.json hashes
|
|
* gstack-autoplan export --out <dir> --public <pub> a machine-path-free copy in <pub>; the private run is only read
|
|
* gstack-autoplan release --out <dir> --attempt <id> drop a reservation for an attempt that never ran
|
|
* gstack-autoplan close --out <dir> --phase <p> --deferred "<reason>" --by <human|agent:<id>> close a phase accepted-with-findings
|
|
* gstack-autoplan budget --out <dir> [--spend-cap <usd>] [--max-rounds <n>] --by <human|agent:<id>> the owner's journaled cap change
|
|
* gstack-autoplan check --out <dir> --attempt <id> --result <file> --model <id> | --unavailable <reason> the delta check before a carry
|
|
* gstack-autoplan checkpoints --from <dir> list checkpoint generations, newest first, with hash ok|bad
|
|
* gstack-autoplan shadow --out <dir> | --runs <file> [--json] export answered gates beside their shadow predictions (read-only)
|
|
* gstack-autoplan contract print the coordinator contract every lane prompt inherits (plan E2)
|
|
*
|
|
* 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=<s> run=<dir>; 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)
|
|
* and bring an older run directory forward (lib/autoplan-migrate.ts) under the run lock.
|
|
*/
|
|
import * as fs from 'node:fs';
|
|
import * as path from 'node:path';
|
|
import { amendmentSteps, answerGate, closeDeferred, recommendGate } from '../lib/autoplan-gate';
|
|
import { checkCeoOnlyFlags, finishRun, refuseCeoOnly } from '../lib/autoplan-ceo-only';
|
|
import { gateCost, gateCostPayload, renderGateCost, type GateCost } from '../lib/autoplan-gate-cost';
|
|
import { attemptEstimate, changeBudget, escalateLine, liftStop } from '../lib/autoplan-budget';
|
|
import { DEFAULT_CARRY_CHECK_CAP_USD, submitCarryCheck } from '../lib/autoplan-carry';
|
|
import { ANSWERED_BY_RE } from '../lib/gate-list';
|
|
import { checkpointLines, checkpointRun, restoreCheckpoint, type CheckpointMoment } from '../lib/autoplan-checkpoint';
|
|
import { admit, touchInstallLease } from '../lib/autoplan-admission';
|
|
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 { 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';
|
|
import { driverFile, type Phase } from '../lib/autoplan-prompts';
|
|
import { EXIT, exitTableHelp } from '../lib/headless-artifacts';
|
|
import { createRunner, familyConflict, type RunnerId } from '../lib/outside-voice-runner';
|
|
import { DEFAULT_MAX_TOKENS, apiTimeoutMs } from '../lib/outside-voice-api';
|
|
import { estimateCostUsd, pricingRow } from '../lib/pricing';
|
|
import { resultLine } from '../lib/result-codes';
|
|
import { release } from '../lib/spend-ledger';
|
|
import { COORDINATOR_CONTRACT } from '../lib/coordinator-contract';
|
|
import { claimShadow, runShadow, shadowBeforeAnswer, shadowSwitch, type ShadowClaim, type ShadowOutcome } from '../lib/autoplan-shadow';
|
|
import { exportShadow, renderShadowExport } from '../lib/autoplan-shadow-reader';
|
|
|
|
const HELP = `gstack-autoplan — unattended /autoplan: next/submit loop, answer, resume (docs/unattended.md)
|
|
DRIVER: ${driverFile()}
|
|
|
|
next --out <dir> [--plan <file>] [--plan-heading <text>] [--scaffold] [--ui|--no-ui] [--developer-tool] [--agent-primary] [--no-dx] [--docs-only] [--ceo-only]
|
|
[--no-outside] [--light] [--spend-cap <usd>] [--max-rounds <n>] [--estimate-usd <n>] [--deadline <min>] [--redispatch <attempt>] [--json]
|
|
--max-rounds (first next): review rounds per phase (default 2 unattended); at the cap a phase closes accepted-with-findings
|
|
--docs-only (first next; also detected when every Implementation-plan path is docs-class): CEO (native voice only) + Eng
|
|
--ceo-only (first next, command line only): the CEO phase alone, no gate; ends status=reviewed with <out>/ceo-review.md, never approved
|
|
--estimate-usd: reserved per new attempt, kept for the rest of the run; with --spend-cap any run (or an unattended run on Capy) reserves a default so the cap binds
|
|
--scaffold (first next): a plan missing one of its two sections is reviewed from <out>/plan-source.md with the heading added
|
|
--light loads each phase's checklist plus the sections its scope needs (the unattended default); interactive kinds load everything
|
|
--no-carry-forward (first next): every later gate revision goes to the owner, even one that asks nothing new
|
|
--carry-check-cap <usd> (first next): the most one delta check may reserve before a carry (default ${DEFAULT_CARRY_CHECK_CAP_USD.toFixed(2)})
|
|
the first next prints REVIEW_ESTIMATE: the most the review can reserve at this scope and round cap
|
|
prepare the current phase; one ATTEMPT: line per voice; ends awaiting_result
|
|
submit --out <dir> --phase <p> --voice native|outside --result <file> | --record <file> [--attest <reason>]
|
|
--model <id> [--attempt <id>] [--runner <r>] [--usage-usd <n>] [--reconcile <jsonl>] [--json]
|
|
bind one reviewer result (receipt, canonical findings, model family) exactly once; closes the phase when both voices are in.
|
|
--attempt may be omitted when exactly one attempt is open. --record takes a hand-run review: the gstack-findings fence,
|
|
one findings table (Severity and Title columns), one severity-tagged list (- [High] title) or a "No findings." line;
|
|
without its INPUT line it binds only with --attest <reason> and --attempt (receipt: attested)
|
|
submit --out <dir> --phase <p> --voice outside --unavailable <reason> | --failed <reason>
|
|
the outside voice could not run: closes the phase native_only once native is bound
|
|
revise --out <dir> --plan <file> [--incorporates <id,...>] [--withdraw <id>] | --settle <id,...>
|
|
review a revised plan in this run: every phase whose reviewed Implementation-plan hash differs reopens (Eng last);
|
|
--incorporates discharges the named accepted changes (the plan must change); when every one resolves below High and no phase
|
|
comes into scope, the edit applies without re-review (APPLIED:); --withdraw (alone or with --plan) drops one;
|
|
--settle records a packaging/ordering change that needs no plan edit and reopens nothing (ids: decision id or d4)
|
|
run --out <dir> --plan <file> --native-model <id> --outside-model <id> [--runner codex-cli|api] [--native-runner api] ...
|
|
next in a loop, only when a runner executes both voices here (hosts without subagents: --native-runner api --runner api);
|
|
--deadline cancels the children it started; --max-tokens caps each api call's output (default 16384; OpenAI counts reasoning tokens in it), and a
|
|
response cut off at that limit is reported truncated; submit's result checks judge every completed response
|
|
answer --out <dir> --gate-rev <rev> --reply "<rec | rec except d3a | d3b uc1a | as-is>" --by <human|agent:<id>> [--json]
|
|
--by agent:<id> needs --owner-reply "<owner's words>" (- reads stdin; --owner-reply-file <path>), stored verbatim;
|
|
--words-by agent:<id> (the same agent) when those words are its own: recorded as its words, never the owner's, never carried;
|
|
--rec-hash <h> binds a rec to the render the owner saw (required once recommend ran); accepted changes leave amend_pending
|
|
recommend --out <dir> --gate-rev <n> --item <id> --option <k> --basis "<why>" [--by <who>]
|
|
set one item's recommendation before relay (provenance recorded, p1 follows); re-render and relay afterwards
|
|
resume --out <dir> [--from <checkpoint>] [--json] --from restores a hash-verified checkpoint into an empty --out first
|
|
(a collection or root restores its newest valid generation; GSTACK_AUTOPLAN_CHECKPOINT_DIR set: every command
|
|
leaving the run at rest publishes a generation under <dir>/<run>/ and prints CHECKPOINT: on stderr)
|
|
check --out <dir> --attempt <id> --result <file> --model <id> [--same-family "<why>"] | --unavailable "<reason>"
|
|
bind the one-reviewer delta check a CARRY_CHECK: line asked for: nothing at High or above carries the owner's
|
|
last answer (CARRIED:); otherwise, or when unavailable, the gate goes to the owner as before
|
|
checkpoints --from <dir> list checkpoint generations, newest first: run, gate_rev, time, hash ok|bad, current
|
|
shadow --out <dir> | --runs <file> [--json]
|
|
read-only export for taste-replay R2: one row per item of each answered gate revision, its shadow prediction
|
|
(recorded before the answer; status recorded, malformed, failed, missing, retrospective or off) beside the
|
|
owner's answer and how he gave it; counts by status, item class, owner_mode and ceo_eligible. An unanswered or
|
|
interrogated revision refuses SHADOW_BEFORE_ANSWER, a CEO-only run CEO_ONLY_NO_GATE. --runs: one run dir per line.
|
|
Shadow mode itself is off by default: gstack-config set autoplan_shadow on (or GSTACK_AUTOPLAN_SHADOW=1) at the
|
|
first next; each gate then gets one hidden model call (autoplan_shadow_model, default claude-opus-5-5) counted
|
|
against --spend-cap, and every command that prints a gate prints SHADOW: first
|
|
close --out <dir> --phase <p> --deferred "<reason>" --by <human|agent:<id>>
|
|
close the phase accepted-with-findings: open voices skipped (dispatched attempts settle unknown at their
|
|
reservation), open findings into tasks.jsonl; Critical, urgent and user-challenge findings become gate items
|
|
budget --out <dir> [--spend-cap <usd>] [--max-rounds <n>] --by <human|agent:<id>>
|
|
the owner's cap change, journaled; a run stopped incomplete (budget_exhausted) resumes with resume afterwards
|
|
export --out <dir> --public <pub>
|
|
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
|
|
status --out <dir> [--json] export --out <dir> release --out <dir> --attempt <id>
|
|
contract print lib/coordinator-contract.ts (the block every lane and reviewer prompt inherits word for word)
|
|
|
|
The first next needs --plan. The native voice is dispatched by the parent from the printed prompt file (a subagent on the
|
|
parent's model); the outside voice runs through gstack-outside-voice or a cross-family subagent. Spend by host subagents is unknown.
|
|
The first next reads codex_reviews: disabled (or an unreadable config) records every phase's outside voice as a terminal
|
|
not_run consent_missing outcome and dispatches none. Enable: gstack-config set codex_reviews enabled.
|
|
${exitTableHelp()}`;
|
|
|
|
function flag(args: string[], name: string): string | undefined {
|
|
const i = args.indexOf(name);
|
|
return i >= 0 ? args[i + 1] : undefined;
|
|
}
|
|
function usage(message: string): number {
|
|
process.stderr.write(`gstack-autoplan: ${message}\n${HELP}\n`);
|
|
return EXIT.usage;
|
|
}
|
|
function num(args: string[], name: string): number | undefined {
|
|
const v = flag(args, name);
|
|
if (v === undefined) return undefined;
|
|
const n = Number(v);
|
|
if (!Number.isFinite(n) || n < 0) throw new RunError('ARTIFACT_SCHEMA', `${name} needs a non-negative number`, 1);
|
|
return n;
|
|
}
|
|
const resultLineFor = (status: string, out: string) => `GSTACK_RESULT: skill=autoplan status=${status} run=${out}`;
|
|
const listFlag = (args: string[], name: string) => args.flatMap((a, i) => (a === name && args[i + 1] ? args[i + 1]!.split(',').map(x => x.trim()).filter(Boolean) : []));
|
|
/** The NEXT line after an answer or revise: per pending change, settle it or edit the plan and revise; else next. */
|
|
function nextLine(state: RunState, out: string): string {
|
|
return pendingAmendments(state).length ? `NEXT: ${amendmentSteps(state, out)}` : `NEXT: gstack-autoplan next --out ${out}`;
|
|
}
|
|
|
|
/**
|
|
* Admission, then under the run lock: bring an existing run forward (GSTACK_VERSION_CHANGED, legacy decision ids)
|
|
* and record an admission override as a deviation. Notices go to stdout before the command's own lines (stderr with --json).
|
|
*/
|
|
function mutating(out: string, json: boolean, fn: () => number | Report): number | Report {
|
|
const admission = admit(process.env);
|
|
touchInstallLease(process.env);
|
|
return withRunLock(out, () => {
|
|
const notices = [...admission.lines];
|
|
const record = (state: RunState) => {
|
|
if (!admission.deviation || (state.deviations ?? []).includes(admission.deviation)) return false;
|
|
(state.deviations ??= []).push(admission.deviation);
|
|
return true;
|
|
};
|
|
if (fs.existsSync(path.join(out, FILES.run))) {
|
|
const state = readState(out);
|
|
const migrated = migrateRun(state);
|
|
if (record(state) || migrated.changed) writeState(state);
|
|
notices.push(...migrated.lines);
|
|
}
|
|
if (notices.length) (json ? process.stderr : process.stdout).write(notices.join('\n') + '\n');
|
|
const result = fn();
|
|
if (admission.deviation && fs.existsSync(path.join(out, FILES.run))) { const state = readState(out); if (record(state)) writeState(state); }
|
|
if (typeof result !== 'number') return claimed(out, result);
|
|
if (result === EXIT.ok) checkpointQuietly(out);
|
|
return result;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* What a command that can leave a gate reports: the lines before the gate, the lines after it, and its JSON payload.
|
|
* `publish` puts the SHADOW line and the gate lines between them once the shadow has run (lib/autoplan-shadow.ts).
|
|
*/
|
|
interface Report { head: string[]; tail: string[]; payload: Record<string, unknown>; gate: boolean; claim?: ShadowClaim; claimLine?: string }
|
|
|
|
/** Still under the command's run lock: a report at a gate claims its shadow (the checkpoint waits for publish); any other checkpoints now. */
|
|
function claimed(out: string, r: Report): Report {
|
|
if (!r.gate) { checkpointQuietly(out); return r; }
|
|
try { const c = claimShadow(out); return { ...r, claim: c.claim, claimLine: c.line }; }
|
|
catch (e: any) { return { ...r, claimLine: `SHADOW: failed internal (${e?.message ?? e}); the gate stands` }; }
|
|
}
|
|
|
|
const shadowField = (o: ShadowOutcome | undefined, line: string | undefined) => (o ? { shadow: { status: o.status, ...(o.code ? { code: o.code } : {}), ...(o.model ? { model: o.model } : {}), ...(o.usd !== undefined ? { usd: o.usd } : {}) } } : line ? { shadow: { line } } : {});
|
|
|
|
/**
|
|
* The one gate-publication step every command that prints a gate shares (next, submit, close, resume, revise, run, check):
|
|
* after the locked step, run the claimed shadow with no lock held, then print SHADOW, the gate and its cost, then
|
|
* checkpoint, so a checkpoint taken at a gate holds its shadow record. A shadow failure never fails the command.
|
|
*/
|
|
async function publish(out: string, json: boolean, r: number | Report): Promise<number> {
|
|
if (typeof r === 'number') return r;
|
|
const outcome = r.claim ? await runShadow(out, r.claim) : undefined;
|
|
const line = outcome?.line ?? r.claimLine;
|
|
const state = r.gate ? readState(out) : undefined;
|
|
emit(json, [...r.head, ...(line ? [line] : []), ...(state ? gateLines(state, out) : []), ...r.tail], { ...r.payload, ...(state ? gateCostField(state, out) : {}), ...shadowField(outcome, line) });
|
|
if (r.gate) gateCheckpoint(out);
|
|
return EXIT.ok;
|
|
}
|
|
function gateCheckpoint(out: string): void {
|
|
try { withRunLock(out, () => checkpointQuietly(out), { waitMs: 30_000 }); }
|
|
catch (e: any) { process.stderr.write(`CHECKPOINT: skipped for ${out}: ${e instanceof RunError ? `${e.detail} (${e.code})` : e?.message ?? e}; the command's result stands\n`); }
|
|
}
|
|
|
|
/** Set by a command whose success is a checkpoint moment beyond rest: a bound voice, a phase transition, the first next. */
|
|
let moment: CheckpointMoment | undefined;
|
|
|
|
/** A checkpoint never changes a committed command's outcome: a failure is a stderr warning, the exit code stands. */
|
|
function checkpointQuietly(out: string): void {
|
|
try {
|
|
const line = checkpointRun(out, process.env, moment);
|
|
if (line) process.stderr.write(line + '\n');
|
|
} catch (e: any) {
|
|
process.stderr.write(`CHECKPOINT: failed for ${out}: ${e instanceof RunError ? `${e.detail} (${e.code})` : e?.message ?? e}; the command's result stands, the previous checkpoint stays current\n`);
|
|
}
|
|
}
|
|
|
|
function emit(json: boolean, lines: string[], payload: Record<string, unknown>): void {
|
|
if (json) process.stdout.write(JSON.stringify(payload) + '\n');
|
|
else process.stdout.write(lines.join('\n') + '\n');
|
|
}
|
|
|
|
function doNext(out: string, rest: string[], price?: NextOptions['price']): Report {
|
|
const cwd = process.cwd();
|
|
const initLines: string[] = [];
|
|
const fresh = !fs.existsSync(path.join(out, FILES.run));
|
|
if (!fresh) checkCeoOnlyFlags(rest, undefined, readState(out));
|
|
if (fresh) {
|
|
const plan = flag(rest, '--plan');
|
|
if (!plan) throw new RunError('RUN_NOT_INITIALIZED', `${out} has no run.json; pass --plan <file> on the first next`, 3);
|
|
const ceoOnly = checkCeoOnlyFlags(rest, path.resolve(plan), undefined, out);
|
|
const ui = rest.includes('--ui') ? true : rest.includes('--no-ui') ? false : undefined;
|
|
const maxRounds = num(rest, '--max-rounds');
|
|
if (maxRounds !== undefined && (!Number.isInteger(maxRounds) || maxRounds < 1)) throw new RunError('ARTIFACT_SCHEMA', '--max-rounds needs an integer >= 1', 1);
|
|
const carryCheckCapUsd = num(rest, '--carry-check-cap');
|
|
if (carryCheckCapUsd !== undefined && !(carryCheckCapUsd >= 0)) throw new RunError('ARTIFACT_SCHEMA', '--carry-check-cap needs a number >= 0', 1);
|
|
const shadow = shadowSwitch({ outsideEnabled: !rest.includes('--no-outside'), ceoOnly }, process.env);
|
|
if (shadow.line) initLines.push(shadow.line);
|
|
initRun({ plan, out, cwd, planHeading: flag(rest, '--plan-heading'), outsideEnabled: !rest.includes('--no-outside'), spendCap: num(rest, '--spend-cap') ?? null, maxRounds,
|
|
carryForward: !rest.includes('--no-carry-forward'), carryCheckCapUsd, ceoOnly, shadow: shadow.shadow,
|
|
deadlineMin: num(rest, '--deadline'), light: rest.includes('--light'), scaffold: rest.includes('--scaffold'), scope: { ui, developerTool: rest.includes('--developer-tool'), agentPrimary: rest.includes('--agent-primary'), dx: rest.includes('--no-dx') ? false : undefined, ...(rest.includes('--docs-only') ? { docsOnly: true } : {}) } }, initLines);
|
|
}
|
|
const redispatch = rest.flatMap((a, i) => (a === '--redispatch' && rest[i + 1] ? [rest[i + 1]!] : []));
|
|
const r = nextStep({ out, cwd, estimateUsd: num(rest, '--estimate-usd'), redispatch, price });
|
|
moment = fresh ? 'init' : r.attempts.some(a => a.new) || r.lines.some(l => l.startsWith('PHASE_DEFERRED: ')) ? 'transition' : undefined;
|
|
const status = r.state.status;
|
|
return { head: [...initLines, ...r.lines], tail: [...(status === 'running' ? [`NEXT: gstack-autoplan next --out ${out}`] : []), resultLineFor(status, out)], gate: status === 'gate_pending',
|
|
payload: { run: r.state.run, status, phase: r.phase ?? null, attempts: r.attempts, gate_rev: r.state.gate_rev ?? null, out } };
|
|
}
|
|
|
|
/** The gate pointer, its cost so far and the price of `rec` (lib/autoplan-gate-cost.ts), plus the owner-facing render to relay under Capy (lib/captain-brief.ts). */
|
|
function gateLines(state: RunState, out: string): string[] {
|
|
const relay = capyRelayLine(out);
|
|
const cost = gateCostOf(state, out);
|
|
const escalate = escalateLine(state);
|
|
return [`GATE: gate_rev=${state.gate_rev} render with: gstack-gate render ${path.join(out, 'gate.json')}`, ...(escalate ? [escalate] : []), ...(cost ? renderGateCost(cost) : []), ...(relay ? [relay] : [])];
|
|
}
|
|
function gateCostOf(state: RunState, out: string): GateCost | undefined {
|
|
const gateFile = path.join(out, 'gate.json');
|
|
if (state.status !== 'gate_pending' || !fs.existsSync(gateFile)) return undefined;
|
|
return gateCost(out, JSON.parse(fs.readFileSync(gateFile, 'utf8')), state, { defaultPerVoiceUsd: attemptEstimate(state, undefined, process.env).usd });
|
|
}
|
|
/** `gate_cost` for a JSON payload when the run sits at a gate. */
|
|
function gateCostField(state: RunState, out: string): Record<string, unknown> {
|
|
const cost = gateCostOf(state, out);
|
|
return cost ? { gate_cost: gateCostPayload(cost) } : {};
|
|
}
|
|
|
|
function doSubmit(out: string, rest: string[]): number | Report {
|
|
const phase = flag(rest, '--phase'); const voice = flag(rest, '--voice'); const result = flag(rest, '--result'); const record = flag(rest, '--record');
|
|
const model = flag(rest, '--model'); const attempt = flag(rest, '--attempt'); const unavailable = flag(rest, '--unavailable'); const failed = flag(rest, '--failed');
|
|
if (!phase || !voice) return usage('submit needs --phase and --voice');
|
|
if (voice !== 'native' && voice !== 'outside') return usage('--voice must be native or outside');
|
|
const outcome = unavailable !== undefined || failed !== undefined;
|
|
if (outcome && (voice !== 'outside' || result || record || (unavailable !== undefined && failed !== undefined))) return usage('--unavailable|--failed "<reason>" records the outside voice only, without --result or --record');
|
|
if (!outcome && (!!result === !!record || !model)) return usage('submit needs exactly one of --result <file> | --record <file>, and --model <id>');
|
|
moment = 'bound';
|
|
const r = submitResult({ out, phase, voice, result: result ? path.resolve(result) : undefined, record: record ? path.resolve(record) : undefined, model, attempt, attest: flag(rest, '--attest'),
|
|
unavailable, failed, runner: flag(rest, '--runner'), usageUsd: num(rest, '--usage-usd'), reconcile: flag(rest, '--reconcile'), cwd: process.cwd() });
|
|
const status = r.state.status;
|
|
return { head: [...r.lines], tail: [...(status === 'running' ? [`NEXT: gstack-autoplan next --out ${out}`] : []), resultLineFor(status, out)], gate: status === 'gate_pending',
|
|
payload: { run: r.state.run, status, phase, voice, attempt: r.state.phases[phase]?.[voice]?.attempt ?? attempt ?? null, closed: r.closed, findings: r.findings, gate_rev: r.state.gate_rev ?? null, out } };
|
|
}
|
|
|
|
function doRevise(out: string, rest: string[]): number | Report {
|
|
const plan = flag(rest, '--plan'); const incorporates = listFlag(rest, '--incorporates'); const withdraw = listFlag(rest, '--withdraw'); const settle = listFlag(rest, '--settle');
|
|
if (!plan && !withdraw.length && !settle.length) return usage('revise needs --plan <file> (and optionally --incorporates <id,...>), --withdraw <decision id> or --settle <id>');
|
|
if (!plan && incorporates.length) return usage('--incorporates binds accepted changes to a revised plan: pass --plan <file>');
|
|
refuseCeoOnly(readState(out), 'revise');
|
|
const r = reviseRun({ out, plan: plan ? path.resolve(plan) : undefined, incorporates, withdraw, settle, cwd: process.cwd() });
|
|
const tail = [...(r.state.status === 'running' || r.state.status === 'amend_pending' ? [nextLine(r.state, out)] : []), resultLineFor(r.state.status, out)];
|
|
return { head: [...r.lines], tail, gate: r.state.status === 'gate_pending',
|
|
payload: { run: r.state.run, status: r.state.status, reopened: r.reopened, amendments: pendingAmendments(r.state).map(a => a.decision), gate_rev: r.state.gate_rev ?? null, out } };
|
|
}
|
|
|
|
function doClose(out: string, rest: string[]): number | Report {
|
|
const phase = flag(rest, '--phase'); const reason = flag(rest, '--deferred'); const by = flag(rest, '--by');
|
|
if (!phase || !reason?.trim()) return usage('close needs --phase <p> --deferred "<reason>" --by <human|agent:<id>>');
|
|
if (by === undefined || !ANSWERED_BY_RE.test(by)) throw new RunError('ANSWER_BY_REQUIRED', `close records who deferred the phase: pass --by human or --by agent:<id> (got ${JSON.stringify(by ?? null)})`, 3);
|
|
const state = readState(out);
|
|
const ps = state.phases[phase];
|
|
if (!state.phase_order.includes(phase as Phase) || ps?.closed_at || ps?.skipped) throw new RunError('PHASE_NOT_AWAITING', `${phase} is ${ps?.skipped ? 'skipped' : ps?.closed_at ? 'already closed' : 'not a phase of this run'}`, 3);
|
|
const stopped = state.status === 'incomplete' && !!state.stop;
|
|
if (!stopped && !['running', 'awaiting_result', 'interrupted'].includes(state.status)) throw new RunError('PHASE_NOT_AWAITING', `run is ${state.status}; close works on a running or budget-stopped run`, 3);
|
|
const r = closeDeferred(state, phase as Phase, { reason: reason.trim(), by, cause: 'owner' });
|
|
moment = 'transition';
|
|
const lines = [...r.lines, ...(stopped ? liftStop(state, `${phase} closed deferred by ${by}`) : [])];
|
|
if (!currentPhase(state)) lines.push(...finishRun(state));
|
|
else { state.status = 'running'; lines.push(`NEXT: gstack-autoplan next --out ${out}`); }
|
|
writeState(state);
|
|
return { head: lines, tail: [resultLineFor(state.status, out)], gate: state.status === 'gate_pending', payload: { run: state.run, status: state.status, phase, blockers: r.blockers, gate_rev: state.gate_rev ?? null, out } };
|
|
}
|
|
|
|
/** `check`: the delta reviewer's verdict before a carry (lib/autoplan-carry.ts). */
|
|
function doCheck(out: string, rest: string[]): number | Report {
|
|
const unavailable = flag(rest, '--unavailable');
|
|
const result = flag(rest, '--result');
|
|
if (unavailable === undefined && (!result || !flag(rest, '--model'))) return usage('check needs --attempt <id> and --result <file> --model <id>, or --unavailable "<reason>"');
|
|
const r = submitCarryCheck({ out, attempt: flag(rest, '--attempt'), result: result ? path.resolve(result) : undefined, model: flag(rest, '--model'), unavailable, sameFamily: flag(rest, '--same-family') });
|
|
moment = 'transition';
|
|
const status = r.state.status;
|
|
return { head: [...r.lines], tail: [...(status === 'amend_pending' || status === 'running' ? [nextLine(r.state, out)] : []), resultLineFor(status, out)], gate: status === 'gate_pending',
|
|
payload: { run: r.state.run, status, gate_rev: r.state.gate_rev ?? null, carry: r.state.carry ?? null, out } };
|
|
}
|
|
|
|
function doBudget(out: string, rest: string[], json: boolean): number {
|
|
const state = readState(out);
|
|
const lines = changeBudget(state, { spendCap: num(rest, '--spend-cap'), maxRounds: num(rest, '--max-rounds'), by: flag(rest, '--by') });
|
|
writeState(state);
|
|
emit(json, [...lines, resultLineFor(state.status, out)], { run: state.run, status: state.status, spend_cap_usd: state.spend_cap_usd, max_rounds: state.max_rounds ?? null, out });
|
|
return EXIT.ok;
|
|
}
|
|
|
|
async function doRun(out: string, rest: string[], json: boolean): Promise<number> {
|
|
const nativeModel = flag(rest, '--native-model'); const outsideModel = flag(rest, '--outside-model');
|
|
const outsideRunner = (flag(rest, '--runner') ?? 'codex-cli') as RunnerId; const nativeRunner = (flag(rest, '--native-runner') ?? 'api') as RunnerId;
|
|
if (!nativeModel || !outsideModel) return usage('run needs --native-model and --outside-model (a runner must execute both voices)');
|
|
if (nativeRunner !== 'api') return usage('--native-runner must be api: the only runner that can execute the native voice here');
|
|
if (!['codex-cli', 'api'].includes(outsideRunner)) return usage('--runner must be codex-cli or api for run (host-subagent cannot execute here; use next/submit)');
|
|
const conflict = familyConflict(outsideModel, nativeModel);
|
|
if (conflict) throw new RunError('MODEL_FAMILY_CONFLICT', conflict, 3);
|
|
const maxTokens = num(rest, '--max-tokens');
|
|
if (maxTokens !== undefined && (!Number.isInteger(maxTokens) || maxTokens <= 0)) return usage('--max-tokens needs a positive integer');
|
|
const deadline = num(rest, '--deadline');
|
|
const deadlineAt = deadline ? Date.now() + deadline * 60_000 : undefined;
|
|
const modelOf = (voice: Voice) => (voice === 'native' ? nativeModel : outsideModel);
|
|
const isApi = (voice: Voice) => (voice === 'native' ? nativeRunner : outsideRunner) === 'api';
|
|
// An api call reserves its worst case (prompt bytes / 3 input tokens plus the output limit it is sent) and settles at its usage.
|
|
const price = (voice: Voice, promptFile: string) => {
|
|
const row = isApi(voice) ? pricingRow(modelOf(voice)) : undefined;
|
|
return row ? +((fs.statSync(promptFile).size / 3 * row.input_per_mtok + (maxTokens ?? DEFAULT_MAX_TOKENS) * row.output_per_mtok) / 1e6).toFixed(6) : undefined;
|
|
};
|
|
const usdOf = (voice: Voice, used: { input_tokens?: number; output_tokens?: number } | undefined) =>
|
|
isApi(voice) && pricingRow(modelOf(voice)) && typeof used?.input_tokens === 'number' && typeof used?.output_tokens === 'number' ? estimateCostUsd({ input: used.input_tokens, output: used.output_tokens }, modelOf(voice)) : undefined;
|
|
// Every exit after a paid call went out settles its attempt: a failure, a cancel, a refused result, or a process that died
|
|
// mid-call (sent_at, found on the next run) settles at its usage, or its reservation when the usage is unknown. Only a call
|
|
// refused before any request left this machine bills nothing, so its attempt stays open for the rerun.
|
|
const NOT_SENT = new Set(['runner_unavailable', 'cli_missing', 'model_unselected']);
|
|
for (let guard = 0; guard < 40; guard++) {
|
|
const step = withRunLock(out, () => { const r = doNext(out, rest, price); return r.gate ? claimed(out, r) : r; });
|
|
const state = readState(out);
|
|
if (state.status !== 'awaiting_result') {
|
|
const outcome = step.claim ? await runShadow(out, step.claim) : undefined;
|
|
const line = outcome?.line ?? step.claimLine;
|
|
const at = readState(out);
|
|
emit(true, [], { ...step.payload, ...gateCostField(at, out), ...shadowField(outcome, line) });
|
|
if (!json) process.stdout.write([...statusLines(at), ...(line ? [line] : []), ...(at.status === 'gate_pending' ? gateLines(at, out) : [])].join('\n') + '\n');
|
|
if (step.gate) gateCheckpoint(out);
|
|
process.stdout.write(resultLineFor(at.status, out) + '\n'); return EXIT.ok;
|
|
}
|
|
emit(true, [], step.payload);
|
|
const phase = state.phase_order.find(p => state.phases[p]?.snapshot && !state.phases[p]?.closed_at)!;
|
|
const lost = (['native', 'outside'] as const).flatMap(voice => (state.phases[phase]![voice]!.attempts ?? []).filter(a => a.state === 'dispatched' && a.sent_at).map(a => [voice, a.attempt] as const));
|
|
if (lost.length) { withRunLock(out, () => { for (const [voice, attempt] of lost) retireAttempt(out, phase as Phase, voice, attempt, 'unknown'); }); continue; }
|
|
for (const voice of ['native', 'outside'] as const) {
|
|
const v = state.phases[phase]![voice]!;
|
|
const open = v.attempts?.find(a => a.state === 'dispatched');
|
|
if (!open) continue;
|
|
const runnerId = voice === 'native' ? nativeRunner : outsideRunner;
|
|
const cost = price(voice, open.prompt);
|
|
if (cost !== undefined) withRunLock(out, () => fitReservation(out, phase as Phase, voice, open.attempt, cost));
|
|
const runner = createRunner(runnerId);
|
|
const remaining = deadlineAt ? deadlineAt - Date.now() : runnerId === 'api' ? apiTimeoutMs(maxTokens) : 300_000;
|
|
if (remaining <= 0) { withRunLock(out, () => { const s = readState(out); s.status = 'interrupted'; writeState(s); }); process.stdout.write(resultLineFor('interrupted', out) + '\n'); return EXIT.fail; }
|
|
const timer = deadlineAt ? setTimeout(() => runner.cancel(), remaining) : undefined;
|
|
withRunLock(out, () => markSent(out, phase as Phase, voice, open.attempt, true));
|
|
const res = await runner.run({ promptFile: open.prompt, outFile: `${open.result}.raw`, model: voice === 'native' ? nativeModel : outsideModel, timeoutMs: Math.min(remaining, runnerId === 'api' ? apiTimeoutMs(maxTokens) : 600_000), cwd: process.cwd(), gate: 'execution', maxTokens: runnerId === 'api' ? maxTokens ?? DEFAULT_MAX_TOKENS : maxTokens });
|
|
if (timer) clearTimeout(timer);
|
|
if (!json) process.stdout.write(`VOICE: ${phase} ${voice} ${res.status} runner=${res.runner} model=${res.model ?? 'unknown'}\n`);
|
|
const retire = () => { if (NOT_SENT.has(res.reason ?? '')) markSent(out, phase as Phase, voice, open.attempt, false); else retireAttempt(out, phase as Phase, voice, open.attempt, usdOf(voice, res.usage) ?? 'unknown'); };
|
|
if (res.status === 'cancelled') { withRunLock(out, () => { retire(); const s = readState(out); s.status = 'interrupted'; writeState(s); }); process.stdout.write(resultLineFor('interrupted', out) + '\n'); return EXIT.fail; }
|
|
if (res.status !== 'completed' && res.status !== 'unverified') {
|
|
if (voice === 'outside') { withRunLock(out, () => markOutside(out, phase as Phase, 'unavailable', `${res.runner} ${res.status}${res.detail ? `: ${res.detail}` : ''}`)); continue; }
|
|
process.stderr.write(`gstack-autoplan run: native voice ${res.status}${res.reason ? `: ${res.reason}` : ''}${res.detail ? `: ${res.detail}` : ''}\n`);
|
|
withRunLock(out, () => { retire(); const s = readState(out); s.status = 'interrupted'; writeState(s); });
|
|
process.stdout.write(resultLineFor('interrupted', out) + '\n');
|
|
return EXIT.fail;
|
|
}
|
|
const usd = usdOf(voice, res.usage);
|
|
const usage = usd === undefined ? [] : ['--usage-usd', String(usd)];
|
|
try {
|
|
const bound = withRunLock(out, () => doSubmit(out, ['--phase', phase, '--voice', voice, '--result', `${open.result}.raw`, '--model', res.model ?? modelOf(voice), '--attempt', open.attempt, '--runner', res.runner, ...usage]));
|
|
if (typeof bound !== 'number') emit(true, [], bound.payload);
|
|
}
|
|
catch (e) {
|
|
if (voice !== 'outside' || !(e instanceof RunError)) { withRunLock(out, () => { retire(); const s = readState(out); s.status = 'interrupted'; writeState(s); }); throw e; }
|
|
withRunLock(out, () => markOutside(out, phase as Phase, 'unavailable', `${res.runner} result refused: ${e.code}`));
|
|
}
|
|
}
|
|
}
|
|
return EXIT.fail;
|
|
}
|
|
|
|
/** `shadow`: the read-only export for taste-replay R2 (lib/autoplan-shadow-reader.ts). */
|
|
function doShadow(rest: string[], json: boolean): number {
|
|
const runs = flag(rest, '--runs'); const one = flag(rest, '--out');
|
|
if (!runs === !one) return usage('shadow needs --out <run dir> or --runs <file> (one run directory per line)');
|
|
const dirs = runs ? fs.readFileSync(runs, 'utf8').split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#')).map(d => path.resolve(d)) : [path.resolve(one!)];
|
|
const r = exportShadow(dirs);
|
|
for (const x of r.refused) process.stderr.write(resultLine('gstack-autoplan shadow', x.code, x.detail) + '\n');
|
|
if (json) process.stdout.write(JSON.stringify(r) + '\n'); else process.stdout.write(renderShadowExport(r).join('\n') + '\n');
|
|
return r.rows.length === 0 && r.refused.length ? EXIT.refused : EXIT.ok;
|
|
}
|
|
|
|
async function main(argv: string[]): Promise<number> {
|
|
const [cmd, ...rest] = argv;
|
|
const json = rest.includes('--json');
|
|
if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; }
|
|
if (cmd === 'contract') { process.stdout.write(COORDINATOR_CONTRACT + '\n'); return EXIT.ok; }
|
|
if (cmd === 'checkpoints') {
|
|
const from = flag(rest, '--from');
|
|
if (!from) return usage('checkpoints needs --from <checkpoint dir>');
|
|
try { process.stdout.write(checkpointLines(from).join('\n') + '\n'); return EXIT.ok; }
|
|
catch (e: any) { if (!(e instanceof RunError)) throw e; process.stderr.write(resultLine('gstack-autoplan checkpoints', e.code, e.detail) + '\n'); return EXIT.refused; }
|
|
}
|
|
const outFlag = flag(rest, '--out');
|
|
if (!outFlag && cmd !== 'shadow') return usage(`${cmd} needs --out <dir>`);
|
|
const out = path.resolve(outFlag ?? '.');
|
|
try {
|
|
if (cmd === 'shadow') return doShadow(rest, json);
|
|
if (cmd === 'next') return await publish(out, json, mutating(out, json, () => doNext(out, rest)));
|
|
if (cmd === 'submit') return await publish(out, json, mutating(out, json, () => doSubmit(out, rest)));
|
|
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 === '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') {
|
|
const state = readState(out);
|
|
if (json) process.stdout.write(JSON.stringify(state) + '\n'); else process.stdout.write(statusLines(state).join('\n') + '\n');
|
|
return EXIT.ok;
|
|
}
|
|
if (cmd === 'resume') {
|
|
const from = flag(rest, '--from');
|
|
const restored = from !== undefined ? restoreCheckpoint(from, out) : [];
|
|
return await publish(out, json, withRunLock(out, () => {
|
|
const r = resumeRun(out);
|
|
return claimed(out, { head: [...restored, ...r.lines], tail: [resultLineFor(r.state.status, out)], gate: r.state.status === 'gate_pending',
|
|
payload: { run: r.state.run, status: r.state.status, execution_unknown: r.unknown, rebound: r.rebound, out } });
|
|
}, { steal: true }));
|
|
}
|
|
if (cmd === 'answer') {
|
|
const rev = flag(rest, '--gate-rev'); const reply = flag(rest, '--reply'); const by = flag(rest, '--by');
|
|
if (reply === undefined) return usage('answer needs --reply "<text>"');
|
|
if (rev === undefined) { const s = readState(out); refuseCeoOnly(s, 'answer'); process.stderr.write(resultLine('gstack-autoplan answer', 'GATE_REV_STALE', `no --gate-rev given; current gate_rev=${s.gate_rev ?? 0}`) + '\n'); return EXIT.refused; }
|
|
const replyFile = flag(rest, '--owner-reply-file'); const ownerFlag = flag(rest, '--owner-reply');
|
|
if (replyFile !== undefined && ownerFlag !== undefined) return usage('--owner-reply and --owner-reply-file are exclusive');
|
|
const wordsBy = flag(rest, '--words-by') ?? 'owner';
|
|
if (wordsBy !== 'owner' && (wordsBy !== by || !by.startsWith('agent:'))) return usage(`--words-by must be owner or the answering agent (--by ${by ?? '<unset>'}), got ${wordsBy}`);
|
|
const ownerReply = replyFile !== undefined ? fs.readFileSync(replyFile, 'utf8') : ownerFlag === '-' ? fs.readFileSync(0, 'utf8') : ownerFlag;
|
|
const shadowLines = await shadowBeforeAnswer(out);
|
|
if (shadowLines.length) (json ? process.stderr : process.stdout).write(shadowLines.join('\n') + '\n');
|
|
return await publish(out, json, mutating(out, json, () => {
|
|
const state = readState(out);
|
|
refuseCeoOnly(state, 'answer');
|
|
const r = answerGate(state, Number(rev), reply, by, { recHash: flag(rest, '--rec-hash'), ownerReply, ...(wordsBy === 'owner' ? {} : { wordsBy }) });
|
|
writeState(state);
|
|
const lines = [...r.lines];
|
|
if (r.outcome === 'reopened' || r.outcome === 'amend_pending') lines.push(nextLine(state, out));
|
|
lines.push(resultLineFor(state.status, out));
|
|
emit(json, lines, { run: state.run, status: state.status, outcome: r.outcome, pending: r.pending, reopened: r.reopened, amendments: pendingAmendments(state).map(a => a.decision), gate_rev: state.gate_rev, out });
|
|
return EXIT.ok;
|
|
}));
|
|
}
|
|
if (cmd === 'recommend') {
|
|
const rev = flag(rest, '--gate-rev'); const item = flag(rest, '--item'); const option = flag(rest, '--option'); const basis = flag(rest, '--basis');
|
|
if (rev === undefined || !item || !option || !basis?.trim()) return usage('recommend needs --gate-rev <n> --item <id> --option <k> --basis "<why>"');
|
|
return await publish(out, json, mutating(out, json, () => {
|
|
const state = readState(out);
|
|
refuseCeoOnly(state, 'recommend');
|
|
const lines = recommendGate(state, Number(rev), item.toLowerCase(), option.toLowerCase(), basis.trim(), flag(rest, '--by') ?? 'parent');
|
|
writeState(state);
|
|
emit(json, [...lines, resultLineFor(state.status, out)], { run: state.run, status: state.status, gate_rev: state.gate_rev, out });
|
|
return EXIT.ok;
|
|
}));
|
|
}
|
|
if (cmd === 'export' && flag(rest, '--public') !== undefined) {
|
|
return withRunLock(out, () => {
|
|
const r = exportPublic(readState(out), path.resolve(flag(rest, '--public')!));
|
|
for (const w of r.warnings) process.stderr.write(w + '\n');
|
|
emit(json, r.files.map(f => `EXPORTED_PUBLIC: ${f}`), { files: r.files, warnings: r.warnings });
|
|
return EXIT.ok;
|
|
});
|
|
}
|
|
if (cmd === 'export') {
|
|
return await publish(out, json, mutating(out, json, () => {
|
|
const state = readState(out);
|
|
const pending = pendingAmendments(state).map(a => a.decision);
|
|
if (state.status === 'complete' && pending.length) throw new RunError('PLAN_AMEND_PENDING', `run says complete with accepted changes not in the plan: ${pending.join(', ')}`, 3);
|
|
const r = exportRun(state);
|
|
writeState(state);
|
|
for (const w of r.warnings) process.stderr.write(`gstack-autoplan export: ${w}\n`);
|
|
emit(json, [...r.files.map(f => `EXPORTED: ${f}`), dispatchLine(state)], { run: state.run, files: r.files, warnings: r.warnings, dispatches: state.dispatches, est_input_tokens: state.est_input_tokens });
|
|
return EXIT.ok;
|
|
}));
|
|
}
|
|
if (cmd === 'release') {
|
|
const attempt = flag(rest, '--attempt');
|
|
if (!attempt) return usage('release needs --attempt <id>');
|
|
const ledger = release(path.join(out, FILES.spend), attempt);
|
|
process.stdout.write(`RELEASED: ${attempt} reserved=${ledger.reserved.length}\n`);
|
|
return EXIT.ok;
|
|
}
|
|
return usage(`unknown command ${cmd}`);
|
|
} catch (e: any) {
|
|
if (e instanceof RunError) {
|
|
process.stderr.write(resultLine(`gstack-autoplan ${cmd}`, e.code, e.detail) + '\n');
|
|
if (e.after.lines?.length) process.stdout.write(e.after.lines.join('\n') + '\n');
|
|
if (['next', 'submit', 'answer', 'resume', 'run', 'revise', 'recommend', 'close', 'budget', 'check'].includes(cmd)) process.stdout.write(resultLineFor(e.after.status ?? 'refused', out) + '\n');
|
|
return e.exit === 3 ? EXIT.refused : EXIT.fail;
|
|
}
|
|
process.stderr.write(`gstack-autoplan ${cmd}: ${e?.message ?? e}\n`);
|
|
return EXIT.fail;
|
|
}
|
|
}
|
|
|
|
process.exitCode = await main(process.argv.slice(2));
|