Autore: Donato Pepe Licenza: MIT
Stagewarden is a production-grade CLI coding agent for controlled software delivery, with Codex-style agent loops, multi-model routing, PRINCE2-aligned governance, structured traces, and safe file/shell execution.
Italian documentation: see README_IT.md. Architecture and trust boundaries: docs/architecture.md.
Agent policy artifacts:
AGENT_MANIFESTO.md: short operating manifestoAGENT_POLICY.md: formal human-readable policyAGENT_POLICY.json: machine-readable policy baselineAGENTS.md: multi-agent startup and handoff protocolAGENT_HANDOFF.md: compatibility handoff for Codex CLI, Kilo CLI, and human maintainers
Caratteristiche principali:
- iterative agent loop
- planner and executor split
- model routing and escalation
RUN_MODEL:handoff execution- persistent PRINCE2 project handoff context with implicit resume
- declarative permission policy with workspace settings and session modes
- shell, file, and git tools
- cross-platform shell execution on macOS, Linux, and Windows
- governed external IO: web search, HTTP/HTTPS download, checksum evidence, gzip compression, and archive verification
- local stub support for smoke tests
Install locally:
python3 -m pip install -e .Local OmniRoute with free models:
export RUN_MODEL_BIN="$PWD/scripts/run_model_omniroute.py"
export STAGEWARDEN_OMNIROUTE_MODEL="auto/coding:free"
./scripts/test_omniroute_free.sh
stagewarden agent "inspect this repository and propose the next safe change"Adapter defaults to http://127.0.0.1:20128/v1 and keeps external credentials outside repository. Override endpoint with OMNIROUTE_BASE_URL. Verified free local routes include auto/coding:free, auto/best-free, and coding-free-fallback. Paid/pro routes stay outside automated tests unless explicitly requested.
Prerequisites:
- Python 3.11+
- Git installed and available in
PATH
Git is mandatory. Stagewarden initializes a repository automatically when needed and commits local snapshots of agent actions.
Git behavior:
- If the workspace has no
.git, Stagewarden runsgit initautomatically. - Runtime files are added to
.gitignore. - Stagewarden creates local commits for workspace snapshots during agent execution.
- If
gitis missing, the agent refuses to start.
Permissions behavior:
- Stagewarden now supports a workspace permission file:
.stagewarden_settings.json - The policy supports:
defaultModeallowaskdeny
- Supported modes:
defaultaccept_editsplanautodont_ask
planblocks mutating shell and file operations.dont_askdenies mutating operations unless explicitly allowed.askrules currently fail closed in the CLI and require an explicit allow rule.
Minimal example:
{
"permissions": {
"defaultMode": "plan",
"allow": ["shell:git status"],
"ask": ["file:secrets.txt"],
"deny": ["shell:rm"]
}
}PRINCE2 handoff behavior:
- Stagewarden treats handoff as the live project context, not as an optional resume command.
- Stagewarden applies PRINCE2 adaptively: small tasks use the lightest viable governance, while complex or risky work increases staged control, validation evidence, and formal checkpoints.
- The agent does not drop PRINCE2 principles on small tasks; it reduces ceremony, not control intent.
- The agent plans in the handoff context, executes one controlled action, updates the same handoff, and records the current
git HEAD. - The handoff file is persisted as
.stagewarden_handoff.json. - Resume is implicit: each new run inherits the latest project handoff context for the workspace.
- The executor prompt always includes the current project handoff summary, so planning and execution stay aligned to the same controlled context.
- PRINCE2 role automation scopes model context by role: Project Manager sees control context, Team Manager sees only the current work package/product-delivery domain, Project Assurance sees validation/risk/issue/quality evidence, Change Authority sees exception/change/tolerance context, and Project Executive sees business justification and stop-go context.
project start,roles setup, androle configure [role]assign provider, provider-model, reasoning parameters, and account per PRINCE2 role.roles domainsshows the PRINCE2 responsibility and context boundary for each role before assigning models.roles tree approvepersists the current PRINCE2 organization tree as the approved role-tree baseline in.stagewarden_models.jsonand.stagewarden_handoff.json.roles baselineshows the approved tree baseline used for future role-routed context handoffs.roles baseline matrixshows the approved baseline matrix, including delegated nodes plus reviewer/fallback route pools.project briefshows the structured project brief stored in runtime handoff; useproject brief set <field> <value>andproject brief clear [field]to manage it.project designshows the pre-design packet that future AI-assisted PRINCE2 tree planning must receive: agent capabilities, current project specification, and any clarification gaps.project tree proposecreates a review-only proportional PRINCE2 organization-tree proposal from the structured project brief;project tree propose --aiasks an available model for additional validated tree patches throughRUN_MODELwhile still avoiding persistence until approval.project tree approvepersists the reviewed proposal as the approved baseline; it blocks open clarification gaps unlessproject tree approve --forceis used.project startnow runs the controlled startup gate: design packet, proportional tree proposal, and approval. It blocks unresolved clarification gaps instead of silently applying the static baseline;project start --aiforces AI-assisted tree proposal before approval.role add-childopens a guided menu, orrole add-child <parent_node> <role_type> [node_id]adds delegated/subordinate PRINCE2 nodes to the approved tree.role assignopens a guided menu, orrole assign <node_id> <provider> <provider_model> [reasoning_effort=<value>] [account=<name>] [pool=<primary|reviewer|fallback>]assigns primary, reviewer, or fallback provider-model routes to a specific role-tree node.- Role-routed model prompts include the active PRINCE2 flow edges, payload scopes, and validation conditions so fallback routing cannot silently widen role context.
stagewarden handoff --jsonandstagewarden "resume --show" --jsonexpose the same runtime state for automation.handoff actionsshows durable action/audit entries recorded in runtime handoff;handoff actions 50 --jsonexposes the same history for tooling.stagewarden status --jsonandstagewarden boundary --jsonexpose operational posture and boundary control state for automation.status,status --json, andstatusline --jsonsurface the latest durable handoff action so the user can immediately see the most recent tracked operation.status --json,statusline --json,overview --json,health --json,preflight --json,report --json,handoff --json,boundary --json, andboard --jsoninclude versionedschemablocks so other agents can validate the payload contracts explicitly.- Those schema blocks are centralized in
stagewarden/json_schema_registry.py, which now covers the stable JSON CLI surfaces for status, help, commands, catalog, goal, models, git, sessions, and the register views. statusandstatus --jsonexpose the active pricing source for the current routed model, so you can see whether pricing came fromopenrouter,artificial_analysis, or the local fallback path.statusline --jsonalso exposes token/context-window usage when a provider returns safe usage metadata.statusandstatus --jsonnow also expose current multiprovider limit posture: model lockouts, blocked accounts, classified provider lockout reason, last known provider message, and latest routed success/failure context.stagewarden board --jsonorstagewarden "stage review" --jsonexposes the PRINCE2 board-level authorization recommendation.stagewarden overview --jsonaggregates status, board review, handoff, transcript, model-usage signals, and provider-limit posture into a single machine-readable snapshot.stagewarden health --jsonexposes a compact readiness snapshot for automation: authorization, boundary decision, open controls, recovery state, and minimal model/transcript signals.stagewarden report --jsonexposes a compact closure/shareable summary with governance state, next action, recent lessons, backlog preview, model activity, and provider-limit posture.stagewarden risks|issues|quality|exception|lessons|todo --jsonexposes PRINCE2 registers and backlog in machine-readable form.risks close <resolution>,issues close <resolution>, andquality close <resolution>close open governance records after explicit mitigation or acceptance.- The executor prompt includes only the PRINCE2 registers allowed by the active role domain, preventing a role-specific model from seeing unrelated governance context by default.
- The planner also reuses those registers to shape the next active step, so resumed work carries forward open risks, issues, quality evidence, lessons, and exception actions.
handoffshows the full persisted project context, whileboundaryshows only the current PRINCE2 stage-boundary recommendation.boundarynow blocks closure when open issues remain and prefers an explicit exception-path decision when an exception plan is active.- On controlled project closure, Stagewarden now closes remaining open issues and risks and clears the exception plan when the project has recovered.
- On controlled project closure, Stagewarden also finalizes quality evidence by marking remaining quality entries as accepted.
boundaryandhandoffnow show both register counts and register closure state, so you can see open vs closed risks/issues and open vs accepted quality evidence.- The final agent summary now includes a governance status line that tells you whether closure is
cleanor still has residual open controls. - The interactive
statusandhandoffviews now include the same governance status line for consistency with the final agent summary. - The interactive
statusandhandoffviews also show the current boundary decision directly, so you can see status plus control decision without switching toboundary. - The interactive
statusandhandoffviews now also show the active stage in compact form. - The interactive
statusandhandoffviews now also show the compact git boundary (baseline HEAD vs current HEAD). - The interactive views now also show a compact
stage healthindicator such asactive,at_risk,exception, orready_to_close. - The interactive views now also show a compact
next actionrecommendation derived from the boundary decision and current stage state. - The final summary,
status, andhandoffnow reuse the same compactoperational postureblock so the high-level reading stays consistent across views. help agentdocuments the multi-agent startup/handoff protocol, including wet-run validation and synchronized handoff files.
Validation behavior:
- Every implementation must include relevant verification checks or tests.
- Dry-runs are not valid completion checkpoints by themselves.
- Steps close only with wet-run evidence such as executed tests, real commands, observed files, or real tool output.
- If the obvious wet-run is blocked, Stagewarden must find another feasible wet-run instead of accepting dry-run completion.
Quick setup:
macOS/Linux:
sh setup.shWindows PowerShell:
.\setup.ps1Platform-specific setup scripts:
sh scripts/setup_macos.sh
sh scripts/setup_linux.sh.\scripts\setup_windows.ps1If editable installation cannot download build dependencies, setup falls back to a source launcher in the user bin/Scripts directory. The stagewarden command still runs from the checked-out repository through PYTHONPATH.
Prerequisite check:
stagewarden doctor
stagewarden doctor --json
stagewarden health
stagewarden health --json
stagewarden report
stagewarden report --json
stagewarden "sources status"
stagewarden "sources status" --json
stagewarden "sources status --strict" --json
stagewarden "update status"
stagewarden "update check --json"doctor validates Python 3.11+, Git availability, PATH launcher visibility, repository state, and provider capabilities/token env expectations without installing anything or initializing git. Use stagewarden doctor --json for machine-readable automation output.
health is the compact operational variant for scripts and dashboards when overview is too broad and board is not enough.
Governed external IO:
stagewarden "web search Stagewarden coding agent"
stagewarden "download https://example.com/file.txt artifacts/file.txt --max-bytes 1048576"
stagewarden "checksum artifacts/file.txt"
stagewarden "compress artifacts/file.txt"
stagewarden "archive verify artifacts/file.txt.gz"External IO is intentionally constrained: only HTTP/HTTPS downloads are allowed, output paths must stay inside the workspace, downloads have a byte limit, and every successful operation records checksum/evidence in the tool transcript and handoff actions.
Self-update governance:
stagewarden "update status"
stagewarden "update check --json"
stagewarden "update apply --yes"update apply is fast-forward only, requires explicit --yes, refuses dirty working trees, and records before/after evidence in handoff actions.
Extension scaffolds:
stagewarden "extension scaffold local-tools"
stagewarden "extensions" --jsonExtensions live under .stagewarden/extensions/<name>/ with commands/, roles/, skills/, hooks/, and mcp/ folders plus extension.json. The scaffold writes schema_version, entrypoints, and execution=disabled-by-default. Discovery is read-only, validates manifest shape and entrypoint paths, reports missing entrypoint directories, and never executes extension code.
report is the shareable operator summary for issue updates, project closure notes, or quick GitHub-ready status text.
sources status verifies local third-party reference clones by path, upstream URL, HEAD, and shallow-clone state without reading or vendoring their source content.
Shell execution:
- macOS/Linux use
bashwhen available, otherwisesh. - Windows uses PowerShell when available, otherwise
cmd. - Shell sessions are persistent within an agent run and constrained to the workspace.
Run:
stagewarden "create a file named hello.txt"Interactive shell:
stagewardenOn terminals with readline support, the shell also keeps a per-workspace history in .stagewarden_history and enables TAB completion for core commands plus selected workspace-path commands such as git history and patch preview.
During interactive task execution, Stagewarden now also forwards live run_model stdout into the shell with compact prefixes such as [model-stream local], while still parsing the final JSON response normally.
Use stream on, stream off, or stream status inside the shell to control this behavior per session.
Task execution is visually split into Running task: ... and Agent result: so the live model stream stays distinct from the final agent summary.
The interactive shell also emits a compact Shell progress (before|after) block with active step, stage health, boundary decision, recovery state, and current git head.
These mini-blocks now also show the planned route before execution and the actual route after execution: model, account, and variant.
The after block also shows the latest local git checkpoint created during the run, so the shell immediately exposes the snapshot just recorded.
Between the full agent summary and the final progress block, the shell now also shows a focused Last step outcome: section with step id, action, status, route, and observed result.
That block now also exposes the concrete evidence source used for the last step, including tool name, tool action, and duration when available.
handoff export and handoff md now also include an Execution Resume Context block in HANDOFF.md with the latest model attempt, route, tool evidence, and git snapshot so resume stays implicit and auditable.
Inside the shell:
stagewarden> /help
stagewarden> /help models
stagewarden> /slash
stagewarden> /slash mo
stagewarden> /help handoff
stagewarden> /models
stagewarden> /model limits
stagewarden> /patch preview changes.diff
stagewarden> /model use openai
stagewarden> /model choose
stagewarden> /model choose chatgpt
stagewarden> /model preset chatgpt
stagewarden> /model list claude
stagewarden> /model variant claude opus
stagewarden> /model variant openai gpt-5.4-mini
stagewarden> /model block openai until 2026-05-01T18:30
stagewarden> /model limit-record chatgpt You've hit your usage limit. Try again at 8:05 PM.
stagewarden> /model limit-clear chatgpt
stagewarden> /model unblock openai
stagewarden> /status
stagewarden> /health
stagewarden> /report
stagewarden> /stream status
stagewarden> /stream off
stagewarden> /boundary
stagewarden> /risks
stagewarden> /issues
stagewarden> /quality
stagewarden> /exception
stagewarden> /lessons
stagewarden> /transcript
stagewarden> /todo
stagewarden> /permissions
stagewarden> /permission mode plan
stagewarden> /permission session mode auto
stagewarden> /permission allow shell:git status
stagewarden> /permission session allow shell:python3 -m pytest
stagewarden> /mode plan
stagewarden> /mode auto
stagewarden> /mode accept-edits
stagewarden> /mode dont-ask
stagewarden> /mode default
stagewarden> /mode caveman ultra
stagewarden> /mode normal
stagewarden> /caveman on ultra
stagewarden> fix failing tests
stagewarden> /quit
Interactive shell rule: commands start with /. Any input without / is sent to the agent as a task.
Interactive help is topic-based: /help shows compact categories, while /help models, /help accounts, /help permissions, /help handoff, /help git, /help caveman, and /help ljson show focused command examples.
Slash UX:
/slash [prefix]shows a Codex/Claude-style command palette with descriptions and workspace-aware hints./slash choose [query]opens a portable guided chooser and returns the selected command without executing it.stagewarden "slash mo" --jsonexposes the same palette as structured data for automation.- Slash search also uses fuzzy/example matching, so prompts such as
slash scaricaorslash upgrade stagewardencan discover the relevant command even when the text does not match the command name exactly. - Slash completion suggests contextual values, including providers, PRINCE2 roles, shell backends, configured account names, provider-model IDs, and
reasoning_effortvalues. - The palette includes operational hints such as enabled providers, active accounts, blocked providers, provider-model examples, and supported parameters.
Model control:
modelsshows enabled, active, preferred, blocked, and backend state.stagewarden models --jsonexposes the same model routing state in machine-readable form.models usageorcostshows persisted model call counts, failures, step coverage, cost tiers, and the routing budget policy.stagewarden "models usage" --jsonemits the same data in machine-readable form.model limitsormodels limitsshows persisted provider/account limit snapshots, reset time, reason, window, and utilization when known.stagewarden "model limits" --jsonemits the same limit snapshot in machine-readable form.model use <local|cheap|chatgpt|openai|claude>pins a preferred model.model choose [provider]opens a guided menu in the interactive shell to choose provider, provider-model, and supported parameters.model preset <provider>without the preset value opens the guided provider-model picker in the interactive shell.- Guided model menus show current provider context before prompting: enabled providers, preferred provider, active accounts, blocked providers, current provider-model, current reasoning effort, and configured accounts.
model add <local|cheap|chatgpt|openai|claude>enables a model.model list <provider>shows the official aliases or model IDs and provider capabilities for that provider.model params <provider>shows supported and current provider-model parameters such asreasoning_effort.model variant <provider> <variant>pins a provider-specific model alias or model ID.model variant-clear <provider>clears the variant override and returns to the provider default.model preset <provider> <fast|balanced|deep|plan>applies a simplified preset that chooses both provider-model and reasoning level.model param set <provider> reasoning_effort <low|medium|high>persists provider-model parameters when supported.model param clear <provider> reasoning_effortclears the persisted parameter override.model remove <local|cheap|chatgpt|openai|claude>disables a model.model block <model> until YYYY-MM-DDTHH:MMblocks a model until a date and time.model limit-record <model> <provider message>stores a pasted provider limit message as a sanitized snapshot and blocks the model when a reset time is detected.model limit-clear <model>clears the stored limit snapshot, message, and temporary block.model unblock <model>removes a temporary block.model clearrestores automatic routing.catalog refreshregenerates the shared model catalog snapshot from OpenRouter-backed discovery.catalog refresh --aaexplicitly includes Artificial Analysis pricing refresh whenSTAGEWARDEN_ARTIFICIAL_ANALYSIS_API_KEYis available.- The GitHub Actions workflow
Refresh AI Model Catalogruns the same refresh path and can pick up the Artificial Analysis API key from repository secrets. - A documented example workspace settings file lives in
examples/stagewarden_settings.example.json. account login chatgpt <profile>follows the Codex-style browser flow and opens the browser automatically.account login openai <profile>keeps the Stagewarden device-code/API-oriented flow.account login-device <chatgpt|openai> <profile>forces the explicit device-code flow.
Provider model selection is aligned to public provider behavior:
openaiandchatgptaccept explicit OpenAI model IDs such asgpt-5.4,gpt-5.4-mini,gpt-5.3-codex,gpt-5.2-codex,gpt-5.1-codex, andcodex-mini-latest.claudeaccepts Claude Code style aliases such asdefault,sonnet,opus,haiku,sonnet[1m], andopusplan.- Stagewarden passes the selected variant to the backend via
STAGEWARDEN_MODEL_VARIANTand the provider-native env var such asOPENAI_MODELorANTHROPIC_MODEL. - Provider auth capabilities live in
stagewarden/provider_registry.py: ChatGPT plan login is separate from OpenAI API-key profiles, Claude can use API keys or imported Claude Code credentials, and Stagewarden does not scrape hidden browser tokens. role configure [role]shows PRINCE2 role responsibility and context scope before provider/model/account assignment.- If no variant is pinned, Stagewarden now selects one automatically from task complexity:
claude: prefershaikufor simple tasks,sonnetfor normal coding,opusfor harder debugging, andopusplanfor explicit planning/design work.openai: prefersgpt-5.4-minifor light work,gpt-5.2-codexfor normal coding, andgpt-5.4for harder debugging or risky changes.chatgpt: preferscodex-mini-latestfor light work,gpt-5.1-codex-minifor standard execution, andgpt-5.3-codexfor harder debugging sessions.
Stagewarden also records online model usage-limit messages such as try again at 8:05 PM and automatically blocks that model until the reported local time.
Project handoff:
- The human-readable implementation handoff lives in
HANDOFF.md. - Runtime handoff remains in
.stagewarden_handoff.json;HANDOFF.mdtracks the durable roadmap and Codex/Claude-inspired implementation backlog. - Use
handoff exportorhandoff mdto update the generated runtime section inHANDOFF.mdfrom the current runtime handoff. stagewarden "handoff export" --jsonandstagewarden "resume --clear" --jsonexpose structured operational results for export/reset workflows.- Every model prompt includes bounded references to
.stagewarden_handoff.json,.stagewarden_memory.json, and.stagewarden_trace.ljson, plus recovery state, backlog status, git boundary, and dirty state. resume --showpreviews the current handoff target,resume --cleararchives and resets handoff, andresumereruns the task stored in handoff after reloading the context.- When the shell starts with a suspended
waitingsession, it auto-resumes the saved task before accepting new input. resume contextshows the latest implicit execution context: last model attempt, routed account/variant, tool evidence, and latest git snapshot.
Tool transcript:
transcriptortraceshows recent tool invocations from workspace memory.stagewarden transcript --jsonemits the recent tool transcript in machine-readable form.stagewarden accounts --jsonexposes configured provider profiles, active account, token-store state, and env mapping.- Transcript entries are persisted in
.stagewarden_memory.jsonusing LJSON.
Persistent shell sessions:
sessionsorsession listshows active shell sessions for the current Stagewarden process.stagewarden sessions --jsonexposes active shell sessions for the current Stagewarden process in machine-readable form.session create [cwd]starts a persistent shell in the workspace or a relative directory.session send <id|last> <command>runs one command in that session and returns marker-based output with exit code.session close <id|last>closes the session.- Permission checks are applied to every
session sendcommand; session IDs are not persisted to the repository.
Patch workflow:
- Model actions can use
preview_patch_filesto validate a unified multi-file diff and get a per-file summary without writing. - Interactive shell users can run
patch preview <diff-file>to validate a unified diff file without writing. patch_filesapplies the same unified diff format and reportsadd,update, anddeleteentries per path.- Duplicate targets in the same diff are rejected before writes, preventing ambiguous multi-hunk edits.
- In
planmode patch preview is allowed, while actual file writes remain blocked.
Model action schema:
- Model responses may use the strict schema
{summary, confidence, risks, validation, action}. - Simpler legacy responses with
{summary, action}remain valid. - Unknown destructive action types are denied before tool execution.
Interactive permission commands:
permissionsshows the active workspace permission settings.stagewarden permissions --jsonexposes workspace, session, and effective permission policy in machine-readable form.permission mode <default|accept_edits|plan|auto|dont_ask>changes the workspace default permission mode.permission session mode <default|accept_edits|plan|auto|dont_ask>changes the permission mode only for the current shell session.permission allow <rule>adds an allow rule.permission ask <rule>adds an ask rule.permission deny <rule>adds a deny rule.permission session allow <rule>,permission session ask <rule>, andpermission session deny <rule>add temporary session-only rules.permission session resetclears all session permission overrides.permission resetresets the workspace permission file to defaults.mode plan|auto|accept-edits|dont-ask|defaultis a fast alias for changing the workspace permission mode.- Interactive
askprompts supporty,n,always,session, anddeny; autonomous/non-interactive tool execution remains fail-closed. - Shell permission classification distinguishes read-only git inspection from mutating git, redirection, package install, and other write/high-risk commands.
Handoff tracking:
handoffnow includes the persisted implementation backlog alongside stage posture, registers, and git boundary context.todoprints the current implementation backlog derived from the active PRINCE2 plan and kept in sync while the agent runs.- The handoff backlog now uses normalized lifecycle states:
planned,ready,in_progress,blocked, anddone. blockedbacklog items surface alongside exception handling so the shell can distinguish a blocked stage from a clean ready queue.- The planner now promotes the first executable stage to
ready, keeps later stages asplanned, and the agent loop only starts stages that arereadyor alreadyin_progress. - When a stage completes under control, the next
plannedstage is promoted automatically toready. - When a project enters
exceptionwith an active exception plan, the planner now injects an explicit recovery lane asrecovery-step-*stages instead of only retrying the failed stage inline. - Recovery stages participate in the same lifecycle gates and can be resumed from persisted handoff context like any other stage.
- The handoff boundary view now reports
recovery_stateasexception_active,recovery_active,recovery_cleared, ornone. recovery_activedrives the next action toward executing recovery stages;recovery_cleareddrives cleanup of exception controls before normal execution resumes.- Completed recovery lanes now close the recovery gate by clearing exception controls, closing open issues/risks with wet-run evidence, and resuming the next normal stage.
Account profiles:
Stagewarden can keep multiple account profiles for the same provider. Secrets are not stored in the repository or model config; profiles store only the environment variable name that already contains the token.
stagewarden> account login chatgpt personale
stagewarden> account add openai lavoro OPENAI_API_KEY_WORK
stagewarden> account add openai personale OPENAI_API_KEY_PERSONAL
stagewarden> account login openai lavoro
stagewarden> account use openai lavoro
stagewarden> account choose
stagewarden> account choose openai
stagewarden> account block openai lavoro until 2026-05-01T18:30
stagewarden> account unblock openai lavoro
stagewarden> accounts
Runtime behavior:
chatgptis a provider distinct fromopenai.chatgptexpects a ChatGPT session token and maps it toCHATGPT_TOKENfor the backend subprocess.- Stagewarden calls
RUN_MODEL: openai:lavoro <prompt>internally. - For ChatGPT plan access it calls
RUN_MODEL: chatgpt:personale <prompt>internally. - The external
run_modelcommand still receivesrun_model openai "<prompt>". - For ChatGPT plan access the external command receives
run_model chatgpt "<prompt>". - Stagewarden sets
STAGEWARDEN_MODEL_ACCOUNT=lavoroandSTAGEWARDEN_MODEL_TARGET=openai:lavoro. - If
OPENAI_API_KEY_WORKexists, Stagewarden maps it toOPENAI_API_KEYonly for that subprocess. account login <model> <profile>starts provider login and saves credentials in macOS Keychain when available. Forchatgptandopenai, Stagewarden uses a Codex-style device-code OAuth flow.- If no environment variable mapping exists, Stagewarden loads the saved profile token and maps it to the provider env var only for the subprocess.
chatgptandopenaistore OAuth-style credential payloads, not a copy-pasted browser token.- For
chatgptandopenai,account login <profile>follows the Codex-style account flow using device authorization and token exchange. - For providers like
claude, interactive browser callback login is disabled; useaccount envwith the provider's official API key or credentials. - If one account reports a usage limit, Stagewarden blocks that account until the reported time and retries another account for the same model before falling back to another model.
Git history commands:
stagewarden> git status
stagewarden> git log 10
stagewarden> git history stagewarden/main.py 20
stagewarden> git show --stat HEAD
stagewarden "git status" --json, stagewarden "git log 10" --json, stagewarden "git history path 10" --json, and stagewarden "git show --stat HEAD" --json expose read-only repository inspection in machine-readable form.
The autonomous executor can also call git_status, git_log, git_show, and git_file_history as first-class tool actions when it needs to inspect modification history before deciding or changing code.
Caveman mode:
stagewarden> status
stagewarden> mode caveman ultra
stagewarden> mode normal
stagewarden> caveman help
stagewarden> caveman on ultra
stagewarden> caveman review
stagewarden> caveman commit
stagewarden> caveman compress notes.md
stagewarden> caveman off
Stagewarden includes a hierarchical multi-node goal loop system under the goal loop command family.
stagewarden> goal loop <task>
stagewarden> goal loop <task> --json
stagewarden> goal loop run <task>
stagewarden> goal loop run <task> --json
stagewarden> goal loop status
stagewarden> goal loop status --json
stagewarden> goal loop add-node <name> <skill_path> [purpose]
stagewarden> goal loop add-node <name> <skill_path> [purpose] --json
stagewarden> goal loop custom-nodes
stagewarden> goal loop custom-nodes --json
goal loop <task>: generates a blueprint with scope, node graph, child prompts, execution order, tolerance matrix, exception policy, validation plan, and final report.goal loop run <task>: executes the multi-node loop with dependency resolution, parallel fan-out, structured messaging, autonomy gates, and tolerance checks.goal loop status: shows current loop execution state from handoff entries.goal loop add-node <name> <skill_path>: registers a custom goal loop node from an extension skill file.goal loop custom-nodes: lists registered custom goal loop nodes.
Set via STAGEWARDEN_GOAL_LOOP_EXECUTION_MODE environment variable:
mock— deterministic canned responses for testingauto(default) — trypi --print, fall back to mock if unavailablepi— require real AI-powered node execution viapiCLI
- 8 nodes in dependency order:
root.scope→orchestrator.graph→subnode.generator→implementation.refactor→validation.wet_run→governance.tolerance→communication.bridge→learning.pi - Each node sends structured messages (FROM/TO/TYPE/SUMMARY/PRIORITY/TOLERANCE IMPACT) via in-memory MessageBus.
- Autonomy gate classifies decisions (low/medium/high risk) and prompts user interactively for high-risk choices.
- Tolerance gate checks execution results against declared tolerances and marks nodes as blocked on violation.
- Handoff recording persists every node status change with full details.
When goal loop run executes, a TCP control socket is started on 127.0.0.1:<random port>.
The port is written to .stagewarden/goal_loop_control.txt for external discovery.
External tools can send structured messages (matching node-communication.md format) to inject decisions,
dependency updates, or blockers into the running loop:
from stagewarden.goal_loop_control import send_control_message, discover_control_port
port = discover_control_port(workspace_root)
if port:
send_control_message(port, {
"FROM": "external.tool",
"TO": "root.scope",
"TYPE": "decision",
"SUMMARY": "User approved the scope.",
"PRIORITY": "high",
})Prompt templates live under .pi/prompts/ and follow pi prompt-template format with YAML frontmatter.
Templates used:
goal-root.md— root scope definitiongoal-loop-orchestrator.md— graph decompositionsubnode-generator.md— child-node prompt generationrefactor-complete.md— TDD refactoring workflowvalidation-wet-run.md— real wet-run evidence gatetolerance-exception.md— deviation and exception policynode-communication.md— structured message formatautonomy-decision.md— risk classificationpi-learning-benchmark.md— pi-agent benchmark study
See .pi/pi-learning-benchmark.md for an 8-dimension study of pi agent compared to Stagewarden.
Acknowledgements:
- Thanks to Julius Brussee for caveman, which influenced the Caveman mode and parts of the command ergonomics.
- Thanks to the public OpenAI Codex CLI sources and documentation for clarifying authentication and provider-model selection patterns.
- Thanks to the public Claude Code sources and Anthropic documentation for the provider-specific model aliasing and credential-handling references.
- Thanks to the public KiloCode sources and documentation for clarifying gateway-based provider routing, model filtering, and CLI/extension synchronization patterns.
- Stagewarden is an independent project and does not include source code from Caveman, Codex CLI, Claude Code, or KiloCode.
- Stagewarden implementation, package structure, routing, handoff system, persistence, tests, and project integration are original work for this repository.