autoprompt-skill
Autoprompt is a coding-agent skill that cuts failures by 45% on agentic coding tasks.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Spielewoy/autoprompt-skill with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Spielewoy/autoprompt-skill'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/spielewoy-autoprompt-skill)HTML
<a href="/listings/spielewoy-autoprompt-skill"><img src="/api/listings/spielewoy-autoprompt-skill/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Use the CLI below, or download an installer from [GitHub Releases](https://github.com/Spielewoy/autoprompt-skill/releases/latest).
1. Install the CLI
npm install -g https://github.com/Spielewoy/autoprompt-skill/releases/download/v2.1.0/autoprompt-skill-2.1.0.tgz
2. Launch the installer
autoprompt
3. Install
Choose your coding agent, confirm its path, and install. `N` means enter another path.
For another CLI or IDE, choose `Custom coding agent` and use the [compatibility guide](docs/guides/custom-agent-compatibility.md).
<details> <summary><strong>Install from source</strong></summary>
git clone https://github.com/Spielewoy/autoprompt-skill cd autoprompt-skill npm install -g . autoprompt
</details>
Requirements
- [Node.js 20+](https://nodejs.org/en/download) - [Python 3.11+](https://www.python.org/downloads/) available as `python3` or `python`, with [PyYAML](https://pypi.org/project/PyYAML/) - [Bash 4.3+](https://www.gnu.org/software/bash/) on macOS or Linux - Windows native provider commands use the installed provider runtime plus the platform sandbox and owned-process controls; WSL and a hypervisor are not required for native paths - Native Windows Codex additionally requires an administrator-run Autoprompt controller and an initialized official Codex Windows sandbox. Setting Codex `windows.sandbox="elevated"` selects that sandbox mode; it does not elevate the Autoprompt controller. - [Git](https://git-scm.com/downloads) only for the GitHub checkout method
Support
| Status | Coding agent | Tested version | Key | |---|---|---|---| | Working | [Claude Code](https://code.claude.com/docs/en/setup) | 2.1.263 | `claude` | | Working | [Codex](https://github.com/openai/codex) | 0.148.0 | `codex` | | Working | [OpenCode](https://opencode.ai/docs/agents) | 1.18.29 | `opencode` | | Working | [Kilo Code](https://kilo.ai/docs/customize/custom-subagents) | 7.5.15 | `kilo` | | Working | [VS Code](https://code.visualstudio.com/docs/agents/subagents) | 1.136.1 | `vscode` | | Working | [Prime Agent](https://github.com/PrimeIntellect-ai/prime-agent) | 0.7.2 | `prime` | | Working | [Oh My Pi](https://omp.sh/) | 18.1.14 | `omp` | | Working | [DeepSeek Harness](https://deepseek.com/harness/en/) | 0.1.2-rc.1 | `deepseek` | | Working | [Reasonix](https://reasonix.io/docs/) | 1.30.0 | `reasonix` | | Working | [Hermes Agent](https://github.com/NousResearch/hermes-agent) | 0.21.1 | `hermes` | | Working | [Grok Build](https://docs.x.ai/build/overview) | 1.0.13 | `grok` |
These versions passed Linux runs. Model and platform availability varies by provider.
Native Windows execution uses AppContainer isolation and Windows Job process ownership, with Node 20 or 24 on x64 or ARM64. Native macOS execution uses the system sandbox and owned-process controls. Windows command tools include the bundled Bash/MSYS/Node runtime; native paths do not require WSL or a VM.
The ten non-Codex providers can run their local capability checks on Linux, Windows, and macOS. All eleven checks must pass for the installed runtime before a mission starts; missing, failed, or skipped checks block activation. Codex uses its separate canonical validation route. On Windows, that route creates a fresh offline account and an own-SID Windows Filtering Platform policy for each activation. Their activation-bound lease is retained for resume. Permanent cleanup removes the account and policy only after owned Jobs drain; uncertain verification or cleanup fails closed and retains recovery records. The Linux version table above does not certify every provider/platform combination. Installer success and `doctor --strict` are prerequisite checks; `local-canary-required` means native validation is still pending. See [configured Linux runtimes](docs/lima-runtime.md) when a native path is unavailable.
See [support and audit notes](docs/faq/which-coding-agents-are-supported.md).
Check, update, or remove an installation
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
README.md · README · 264 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- <p align="center">
- <img src="assets/banner.svg" alt="Autoprompt Skill: pink clouds and flying geese" width="1000"/>
- </p>
- <p align="center">Autoprompt is a coding-agent workflow that cuts failures by 45% by reviewing, fixing, and rechecking its work.</p>
- <p align="center">
- <a href="#benchmarks"><img src="https://img.shields.io/badge/Terminal--Bench%202.1-%2B14.61%20points-965477?style=flat-square&labelColor=302335" alt="Terminal-Bench 2.1: plus 14.61 points"/></a>
- <a href="https://github.com/Spielewoy/autoprompt-skill/releases/latest"><img src="https://img.shields.io/github/v/release/Spielewoy/autoprompt-skill?style=flat-square&label=version&color=965477&labelColor=302335" alt="Latest release"/></a>
- <a href="#install"><img src="https://img.shields.io/badge/support-11%20supported%20providers-965477?style=flat-square&labelColor=302335" alt="Eleven supported providers"/></a>
- <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-965477?style=flat-square&labelColor=302335" alt="License MIT"/></a>
- </p>
- <p align="center">
- <a href="README.md"><b>English</b></a> |
- <a href="docs/translations/zh.md">中文</a> |
- <a href="docs/translations/ko.md">한국어</a> |
- <a href="docs/translations/es.md">Español</a> |
- <a href="docs/translations/ar.md">العربية</a>
- </p>
- ## Contents
- [Install](#install) · [Benchmarks](#benchmarks) · [Invocation](#anatomy-of-an-invocation) · [Run controls](#run-controls) · [Workflow](#how-it-works) · [Agents](#the-agents) · [Examples](#examples) · [FAQ](#faq) · [License](#license)
- ## Install
- Use the CLI below, or download an installer from [GitHub Releases](https://github.com/Spielewoy/autoprompt-skill/releases/latest).
- ### 1. Install the CLI
- ```bash
- npm install -g https://github.com/Spielewoy/autoprompt-skill/releases/download/v2.1.0/autoprompt-skill-2.1.0.tgz
- ```
- ### 2. Launch the installer
- ```bash
- autoprompt
- ```
- ### 3. Install
- Choose your coding agent, confirm its path, and install. `N` means enter another path.
- For another CLI or IDE, choose `Custom coding agent` and use the [compatibility guide](docs/guides/custom-agent-compatibility.md).
- <details>
- <summary><strong>Install from source</strong></summary>
- ```bash
- git clone https://github.com/Spielewoy/autoprompt-skill
- cd autoprompt-skill
- npm install -g .
- autoprompt
- ```
- </details>
- ### Requirements
- - [Node.js 20+](https://nodejs.org/en/download)
- - [Python 3.11+](https://www.python.org/downloads/) available as `python3` or `python`, with [PyYAML](https://pypi.org/project/PyYAML/)
- - [Bash 4.3+](https://www.gnu.org/software/bash/) on macOS or Linux
- - Windows native provider commands use the installed provider runtime plus the platform sandbox and owned-process controls; WSL and a hypervisor are not required for native paths
- - Native Windows Codex additionally requires an administrator-run Autoprompt controller and an initialized official Codex Windows sandbox. Setting Codex `windows.sandbox="elevated"` selects that sandbox mode; it does not elevate the Autoprompt controller.
- - [Git](https://git-scm.com/downloads) only for the GitHub checkout method
- ### Support
- | Status | Coding agent | Tested version | Key |
- |---|---|---|---|
- | Working | [Claude Code](https://code.claude.com/docs/en/setup) | 2.1.263 | `claude` |
- | Working | [Codex](https://github.com/openai/codex) | 0.148.0 | `codex` |
- | Working | [OpenCode](https://opencode.ai/docs/agents) | 1.18.29 | `opencode` |
- | Working | [Kilo Code](https://kilo.ai/docs/customize/custom-subagents) | 7.5.15 | `kilo` |
- | Working | [VS Code](https://code.visualstudio.com/docs/agents/subagents) | 1.136.1 | `vscode` |
- | Working | [Prime Agent](https://github.com/PrimeIntellect-ai/prime-agent) | 0.7.2 | `prime` |
- | Working | [Oh My Pi](https://omp.sh/) | 18.1.14 | `omp` |
- | Working | [DeepSeek Harness](https://deepseek.com/harness/en/) | 0.1.2-rc.1 | `deepseek` |
- | Working | [Reasonix](https://reasonix.io/docs/) | 1.30.0 | `reasonix` |
- | Working | [Hermes Agent](https://github.com/NousResearch/hermes-agent) | 0.21.1 | `hermes` |
- | Working | [Grok Build](https://docs.x.ai/build/overview) | 1.0.13 | `grok` |
- These versions passed Linux runs. Model and platform availability varies by provider.
- Native Windows execution uses AppContainer isolation and Windows Job process
- ownership, with Node 20 or 24 on x64 or ARM64. Native macOS execution uses the
- system sandbox and owned-process controls. Windows command tools include the
- bundled Bash/MSYS/Node runtime; native paths do not require WSL or a VM.
- The ten non-Codex providers can run their local capability checks on Linux,
- Windows, and macOS. All eleven checks must pass for the installed runtime before
- a mission starts; missing, failed, or skipped checks block activation. Codex uses
- its separate canonical validation route. On Windows, that route creates a fresh
- offline account and an own-SID Windows Filtering Platform policy for each
- activation. Their activation-bound lease is retained for resume. Permanent
- cleanup removes the account and policy only after owned Jobs drain; uncertain
- verification or cleanup fails closed and retains recovery records. The Linux
- version table above does not
- certify every provider/platform combination. Installer success and
- `doctor --strict` are prerequisite checks; `local-canary-required` means native
- validation is still pending. See [configured Linux runtimes](docs/lima-runtime.md)
- when a native path is unavailable.
- See [support and audit notes](docs/faq/which-coding-agents-are-supported.md).
- ### Check, update, or remove an installation
- - Check every detected installation: `autoprompt doctor --strict`
- - Check one provider: `autoprompt doctor PROVIDER --strict`
- - Update or repair: `autoprompt`, then choose an installed provider
- - Uninstall interactively: `autoprompt uninstall`
- - Uninstall one provider: `autoprompt uninstall PROVIDER`
- - Show every command: `autoprompt help`
- Replace `PROVIDER` with a key from the support table, such as `claude`, `codex`, or `prime`.
- ## Benchmarks
- These are **version 1 benchmarks**. Version 2 benchmarks will follow.
- <p align="center">
- <img src="assets/terminal-bench-2.1-leaderboard.svg" width="1000" alt="Terminal-Bench 2.1 leaderboard with 18 Artificial Analysis reference scores and measured DeepSeek V4 Flash 0731 scores with and without Autoprompt."/>
- </p>
- <details>
- <summary><strong>Measured OpenCode comparison</strong></summary>
- <p align="center">
- <img src="assets/terminal-bench-2.1.svg" width="900" alt="OpenCode 1.18.7 on Terminal-Bench 2.1: OpenCode solved 60 of 89 tasks and OpenCode with Autoprompt solved 73 of 89 tasks."/>
- </p>
- | Track | Solved | Score | Failed |
- |---|---:|---:|---:|
- | OpenCode | 60/89 | 67.42% | 29 |
- | **OpenCode + Autoprompt** | **73/89** | **82.02%** | **16** |
- | **Change** | **+13 solves** | **+14.61 points** | **45% fewer** |
- </details>
- DeepSeek's 82.7% used its own test setup, so it is a reference point, not a comparable third run. Read the [setup and evidence boundaries](docs/benchmarks/terminal-bench-2.1.md), or [request another benchmark](https://github.com/Spielewoy/autoprompt-skill/issues/new).
- <details>
- <summary><strong>Expected trade-off:</strong> about 3x the time and 2x the tokens.</summary>
- Timing and token logs were not retained, so these are planning estimates based on user experience reports, not measured benchmark results. The measured result was 29 to 16 failures (45% fewer) in this run, which translates to about 2x fewer mistakes. Note: for very small tasks, this may differ significantly.
- </details>
- ## Anatomy of an invocation
- ```bash
- autoprompt activate PROVIDER --target /absolute/project -- "<goal>"
- ```
- | Part | What it does |
- |---|---|
- | `PROVIDER` | A key from the support table, such as `claude`, `codex`, or `grok`. |
- | `--target` | The project to work on. Omit it to use the current directory. |
- | `--` | Separates launcher options from the request. |
- | `<goal>` | The result you want, constraints, and how to check success. |
- | `path=` | Optional `auto`, `direct`, `light`, or `roadmap`, before the quoted goal. See [work paths](docs/faq/work-paths.md). |
- ```bash
- autoprompt activate codex -- path=light "add retries and test the edge cases"
- ```
- ## Run controls
- The same controls apply to all eleven providers. [Custom model setup](docs/faq/how-to-add-custom-models.md)
- | Control | What it does |
- |---|---|
- | `--concurrency tokensaver` | Runs at most six subagents at once. |
- | `--concurrency wide` | Starts ready, independent work up to the host limit. |
- | `--concurrency custom --max-subs N` | Sets your own concurrency limit. |
- | `configure PROVIDER --agents off` | Uses the provider's configured model. |
- | `configure PROVIDER --agents MODEL` | Selects one model. Add `--effort LEVEL` where supported. |
- | `configure PROVIDER --agents auto --model-map FILE` | Chooses from a measured model registry. A comma-separated model list also requires `--model-map`. |
- Pass concurrency controls after `--`, before the quoted goal:
- ```bash
- autoprompt activate codex -- --concurrency custom --max-subs 4 "add retries and tests"
- autoprompt configure claude --agents provider/model --effort low
- ```
- ## How it works
- <p align="center">
- <a href="assets/how-it-works-loop.svg"><img src="assets/how-it-works-loop.svg" alt="Autoprompt workflow: choose a route, plan, build, check, and finish" width="1100"/></a>
- </p>
- ## The agents
- <p align="center">
- <a href="assets/how-it-works-hierarchy.svg"><img src="assets/how-it-works-hierarchy.svg" alt="Autoprompt agents: run coordinator, workers, independent checkers, and coordinators for larger jobs" width="1100"/></a>
- </p>
- ## Examples
- | Goal | Prompt |
- |---|---|
- | Fix | `autoprompt activate claude -- "fix the registration race and add a regression test"` |
- | Build | `autoprompt activate codex -- --concurrency wide "build the booking flow from API to checkout"` |
- | Research | `autoprompt activate hermes -- "compare job queues against this codebase and recommend one"` |
- | Limit parallel work | `autoprompt activate grok -- --concurrency custom --max-subs 4 "migrate every model"` |
- Run these commands from your project, or supply `--target /absolute/project` before `--`.
- ## FAQ
- <details>
- <summary><strong>Does Autoprompt mean I literally do not have to prompt?</strong></summary>
- No. Give it a clear goal, constraints, and success criteria. Autoprompt handles the execution loop, so you do not have to prompt every step. [Details](docs/faq/does-autoprompt-mean-i-do-not-have-to-prompt.md)
- </details>
- <details>
- <summary><strong>How autonomous is Autoprompt?</strong></summary>
- It can scope, implement, test, review, repair, and verify a goal. It stops for choices that change the result, actions that need your authority, or blockers it cannot safely resolve. [Details](docs/faq/how-autonomous-is-autoprompt.md)
- </details>
- <details>
- <summary><strong>What are the layers for?</strong></summary>
- The layers separate coordination, management, execution, and independent judgment. That separation keeps one agent from planning, approving, and verifying its own work. [Details](docs/faq/what-are-the-layers-for.md)
- </details>
- <details>
- <summary><strong>What are the paths?</strong></summary>
- `path=auto` selects a route for the task. `direct` starts focused work, `light` adds a short plan, and `roadmap` organizes dependent work before execution. Every path includes independent verification. [Details](docs/faq/work-paths.md)
- </details>
- <details>
- <summary><strong>What do concurrency, models, and paths control?</strong></summary>
- `--concurrency` and `--max-subs` set parallel work limits. `configure --agents` selects models, and `path=` selects how work is planned and coordinated. [Details](docs/faq/tokensaver-vs-wide-vs-custom.md)
- </details>
- <details>
- <summary><strong>Why does Autoprompt not start in the background?</strong></summary>
- Because it changes cost, time, and workflow. Start it explicitly with `autoprompt activate PROVIDER -- "<goal>"`.
- </details>
- ## License
- [MIT](LICENSE). Copyright 2026 [Spielewoy](https://github.com/Spielewoy).
- Community: [Contributors](docs/CONTRIBUTORS.md), [Contributing](docs/CONTRIBUTING.md), [Code of Conduct](docs/CODE_OF_CONDUCT.md), [Security](docs/SECURITY.md), and [Support](docs/SUPPORT.md).
- ### Contributors
- [johnatag](https://github.com/johnatag) · [rollingdice](https://github.com/rollingdice) · [AincradBot](https://github.com/AincradBot) · [lunar-me](https://github.com/lunar-me) · [fatinghenji](https://github.com/fatinghenji) · [c8dhjp4tyv-bit](https://github.com/c8dhjp4tyv-bit) · [Alexis-Fiolleau-LaPoste-BGPN](https://github.com/Alexis-Fiolleau-LaPoste-BGPN) · [Oscar-Williams](https://github.com/Oscar-Williams)
agents/claude/workflow/supervisor.ps1 · Bundled script · 1,614 lines · 2 findings marked
- <#
- .SYNOPSIS
- autoprompt supervisor (Windows PowerShell 5.1 port of supervisor.sh) --
- external auto-relaunch for a one-sitting unattended run.
- .DESCRIPTION
- This is a STANDALONE OS PROCESS, NOT a Claude Code hook. It touches no
- settings.json, registers no hook, and is launched by the operator. It honors
- the global no-hooks rule.
- It relaunches the autoprompt CLI with RESUME on any unexpected exit, loops
- until the JANITOR has written the DONE-sentinel (autoprompt/DONE-<nonce>),
- and has a crash-loop/poison-restart guard that distinguishes:
- - a FINISHED run (sentinel present) -> clean halt (exit 0)
- - a HEALTHY-LONG run (frontier advances) -> keep relaunching, no escalation
- - a TRULY-STUCK run (no frontier progress) -> escalate, stop relaunching (exit 1)
- Behavior-faithful to agents/claude/workflow/supervisor.sh: identical sentinel glob
- (autoprompt/DONE-*), identical "done": true check, identical env var names
- (AUTOPROMPT_RESUME / AUTOPROMPT_UNATTENDED), identical --launcher selection,
- identical backoff schedule and poison guard.
- .PARAMETER Launcher
- apidemo | codexdemo (or any launcher command on PATH). Defaults to
- $env:AUTOPROMPT_LAUNCHER. Exec'd as a bare command name.
- .PARAMETER Cmd
- Verbatim launch command (e.g. "claude --dangerously-skip-permissions -p"),
- Note: Starts a coding agent with its permission prompts off
- Line 28 on GitHub
- word-split with the mission appended. Overrides -Launcher. Defaults to
- $env:AUTOPROMPT_LAUNCH_CMD. A fresh user with no apidemo/codexdemo alias
- uses --cmd with their real CLI.
- .PARAMETER Mission
- The mission text passed through to the launch command.
- .EXAMPLE
- powershell -File supervisor.ps1 --launcher apidemo "<mission>"
- .EXAMPLE
- powershell -File supervisor.ps1 --cmd "claude --dangerously-skip-permissions -p" "<mission>"
- Note: Starts a coding agent with its permission prompts off
- Line 40 on GitHub
- .EXAMPLE
- powershell -File supervisor.ps1 --agents "auto:strong,cheap" --model-registry "$HOME\.claude\autoprompt-models.json" --cmd "claude -p" "<mission>"
- .NOTES
- Env (all optional), mirroring supervisor.sh:
- AUTOPROMPT_LAUNCH_CMD verbatim launch command (overrides --launcher)
- AUTOPROMPT_LAUNCHER default launcher label if --launcher is omitted
- AUTOPROMPT_AGENTS off | auto | <list> | auto:<list> (default off)
- AUTOPROMPT_MODEL_REGISTRY optional registry path; defaults to ~/.claude/autoprompt-models.json for auto modes
- LEDGER_DIR default "autoprompt"
- SENTINEL explicit sentinel glob (default <LEDGER_DIR>/DONE-*).
- Passed to Get-ChildItem -Path as ONE pattern (no word-
- split), so a single dir-wildcard like 'autoprompt/*/DONE-*'
- works but a space-separated MULTI-pattern (a .sh-only escape
- hatch) does not -- use one wildcard on PowerShell. When UNSET
- (the default -- every real run) the glob is <LEDGER_DIR>/DONE-*
- as one quoted path, so a LEDGER_DIR containing spaces (a
- Windows path) still matches its own DONE-* sentinel.
- MAX_RESTARTS rapid restarts allowed in WINDOW without progress (default 5)
- WINDOW rolling window seconds for the poison guard (default 600)
- RETRY_BASE base backoff seconds between relaunches (default 5; 0 in tests)
- RETRY_CAP max backoff seconds (default 300)
- AUTOPROMPT_KEEP_MODEL_PIN when "1", SKIP neutralizing CLAUDE_CODE_SUBAGENT_MODEL
- for the child CLI. By DEFAULT (unset) the supervisor strips
- CLAUDE_CODE_SUBAGENT_MODEL from the CHILD ONLY so the skill's
- `model: inherit` contract resolves to the real session/--model
- selection instead of the operator's force-pin. Set to 1 to
- preserve the operator's pin and let it reach the child as before.
- AUTOPROMPT_MODE tokensaver | wide | billionaire | custom (default tokensaver).
- WIDE and BILLIONAIRE share wide semantics. CUSTOM requires a
- positive numeric AUTOPROMPT_MAX_CONCURRENT value, floors it
- to a whole-agent ceiling, and passes both values through.
- The 5-level topology (L0 conductor -> L1 coordinators -> L2 managers -> L3
- executors -> L4 leaves) lives in the harness; rule 68 (L1 never executes) and
- rule 67 (single-block spawns) are enforced there. This OS-level supervisor only
- relaunches the L0 entry process and passes the mode through; it spawns no agents.
- Test hooks (only honored with --dry-run):
- FAKE_EXITS space-separated exit codes the fake launcher returns in turn
- FAKE_SENTINEL_AFTER write the sentinel before the launch with this 1-based index
- FAKE_POISON 1 => fake never advances the frontier and always exits non-zero
- #>
- Set-StrictMode -Version Latest
- $ErrorActionPreference = 'Stop'
- function Get-EnvOrDefault {
- param([string]$Name, $Default)
- $value = [Environment]::GetEnvironmentVariable($Name)
- if ([string]::IsNullOrEmpty($value)) { return $Default }
- return $value
- }
- function Get-RequiredArgumentValue {
- param([string]$Flag, [int]$Index, [string[]]$Arguments)
- if ($Index -lt $Arguments.Count) { return $Arguments[$Index] }
- [Console]::Error.WriteLine("supervisor: $Flag requires a value")
- return $null
- }
- function ConvertTo-NativeArgument {
- param([AllowEmptyString()][string]$Value)
- if ($Value.Length -gt 0 -and $Value -notmatch '[\s"]') { return $Value }
- $builder = New-Object Text.StringBuilder
- $backslash = [char]92
- $quote = [char]34
- $backslashCount = 0
- [void]$builder.Append($quote)
- foreach ($character in $Value.ToCharArray()) {
- if ($character -eq $backslash) {
- $backslashCount += 1
- continue
- }
- if ($character -eq $quote) {
- for ($index = 0; $index -lt (($backslashCount * 2) + 1); $index += 1) {
- [void]$builder.Append($backslash)
- }
- [void]$builder.Append($quote)
- $backslashCount = 0
- continue
- }
- for ($index = 0; $index -lt $backslashCount; $index += 1) {
- [void]$builder.Append($backslash)
- }
- $backslashCount = 0
- [void]$builder.Append($character)
- }
- for ($index = 0; $index -lt ($backslashCount * 2); $index += 1) {
- [void]$builder.Append($backslash)
- }
- [void]$builder.Append($quote)
- return $builder.ToString()
- }
- function Join-NativeArguments {
- param([string[]]$Arguments)
- return (($Arguments | ForEach-Object { ConvertTo-NativeArgument -Value $_ }) -join ' ')
- }
- function Get-AgentDefinitionsHash {
- param([string]$ModelCastingPath, [string]$AgentsDirectory)
- if (-not (Test-Path -LiteralPath $ModelCastingPath -PathType Leaf) -or
- -not (Test-Path -LiteralPath $AgentsDirectory -PathType Container)) {
- return 'unknown'
- }
- $files = @($ModelCastingPath) + @(
- Get-ChildItem -LiteralPath $AgentsDirectory -File -Filter 'ap-*.md' |
- Sort-Object Name |
- ForEach-Object { $_.FullName }
- )
- $sha = [Security.Cryptography.SHA256]::Create()
- try {
- foreach ($file in $files) {
- $label = [IO.Path]::GetFileName($file)
- $labelBytes = [Text.Encoding]::UTF8.GetBytes($label)
- $lengthBytes = [Text.Encoding]::UTF8.GetBytes(([string]$labelBytes.Length) + ':')
- $null = $sha.TransformBlock($lengthBytes, 0, $lengthBytes.Length, $lengthBytes, 0)
- $null = $sha.TransformBlock($labelBytes, 0, $labelBytes.Length, $labelBytes, 0)
- $content = [IO.File]::ReadAllBytes($file)
- $contentLength = [Text.Encoding]::UTF8.GetBytes(([string]$content.Length) + ':')
- $null = $sha.TransformBlock($contentLength, 0, $contentLength.Length, $contentLength, 0)
- $null = $sha.TransformBlock($content, 0, $content.Length, $content, 0)
- }
- $null = $sha.TransformFinalBlock([byte[]]@(), 0, 0)
- return 'sha256:' + ([BitConverter]::ToString($sha.Hash) -replace '-', '').ToLowerInvariant()
- } finally {
- $sha.Dispose()
- }
- }
- function Invoke-Supervisor {
- param([string[]]$Argv)
- function Test-CapabilityAttestation {
- param([string]$Raw, [string[]]$Expected)
- try {
- $attestation = $Raw | ConvertFrom-Json -ErrorAction Stop
- } catch {
- return $false
- }
- $bindings = @(
- 'provider', 'cliVersion', 'permissionProfile', 'agentSelector',
- 'agentDefinitionsHash', 'castingHash', 'effortStatus', 'effortSource'
- )
- for ($index = 0; $index -lt $bindings.Count; $index += 1) {
- $property = $attestation.PSObject.Properties[$bindings[$index]]
- if ($null -eq $property -or
- $property.Value -isnot [string] -or
- $property.Value -cne $Expected[$index]) {
- return $false
- }
- }
- $schemaVersion = $attestation.PSObject.Properties['schemaVersion']
- $proofKind = $attestation.PSObject.Properties['proofKind']
- $proofHash = $attestation.PSObject.Properties['proofHash']
- $proofBytes = $attestation.PSObject.Properties['proofBytes']
- if ($null -eq $schemaVersion -or
- $schemaVersion.Value -isnot [int] -or
- $schemaVersion.Value -ne 4 -or
- $null -eq $proofKind -or
- $proofKind.Value -isnot [string] -or
- $proofKind.Value -cne 'disposable-scratch' -or
- $null -eq $proofHash -or
- $proofHash.Value -isnot [string] -or
- $proofHash.Value -cnotmatch '^sha256:[a-f0-9]{64}$') {
- return $false
- }
- # The proof hash must recompute from the inspectable scratch bytes the
- # attestation carries; a bare well-formed hash string proves nothing.
- if ($null -eq $proofBytes -or
- $proofBytes.Value -isnot [string] -or
- $proofBytes.Value.Length -eq 0 -or
- $proofBytes.Value.Length -gt 4096) {
- return $false
- }
- $sha = [Security.Cryptography.SHA256]::Create()
- try {
- $recomputed = 'sha256:' + ([BitConverter]::ToString(
- $sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($proofBytes.Value))
- ) -replace '-', '').ToLowerInvariant()
- } finally {
- $sha.Dispose()
- }
- if ($recomputed -cne $proofHash.Value) {
- return $false
- }
- foreach ($name in @('run', 'read', 'write')) {
- $property = $attestation.PSObject.Properties[$name]
- if ($null -eq $property -or
- $property.Value -isnot [bool] -or
- $property.Value -ne $true) {
- return $false
- }
- }
- return $true
- }
- $launcher = Get-EnvOrDefault 'AUTOPROMPT_LAUNCHER' ''
- $launchCmd = Get-EnvOrDefault 'AUTOPROMPT_LAUNCH_CMD' ''
- $agentsSelector = Get-EnvOrDefault 'AUTOPROMPT_AGENTS' 'off'
- $modelRegistry = Get-EnvOrDefault 'AUTOPROMPT_MODEL_REGISTRY' ''
- $providerCapability = Get-EnvOrDefault 'AUTOPROMPT_PROVIDER_CAPABILITY' ''
- $ledgerDir = Get-EnvOrDefault 'LEDGER_DIR' 'autoprompt'
- $maxRestarts = [int](Get-EnvOrDefault 'MAX_RESTARTS' 5)
- $window = [int](Get-EnvOrDefault 'WINDOW' 600)
- $retryBase = [int](Get-EnvOrDefault 'RETRY_BASE' 5)
- $retryCap = [int](Get-EnvOrDefault 'RETRY_CAP' 300)
- # P1 (PLAN-idle-watchdog) - heartbeat env defaults, IDENTICAL to supervisor.sh.
- # IDLE_TIMEOUT defaults to 1800s (30 min) so a long-but-progressing build/test does
- # NOT trip the heartbeat (the frontier count grows on ANY artifact write and resets
- # the timer); operators with long atomic steps raise AUTOPROMPT_IDLE_TIMEOUT.
- $idleTimeout = [int](Get-EnvOrDefault 'AUTOPROMPT_IDLE_TIMEOUT' 1800)
- $heartbeatInterval = [int](Get-EnvOrDefault 'AUTOPROMPT_HEARTBEAT_INTERVAL' 60)
- # PLAN-auto-compact-threshold: proactive, SUPERVISOR-FIRED compaction below the
- # harness ~400k ceiling. IDENTICAL semantics + knobs to supervisor.sh. The supervisor
- # observes the parent's context size from OUTSIDE (parent session transcript;
- # watermark/ledger-byte fallbacks) and, on crossing $compactAt, writes COMPACT-REQUEST,
- # then on grace timeout fires the kill->RESUME (the parent cannot /compact itself).
- $compactAt = Get-EnvOrDefault 'AUTOPROMPT_COMPACT_AT' '200000'
- $parsedCompactAt = 0
- if (-not [int]::TryParse([string]$compactAt, [ref]$parsedCompactAt) -or $parsedCompactAt -le 0 -or $parsedCompactAt -ge 10000000) {
- $parsedCompactAt = 200000 # absurd/non-numeric -> default (never disables the guard, never fires every tick)
- }
- $compactAt = $parsedCompactAt
- $bytesPerToken = [int](Get-EnvOrDefault 'AUTOPROMPT_BYTES_PER_TOKEN' 4)
- if ($bytesPerToken -le 0) { $bytesPerToken = 4 }
- $compactCooldown = [int](Get-EnvOrDefault 'AUTOPROMPT_COMPACT_COOLDOWN' 120)
- $compactGrace = [int](Get-EnvOrDefault 'AUTOPROMPT_COMPACT_GRACE' 180)
- $externalCompactDelta = [int](Get-EnvOrDefault 'AUTOPROMPT_EXTERNAL_COMPACT_DELTA' 50000)
- # Execution mode selects the 5-level topology's wave cap. Unknown modes retain
- # the safe tokensaver fallback. CUSTOM is an explicit request for a caller-supplied
- # ceiling, so a missing or invalid value fails closed.
- $autopromptMode = Get-EnvOrDefault 'AUTOPROMPT_MODE' 'tokensaver'
- switch -CaseSensitive ($autopromptMode) {
- 'tokensaver' { $fanout = 'up to 6 live per wave'; $l3Tracks = 'parallel' }
- 'wide' { $fanout = 'wide up to the runtime ceiling'; $l3Tracks = 'parallel' }
- 'billionaire' { $fanout = 'wide up to the runtime ceiling'; $l3Tracks = 'parallel' }
- 'custom' {
- $rawCustomMax = Get-EnvOrDefault 'AUTOPROMPT_MAX_CONCURRENT' ''
- [double]$parsedCustomMax = 0
- $validCustomMax = [double]::TryParse(
- [string]$rawCustomMax,
- [Globalization.NumberStyles]::Float,
- [Globalization.CultureInfo]::InvariantCulture,
- [ref]$parsedCustomMax
- )
- if (-not $validCustomMax -or [double]::IsNaN($parsedCustomMax) -or
- [double]::IsInfinity($parsedCustomMax) -or $parsedCustomMax -lt 1) {
- [Console]::Error.WriteLine('supervisor: custom mode requires a positive numeric AUTOPROMPT_MAX_CONCURRENT')
- return 2
- }
- $customMax = [Math]::Floor($parsedCustomMax)
- $env:AUTOPROMPT_MAX_CONCURRENT = [string]$customMax
- $fanout = "up to $customMax live per wave (AUTOPROMPT_MAX_CONCURRENT)"
- $l3Tracks = 'parallel'
- }
- default { $autopromptMode = 'tokensaver'; $fanout = 'up to 6 live per wave'; $l3Tracks = 'parallel' }
- }
- # Scope wall-clock budget, with semantics matching supervisor.sh. A slow scope can
- # keep producing ROADMAP.md and roadmap-scout-*.md checkpoints, resetting the idle
- # clock while never converging. This budget is anchored to scope entry, not frontier
- # growth. Each knob is validated with [int]::TryParse (like $compactAt): an absurd or
- # non-numeric value falls back to the default (never disables the guard).
- $scopeSoftSec = 60
- if (-not [int]::TryParse([string](Get-EnvOrDefault 'AUTOPROMPT_SCOPE_SOFT_SEC' '60'), [ref]$scopeSoftSec) -or $scopeSoftSec -le 0) { $scopeSoftSec = 60 }
- $scopeHardSec = 300
- if (-not [int]::TryParse([string](Get-EnvOrDefault 'AUTOPROMPT_SCOPE_HARD_SEC' '300'), [ref]$scopeHardSec) -or $scopeHardSec -le 0) { $scopeHardSec = 300 }
- $scopeGraceSec = 60
- if (-not [int]::TryParse([string](Get-EnvOrDefault 'AUTOPROMPT_SCOPE_GRACE' '60'), [ref]$scopeGraceSec) -or $scopeGraceSec -lt 0) { $scopeGraceSec = 60 }
- $maxScopeResets = 1
- if (-not [int]::TryParse([string](Get-EnvOrDefault 'AUTOPROMPT_MAX_SCOPE_RESETS' '1'), [ref]$maxScopeResets) -or $maxScopeResets -lt 0) { $maxScopeResets = 1 }
- $dryRun = $false
- $mission = ''
- # EDIT 23a: the supervisor sits in .../workflow/ next to autoprompt-ledger-check.js,
- # so derive that resolver's absolute path from its own location and export it to the
- # child (gate.js EDIT 4a reads AUTOPROMPT_LEDGER_CHECK; the SCRIBE/JANITOR briefs
- # interpolate it). An operator override wins; else the script-dir sibling is used.
- # $PSCommandPath is the .ps1's own full path (this script), the analog of the .sh $0.
- $scriptDir = Split-Path -Parent $PSCommandPath
- $ledgerCheckPath = if ($env:AUTOPROMPT_LEDGER_CHECK) { $env:AUTOPROMPT_LEDGER_CHECK } else { Join-Path $scriptDir 'autoprompt-ledger-check.js' }
- $modelCastingPath = if ($env:AUTOPROMPT_MODEL_CASTING) { $env:AUTOPROMPT_MODEL_CASTING } else { Join-Path $scriptDir 'model-casting.js' }
- $agentDefinitionsPath = if ($env:AUTOPROMPT_AGENT_DEFINITIONS_DIR) { $env:AUTOPROMPT_AGENT_DEFINITIONS_DIR } else { Join-Path (Split-Path -Parent $scriptDir) 'agents' }
- $agentDefinitionsCli = if ($env:AUTOPROMPT_AGENT_DEFINITIONS_CLI) { $env:AUTOPROMPT_AGENT_DEFINITIONS_CLI } else { Join-Path $scriptDir 'agent-definitions-cli.js' }
- # F-SPEED steer-2 B3: the phase-budget verdict CLI sits next to the ledger-check.
- # An operator override wins; the Test-Path guard at the call site fail-opens if
- # node/module are absent (same posture as the ledger-check).
- $phaseBudgetPath = if ($env:AUTOPROMPT_PHASE_BUDGET) { $env:AUTOPROMPT_PHASE_BUDGET } else { Join-Path $scriptDir 'phase-budget.js' }
- # EDIT 23: per-conversation session token. The supervisor is the durable producer
- # across relaunches of one conversation: seed it (env > file > empty) before the
- # loop, re-export the held token to each child, and HARVEST the resolver-minted
- # marker token after each launch so a 2nd prompt rejoins the same session_NN.
- $sessionToken = Get-EnvOrDefault 'AUTOPROMPT_SESSION_TOKEN' ''
- $initialResume = (Get-EnvOrDefault 'AUTOPROMPT_RESUME' '').Trim().ToLowerInvariant() -in @('1', 'true', 'yes')
- $runNonce = Get-EnvOrDefault 'AUTOPROMPT_RUN_NONCE' ''
- $legacySentinel = (Get-EnvOrDefault 'AUTOPROMPT_LEGACY_SENTINEL' '0') -eq '1'
- # --- arg parse (mirrors the .sh case loop) ----------------------------------
- $i = 0
- while ($i -lt $Argv.Count) {
- $arg = $Argv[$i]
- switch -CaseSensitive ($arg) {
- '--launcher' {
- $value = Get-RequiredArgumentValue -Flag $arg -Index ($i + 1) -Arguments $Argv
- if ($null -eq $value) { return 2 }
- $launcher = $value; $i += 2; continue
- }
- '--cmd' {
- $value = Get-RequiredArgumentValue -Flag $arg -Index ($i + 1) -Arguments $Argv
- if ($null -eq $value) { return 2 }
- $launchCmd = $value; $i += 2; continue
- }
- '--agents' {
- $value = Get-RequiredArgumentValue -Flag $arg -Index ($i + 1) -Arguments $Argv
- if ($null -eq $value) { return 2 }
- $agentsSelector = $value; $i += 2; continue
- }
- '--model-registry' {
- $value = Get-RequiredArgumentValue -Flag $arg -Index ($i + 1) -Arguments $Argv
- if ($null -eq $value) { return 2 }
- $modelRegistry = $value; $i += 2; continue
- }
- '--provider-capability' {
- $value = Get-RequiredArgumentValue -Flag $arg -Index ($i + 1) -Arguments $Argv
- if ($null -eq $value) { return 2 }
- $providerCapability = $value; $i += 2; continue
- }
- '--dry-run' { $dryRun = $true; $i += 1; continue }
- '--ledger-dir' {
- $value = Get-RequiredArgumentValue -Flag $arg -Index ($i + 1) -Arguments $Argv
- if ($null -eq $value) { return 2 }
- $ledgerDir = $value; $i += 2; continue
- }
- '--' {
- # A trailing bare '--' with no following tokens yields an EMPTY
- # mission (matches supervisor.sh `shift; MISSION="$*"`). Only build
- # the slice when there is at least one token after '--', else the
- # range reverses (e.g. 2..1) and throws "index out of range".
- if (($i + 1) -lt $Argv.Count) {
- $mission = ($Argv[($i + 1)..($Argv.Count - 1)] -join ' ')
- } else {
- $mission = ''
- }
- $i = $Argv.Count; continue
- }
- default {
- if ($arg -like '-*') {
- [Console]::Error.WriteLine("supervisor: unknown flag $arg")
- return 2
- }
- $mission = $arg; $i += 1; continue
- }
- }
- }
- $missionBytes = [Text.Encoding]::UTF8.GetBytes($mission)
- $missionSha = [Security.Cryptography.SHA256]::Create()
- try {
- $scopeMissionBinding = 'sha256:' + ([BitConverter]::ToString($missionSha.ComputeHash($missionBytes)) -replace '-', '').ToLowerInvariant()
- } finally {
- $missionSha.Dispose()
- }
- if (-not $legacySentinel) {
- if ([string]::IsNullOrEmpty($runNonce)) {
- $nonceBytes = New-Object byte[] 16
- $generator = [Security.Cryptography.RandomNumberGenerator]::Create()
- try { $generator.GetBytes($nonceBytes) } finally { $generator.Dispose() }
- $runNonce = 'NONCE-' + ([BitConverter]::ToString($nonceBytes) -replace '-', '').ToLowerInvariant()
- } elseif ($runNonce -cnotmatch '^NONCE-[A-Za-z0-9_-]+$') {
- [Console]::Error.WriteLine('supervisor: AUTOPROMPT_RUN_NONCE is malformed')
- return 2
- }
- }
- $casting = $null
- $castingJson = ''
- $castingEnabled = $false
- $castingBaseUrl = ''
- $castingApiKeyEnv = ''
- $castingAuthToken = ''
- $capabilityProvider = 'claude-code'
- $capabilityCliVersion = 'unknown'
- $capabilityPermissionProfile = 'default'
- $capabilityAgentDefinitionsHash = 'unknown'
- $capabilityCastingHash = 'none'
- $capabilityEffortStatus = 'inherited-only'
- $capabilityEffortSource = 'session-inheritance'
- $suppliedCapabilityAttestation = Get-EnvOrDefault 'AUTOPROMPT_CAPABILITY_ATTESTATION' ''
- $capabilityAttestation = $null
- $selectorControl = $agentsSelector.Trim().ToLowerInvariant()
- if (-not [string]::IsNullOrEmpty($selectorControl) -and $selectorControl -ne 'off') {
- if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
- [Console]::Error.WriteLine('supervisor: model casting requires node on PATH')
- return 2
- }
- if (-not (Test-Path -LiteralPath $modelCastingPath -PathType Leaf)) {
- [Console]::Error.WriteLine("supervisor: model casting resolver is not readable: $modelCastingPath")
- return 2
- }
- $nodeArgs = @($modelCastingPath, '--selector', $agentsSelector)
- if (-not [string]::IsNullOrEmpty($modelRegistry)) {
- $nodeArgs += @('--registry', $modelRegistry)
- }
- if (-not [string]::IsNullOrEmpty($providerCapability)) {
- $nodeArgs += @('--provider-capability', $providerCapability)
- }
- $previousErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Continue'
- $castingOutput = @(& node @nodeArgs 2>&1)
- $castingExitCode = $LASTEXITCODE
- } finally {
- $ErrorActionPreference = $previousErrorActionPreference
- }
- $castingJson = ($castingOutput | ForEach-Object { [string]$_ }) -join [Environment]::NewLine
- if ($castingExitCode -ne 0) {
- [Console]::Error.WriteLine($castingJson.Trim())
- return 2
- }
- try {
- $casting = $castingJson | ConvertFrom-Json -ErrorAction Stop
- } catch {
- [Console]::Error.WriteLine("supervisor: model casting resolver returned invalid JSON: $($_.Exception.Message)")
- return 2
- }
- $castingEnabled = [bool]$casting.enabled
- if ($castingEnabled) {
- $keepModelPin = (Get-EnvOrDefault 'AUTOPROMPT_KEEP_MODEL_PIN' '0') -eq '1'
- if ($keepModelPin -and -not [string]::IsNullOrEmpty($env:CLAUDE_CODE_SUBAGENT_MODEL)) {
- [Console]::Error.WriteLine('supervisor: AUTOPROMPT_KEEP_MODEL_PIN=1 conflicts with model casting because CLAUDE_CODE_SUBAGENT_MODEL is set')
- return 2
- }
- $baseUrlProperty = $casting.endpoint.PSObject.Properties['baseUrl']
- if ($null -ne $baseUrlProperty) { $castingBaseUrl = [string]$baseUrlProperty.Value }
- $apiKeyProperty = $casting.endpoint.PSObject.Properties['apiKeyEnv']
- if ($null -ne $apiKeyProperty) { $castingApiKeyEnv = [string]$apiKeyProperty.Value }
- if (-not [string]::IsNullOrEmpty($castingApiKeyEnv)) {
- $castingAuthToken = [Environment]::GetEnvironmentVariable($castingApiKeyEnv)
- if ([string]::IsNullOrEmpty($castingAuthToken)) {
- [Console]::Error.WriteLine("supervisor: model casting credential environment variable is unset or empty: $castingApiKeyEnv")
- return 2
- }
- }
- }
- }
- if (Get-Command node -ErrorAction SilentlyContinue) {
- $configuredVersion = Get-EnvOrDefault 'AUTOPROMPT_CLI_VERSION' ''
- if (-not [string]::IsNullOrEmpty($configuredVersion)) {
- $capabilityCliVersion = $configuredVersion
- } else {
- $cliCommand = if (-not [string]::IsNullOrEmpty($launchCmd)) { ($launchCmd -split '\s+')[0] } else { $launcher }
- if (-not [string]::IsNullOrEmpty($cliCommand) -and (Get-Command $cliCommand -ErrorAction SilentlyContinue)) {
- try { $capabilityCliVersion = [string]((& $cliCommand --version 2>$null | Select-Object -First 1)) } catch {}
- }
- }
- if ($launchCmd -match '(?:^|\s)--dangerously-skip-permissions(?:\s|$)') {
- $capabilityPermissionProfile = 'bypass-permissions'
- } else {
- $capabilityPermissionProfile = Get-EnvOrDefault 'AUTOPROMPT_PERMISSION_PROFILE' 'default'
- }
- $capabilityAgentDefinitionsHash = Get-AgentDefinitionsHash `
- -ModelCastingPath $modelCastingPath `
- -AgentsDirectory $agentDefinitionsPath
- if ($castingEnabled) {
- $bytes = [Text.Encoding]::UTF8.GetBytes($castingJson)
- $sha = [Security.Cryptography.SHA256]::Create()
- try { $capabilityCastingHash = 'sha256:' + ([BitConverter]::ToString($sha.ComputeHash($bytes)) -replace '-', '').ToLowerInvariant() }
- finally { $sha.Dispose() }
- $capabilityEffortStatus = [string]$casting.effort.status
- $capabilityEffortSource = [string]$casting.effort.source
- }
- if ($capabilityCliVersion -ne 'unknown' -and
- $capabilityAgentDefinitionsHash -ne 'unknown' -and
- -not [string]::IsNullOrEmpty($suppliedCapabilityAttestation)) {
- $expectedBindings = @(
- $capabilityProvider,
- $capabilityCliVersion,
- $capabilityPermissionProfile,
- $agentsSelector,
- $capabilityAgentDefinitionsHash,
- $capabilityCastingHash,
- $capabilityEffortStatus,
- $capabilityEffortSource
- )
- if (Test-CapabilityAttestation `
- -Raw $suppliedCapabilityAttestation `
- -Expected $expectedBindings) {
- $capabilityAttestation = $suppliedCapabilityAttestation
- }
- }
- }
- $agentDefinitionsJson = ''
- if (-not $dryRun) {
- if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
- [Console]::Error.WriteLine('supervisor: activation-scoped agents require node on PATH')
- return 2
- }
- if (-not (Test-Path -LiteralPath $agentDefinitionsCli -PathType Leaf)) {
- [Console]::Error.WriteLine("supervisor: agent-definition converter is not readable: $agentDefinitionsCli")
- return 2
- }
- $previousErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Continue'
- $agentDefinitionsOutput = @(
- & node $agentDefinitionsCli $agentDefinitionsPath 2>&1
- )
- $agentDefinitionsExitCode = $LASTEXITCODE
- } finally {
- $ErrorActionPreference = $previousErrorActionPreference
- }
- if ($agentDefinitionsExitCode -ne 0) {
- [Console]::Error.WriteLine(($agentDefinitionsOutput | ForEach-Object { [string]$_ }) -join [Environment]::NewLine)
- return 2
- }
- $agentDefinitionsJson = $agentDefinitionsOutput -join [Environment]::NewLine
- if ([string]::IsNullOrEmpty($agentDefinitionsJson)) {
- [Console]::Error.WriteLine('supervisor: agent-definition converter returned an empty cast')
- return 2
- }
- }
- $sentinelGlob = Get-EnvOrDefault 'SENTINEL' (Join-Path $ledgerDir 'DONE-*')
- $escalateFile = Join-Path $ledgerDir 'SUPERVISOR-ESCALATE'
- $snapshotFile = Join-Path $ledgerDir '.sentinel-snapshot'
- # EDIT 23: durable session-token store under the ledger dir, surviving across
- # relaunches of one conversation. Seeded before the loop, harvested after launches.
- $sessionTokenFile = Join-Path $ledgerDir '.session-token'
- # PLAN-auto-compact-threshold path vars. Discovery is CWD-AGNOSTIC and slug-free: it
- # matches the supervisor's own run cwd against each transcript's embedded "cwd" after
- # normalization -- NO slug derivation, NO launcher edit. Identical to supervisor.sh.
- $runCwd = (Get-EnvOrDefault 'RUN_CWD' (Get-Location).Path)
- $parentTranscript = Get-EnvOrDefault 'AUTOPROMPT_PARENT_TRANSCRIPT' ''
- $watermarkFile = Join-Path $ledgerDir '.context-watermark'
- $compactRequestFile = Join-Path $ledgerDir 'COMPACT-REQUEST'
- $compactStateFile = Join-Path $ledgerDir '.compaction-state'
- # Scope-budget state survives relaunches. The start epoch does not reset on
- # frontier growth; the reset counter clears once build evidence lands.
- $scopePhaseStartFile = Join-Path $ledgerDir '.scope-phase-start'
- $scopeResetsFile = Join-Path $ledgerDir '.scope-forced-resets'
- if (-not (Test-Path -LiteralPath $ledgerDir)) {
- New-Item -ItemType Directory -Path $ledgerDir -Force | Out-Null
- }
- # Supervisor start time (captured BEFORE the first launch). It is no longer part
- # of the stale-sentinel guarantee (see below) -- it is kept only to name the
- # quarantine target (superseded-<epoch>-...). Get-Date cannot fail here.
- $startTime = Get-Date
- # THE stale-sentinel guarantee is a LIVE STARTUP SNAPSHOT, not LastWriteTime.
- # Before the first launch we record every pre-existing DONE-* PATH into
- # $snapshotFile. Test-SentinelPresent REFUSES any DONE-* whose path is in that
- # snapshot -- regardless of LastWriteTime. As quarantine SUCCESSFULLY renames each
- # stale occupant aside it PRUNES that path from the snapshot, so a path is vetoed
- # IFF its stale occupant still physically exists. A DONE-* counts as THIS run's
- # completion if its path was NOT present at startup OR was present but has since
- # been cleared by a successful quarantine (the launcher then wrote a FRESH one
- # there -- the same-activation DONE-<nonce> case). A failed quarantine
- # rename leaves the path vetoed -> RELAUNCH, never a false halt. The
- # LastWriteTime>=start belt is gone -- it could not backstop the same-second
- # class, which is the whole reason this defense exists. FAIL-SAFE: if the snapshot
- # cannot be written or read, ALL DONE-* are treated as suspect -> relaunch.
- $script:state = @{
- DryRun = $dryRun
- LedgerDir = $ledgerDir
- SentinelGlob = $sentinelGlob
- LaunchIndex = 0
- StartTime = $startTime
- SnapshotFile = $snapshotFile
- SnapshotOk = $false
- SnapshotPaths = @{}
- ScopeEscalate = $false
- ScopeTerminal = $false
- }
- function Write-SupLog {
- param([string]$Message)
- $ts = (Get-Date).ToString('yyyy-MM-ddTHH:mm:ss')
- Write-Host "[supervisor $ts] $Message"
- }
- # Take the startup snapshot of pre-existing DONE-* PATHS, BEFORE the first
- # launch and BEFORE any sentinel check or quarantine. Each path is written on
- # its own line to $snapshotFile and held in a hashtable for O(1) lookup.
- # SnapshotOk=$true marks a trustworthy snapshot; if writing fails we leave it
- # $false, and Test-SentinelPresent then treats EVERY DONE-* as suspect
- # (relaunch), the fail-safe direction.
- function Save-PreExistingSentinels {
- $script:state.SnapshotOk = $false
- $script:state.SnapshotPaths = @{}
- try {
- $found = @(Get-ChildItem -Path $script:state.SentinelGlob -ErrorAction SilentlyContinue)
- $lines = New-Object System.Collections.Generic.List[string]
- foreach ($file in $found) {
- $lines.Add($file.FullName)
- $script:state.SnapshotPaths[$file.FullName] = $true
- }
- Set-Content -LiteralPath $script:state.SnapshotFile -Value $lines -Encoding ascii -ErrorAction Stop
- $script:state.SnapshotOk = $true
- } catch {
- $script:state.SnapshotOk = $false
- }
- }
- # Is $Path one of the paths recorded in the startup snapshot? If the snapshot is
- # not trustworthy (SnapshotOk=$false) we answer YES for every path -> every
- # DONE-* is treated as pre-existing -> never halts -> relaunch. That is the
- # deliberate fail-safe: a missing/unreadable snapshot must never permit a halt.
- function Test-PathInSnapshot {
- param([string]$Path)
- if (-not $script:state.SnapshotOk) { return $true }
- return $script:state.SnapshotPaths.ContainsKey($Path)
- }
- # Drop one path from the live snapshot so a genuinely-fresh sentinel can later
- # reclaim it. Called by quarantine ONLY after a SUCCESSFUL rename: once the stale
- # occupant has been moved aside, the path is empty, so the ONLY thing that can
- # appear there is a fresh sentinel written by THIS run. The activation nonce is
- # minted once (CSPRNG) and re-exported unchanged to every relaunched child (no
- # clock), so a re-launch of
- # the SAME activation writes the SAME path the snapshot recorded -- if the snapshot
- # kept vetoing it, that fresh sentinel would be refused forever and the supervisor
- # would relaunch without end (the livelock). We drop it from the in-memory set AND
- # rewrite $SnapshotFile so a mid-run re-read agrees. If the rewrite fails we KEEP
- # the path in memory (over-veto = relaunch, never a false halt). A path whose
- # rename FAILED is never pruned, so it stays vetoed while its occupant still exists.
- function Remove-PathFromSnapshot {
- param([string]$Path)
- if (-not $script:state.SnapshotOk) { return }
- $script:state.SnapshotPaths.Remove($Path) | Out-Null
- try {
- $lines = New-Object System.Collections.Generic.List[string]
- foreach ($key in $script:state.SnapshotPaths.Keys) { $lines.Add($key) }
- Set-Content -LiteralPath $script:state.SnapshotFile -Value $lines -Encoding ascii -ErrorAction Stop
- } catch {
- # Rewrite failed: the in-memory set already dropped the path (the source of
- # truth for this process); the on-disk copy is only for a mid-run re-read,
- # which this port does not do. Leaving it stale cannot cause a false halt.
- }
- }
- # A DONE-sentinel counts as THIS run's completion iff it exists, carries the
- # done marker, AND its path is NOT in the LIVE startup snapshot. The snapshot
- # starts as every pre-existing DONE-* path and is pruned as quarantine clears
- # each one, so a path is vetoed IFF its stale occupant still physically exists;
- # a fresh sentinel at a cleared path is honored. Mirrors the .sh for-loop glob +
- # grep '"done"\s*:\s*true'.
- function Test-SentinelPresent {
- if (-not $legacySentinel) {
- $sentinelPath = Join-Path $script:state.LedgerDir "DONE-$runNonce"
- if (-not (Test-Path -LiteralPath $sentinelPath -PathType Leaf) -or
- (Test-PathInSnapshot $sentinelPath)) {
- return $false
- }
- try {
- $sentinel = Get-Content -LiteralPath $sentinelPath -Raw -ErrorAction Stop |
- ConvertFrom-Json -ErrorAction Stop
- $done = $sentinel.PSObject.Properties['done']
- $nonce = $sentinel.PSObject.Properties['nonce']
- return $null -ne $done -and $done.Value -is [bool] -and $done.Value -eq $true -and
- $null -ne $nonce -and $nonce.Value -is [string] -and $nonce.Value -ceq $runNonce
- } catch {
- return $false
- }
- }
- $found = @(Get-ChildItem -Path $script:state.SentinelGlob -File -ErrorAction SilentlyContinue)
- foreach ($file in $found) {
- $content = Get-Content -LiteralPath $file.FullName -Raw -ErrorAction SilentlyContinue
- if ($null -ne $content -and $content -match '"done"\s*:\s*true') {
- if (-not (Test-PathInSnapshot $file.FullName)) {
- return $true
- }
- }
- }
- return $false
- }
- # At startup, BEFORE the first launch, QUARANTINE every pre-existing done:true
- # DONE-* sentinel: rename it aside to <dir>\superseded-<start-epoch>-<name> so
- # the new name no longer starts with DONE- and thus no longer matches the live
- # DONE-* glob -- it cannot halt this fresh mission. (Prefixing, NOT suffixing: a
- # DONE-X.superseded-N name would STILL match DONE-* and re-trip the same-second
- # halt, so the leading DONE- must be displaced.) This is the PRIMARY fix for the
- # whole stale-sentinel class -- after quarantine there is no leftover sentinel
- # left to race, so a same-second / sub-second LastWriteTime collision is moot.
- # We RENAME, never delete (deleting artifacts is the JANITOR's job; never
- # silently remove operator files) and log a loud line naming each quarantined
- # file. On a SUCCESSFUL rename the path is pruned from the live snapshot so a
- # genuine fresh same-activation DONE-<nonce> (the minted nonce is re-exported to
- # every relaunched child, no clock) can reclaim it -- else the snapshot would veto
- # that fresh sentinel forever and the supervisor would relaunch without end
- # (livelock). If a rename FAILS (read-only dir / permissions / clobber) the
- # leftover DONE-* still matches the live glob, its path is NOT pruned, and
- # Test-SentinelPresent unconditionally refuses it. A failed rename degrades to
- # RELAUNCH, never a halt. Net invariant: the snapshot vetoes a path IFF its stale
- # occupant still exists.
- function Move-StaleSentinelAside {
- $startEpoch = [int64][Math]::Floor(([DateTimeOffset]$script:state.StartTime).ToUnixTimeSeconds())
- $found = @(Get-ChildItem -Path $script:state.SentinelGlob -File -ErrorAction SilentlyContinue)
- foreach ($file in $found) {
- $content = Get-Content -LiteralPath $file.FullName -Raw -ErrorAction SilentlyContinue
- if ($null -ne $content -and $content -match '"done"\s*:\s*true') {
- $quarantined = Join-Path $file.DirectoryName "superseded-$startEpoch-$($file.Name)"
- try {
- Move-Item -LiteralPath $file.FullName -Destination $quarantined -Force -ErrorAction Stop
- # The stale occupant is gone, so this path can no longer hold
- # anything but a FRESH this-run sentinel. Drop it from the live
- # snapshot so the same-activation DONE-<nonce> is
- # reclaimable -- otherwise the snapshot would veto the genuine
- # fresh sentinel forever (the livelock).
- Remove-PathFromSnapshot $file.FullName
- Write-SupLog "QUARANTINE: pre-existing DONE-sentinel '$($file.FullName)' (from a prior run) renamed to '$quarantined' so it cannot halt this fresh mission. It is preserved, not deleted."
- } catch {
- Write-SupLog "WARNING: could not quarantine pre-existing DONE-sentinel '$($file.FullName)' -- it is IGNORED for halting by the startup snapshot and will not stop this mission. Remove it if it is no longer relevant."
- }
- }
- }
- }
- # The frontier marker is a monotonic forward-progress counter, not a success
- # counter. In real runs it counts roadmap/scout, plan, build, assurance, sweep,
- # arbitration, and goal-check artifacts. Versioned, per-feature, retained-scout,
- # and per-round files multiply as work proceeds, so an advancing pre-build scope
- # that writes roadmap and retained scout evidence long
- # before any plan-final -- bumps the count every relaunch and resets the
- # poison window; a run writing nothing new stays flat and still trips poison.
- function Get-FrontierCount {
- if ($script:state.DryRun) {
- if ((Get-EnvOrDefault 'FAKE_POISON' '0') -eq '1') { return 0 }
- $counterFile = Join-Path $script:state.LedgerDir '.fake-frontier'
- if (Test-Path -LiteralPath $counterFile) {
- return [int]((Get-Content -LiteralPath $counterFile -Raw).Trim())
- }
- return 0
- }
- $count = 0
- # Three artifact layouts must ALL be counted, or a run driven by one of them
- # is invisible to the frontier and a healthy-long run trips POISON:
- # prose/agent (SKILL.md/GATES.md): autoprompt/prompt-NNN-<slug>/artifacts/
- # harness (autoprompt-gate.js ARTIFACT_DIR): autoprompt/.artifacts/<run-tag>/
- # session ledger (SPEC-1 SCRIBE): autoprompt/session_NN/prompt_NN-<slug>/ and
- # its optional artifacts/ subdir. The per-prompt ledger .md files
- # (BRIEF/GATELOG/COVERAGE...) count as forward progress (monotonic; same
- # rationale as the multiplying-artifacts globs), so a run advancing ONLY in
- # the new layout is never falsely poisoned.
- # The leading-dot harness dir is not matched by the prose "*" wildcard and its
- # nesting differs, so it needs its own glob -- which also stops the prose glob
- # from double-counting it. Ledger-root prose files (BRIEF/PLAN/GATELOG...) live
- # one level above artifacts/ so they are not counted by the first two globs; the
- # session-ledger glob counts them at their nested depth. The DONE sentinel lives
- # at the ledger root, not under any artifacts/ dir.
- $proseArtifacts = Join-Path (Join-Path $script:state.LedgerDir '*') 'artifacts'
- $harnessArtifacts = Join-Path (Join-Path $script:state.LedgerDir '.artifacts') '*'
- $artifactGlobs = @(
- (Join-Path $proseArtifacts '*.md')
- (Join-Path $harnessArtifacts '*.md')
- (Join-Path (Join-Path (Join-Path $script:state.LedgerDir 'session_*') 'prompt_*') (Join-Path 'artifacts' '*.md'))
- (Join-Path (Join-Path (Join-Path $script:state.LedgerDir 'session_*') 'prompt_*') '*.md')
- )
- $count += @(Get-ChildItem -Path $artifactGlobs -File -ErrorAction SilentlyContinue).Count
- return $count
- }
- # Scope wall-clock budget starts at launch, before the author can emit an artifact,
- # and goes dormant only when build evidence lands.
- function Get-ScopePhaseElapsed {
- if ($script:state.DryRun) {
- $fse = Get-EnvOrDefault 'FAKE_SCOPE_ELAPSED' ''
- if (-not [string]::IsNullOrEmpty($fse)) { return [int]$fse }
- return $null
- }
- $ld = $script:state.LedgerDir
- $buildGlobs = @(
- (Join-Path (Join-Path (Join-Path $ld '.artifacts') '*') '*-impl-v*.md')
- (Join-Path (Join-Path (Join-Path $ld '*') 'artifacts') '*-impl-v*.md')
- (Join-Path (Join-Path (Join-Path (Join-Path $ld 'session_*') 'prompt_*') 'artifacts') '*-impl-v*.md')
- )
- if (@(Get-ChildItem -Path $buildGlobs -File -ErrorAction SilentlyContinue).Count -gt 0) {
- Remove-Item -LiteralPath $scopePhaseStartFile -Force -ErrorAction SilentlyContinue
- Remove-Item -LiteralPath $scopeResetsFile -Force -ErrorAction SilentlyContinue
- Remove-Item -LiteralPath (Join-Path $ld 'SCOPE-CONVERGE-REQUEST') -Force -ErrorAction SilentlyContinue
- Remove-Item -LiteralPath (Join-Path $ld 'SCOPE-BUDGET-BREACH') -Force -ErrorAction SilentlyContinue
- return $null
- }
- $nowS = [int64][Math]::Floor(([DateTimeOffset](Get-Date)).ToUnixTimeSeconds())
- $startS = 0
- $storedBinding = ''
- if (Test-Path -LiteralPath $scopePhaseStartFile) {
- try {
- $first = (Get-Content -LiteralPath $scopePhaseStartFile -First 1 -ErrorAction Stop)
- if ($null -ne $first) {
- $fields = ([string]$first).Trim() -split '\s+'
- if ($fields.Count -ge 1) { [void][int64]::TryParse($fields[0], [ref]$startS) }
- if ($fields.Count -ge 2) { $storedBinding = $fields[1] }
- }
- } catch { $startS = 0; $storedBinding = '' }
- }
- if ($storedBinding -cne $scopeMissionBinding) {
- $startS = 0
- Remove-Item -LiteralPath (Join-Path $ld 'SCOPE-CONVERGE-REQUEST') -Force -ErrorAction SilentlyContinue
- Remove-Item -LiteralPath (Join-Path $ld 'SCOPE-BUDGET-BREACH') -Force -ErrorAction SilentlyContinue
- Remove-Item -LiteralPath $scopeResetsFile -Force -ErrorAction SilentlyContinue
- }
- if ($startS -le 0) {
- $startS = $nowS
- try {
- $tmp = "$scopePhaseStartFile.tmp"
- "$startS $scopeMissionBinding" | Set-Content -LiteralPath $tmp -Encoding ascii
- Move-Item -LiteralPath $tmp -Destination $scopePhaseStartFile -Force
- } catch { }
- }
- $elapsed = $nowS - $startS
- if ($elapsed -lt 0) { $elapsed = 0 }
- return [int]$elapsed
- }
- # Honest retained scope evidence: roadmap-scout-N on new runs, scope-<key> on
- # legacy resumes. Missing evidence stays missing rather than being invented.
- function Get-ScopeLandedAngles {
- if ($script:state.DryRun) { return (Get-EnvOrDefault 'FAKE_SCOPE_LANDED' '') }
- $ld = $script:state.LedgerDir
- $scopeGlobs = @(
- (Join-Path (Join-Path (Join-Path $ld '.artifacts') '*') 'roadmap-scout-*.md')
- (Join-Path (Join-Path (Join-Path $ld '*') 'artifacts') 'roadmap-scout-*.md')
- (Join-Path (Join-Path (Join-Path (Join-Path $ld 'session_*') 'prompt_*') 'artifacts') 'roadmap-scout-*.md')
- (Join-Path (Join-Path (Join-Path $ld '.artifacts') '*') 'scope-*.md')
- (Join-Path (Join-Path (Join-Path $ld '*') 'artifacts') 'scope-*.md')
- (Join-Path (Join-Path (Join-Path (Join-Path $ld 'session_*') 'prompt_*') 'artifacts') 'scope-*.md')
- )
- $keys = New-Object System.Collections.Generic.List[string]
- foreach ($file in @(Get-ChildItem -Path $scopeGlobs -File -ErrorAction SilentlyContinue)) {
- $key = if ($file.Name -like 'roadmap-scout-*.md') {
- $file.Name -replace '\.md$', ''
- } else {
- $file.Name -replace '^scope-', '' -replace '-v[0-9]+\.md$', '' -replace '\.md$', ''
- }
- if (-not [string]::IsNullOrEmpty($key) -and -not $keys.Contains($key)) { $keys.Add($key) }
- }
- return ($keys -join ',')
- }
- # Age (seconds) of the pending SCOPE-CONVERGE-REQUEST, or 0 when none exists.
- function Get-ScopeConvergeRequestAge {
- $req = Join-Path $script:state.LedgerDir 'SCOPE-CONVERGE-REQUEST'
- if (-not (Test-Path -LiteralPath $req)) { return 0 }
- $nowS = [int64][Math]::Floor(([DateTimeOffset](Get-Date)).ToUnixTimeSeconds())
- $reqTs = 0
- try {
- $first = (Get-Content -LiteralPath $req -First 1 -ErrorAction Stop)
- if ($null -ne $first) { $f = ([string]$first).Trim() -split '\s+'; if ($f.Count -ge 1) { [void][int64]::TryParse($f[0], [ref]$reqTs) } }
- } catch { $reqTs = 0 }
- $age = $nowS - $reqTs
- if ($age -lt 0) { $age = 0 }
- return [int]$age
- }
- # === PLAN-auto-compact-threshold: proactive supervisor-fired compaction ==========
- # The PowerShell port of canon_path / find_parent_transcript / read_context_estimate
- # / note_external_compaction / maybe_request_compaction / kill_tree. The slug-free
- # discovery rule (single-level glob + embedded-cwd match + newest-since-launch) is
- # BYTE-FOR-BYTE the same decision as supervisor.sh -- there is no slug to diverge on.
- # Canonicalize a path for cross-platform cwd comparison (win32 AND posix): lowercase;
- # collapse \ and / runs to a single /; map a leading "<drive>:" to "/<drive>".
- function Get-CanonPath {
- param([string]$Path)
- if ($null -eq $Path) { return '' }
- $p = $Path.ToLowerInvariant() -replace '\\', '/'
- $p = $p -replace '/+', '/'
- $p = $p -replace '^([a-z]):', '/$1'
- return $p
- }
- # Find the live parent session .jsonl. Slug-free: matches $runCwd against each
- # transcript's embedded "cwd" after canonicalization. Single-level glob excludes
- # nested subagent/tool-result transcripts. Returns the path or $null.
- function Find-ParentTranscript {
- param([long]$LaunchEpoch)
- if (-not [string]::IsNullOrEmpty($parentTranscript) -and (Test-Path -LiteralPath $parentTranscript)) {
- return $parentTranscript
- }
- $cfg = Get-EnvOrDefault 'CLAUDE_CONFIG_DIR' (Join-Path $HOME '.claude')
- $want = Get-CanonPath $runCwd
- $glob = Join-Path (Join-Path $cfg 'projects') (Join-Path '*' '*.jsonl')
- $newest = $null; $newestMt = [long]0
- foreach ($f in @(Get-ChildItem -Path $glob -File -ErrorAction SilentlyContinue)) {
- $mt = [int64][Math]::Floor(([DateTimeOffset]$f.LastWriteTimeUtc).ToUnixTimeSeconds())
- if ($mt -lt $LaunchEpoch) { continue } # stale prior session
- $tcwd = $null
- try {
- foreach ($line in [System.IO.File]::ReadLines($f.FullName)) {
- $m = [regex]::Match($line, '"cwd":"([^"]*)"')
- if ($m.Success) { $tcwd = $m.Groups[1].Value; break }
- }
- } catch { $tcwd = $null }
- if ([string]::IsNullOrEmpty($tcwd)) { continue }
- $tcwd = $tcwd -replace '\\\\', '\' # un-escape JSON doubled backslashes
- if ((Get-CanonPath $tcwd) -ne $want) { continue }
- if ($mt -gt $newestMt) { $newest = $f.FullName; $newestMt = $mt }
- }
- return $newest
- }
- # Read the PARENT's context size in three tiers; returns an integer (0 = unavailable).
- # TIER 1 parse transcript usage (byte proxy on parse failure); TIER 2 watermark
- # (stale-rejected); TIER 3 coarse ledger-byte proxy. Honors FAKE_WATERMARK in dry-run.
- function Read-ContextEstimate {
- param([long]$LaunchEpoch)
- if ($script:state.DryRun) {
- $fw = Get-EnvOrDefault 'FAKE_WATERMARK' ''
- if (-not [string]::IsNullOrEmpty($fw)) { return [int]$fw }
- return 0
- }
- $tx = Find-ParentTranscript -LaunchEpoch $LaunchEpoch
- if (-not [string]::IsNullOrEmpty($tx) -and (Test-Path -LiteralPath $tx)) {
- $lastUsage = $null
- try {
- foreach ($line in [System.IO.File]::ReadLines($tx)) {
- if ($line -notmatch '"usage"') { continue }
- try {
- $obj = $line | ConvertFrom-Json
- if ($obj.message -and $obj.message.usage) { $lastUsage = $obj.message.usage }
- } catch { }
- }
- } catch { $lastUsage = $null }
- if ($null -ne $lastUsage) {
- $sum = 0
- foreach ($k in @('input_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens')) {
- $v = $lastUsage.$k
- if ($null -ne $v) { $sum += [int]$v }
- }
- if ($sum -gt 0) { return $sum }
- }
- try {
- $sz = (Get-Item -LiteralPath $tx).Length
- if ($sz -gt 0) { return [int]([math]::Floor($sz / $bytesPerToken)) }
- } catch { }
- }
- if (Test-Path -LiteralPath $watermarkFile) {
- try {
- $first = (Get-Content -LiteralPath $watermarkFile -First 1 -ErrorAction Stop)
- if ($null -ne $first) {
- $fields = ([string]$first).Trim() -split '\s+'
- $wmTok = 0
- if ($fields.Count -ge 1 -and [int]::TryParse($fields[0], [ref]$wmTok)) {
- $wmTs = $null
- if ($fields.Count -ge 2) { $parsedTs = [long]0; if ([long]::TryParse($fields[1], [ref]$parsedTs)) { $wmTs = $parsedTs } }
- if ($null -eq $wmTs -or $wmTs -ge $LaunchEpoch) { return $wmTok }
- }
- }
- } catch { }
- }
- $bytes = [long]0
- $ledgerGlobs = @(
- (Join-Path (Join-Path (Join-Path $script:state.LedgerDir 'session_*') 'prompt_*') '*.md')
- (Join-Path (Join-Path (Join-Path $script:state.LedgerDir 'session_*') 'prompt_*') (Join-Path 'artifacts' '*.md'))
- (Join-Path (Join-Path $script:state.LedgerDir '*') (Join-Path 'artifacts' '*.md'))
- )
- foreach ($g in $ledgerGlobs) {
- foreach ($f in @(Get-ChildItem -Path $g -File -ErrorAction SilentlyContinue)) { $bytes += $f.Length }
- }
- return [int]([math]::Floor($bytes / $bytesPerToken))
- }
- # Detect a harness-fired compaction (a sharp estimate DROP across ticks): arm the
- # cooldown and clear any pending request so the supervisor does NOT double-fire.
- # Returns $true when an external compaction was detected.
- function Note-ExternalCompaction {
- param([long]$Now, [int]$CurrentEst)
- $prevEst = 0; $lastCompact = 0
- if (Test-Path -LiteralPath $compactStateFile) {
- try {
- $first = (Get-Content -LiteralPath $compactStateFile -First 1 -ErrorAction Stop)
- if ($null -ne $first) {
- $f = ([string]$first).Trim() -split '\s+'
- if ($f.Count -ge 1) { [void][int]::TryParse($f[0], [ref]$lastCompact) }
- if ($f.Count -ge 2) { [void][int]::TryParse($f[1], [ref]$prevEst) }
- }
- } catch { }
- }
- if ($prevEst -gt 0 -and (($prevEst - $CurrentEst) -ge $externalCompactDelta)) {
- try {
- $tmp = "$compactStateFile.tmp"
- "$Now $CurrentEst external_compaction" | Set-Content -LiteralPath $tmp -Encoding ascii
- Move-Item -LiteralPath $tmp -Destination $compactStateFile -Force
- } catch { }
- if (Test-Path -LiteralPath $compactRequestFile) { Remove-Item -LiteralPath $compactRequestFile -Force -ErrorAction SilentlyContinue }
- Write-SupLog "EXTERNAL COMPACTION detected: context estimate dropped $prevEst->$CurrentEst (>=$externalCompactDelta) -- arming cooldown and clearing any pending COMPACT-REQUEST (no double-fire)."
- return $true
- }
- try {
- $tmp = "$compactStateFile.tmp"
- "$lastCompact $CurrentEst" | Set-Content -LiteralPath $tmp -Encoding ascii
- Move-Item -LiteralPath $tmp -Destination $compactStateFile -Force
- } catch { }
- return $false
- }
- # Decide whether to request/force a compaction. Returns @{Requested=$bool; Force=$bool}.
- # Guards: cooldown, in-flight request, external-compaction detection.
- function Request-CompactionIfNeeded {
- param([long]$LaunchEpoch, [long]$Now)
- $result = @{ Requested = $false; Force = $false }
- $est = Read-ContextEstimate -LaunchEpoch $LaunchEpoch
- if (Note-ExternalCompaction -Now $Now -CurrentEst $est) { return $result }
- $lastCompact = 0
- if (Test-Path -LiteralPath $compactStateFile) {
- try {
- $first = (Get-Content -LiteralPath $compactStateFile -First 1 -ErrorAction Stop)
- if ($null -ne $first) { $f = ([string]$first).Trim() -split '\s+'; if ($f.Count -ge 1) { [void][int]::TryParse($f[0], [ref]$lastCompact) } }
- } catch { }
- }
- if ($lastCompact -gt 0 -and (($Now - $lastCompact) -lt $compactCooldown)) { return $result }
- if (Test-Path -LiteralPath $compactRequestFile) {
- $reqTs = 0
- try {
- $first = (Get-Content -LiteralPath $compactRequestFile -First 1 -ErrorAction Stop)
- if ($null -ne $first) { $f = ([string]$first).Trim() -split '\s+'; if ($f.Count -ge 1) { [void][int]::TryParse($f[0], [ref]$reqTs) } }
- } catch { }
- if (($Now - $reqTs) -ge $compactGrace) { $result.Force = $true; $result.Requested = $true }
- return $result
- }
- if ($est -ge $compactAt) {
- try {
- $tmp = "$compactRequestFile.tmp"
- "$Now proactive est=$est threshold=$compactAt" | Set-Content -LiteralPath $tmp -Encoding ascii
- Move-Item -LiteralPath $tmp -Destination $compactRequestFile -Force
- Write-SupLog "COMPACT-REQUEST written: context est=$est tokens >= AUTOPROMPT_COMPACT_AT=$compactAt. Parent will checkpoint+compact at its next gate boundary (not a wipe, not a stop)."
- } catch { }
- $result.Requested = $true
- }
- return $result
- }
- # Kill the child process AND every descendant so a wedged parent leaves NO orphaned
- # subagent (the ps1 analog of the .sh process-group kill_tree). Walks Win32_Process
- # ParentProcessId, killing leaves-first, then the root.
- function Stop-ProcessTree {
- param($Proc)
- if ($null -eq $Proc) { return }
- $rootId = $null
- try { $rootId = $Proc.Id } catch { $rootId = $null }
- if ($null -ne $rootId) {
- try {
- & taskkill.exe /T /F /PID $rootId 2>$null | Out-Null
- if ($LASTEXITCODE -eq 0) { return }
- } catch { }
- # Fallback: manual descendant walk if taskkill is unavailable or fails.
- try {
- $all = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue
- $toKill = New-Object System.Collections.Generic.List[int]
- $queue = New-Object System.Collections.Generic.Queue[int]
- $queue.Enqueue([int]$rootId)
- while ($queue.Count -gt 0) {
- $procId = $queue.Dequeue(); $toKill.Add($procId)
- foreach ($c in @($all | Where-Object { $_.ParentProcessId -eq $procId })) { $queue.Enqueue([int]$c.ProcessId) }
- }
- foreach ($victim in ($toKill.ToArray() | Sort-Object -Descending)) {
- try { Stop-Process -Id $victim -Force -ErrorAction SilentlyContinue } catch { }
- }
- } catch { }
- }
- try { $Proc.Kill() } catch { }
- }
- # Run the real or fake launcher once; return its exit code.
- #
- # HEARTBEAT (PLAN-idle-watchdog P3, behavior-parallel to supervisor.sh V3): the
- # child is launched in the BACKGROUND on BOTH the real exec AND the dry-run fake
- # path (via Start-Process -PassThru), so a SINGLE poll loop watches liveness +
- # frontier-COUNT staleness regardless of path (blocker 2: the poll loop is genuinely
- # exercised under --dry-run against a real process handle). While the child is alive,
- # if Get-FrontierCount has NOT grown beyond last-seen within $idleTimeout and no
- # sentinel exists, the run is ALIVE-BUT-IDLE -> Stop-Process so the outer relaunch
- # loop RESUMEs it (the automatic CONTINUE). DISTINCT from the EXIT-keyed poison guard
- # and FEEDS it: a heartbeat kill that produced no count growth is a no-progress
- # restart for the outer loop, so a wedged child still trips POISON after MAX_RESTARTS
- # (anti-thrash). The model-pin / session-token save -> set -> restore-in-finally
- # quartet wraps the Start-Process so the child inherits the neutralized env and this
- # supervisor's own env is restored after the child fully exits.
- function Invoke-Launcher {
- $script:state.LaunchIndex += 1
- $idx = $script:state.LaunchIndex
- $childLaunchEpoch = [int64][Math]::Floor(([DateTimeOffset](Get-Date)).ToUnixTimeSeconds())
- if (-not $script:state.DryRun) {
- $storedBinding = ''
- if (Test-Path -LiteralPath $scopePhaseStartFile) {
- try {
- $first = Get-Content -LiteralPath $scopePhaseStartFile -First 1 -ErrorAction Stop
- if ($null -ne $first) {
- $fields = ([string]$first).Trim() -split '\s+'
- if ($fields.Count -ge 2) { $storedBinding = $fields[1] }
- }
- } catch { $storedBinding = '' }
- }
- if ($storedBinding -cne $scopeMissionBinding) {
- Remove-Item -LiteralPath (Join-Path $ledgerDir 'SCOPE-CONVERGE-REQUEST') -Force -ErrorAction SilentlyContinue
- Remove-Item -LiteralPath (Join-Path $ledgerDir 'SCOPE-BUDGET-BREACH') -Force -ErrorAction SilentlyContinue
- Remove-Item -LiteralPath $scopeResetsFile -Force -ErrorAction SilentlyContinue
- try {
- $tmp = "$scopePhaseStartFile.tmp"
- "$childLaunchEpoch $scopeMissionBinding" | Set-Content -LiteralPath $tmp -Encoding ascii
- Move-Item -LiteralPath $tmp -Destination $scopePhaseStartFile -Force
- } catch {}
- }
- }
- $absLedger = $script:state.LedgerDir
- if (-not [System.IO.Path]::IsPathRooted($absLedger)) {
- $absLedger = Join-Path (Get-Location).Path $absLedger
- }
- if ($script:state.DryRun) {
- # Compute everything in the PARENT (idx-indexed), then background a generated
- # fake-child script via Start-Process so the poll loop has a real handle. The
- # fake writes the sentinel / advances the frontier / optionally stays alive
- # (FAKE_CHILD_ALIVE seconds) then exits with the popped code - exactly the
- # work the old synchronous fake did, now in a real backgrounded process.
- $sentinelAfter = Get-EnvOrDefault 'FAKE_SENTINEL_AFTER' ''
- $writeSentinel = (-not [string]::IsNullOrEmpty($sentinelAfter) -and $idx -ge [int]$sentinelAfter)
- $advance = ((Get-EnvOrDefault 'FAKE_POISON' '0') -ne '1')
- $alive = [int](Get-EnvOrDefault 'FAKE_CHILD_ALIVE' 0)
- $fakeExits = (Get-EnvOrDefault 'FAKE_EXITS' '0').Trim()
- $codes = @($fakeExits -split '\s+' | Where-Object { $_ -ne '' })
- $code = 0
- if ($idx -ge 1 -and $idx -le $codes.Count) { $code = [int]$codes[$idx - 1] }
- $fakeChild = Join-Path $absLedger '.fake-child.ps1'
- @(
- 'param($Ledger,$WriteSentinel,$Advance,$Alive,$Code)'
- 'if ($WriteSentinel -eq "1") {'
- ' $done = Join-Path $Ledger "DONE-FAKE"'
- ' $tmp = "$done.tmp"'
- ' ''{"done": true, "nonce": "FAKE", "verdict": "fake done", "ts": "now"}'' | Set-Content -LiteralPath $tmp -Encoding ascii -NoNewline'
- ' Move-Item -LiteralPath $tmp -Destination $done -Force'
- '}'
- 'if ($Advance -eq "1") {'
- ' $cf = Join-Path $Ledger ".fake-frontier"'
- ' $cur = 0; if (Test-Path -LiteralPath $cf) { $cur = [int]((Get-Content -LiteralPath $cf -Raw).Trim()) }'
- ' ($cur + 1) | Set-Content -LiteralPath $cf -Encoding ascii -NoNewline'
- '}'
- 'if ($Alive -gt 0) { Start-Sleep -Seconds $Alive }'
- 'exit $Code'
- ) -join "`n" | Set-Content -LiteralPath $fakeChild -Encoding ascii
- $wsArg = if ($writeSentinel) { '1' } else { '0' }
- $advArg = if ($advance) { '1' } else { '0' }
- $proc = Start-Process -FilePath 'powershell' `
- -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $fakeChild, $absLedger, $wsArg, $advArg, "$alive", "$code") `
- -PassThru -NoNewWindow -WorkingDirectory (Get-Location).Path
- return (Wait-ChildWithHeartbeat -Proc $proc)
- }
- # Launch one is fresh unless the operator explicitly requested resume.
- # Relaunches always export AUTOPROMPT_RESUME=1.
- # When $launchCmd is set it is used VERBATIM (word-split into command +
- # args, mission appended) so a fresh user can pass their real CLI;
- # otherwise the bare $launcher label is exec'd as before.
- # Neutralize the operator's CLAUDE_CODE_SUBAGENT_MODEL for the CHILD CLI
- # ONLY. That var has HIGHEST precedence in the harness and force-pins every
- # (even nested) subagent onto a fixed model, defeating the skill's
- # `model: inherit` contract. PowerShell env is process-scoped, so the
- # faithful analog of the .sh `env -u` is save -> set $null -> restore in
- # `finally`: the backgrounded child inherits the var UNSET while this
- # supervisor process's own value (and the operator's shell/profile) is
- # restored intact after the child exits. `inherit` then resolves to the real
- # session/--model selection. Idempotent: a null/inherit/unset prior value
- # round-trips with no error. AUTOPROMPT_KEEP_MODEL_PIN=1 opts OUT.
- $keepModelPin = (Get-EnvOrDefault 'AUTOPROMPT_KEEP_MODEL_PIN' '0') -eq '1'
- $previousSubagentModel = $env:CLAUDE_CODE_SUBAGENT_MODEL
- $previousUnattended = $env:AUTOPROMPT_UNATTENDED
- $previousResume = $env:AUTOPROMPT_RESUME
- $previousMode = $env:AUTOPROMPT_MODE
- $previousRunNonce = $env:AUTOPROMPT_RUN_NONCE
- $previousLedgerCheck = $env:AUTOPROMPT_LEDGER_CHECK
- $previousSessionToken = $env:AUTOPROMPT_SESSION_TOKEN
- $previousAgents = $env:AUTOPROMPT_AGENTS
- $previousAgentCasting = $env:AUTOPROMPT_AGENT_CASTING
- $previousCapabilityAttestation = $env:AUTOPROMPT_CAPABILITY_ATTESTATION
- $previousProvider = $env:AUTOPROMPT_PROVIDER
- $previousCliVersion = $env:AUTOPROMPT_CLI_VERSION
- $previousPermissionProfile = $env:AUTOPROMPT_PERMISSION_PROFILE
- $previousAgentDefinitionsHash = $env:AUTOPROMPT_AGENT_DEFINITIONS_HASH
- $previousCastingHash = $env:AUTOPROMPT_CASTING_HASH
- $previousOpusModel = $env:ANTHROPIC_DEFAULT_OPUS_MODEL
- $previousSonnetModel = $env:ANTHROPIC_DEFAULT_SONNET_MODEL
- $previousHaikuModel = $env:ANTHROPIC_DEFAULT_HAIKU_MODEL
- $previousBaseUrl = $env:ANTHROPIC_BASE_URL
- $previousAuthToken = $env:ANTHROPIC_AUTH_TOKEN
- $env:AUTOPROMPT_UNATTENDED = '1'
- if ($idx -gt 1 -or $initialResume) {
- $env:AUTOPROMPT_RESUME = '1'
- } else {
- $env:AUTOPROMPT_RESUME = $null
- }
- $env:AUTOPROMPT_MODE = $autopromptMode
- if (-not $legacySentinel) { $env:AUTOPROMPT_RUN_NONCE = $runNonce }
- $env:AUTOPROMPT_LEDGER_CHECK = $ledgerCheckPath
- if (-not [string]::IsNullOrEmpty($sessionToken)) {
- $env:AUTOPROMPT_SESSION_TOKEN = $sessionToken
- } else {
- $env:AUTOPROMPT_SESSION_TOKEN = $null
- }
- if (-not $keepModelPin) { $env:CLAUDE_CODE_SUBAGENT_MODEL = $null }
- $env:AUTOPROMPT_AGENTS = $agentsSelector
- $env:AUTOPROMPT_PROVIDER = $capabilityProvider
- $env:AUTOPROMPT_CLI_VERSION = $capabilityCliVersion
- $env:AUTOPROMPT_PERMISSION_PROFILE = $capabilityPermissionProfile
- $env:AUTOPROMPT_AGENT_DEFINITIONS_HASH = $capabilityAgentDefinitionsHash
- $env:AUTOPROMPT_CASTING_HASH = $capabilityCastingHash
- $env:AUTOPROMPT_CAPABILITY_ATTESTATION = $capabilityAttestation
- if ($castingEnabled) {
- $env:AUTOPROMPT_AGENT_CASTING = $castingJson
- $env:ANTHROPIC_DEFAULT_OPUS_MODEL = [string]$casting.aliases.opus
- $env:ANTHROPIC_DEFAULT_SONNET_MODEL = [string]$casting.aliases.sonnet
- $env:ANTHROPIC_DEFAULT_HAIKU_MODEL = [string]$casting.aliases.haiku
- if (-not [string]::IsNullOrEmpty($castingBaseUrl)) {
- $env:ANTHROPIC_BASE_URL = $castingBaseUrl
- }
- if (-not [string]::IsNullOrEmpty($castingApiKeyEnv)) {
- $env:ANTHROPIC_AUTH_TOKEN = $castingAuthToken
- }
- }
- try {
- $launchWorkingDirectory = (Get-Location).Path
- if (-not [string]::IsNullOrEmpty($launchCmd)) {
- $parts = @($launchCmd -split '\s+' | Where-Object { $_ -ne '' })
- $exe = $parts[0]
- $rest = @($parts | Select-Object -Skip 1)
- $procArgs = @($rest + @('--agents', $agentDefinitionsJson, $mission))
- } else {
- $exe = $launcher
- $procArgs = @('--agents', $agentDefinitionsJson, $mission)
- }
- $nativeArguments = Join-NativeArguments -Arguments $procArgs
- $proc = Start-Process -FilePath $exe `
- -ArgumentList $nativeArguments -PassThru -NoNewWindow `
- -WorkingDirectory $launchWorkingDirectory
- return (Wait-ChildWithHeartbeat -Proc $proc)
- } catch {
- # A launcher that cannot be executed (a bad --cmd/--launcher: user typo
- # or missing alias) throws a TERMINATING error under 'Stop'. Mirror the
- # bash exit 127 so it feeds the SAME poison-guard/relaunch path instead
- # of unwinding the loop and crashing the supervisor with a stack trace.
- Write-SupLog "launch failed: $($_.Exception.Message)"
- return 127
- } finally {
- $env:AUTOPROMPT_UNATTENDED = $previousUnattended
- $env:AUTOPROMPT_RESUME = $previousResume
- $env:AUTOPROMPT_MODE = $previousMode
- $env:AUTOPROMPT_RUN_NONCE = $previousRunNonce
- $env:AUTOPROMPT_LEDGER_CHECK = $previousLedgerCheck
- $env:AUTOPROMPT_SESSION_TOKEN = $previousSessionToken
- $env:AUTOPROMPT_AGENTS = $previousAgents
- $env:AUTOPROMPT_AGENT_CASTING = $previousAgentCasting
- $env:AUTOPROMPT_CAPABILITY_ATTESTATION = $previousCapabilityAttestation
- $env:AUTOPROMPT_PROVIDER = $previousProvider
- $env:AUTOPROMPT_CLI_VERSION = $previousCliVersion
- $env:AUTOPROMPT_PERMISSION_PROFILE = $previousPermissionProfile
- $env:AUTOPROMPT_AGENT_DEFINITIONS_HASH = $previousAgentDefinitionsHash
- $env:AUTOPROMPT_CASTING_HASH = $previousCastingHash
- $env:ANTHROPIC_DEFAULT_OPUS_MODEL = $previousOpusModel
- $env:ANTHROPIC_DEFAULT_SONNET_MODEL = $previousSonnetModel
- $env:ANTHROPIC_DEFAULT_HAIKU_MODEL = $previousHaikuModel
- $env:ANTHROPIC_BASE_URL = $previousBaseUrl
- $env:ANTHROPIC_AUTH_TOKEN = $previousAuthToken
- $env:CLAUDE_CODE_SUBAGENT_MODEL = $previousSubagentModel
- $restoredModelPin = $env:CLAUDE_CODE_SUBAGENT_MODEL
- if ([string]::IsNullOrEmpty($restoredModelPin)) { $restoredModelPin = 'UNSET' }
- Write-SupLog "model-pin restored to $restoredModelPin"
- if ($castingEnabled) { Write-SupLog 'model-casting environment restored' }
- }
- }
- # Wait-ChildWithHeartbeat: poll a backgrounded child process for liveness +
- # frontier-COUNT staleness, killing it on an idle-timeout so the outer relaunch
- # loop RESUMEs it. Behavior-parallel to the supervisor.sh poll loop. Returns the
- # child's exit code (or 0 if a heartbeat kill pre-empted a clean exit code - the
- # outer loop then sees no count growth and treats it as a no-progress restart).
- # The poll wakes on a RESPONSIVE 200ms slice so a fast-exiting child is detected
- # promptly; the staleness evaluation runs only once per $heartbeatInterval of
- # elapsed wall-clock, preserving the exact heartbeat cadence.
- function Wait-ChildWithHeartbeat {
- param($Proc)
- $handle = $Proc.Handle # cache the OS handle so .ExitCode populates on exit
- $nowEpoch = { [int64][Math]::Floor(([DateTimeOffset](Get-Date)).ToUnixTimeSeconds()) }
- $childLaunchEpoch = & $nowEpoch
- $lastProgress = & $nowEpoch
- $lastEval = $lastProgress
- $lastSeenCount = Get-FrontierCount
- while (-not $Proc.HasExited) {
- Start-Sleep -Milliseconds 200
- if (Test-SentinelPresent) { break }
- $now = & $nowEpoch
- if (($now - $lastEval) -lt $heartbeatInterval) { continue }
- $lastEval = $now
- $curCount = Get-FrontierCount
- if ($curCount -gt $lastSeenCount) {
- $lastSeenCount = $curCount; $lastProgress = $now
- } elseif (($now - $lastProgress) -ge $idleTimeout) {
- Write-SupLog "HEARTBEAT: no frontier progress for >=${idleTimeout}s while alive and no sentinel -- killing to relaunch with RESUME (auto-continue an idle agent)."
- Stop-ProcessTree -Proc $Proc
- break
- }
- # PLAN-auto-compact-threshold: proactive supervisor-fired compaction check.
- $compact = Request-CompactionIfNeeded -LaunchEpoch $childLaunchEpoch -Now $now
- if ($compact.Force) {
- Write-SupLog "COMPACT FALLBACK: request unhonored for >=${compactGrace}s (parent likely wedged) -- recording a .forced-reset marker, then killing the WHOLE child process tree so no subagent is orphaned; the outer loop RESUMEs from the SCRIBE-refreshed ANCHOR.md."
- try {
- $tmp = (Join-Path $ledgerDir '.forced-reset.tmp')
- "$now forced est_unhonored grace=$compactGrace" | Set-Content -LiteralPath $tmp -Encoding ascii
- Move-Item -LiteralPath $tmp -Destination (Join-Path $ledgerDir '.forced-reset') -Force
- } catch { }
- try {
- $tmp2 = "$compactStateFile.tmp"
- "$now forced" | Set-Content -LiteralPath $tmp2 -Encoding ascii
- Move-Item -LiteralPath $tmp2 -Destination $compactStateFile -Force
- } catch { }
- if (Test-Path -LiteralPath $compactRequestFile) { Remove-Item -LiteralPath $compactRequestFile -Force -ErrorAction SilentlyContinue }
- Stop-ProcessTree -Proc $Proc
- break
- }
- # F-SPEED steer-2 B3: PHASE WALL-CLOCK BUDGET check. Once per tick, when the
- # SCOPE phase is active, consult phase-budget.js. Anchored to scope ENTRY, NOT
- # reset by frontier growth. Fail-open: an absent node/module skips the block.
- $scopeEl = Get-ScopePhaseElapsed
- if ($null -ne $scopeEl -and (Test-Path -LiteralPath $phaseBudgetPath)) {
- $reqAge = Get-ScopeConvergeRequestAge
- $prior = 0
- if (Test-Path -LiteralPath $scopeResetsFile) {
- try {
- $pf = (Get-Content -LiteralPath $scopeResetsFile -First 1 -ErrorAction Stop)
- if ($null -ne $pf) { [void][int]::TryParse(([string]$pf).Trim(), [ref]$prior) }
- } catch { $prior = 0 }
- }
- $landed = Get-ScopeLandedAngles
- & node $phaseBudgetPath --verdict --phase scope --elapsed $scopeEl `
- --soft $scopeSoftSec --hard $scopeHardSec --request-age $reqAge `
- --grace $scopeGraceSec --prior-resets $prior --max-resets $maxScopeResets `
- --landed $landed *> $null
- $verdictCode = $LASTEXITCODE
- $convergeReqFile = Join-Path $ledgerDir 'SCOPE-CONVERGE-REQUEST'
- if ($verdictCode -eq 10) {
- # SOFT breach: write the converge heads-up ONCE (idempotent), keep running.
- if (-not (Test-Path -LiteralPath $convergeReqFile)) {
- try {
- $tmp = "$convergeReqFile.tmp"
- "$now soft scope budget: mission=$scopeMissionBinding elapsed=${scopeEl}s soft=${scopeSoftSec}s landed=$landed -- converge on the landed angles; do NOT fabricate unscoped ones." | Set-Content -LiteralPath $tmp -Encoding ascii
- Move-Item -LiteralPath $tmp -Destination $convergeReqFile -Force
- } catch { }
- Write-SupLog "SCOPE BUDGET soft breach at ${scopeEl}s (>= ${scopeSoftSec}s, frontier advancing) -- wrote SCOPE-CONVERGE-REQUEST (converge on landed=$landed); child NOT killed."
- }
- } elseif ($verdictCode -eq 20) {
- # HARD/grace breach: durable marker (honest landed residual), bump counter, kill->RESUME.
- try {
- $breachFile = Join-Path $ledgerDir 'SCOPE-BUDGET-BREACH'
- $tmp = "$breachFile.tmp"
- "$now hard scope budget breach: mission=$scopeMissionBinding elapsed=${scopeEl}s hard=${scopeHardSec}s landed=$landed residual=$landed -- converge on landed, surface any unscoped angle; DO NOT fabricate." | Set-Content -LiteralPath $tmp -Encoding ascii
- Move-Item -LiteralPath $tmp -Destination $breachFile -Force
- } catch { }
- try {
- $tmpR = "$scopeResetsFile.tmp"
- "$($prior + 1)" | Set-Content -LiteralPath $tmpR -Encoding ascii
- Move-Item -LiteralPath $tmpR -Destination $scopeResetsFile -Force
- } catch { }
- Write-SupLog "SCOPE BUDGET hard breach at ${scopeEl}s (frontier was advancing) -- wrote SCOPE-BUDGET-BREACH (residual=$landed); killing the process tree and terminating this supervisor run."
- $script:state.ScopeTerminal = $true
- Stop-ProcessTree -Proc $Proc
- break
- } elseif ($verdictCode -eq 30) {
- # RE-BREACH past the reset cap: escalate honestly, never fake a roadmap.
- try {
- $lines = @(
- "supervisor escalation: scope budget breached past MAX_SCOPE_RESETS=$maxScopeResets"
- "scope_elapsed=$scopeEl hard=$scopeHardSec prior_resets=$prior landed=$landed"
- 'converge unreachable -- landed angles surfaced as the honest residual; NO fabricated roadmap'
- "ts=$((Get-Date).ToString())"
- )
- $lines -join [Environment]::NewLine | Set-Content -LiteralPath $escalateFile -Encoding ascii
- } catch { }
- Write-SupLog "SCOPE BUDGET escalation at ${scopeEl}s -- breached past MAX_SCOPE_RESETS=$maxScopeResets; landed=$landed surfaced as residual; killing and exiting 1."
- $script:state.ScopeEscalate = $true
- Stop-ProcessTree -Proc $Proc
- break
- }
- }
- }
- try { $Proc.WaitForExit() } catch {}
- $exit = 0
- try { if ($Proc.HasExited) { $exit = $Proc.ExitCode } } catch { $exit = 0 }
- if ($null -eq $exit) { $exit = 0 }
- return $exit
- }
- # Legacy broad DONE-* matching is a DOWNGRADE honored only for a verified
- # legacy resume: the operator opted in explicitly AND the ledger directory
- # carries physical evidence of a pre-nonce run (legacy governance files a
- # three-file new-format run never creates). A fresh or new-format directory
- # fails closed so the downgrade can never weaken a current-format run.
- if ($legacySentinel) {
- $legacyEvidence = $false
- foreach ($marker in @('BRIEF.md', 'AGENTS.md', 'bucketlist.md', 'ANCHOR.md')) {
- if (Test-Path -LiteralPath (Join-Path $ledgerDir $marker) -PathType Leaf) {
- $legacyEvidence = $true
- break
- }
- }
- if (-not $legacyEvidence) {
- [Console]::Error.WriteLine("supervisor: AUTOPROMPT_LEGACY_SENTINEL=1 requires a verified legacy resume (legacy governance files under $ledgerDir); unset it for new runs")
- return 2
- }
- }
- if ([string]::IsNullOrEmpty($launcher) -and [string]::IsNullOrEmpty($launchCmd) -and -not $dryRun) {
- [Console]::Error.WriteLine('supervisor: no launch command (use --cmd "<your CLI>" / AUTOPROMPT_LAUNCH_CMD, or --launcher apidemo|codexdemo / AUTOPROMPT_LAUNCHER)')
- return 2
- }
- $launcherLabel =
- if (-not [string]::IsNullOrEmpty($launchCmd)) { $launchCmd }
- elseif (-not [string]::IsNullOrEmpty($launcher)) { $launcher }
- else { '<dry-run>' }
- Write-SupLog "starting: launcher=$launcherLabel ledger=$ledgerDir mission=`"$mission`""
- Write-SupLog "topology: 5-level L0->L4; mode=$autopromptMode; per-L3 fan-out=$fanout; L3 tracks=$l3Tracks; L1 never executes (rule 68); single-block spawns (rule 67) -- enforced in the harness."
- # Snapshot pre-existing DONE-* PATHS FIRST, THEN quarantine. Order matters: the
- # snapshot must see the dir as it was before any rename, so a failed rename still
- # leaves the path recorded (and vetoed). Quarantine prunes each SUCCESSFULLY
- # renamed path back out of the snapshot, so the net invariant after this pair is:
- # a path is vetoed IFF its stale occupant still physically exists.
- Save-PreExistingSentinels
- Move-StaleSentinelAside
- # EDIT 23: seed the per-conversation session token ONCE, before the relaunch loop.
- # An env-supplied token (operator or a prior same-conversation export) wins and is
- # persisted to the durable file; else a previously-harvested token is read back;
- # else the token stays empty and the first SCRIBE-run resolver MINTS one. Fail-soft:
- # an unwritable/unreadable token file never aborts the run.
- if (-not [string]::IsNullOrEmpty($sessionToken)) {
- try { Set-Content -LiteralPath $sessionTokenFile -Value $sessionToken -Encoding ascii -ErrorAction Stop } catch {}
- } elseif (Test-Path -LiteralPath $sessionTokenFile) {
- try {
- $fileToken = (Get-Content -LiteralPath $sessionTokenFile -First 1 -ErrorAction Stop)
- if ($null -ne $fileToken) { $sessionToken = ([string]$fileToken).Trim() }
- } catch {}
- }
- [long[]]$restartTimes = @() # epoch seconds of recent restarts (no progress)
- $lastFrontier = Get-FrontierCount
- $backoff = $retryBase
- while ($true) {
- if (Test-SentinelPresent) {
- Write-SupLog 'DONE-sentinel present -- run complete, halting cleanly.'
- return 0
- }
- $exitCode = Invoke-Launcher
- # Scope budget termination is checked before sentinels so a breach cannot be
- # masked by output written during the same tick or poison-relaunch the mission.
- if ($script:state.ScopeEscalate) {
- return 1
- }
- if ($script:state.ScopeTerminal) {
- Write-SupLog 'SCOPE BUDGET terminal stop -- no same-mission relaunch will consume another worker.'
- return 124
- }
- if (Test-SentinelPresent) {
- Write-SupLog "DONE-sentinel present after launch (exit $exitCode) -- run complete, halting cleanly."
- return 0
- }
- # P4 (MANDATORY terminal caller, behavior-parallel to supervisor.sh V5): the
- # child EXITED with no DONE-sentinel -- a TERMINAL boundary for that child. Write
- # the RUN-ENDED marker so a ledger audit treats this as run-ended, then (real-run
- # only) run a best-effort terminal IDLE-FINISH audit. RUN-ENDED is the marker
- # autoprompt-ledger-check.js reads to set runEnded=true. Written every exit-
- # without-sentinel; idempotent (overwritten each exit). The clean-DONE path
- # short-circuits at the sentinel checks above, so RUN-ENDED is only ever written
- # when the run is genuinely not done.
- try {
- "run-ended exit=$exitCode ts=$(Get-Date)" | Set-Content -LiteralPath (Join-Path $ledgerDir 'RUN-ENDED') -Encoding ascii
- } catch {}
- if (-not $dryRun -and (Test-Path -LiteralPath $ledgerCheckPath)) {
- # Best-effort loud-log: the marker alone is sufficient for the rule to fire on
- # the NEXT audit, so this node call's non-zero exit is informational; the
- # relaunch happens regardless.
- try {
- & node $ledgerCheckPath --ledger-dir $ledgerDir --transcript-dir $ledgerDir --terminal *> $null
- if ($LASTEXITCODE -ne 0) {
- Write-SupLog 'IDLE-FINISH terminal audit flagged a P0 (run ended with open work, no live agent) -- relaunching with RESUME to re-drive.'
- }
- } catch {}
- }
- $now = [int64][Math]::Floor(([DateTimeOffset](Get-Date)).ToUnixTimeSeconds())
- $curFrontier = Get-FrontierCount
- # EDIT 23: HARVEST the resolver-minted session token after a launch when the
- # supervisor holds none yet. The SCRIBE-run --resolve-prompt-dir CLI writes the
- # marker "<LedgerDir>/.session-current" as "session_NN <token>" (two
- # whitespace-separated fields -- the EDIT 7 contract). Read the 2nd field and
- # persist it so the NEXT launch re-exports the SAME token and a 2nd prompt
- # rejoins the same session_NN. Fail-soft: an absent/corrupt marker (no 2nd
- # field) leaves the token empty and the next launch mints again.
- if ([string]::IsNullOrEmpty($sessionToken)) {
- $markerPath = Join-Path $ledgerDir '.session-current'
- if (Test-Path -LiteralPath $markerPath) {
- try {
- $markerLine = (Get-Content -LiteralPath $markerPath -First 1 -ErrorAction Stop)
- if ($null -ne $markerLine) {
- $fields = ([string]$markerLine).Trim() -split '\s+'
- if ($fields.Count -ge 2 -and -not [string]::IsNullOrEmpty($fields[1])) {
- $sessionToken = $fields[1]
- try { Set-Content -LiteralPath $sessionTokenFile -Value $sessionToken -Encoding ascii -ErrorAction Stop } catch {}
- }
- }
- } catch {}
- }
- }
- Write-SupLog "launcher exited ($exitCode); frontier $lastFrontier -> $curFrontier; no sentinel -- relaunching with RESUME."
- if ($curFrontier -gt $lastFrontier) {
- # Healthy-long: progress was made. Reset the poison window and backoff.
- $restartTimes = @()
- $backoff = $retryBase
- $lastFrontier = $curFrontier
- } else {
- # No progress since the last launch. Record this restart in the rolling
- # window and check the poison guard.
- $newTimes = New-Object System.Collections.Generic.List[long]
- $rapid = 1
- foreach ($t in $restartTimes) {
- if (($now - $t) -lt $window) {
- $newTimes.Add($t)
- $rapid += 1
- }
- }
- $newTimes.Add($now)
- $restartTimes = $newTimes.ToArray()
- if ($rapid -ge $maxRestarts) {
- Write-SupLog "POISON: $rapid restarts within ${window}s with NO frontier progress -- escalating, not relaunching."
- $escalateTs = (Get-Date).ToString()
- $lines = @(
- 'supervisor escalation: crash-loop with no frontier progress'
- "restarts_in_window=$rapid window_s=$window last_exit=$exitCode frontier=$curFrontier"
- "ts=$escalateTs"
- )
- $lines -join [Environment]::NewLine | Set-Content -LiteralPath $escalateFile -Encoding ascii
- return 1
- }
- # Exponential backoff, capped, between unproductive relaunches.
- if ($backoff -gt 0) { Start-Sleep -Seconds $backoff }
- $next = $backoff * 2
- if ($next -gt $retryCap) { $next = $retryCap }
- $backoff = $next
- }
- }
- }
- # Only auto-run when invoked as a script, not when dot-sourced by the test suite.
- if ($MyInvocation.InvocationName -ne '.') {
- $exit = Invoke-Supervisor -Argv $args
- exit $exit
- }
agents/claude/workflow/supervisor.sh · Bundled script · 1,272 lines · 1 finding marked
- #!/bin/sh
- # autoprompt supervisor - external auto-relaunch for a one-sitting unattended run.
- #
- # This is a STANDALONE OS PROCESS, NOT a Claude Code hook. It touches no
- # settings.json, registers no hook, and is launched by the operator (or a
- # tmux/nohup line). It honors the global no-hooks rule.
- #
- # It relaunches the autoprompt CLI with RESUME on any unexpected exit, loops
- # until the JANITOR has written the DONE-sentinel (autoprompt/DONE-<nonce>),
- # and has a crash-loop/poison-restart guard that distinguishes:
- # - a FINISHED run (sentinel present) -> clean halt
- # - a HEALTHY-LONG run (frontier advances) -> keep relaunching, no escalation
- # - a TRULY-STUCK run (no frontier progress) -> escalate, stop relaunching
- #
- # Usage:
- # supervisor.sh --launcher apidemo|codexdemo "<mission>"
- # supervisor.sh --cmd "claude --dangerously-skip-permissions -p" "<mission>"
- Note: Starts a coding agent with its permission prompts off
- Line 17 on GitHub
- # supervisor.sh --agents "auto:strong,cheap" --model-registry ~/.claude/autoprompt-models.json --cmd "claude -p" "<mission>"
- #
- # The launch command is resolved in this precedence:
- # 1. --cmd "<command>" / AUTOPROMPT_LAUNCH_CMD (used VERBATIM, word-split,
- # with the mission appended) -- the explicit, copy-pasteable escape hatch.
- # 2. --launcher <label> / AUTOPROMPT_LAUNCHER (the bare command name, e.g.
- # apidemo|codexdemo, exec'd directly -- requires that name to be on PATH).
- # A fresh user with no apidemo/codexdemo alias uses --cmd with their real CLI.
- # Env (all optional):
- # AUTOPROMPT_LAUNCH_CMD verbatim launch command (overrides --launcher)
- # AUTOPROMPT_LAUNCHER default launcher label if --launcher is omitted
- # AUTOPROMPT_AGENTS off | auto | <list> | auto:<list> (default off)
- # AUTOPROMPT_MODEL_REGISTRY optional registry path; defaults to ~/.claude/autoprompt-models.json for auto modes
- # LEDGER_DIR default "autoprompt"
- # SENTINEL explicit sentinel glob/patterns (default <LEDGER_DIR>/DONE-*).
- # When SET, the value is WORD-SPLIT into one-or-more shell
- # globs (an explicit multi-pattern escape hatch) and so MUST
- # NOT contain spaces in any single path. When UNSET (the
- # default -- every real run) the glob is "$LEDGER_DIR"/DONE-*
- # with the DIR QUOTED and only the * unquoted, so a LEDGER_DIR
- # containing spaces (e.g. a Windows path) still matches its
- # DONE-* sentinel. NOTE: the .ps1 port passes an explicit
- # SENTINEL as ONE Get-ChildItem -Path pattern (no word-split),
- # so a space-separated multi-pattern SENTINEL is a .sh-only
- # feature; on PowerShell use a single dir-wildcard instead.
- # MAX_RESTARTS rapid restarts allowed in WINDOW without progress (default 5)
- # WINDOW rolling window seconds for the poison guard (default 600)
- # RETRY_BASE base backoff seconds between relaunches (default 5; 0 in tests)
- # RETRY_CAP max backoff seconds (default 300)
- # AUTOPROMPT_KEEP_MODEL_PIN when "1", SKIP neutralizing CLAUDE_CODE_SUBAGENT_MODEL
- # for the child CLI. By DEFAULT (unset) the supervisor strips
- # CLAUDE_CODE_SUBAGENT_MODEL from the CHILD ONLY (env -u) so the
- # skill's `model: inherit` contract resolves to the real session/
- # --model selection instead of the operator's force-pin. Set to 1
- # to preserve the operator's pin and let it reach the child as before.
- # AUTOPROMPT_MODE tokensaver | wide | billionaire | custom (default
- # tokensaver). WIDE and BILLIONAIRE share wide semantics.
- # CUSTOM requires a positive numeric
- # AUTOPROMPT_MAX_CONCURRENT value, floors it to a whole-agent
- # ceiling, and passes both values through to the harness.
- # The 5-level topology (L0 conductor -> L1 coordinators -> L2 managers -> L3
- # executors -> L4 leaves) lives in the harness; rule 68 (L1 never executes) and
- # rule 67 (single-block spawns) are enforced there. This OS-level supervisor only
- # relaunches the L0 entry process and passes the mode through; it spawns no agents.
- # Test hooks (only honored with --dry-run):
- # FAKE_EXITS space-separated exit codes the fake launcher returns in turn
- # FAKE_SENTINEL_AFTER write the sentinel before the launch with this 1-based index
- # FAKE_POISON 1 => fake never advances the frontier and always exits non-zero
- set -u
- LAUNCHER="${AUTOPROMPT_LAUNCHER:-}"
- LAUNCH_CMD="${AUTOPROMPT_LAUNCH_CMD:-}"
- AGENTS_SELECTOR="${AUTOPROMPT_AGENTS:-off}"
- MODEL_REGISTRY="${AUTOPROMPT_MODEL_REGISTRY:-}"
- PROVIDER_CAPABILITY="${AUTOPROMPT_PROVIDER_CAPABILITY:-}"
- LEDGER_DIR="${LEDGER_DIR:-autoprompt}"
- MAX_RESTARTS="${MAX_RESTARTS:-5}"
- WINDOW="${WINDOW:-600}"
- RETRY_BASE="${RETRY_BASE:-5}"
- RETRY_CAP="${RETRY_CAP:-300}"
- IDLE_TIMEOUT="${AUTOPROMPT_IDLE_TIMEOUT:-1800}" # seconds of frontier-count staleness while alive -> kill -> relaunch (continue)
- HEARTBEAT_INTERVAL="${AUTOPROMPT_HEARTBEAT_INTERVAL:-60}" # poll cadence while the child is alive
- # V4 (long-tool-call guard): IDLE_TIMEOUT defaults to 1800s (30 min) precisely so a
- # long-but-progressing build/test does NOT trip the heartbeat - the frontier count
- # grows when ANY artifact is written, so a progressing run resets the timer well before
- # 30 min. Operators with long single atomic steps raise AUTOPROMPT_IDLE_TIMEOUT.
- # PLAN-auto-compact-threshold: proactive, SUPERVISOR-FIRED compaction below the harness
- # ~400k ceiling. The supervisor observes the parent's context size from OUTSIDE (it
- # parses the parent's own Claude Code session transcript; watermark/ledger-byte
- # fallbacks) and, when it crosses COMPACT_AT, writes COMPACT-REQUEST (a heads-up so the
- # parent checkpoints + STOPS its subagents at the next gate boundary) and, on grace
- # timeout, fires the kill->RESUME itself (the parent cannot /compact itself).
- COMPACT_AT="${AUTOPROMPT_COMPACT_AT:-200000}" # proactive compaction watermark (tokens); below the harness ~400k ceiling
- BYTES_PER_TOKEN="${AUTOPROMPT_BYTES_PER_TOKEN:-4}" # bytes->tokens divisor for the fallback proxies
- COMPACT_COOLDOWN="${AUTOPROMPT_COMPACT_COOLDOWN:-120}" # seconds after a compaction before another may be requested
- COMPACT_GRACE="${AUTOPROMPT_COMPACT_GRACE:-180}" # seconds to let the parent honor a request before the forced fallback
- EXTERNAL_COMPACT_DELTA="${AUTOPROMPT_EXTERNAL_COMPACT_DELTA:-50000}" # an estimate DROP >= this across ticks = a harness-fired compaction
- # Validate COMPACT_AT to a positive integer; an absurd/non-numeric value falls back to
- # the default (never disables the guard, never fires every tick -- the zero-threshold trap).
- case "$COMPACT_AT" in (*[!0-9]*|"") COMPACT_AT=200000 ;; esac
- [ "$COMPACT_AT" -gt 0 ] 2>/dev/null || COMPACT_AT=200000
- [ "$COMPACT_AT" -lt 10000000 ] 2>/dev/null || COMPACT_AT=200000
- case "$BYTES_PER_TOKEN" in (*[!0-9]*|""|0) BYTES_PER_TOKEN=4 ;; esac
- # F-SPEED steer-2 B3: PHASE WALL-CLOCK BUDGET for the SCOPE phase. IDLE_TIMEOUT
- # (above) fires only on frontier STALENESS; a slow scope can keep producing
- # ROADMAP.md and roadmap-scout-*.md checkpoints, resetting the idle clock while never
- # bounded. This budget is anchored to scope-phase ENTRY and NOT reset by frontier
- # growth - the exact hole IDLE_TIMEOUT leaves. Soft => a converge REQUEST; hard (or an
- # unhonored converge past grace) => a durable breach marker + REAL kill->RESUME on the
- # honest landed set; a re-breach past the reset cap => SUPERVISOR-ESCALATE. It NEVER
- # fabricates a roadmap. Each knob is validated with the SAME positive-integer idiom as
- # COMPACT_AT: an absurd/non-numeric value falls back to the default (never disables the
- # guard, never a zero-budget trap that fires every tick).
- SCOPE_SOFT_SEC="${AUTOPROMPT_SCOPE_SOFT_SEC:-60}" # bounded scope target
- SCOPE_HARD_SEC="${AUTOPROMPT_SCOPE_HARD_SEC:-300}" # ordinary multi-surface ceiling
- SCOPE_GRACE_SEC="${AUTOPROMPT_SCOPE_GRACE:-60}" # converge-request grace
- MAX_SCOPE_RESETS="${AUTOPROMPT_MAX_SCOPE_RESETS:-1}" # budget-forced scope resets before escalation
- case "$SCOPE_SOFT_SEC" in (*[!0-9]*|"") SCOPE_SOFT_SEC=60 ;; esac
- [ "$SCOPE_SOFT_SEC" -gt 0 ] 2>/dev/null || SCOPE_SOFT_SEC=60
- case "$SCOPE_HARD_SEC" in (*[!0-9]*|"") SCOPE_HARD_SEC=300 ;; esac
- [ "$SCOPE_HARD_SEC" -gt 0 ] 2>/dev/null || SCOPE_HARD_SEC=300
- case "$SCOPE_GRACE_SEC" in (*[!0-9]*|"") SCOPE_GRACE_SEC=60 ;; esac
- [ "$SCOPE_GRACE_SEC" -ge 0 ] 2>/dev/null || SCOPE_GRACE_SEC=60
- case "$MAX_SCOPE_RESETS" in (*[!0-9]*|"") MAX_SCOPE_RESETS=1 ;; esac
- [ "$MAX_SCOPE_RESETS" -ge 0 ] 2>/dev/null || MAX_SCOPE_RESETS=1
- # Execution mode selects the 5-level topology's wave cap. Unknown modes retain the
- # safe tokensaver fallback. CUSTOM is different: it is an explicit request for a
- # caller-supplied ceiling, so a missing or invalid ceiling fails closed.
- AUTOPROMPT_MODE="${AUTOPROMPT_MODE:-tokensaver}"
- case "$AUTOPROMPT_MODE" in
- tokensaver) FANOUT="up to 6 live per wave"; L3_TRACKS="parallel" ;;
- wide|billionaire) FANOUT="wide up to the runtime ceiling"; L3_TRACKS="parallel" ;;
- custom)
- CUSTOM_MAX=$(awk -v raw="${AUTOPROMPT_MAX_CONCURRENT:-}" 'BEGIN {
- if (raw ~ /^[+]?[0-9]+([.][0-9]+)?$/ && (raw + 0) >= 1) printf "%d", int(raw + 0)
- }')
- if [ -z "$CUSTOM_MAX" ]; then
- echo "supervisor: custom mode requires a positive numeric AUTOPROMPT_MAX_CONCURRENT" >&2
- exit 2
- fi
- AUTOPROMPT_MAX_CONCURRENT="$CUSTOM_MAX"
- export AUTOPROMPT_MAX_CONCURRENT
- FANOUT="up to $CUSTOM_MAX live per wave (AUTOPROMPT_MAX_CONCURRENT)"
- L3_TRACKS="parallel"
- ;;
- *) AUTOPROMPT_MODE="tokensaver"; FANOUT="up to 6 live per wave"; L3_TRACKS="parallel" ;;
- esac
- # EDIT 23a: the supervisor sits in .../workflow/ next to autoprompt-ledger-check.js,
- # so it derives that resolver's ABSOLUTE path from its own location and exports it to
- # the child (gate.js EDIT 4a reads AUTOPROMPT_LEDGER_CHECK; the SCRIBE/JANITOR briefs
- # interpolate it to RUN `node "$AUTOPROMPT_LEDGER_CHECK" --resolve-prompt-dir ...`).
- # An operator override wins; otherwise the script-dir sibling is used. CDPATH= guards
- # a hostile CDPATH from redirecting the cd, and -- ends option parsing for odd $0.
- SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
- LEDGER_CHECK_PATH="${AUTOPROMPT_LEDGER_CHECK:-$SCRIPT_DIR/autoprompt-ledger-check.js}"
- MODEL_CASTING_PATH="${AUTOPROMPT_MODEL_CASTING:-$SCRIPT_DIR/model-casting.js}"
- AGENT_DEFINITIONS_PATH="${AUTOPROMPT_AGENT_DEFINITIONS_DIR:-$SCRIPT_DIR/../agents}"
- AGENT_DEFINITIONS_CLI="${AUTOPROMPT_AGENT_DEFINITIONS_CLI:-$SCRIPT_DIR/agent-definitions-cli.js}"
- # F-SPEED steer-2 B3: the phase-budget verdict CLI sits next to the ledger-check in
- # .../workflow/. An operator override wins; otherwise the script-dir sibling is used.
- # Consulted once per heartbeat tick, scope-phase only, and guarded by [ -r ] so an
- # absent node/module fail-opens to IDLE_TIMEOUT alone (same posture as the ledger-check).
- PHASE_BUDGET_PATH="${AUTOPROMPT_PHASE_BUDGET:-$SCRIPT_DIR/phase-budget.js}"
- # EDIT 23: per-conversation session token, defaulted here for `set -u` safety. The
- # supervisor is the durable producer across relaunches of one conversation: it seeds
- # this token (env > file > empty) before the loop and HARVESTs the resolver-minted
- # marker token after each launch, re-exporting the SAME token so a 2nd prompt lands
- # in the SAME session_NN (SPEC-1 S2). RESUME is always same-session regardless.
- AUTOPROMPT_SESSION_TOKEN="${AUTOPROMPT_SESSION_TOKEN:-}"
- INITIAL_RESUME="${AUTOPROMPT_RESUME:-}"
- case "$(printf '%s' "$INITIAL_RESUME" | tr '[:upper:]' '[:lower:]')" in
- 1|true|yes) INITIAL_RESUME=1 ;;
- *) INITIAL_RESUME=0 ;;
- esac
- SCOPE_MISSION_BINDING="unbound"
- RUN_NONCE="${AUTOPROMPT_RUN_NONCE:-}"
- LEGACY_SENTINEL="${AUTOPROMPT_LEGACY_SENTINEL:-0}"
- SCOPE_BUDGET_TERMINAL=0
- DRY_RUN=0
- MISSION=""
- require_flag_value() {
- [ "$2" -ge 2 ] && return 0
- echo "supervisor: $1 requires a value" >&2
- exit 2
- }
- while [ $# -gt 0 ]; do
- case "$1" in
- --launcher) require_flag_value "$1" "$#"; LAUNCHER="$2"; shift 2 ;;
- --cmd) require_flag_value "$1" "$#"; LAUNCH_CMD="$2"; shift 2 ;;
- --agents) require_flag_value "$1" "$#"; AGENTS_SELECTOR="$2"; shift 2 ;;
- --model-registry) require_flag_value "$1" "$#"; MODEL_REGISTRY="$2"; shift 2 ;;
- --provider-capability) require_flag_value "$1" "$#"; PROVIDER_CAPABILITY="$2"; shift 2 ;;
- --dry-run) DRY_RUN=1; shift ;;
- --ledger-dir) require_flag_value "$1" "$#"; LEDGER_DIR="$2"; shift 2 ;;
- --) shift; MISSION="$*"; break ;;
- -*) echo "supervisor: unknown flag $1" >&2; exit 2 ;;
- *) MISSION="$1"; shift ;;
- esac
- done
- if command -v node >/dev/null 2>&1; then
- SCOPE_MISSION_BINDING=$(printf '%s' "$MISSION" | node -e '
- const crypto = require("crypto")
- let input = ""
- process.stdin.setEncoding("utf8")
- process.stdin.on("data", chunk => { input += chunk })
- process.stdin.on("end", () => process.stdout.write("sha256:" + crypto.createHash("sha256").update(input, "utf8").digest("hex")))
- ' 2>/dev/null || echo unbound)
- fi
- if [ "$LEGACY_SENTINEL" != "1" ]; then
- case "$RUN_NONCE" in
- NONCE-[A-Za-z0-9_-]*) ;;
- "")
- if command -v node >/dev/null 2>&1; then
- RUN_NONCE="NONCE-$(node -e 'process.stdout.write(require("crypto").randomBytes(16).toString("hex"))' 2>/dev/null || true)"
- fi
- case "$RUN_NONCE" in
- NONCE-[A-Za-z0-9_-]*) ;;
- *) echo "supervisor: could not mint a cryptographically strong activation nonce" >&2; exit 2 ;;
- esac
- ;;
- *) echo "supervisor: AUTOPROMPT_RUN_NONCE is malformed" >&2; exit 2 ;;
- esac
- fi
- # Sentinel matching has two modes. DEFAULT (SENTINEL unset -- every real run):
- # the glob is "$LEDGER_DIR"/DONE-* iterated with the DIR QUOTED and only the *
- # unquoted, so a LEDGER_DIR containing spaces (a Windows path) still matches its
- # own DONE-* sentinel. EXPLICIT (SENTINEL set): the value is word-split into one
- # or more shell globs -- an intentional multi-pattern escape hatch -- so no single
- # path in it may contain spaces. SENTINEL_SET records which mode is active; the
- # unquoted word-split is confined to the explicit case where the user opted in.
- if [ -n "${SENTINEL:-}" ]; then
- SENTINEL_SET=1
- SENTINEL_GLOB="$SENTINEL"
- else
- SENTINEL_SET=0
- SENTINEL_GLOB="$LEDGER_DIR/DONE-*" # reference/logging only; never iterated unquoted
- fi
- ESCALATE_FILE="$LEDGER_DIR/SUPERVISOR-ESCALATE"
- SNAPSHOT_FILE="$LEDGER_DIR/.sentinel-snapshot"
- # EDIT 23: the durable session-token store, under the ledger dir so it survives across
- # relaunches of one conversation. Seeded before the loop, harvested after each launch.
- SESSION_TOKEN_FILE="$LEDGER_DIR/.session-token"
- # PLAN-auto-compact-threshold path vars. Discovery is CWD-AGNOSTIC and slug-free: it
- # matches the supervisor's own RUN_CWD (POSIX on gitbash) against each transcript's
- # embedded OS-native "cwd" after normalization -- NO slug derivation, NO launcher edit.
- RUN_CWD="${RUN_CWD:-$PWD}" # run cwd; matched against each transcript's embedded "cwd"
- PARENT_TRANSCRIPT="${AUTOPROMPT_PARENT_TRANSCRIPT:-}" # OPTIONAL explicit override of the parent .jsonl path
- WATERMARK_FILE="$LEDGER_DIR/.context-watermark" # FALLBACK: parent-emitted watermark (only when transcript unreadable)
- COMPACT_REQUEST_FILE="$LEDGER_DIR/COMPACT-REQUEST"
- COMPACT_STATE_FILE="$LEDGER_DIR/.compaction-state" # holds: last_compact_epoch + last seen estimate (for cooldown + drop-detection)
- # Scope-budget state under the ledger dir, durable across relaunches. The start epoch
- # does not reset on frontier growth; the reset counter clears once build evidence lands.
- SCOPE_PHASE_START_FILE="$LEDGER_DIR/.scope-phase-start"
- SCOPE_RESETS_FILE="$LEDGER_DIR/.scope-forced-resets"
- SNAPSHOT_OK=0
- mkdir -p "$LEDGER_DIR" 2>/dev/null || true
- # Supervisor start epoch (captured BEFORE the first launch). It is no longer part
- # of the stale-sentinel guarantee (see below) -- it is kept only to name the
- # quarantine target (superseded-<epoch>-...) and is read fail-safe: if `date +%s`
- # fails we leave it EMPTY (not 0), so the quarantine name degrades to
- # superseded-unknown-... rather than colliding on a fixed "0".
- SUPERVISOR_START_EPOCH=$(date +%s 2>/dev/null || echo)
- # THE stale-sentinel guarantee is a STARTUP SNAPSHOT, not mtime. Before the first
- # launch we record every pre-existing DONE-* PATH into $SNAPSHOT_FILE.
- # sentinel_present then REFUSES any DONE-* whose path is still in that snapshot --
- # regardless of mtime. THE LIVE INVARIANT: a path stays in the snapshot IFF its
- # stale occupant still physically exists. Quarantine renames each pre-existing
- # done:true sentinel aside; on a SUCCESSFUL rename the path is now empty, so it is
- # PRUNED from the snapshot -- the only thing that can later appear there is a
- # genuinely fresh this-run sentinel, which must be honored (otherwise the
- # same-activation DONE-<nonce> - the supervisor-minted CSPRNG nonce re-exported
- # unchanged to every relaunched child, with NO clock - would be vetoed forever
- # and the supervisor would relaunch without end --
- # the livelock). A path whose rename FAILED is NOT pruned: its stale occupant is
- # still there, so it stays vetoed and a failed quarantine degrades to RELAUNCH,
- # never a false halt. The mtime `>=start` belt is gone -- it could not backstop
- # the same-second class, which is the whole reason this defense exists. FAIL-SAFE:
- # if the snapshot cannot be written or read, ALL DONE-* are treated as suspect ->
- # relaunch, never halt.
- log() { echo "[supervisor $(date '+%Y-%m-%dT%H:%M:%S' 2>/dev/null)] $*"; }
- CASTING_ENABLED=0
- CASTING_JSON=""
- CASTING_OPUS=""
- CASTING_SONNET=""
- CASTING_HAIKU=""
- CASTING_BASE_URL=""
- CASTING_API_KEY_ENV=""
- CASTING_AUTH_TOKEN=""
- CAPABILITY_PROVIDER="claude-code"
- CAPABILITY_CLI_VERSION="unknown"
- CAPABILITY_PERMISSION_PROFILE="default"
- CAPABILITY_AGENT_DEFINITIONS_HASH="unknown"
- CAPABILITY_CASTING_HASH="unknown"
- CAPABILITY_EFFORT_STATUS="inherited-only"
- CAPABILITY_EFFORT_SOURCE="session-inheritance"
- AUTOPROMPT_CAPABILITY_ATTESTATION="${AUTOPROMPT_CAPABILITY_ATTESTATION:-}"
- casting_json_field() {
- field="$1"
- printf '%s' "$CASTING_JSON" | node -e '
- let input = ""
- process.stdin.setEncoding("utf8")
- process.stdin.on("data", chunk => { input += chunk })
- process.stdin.on("end", () => {
- let value = JSON.parse(input)
- for (const key of process.argv[1].split(".")) value = value == null ? undefined : value[key]
- if (value != null) process.stdout.write(String(value))
- })
- ' "$field"
- }
- resolve_model_casting() {
- control=$(printf '%s' "$AGENTS_SELECTOR" | tr '[:upper:]' '[:lower:]')
- [ -z "$control" ] || [ "$control" = "off" ] || {
- command -v node >/dev/null 2>&1 || {
- echo "supervisor: model casting requires node on PATH" >&2
- return 2
- }
- [ -r "$MODEL_CASTING_PATH" ] || {
- echo "supervisor: model casting resolver is not readable: $MODEL_CASTING_PATH" >&2
- return 2
- }
- set -- "$MODEL_CASTING_PATH" --selector "$AGENTS_SELECTOR"
- if [ -n "$MODEL_REGISTRY" ]; then
- set -- "$@" --registry "$MODEL_REGISTRY"
- fi
- if [ -n "$PROVIDER_CAPABILITY" ]; then
- set -- "$@" --provider-capability "$PROVIDER_CAPABILITY"
- fi
- CASTING_JSON=$(node "$@") || return 2
- CASTING_ENABLED=$(casting_json_field enabled) || return 2
- [ "$CASTING_ENABLED" = "true" ] || return 0
- CASTING_OPUS=$(casting_json_field aliases.opus) || return 2
- CASTING_SONNET=$(casting_json_field aliases.sonnet) || return 2
- CASTING_HAIKU=$(casting_json_field aliases.haiku) || return 2
- CASTING_BASE_URL=$(casting_json_field endpoint.baseUrl) || return 2
- CASTING_API_KEY_ENV=$(casting_json_field endpoint.apiKeyEnv) || return 2
- if [ "${AUTOPROMPT_KEEP_MODEL_PIN:-0}" = "1" ] && [ -n "${CLAUDE_CODE_SUBAGENT_MODEL:-}" ]; then
- echo "supervisor: AUTOPROMPT_KEEP_MODEL_PIN=1 conflicts with model casting because CLAUDE_CODE_SUBAGENT_MODEL is set" >&2
- return 2
- fi
- if [ -n "$CASTING_API_KEY_ENV" ]; then
- CASTING_AUTH_TOKEN=$(printenv "$CASTING_API_KEY_ENV" 2>/dev/null || true)
- [ -n "$CASTING_AUTH_TOKEN" ] || {
- echo "supervisor: model casting credential environment variable is unset or empty: $CASTING_API_KEY_ENV" >&2
- return 2
- }
- fi
- }
- }
- sha256_file() {
- file="$1"
- node -e '
- const fs = require("fs")
- const crypto = require("crypto")
- const file = process.argv[1]
- process.stdout.write("sha256:" + crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"))
- ' "$file"
- }
- sha256_text() {
- node -e '
- const crypto = require("crypto")
- process.stdin.setEncoding("utf8")
- let input = ""
- process.stdin.on("data", chunk => { input += chunk })
- process.stdin.on("end", () => process.stdout.write("sha256:" + crypto.createHash("sha256").update(input, "utf8").digest("hex")))
- '
- }
- hash_agent_definitions() {
- agents_dir=$(CDPATH= cd -- "$AGENT_DEFINITIONS_PATH" 2>/dev/null && pwd) || return 1
- node -e '
- const crypto = require("crypto")
- const fs = require("fs")
- const path = require("path")
- const [castingPath, agentsDir] = process.argv.slice(1)
- const files = [castingPath, ...fs.readdirSync(agentsDir)
- .filter(name => /^ap-.*\.md$/.test(name))
- .sort()
- .map(name => path.join(agentsDir, name))]
- const hash = crypto.createHash("sha256")
- for (const file of files) {
- const label = path.basename(file)
- hash.update(String(Buffer.byteLength(label, "utf8"))).update(":").update(label)
- const content = fs.readFileSync(file)
- hash.update(String(content.length)).update(":").update(content)
- }
- process.stdout.write("sha256:" + hash.digest("hex"))
- ' "$MODEL_CASTING_PATH" "$agents_dir"
- }
- resolve_agent_definitions_json() {
- command -v node >/dev/null 2>&1 || {
- echo "supervisor: activation-scoped agents require node on PATH" >&2
- return 2
- }
- [ -r "$AGENT_DEFINITIONS_CLI" ] || {
- echo "supervisor: agent-definition converter is not readable: $AGENT_DEFINITIONS_CLI" >&2
- return 2
- }
- AGENT_DEFINITIONS_JSON=$(node "$AGENT_DEFINITIONS_CLI" "$AGENT_DEFINITIONS_PATH") || return 2
- [ -n "$AGENT_DEFINITIONS_JSON" ] || {
- echo "supervisor: agent-definition converter returned an empty cast" >&2
- return 2
- }
- }
- resolve_capability_binding() {
- supplied_attestation="$AUTOPROMPT_CAPABILITY_ATTESTATION"
- AUTOPROMPT_CAPABILITY_ATTESTATION=""
- command -v node >/dev/null 2>&1 || return 0
- CAPABILITY_CLI_VERSION="${AUTOPROMPT_CLI_VERSION:-}"
- if [ -z "$CAPABILITY_CLI_VERSION" ]; then
- cli_cmd="${LAUNCH_CMD%% *}"
- [ -n "$cli_cmd" ] || cli_cmd="$LAUNCHER"
- if [ -n "$cli_cmd" ] && command -v "$cli_cmd" >/dev/null 2>&1; then
- CAPABILITY_CLI_VERSION=$($cli_cmd --version 2>/dev/null | head -n1 || true)
- fi
- fi
- [ -n "$CAPABILITY_CLI_VERSION" ] || CAPABILITY_CLI_VERSION="unknown"
- case " $LAUNCH_CMD " in
- *" --dangerously-skip-permissions "*) CAPABILITY_PERMISSION_PROFILE="bypass-permissions" ;;
- *) CAPABILITY_PERMISSION_PROFILE="${AUTOPROMPT_PERMISSION_PROFILE:-default}" ;;
- esac
- if [ -r "$MODEL_CASTING_PATH" ]; then
- CAPABILITY_AGENT_DEFINITIONS_HASH=$(hash_agent_definitions 2>/dev/null || echo unknown)
- fi
- CAPABILITY_CASTING_HASH="none"
- if [ "$CASTING_ENABLED" = "true" ]; then
- CAPABILITY_CASTING_HASH=$(printf '%s' "$CASTING_JSON" | sha256_text) || return 2
- CAPABILITY_EFFORT_STATUS=$(casting_json_field effort.status) || return 2
- CAPABILITY_EFFORT_SOURCE=$(casting_json_field effort.source) || return 2
- fi
- if [ "$CAPABILITY_CLI_VERSION" = "unknown" ] || [ "$CAPABILITY_AGENT_DEFINITIONS_HASH" = "unknown" ] || [ -z "$supplied_attestation" ]; then
- return 0
- fi
- AUTOPROMPT_CAPABILITY_ATTESTATION=$(node -e '
- const crypto = require("crypto")
- const raw = process.argv[1]
- const expected = process.argv.slice(2)
- let attestation
- try { attestation = JSON.parse(raw) } catch { process.exit(1) }
- const bindings = [
- "provider", "cliVersion", "permissionProfile", "agentSelector",
- "agentDefinitionsHash", "castingHash", "effortStatus", "effortSource",
- ]
- const proofBytesOk = typeof attestation.proofBytes === "string" &&
- attestation.proofBytes !== "" && attestation.proofBytes.length <= 4096
- const proofOk = proofBytesOk &&
- "sha256:" + crypto.createHash("sha256").update(attestation.proofBytes, "utf8").digest("hex") === attestation.proofHash
- const valid = attestation && attestation.schemaVersion === 4 &&
- attestation.run === true && attestation.read === true && attestation.write === true &&
- attestation.proofKind === "disposable-scratch" &&
- typeof attestation.proofHash === "string" && /^sha256:[a-f0-9]{64}$/.test(attestation.proofHash) &&
- proofOk &&
- bindings.every((field, index) => attestation[field] === expected[index])
- if (!valid) process.exit(1)
- process.stdout.write(JSON.stringify(attestation))
- ' "$supplied_attestation" "$CAPABILITY_PROVIDER" "$CAPABILITY_CLI_VERSION" \
- "$CAPABILITY_PERMISSION_PROFILE" "$AGENTS_SELECTOR" "$CAPABILITY_AGENT_DEFINITIONS_HASH" \
- "$CAPABILITY_CASTING_HASH" "$CAPABILITY_EFFORT_STATUS" "$CAPABILITY_EFFORT_SOURCE" 2>/dev/null) || {
- AUTOPROMPT_CAPABILITY_ATTESTATION=""
- return 0
- }
- }
- # Take the startup snapshot of pre-existing DONE-* PATHS, BEFORE the first launch
- # and BEFORE any sentinel check or quarantine. Each path is written on its own
- # line to $SNAPSHOT_FILE. SNAPSHOT_OK=1 marks a trustworthy snapshot; if writing
- # fails we leave it 0, and sentinel_present then treats EVERY DONE-* as suspect
- # (relaunch), the fail-safe direction. The snapshot is the authoritative record
- # of "what was already here", so it is taken from the live glob exactly once.
- snapshot_pre_existing_sentinels() {
- SNAPSHOT_OK=0
- # `:` is a POSIX SPECIAL builtin: under dash a redirection error on it aborts
- # the whole non-interactive shell BEFORE `|| return` can run (bash only
- # returns). Wrapping it in a subshell isolates the abort to the subshell, so
- # an unwritable snapshot file degrades to RELAUNCH (fail-safe) under dash too.
- ( : > "$SNAPSHOT_FILE" ) 2>/dev/null || return
- if [ "$SENTINEL_SET" -eq 1 ]; then set -- $SENTINEL_GLOB; else set -- "$LEDGER_DIR"/DONE-*; fi
- for f in "$@"; do
- [ -e "$f" ] || continue
- printf '%s\n' "$f" >> "$SNAPSHOT_FILE" 2>/dev/null || return
- done
- SNAPSHOT_OK=1
- }
- # Is $1 one of the paths recorded in the startup snapshot? Exact whole-line match.
- # If the snapshot is not trustworthy (SNAPSHOT_OK=0) we answer YES for every path
- # -> every DONE-* is treated as pre-existing -> never halts -> relaunch. That is
- # the deliberate fail-safe: a missing/unreadable snapshot must never permit a halt.
- path_in_snapshot() {
- [ "$SNAPSHOT_OK" -eq 1 ] 2>/dev/null || return 0
- # If the snapshot file became unreadable/removed after SNAPSHOT_OK was set, the
- # read loop below would never run and we would fall through to `return 1` (= not
- # snapshotted = halt ALLOWED) -- fail-OPEN. The header contract says a snapshot
- # that cannot be READ makes every path suspect, so veto here too (return 0).
- [ -r "$SNAPSHOT_FILE" ] || return 0
- while IFS= read -r line; do
- [ "$line" = "$1" ] && return 0
- done < "$SNAPSHOT_FILE" 2>/dev/null
- return 1
- }
- # Drop one path from the live snapshot (in $SNAPSHOT_FILE) so a genuinely-fresh
- # sentinel can later reclaim it. Called by quarantine ONLY after a SUCCESSFUL
- # rename: once the stale occupant has been moved aside, the path is empty, so the
- # ONLY thing that can appear there is a fresh sentinel written by THIS run. The
- # activation nonce is minted once (CSPRNG) and re-exported unchanged to every
- # relaunched child (no clock), so a re-launch of the SAME activation writes the
- # SAME path the snapshot recorded -- if
- # the snapshot kept vetoing it, that fresh sentinel would be refused forever and
- # the supervisor would relaunch without end (the livelock). Rewrite is atomic via
- # a temp file. If the rewrite itself fails we KEEP the path (over-veto = relaunch,
- # never a false halt) -- the safe direction. A path whose rename FAILED is never
- # pruned, so it stays vetoed while its stale occupant still physically exists.
- prune_path_from_snapshot() {
- [ "$SNAPSHOT_OK" -eq 1 ] 2>/dev/null || return 0
- pruned="$SNAPSHOT_FILE.prune"
- ( : > "$pruned" ) 2>/dev/null || return 0
- while IFS= read -r line; do
- [ "$line" = "$1" ] && continue
- printf '%s\n' "$line" >> "$pruned" 2>/dev/null || { rm -f "$pruned" 2>/dev/null; return 0; }
- done < "$SNAPSHOT_FILE" 2>/dev/null
- mv "$pruned" "$SNAPSHOT_FILE" 2>/dev/null || rm -f "$pruned" 2>/dev/null
- }
- sentinel_json_matches() {
- file="$1"
- expected_nonce="$2"
- node -e '
- const fs = require("fs")
- let value
- try { value = JSON.parse(fs.readFileSync(process.argv[1], "utf8")) }
- catch { process.exit(1) }
- process.exit(value && value.done === true && value.nonce === process.argv[2] ? 0 : 1)
- ' "$file" "$expected_nonce" >/dev/null 2>&1
- }
- sentinel_present() {
- if [ "$LEGACY_SENTINEL" != "1" ]; then
- f="$LEDGER_DIR/DONE-$RUN_NONCE"
- [ -f "$f" ] || return 1
- path_in_snapshot "$f" && return 1
- sentinel_json_matches "$f" "$RUN_NONCE"
- return $?
- fi
- if [ "$SENTINEL_SET" -eq 1 ]; then set -- $SENTINEL_GLOB; else set -- "$LEDGER_DIR"/DONE-*; fi
- for f in "$@"; do
- [ -f "$f" ] || continue
- grep -q '"done"[[:space:]]*:[[:space:]]*true' "$f" 2>/dev/null || continue
- path_in_snapshot "$f" && continue
- return 0
- done
- return 1
- }
- # At startup, BEFORE the first launch, QUARANTINE every pre-existing done:true
- # DONE-* sentinel: rename it aside to <dir>/superseded-<start-epoch>-<name> so the
- # new name no longer starts with DONE- and thus no longer matches the live DONE-*
- # glob -- it cannot halt this fresh mission. (Prefixing, NOT suffixing: a
- # DONE-X.superseded-N name would STILL match DONE-* and re-trip the same-second
- # halt, so the leading DONE- must be displaced.) This is the PRIMARY fix for the
- # whole stale-sentinel class -- after quarantine there is no leftover sentinel
- # left to race, so a same-second / zero-epoch / sub-second mtime collision is
- # moot. We RENAME, never delete (deleting artifacts is the JANITOR's job; never
- # silently rm operator files) and log a loud line naming each quarantined file.
- # On a SUCCESSFUL rename the path is pruned from the live snapshot so a genuine
- # fresh same-activation DONE-<nonce> (the minted nonce is re-exported to every
- # relaunched child, no clock) can reclaim it -- else the snapshot would veto that
- # fresh sentinel forever and the supervisor would relaunch without end (livelock).
- # If a rename FAILS (read-only dir / permissions / clobber) the leftover DONE-*
- # still matches the live glob, its path is NOT pruned, and sentinel_present
- # unconditionally refuses it. A failed rename degrades to RELAUNCH, never a halt.
- # Net invariant: the snapshot vetoes a path IFF its stale occupant still exists.
- quarantine_stale_sentinels() {
- if [ "$SENTINEL_SET" -eq 1 ]; then set -- $SENTINEL_GLOB; else set -- "$LEDGER_DIR"/DONE-*; fi
- for f in "$@"; do
- [ -f "$f" ] || continue
- if grep -q '"done"[[:space:]]*:[[:space:]]*true' "$f" 2>/dev/null; then
- dir=$(dirname "$f"); base=$(basename "$f")
- quarantined="$dir/superseded-${SUPERVISOR_START_EPOCH:-unknown}-$base"
- if mv "$f" "$quarantined" 2>/dev/null; then
- # The stale occupant is gone, so this path can no longer hold anything
- # but a FRESH this-run sentinel. Drop it from the live snapshot so the
- # same-activation DONE-<nonce> is reclaimable -- otherwise the
- # snapshot would veto the genuine fresh sentinel forever (the livelock).
- prune_path_from_snapshot "$f"
- log "QUARANTINE: pre-existing DONE-sentinel '$f' (from a prior run) renamed to '$quarantined' so it cannot halt this fresh mission. It is preserved, not deleted."
- else
- log "WARNING: could not quarantine pre-existing DONE-sentinel '$f' -- it is IGNORED for halting by the startup snapshot and will not stop this mission. Remove it if it is no longer relevant."
- fi
- fi
- done
- }
- # The frontier marker: how much forward progress exists on disk. It is a
- # MONOTONIC progress counter, not a success counter - it counts EVERY gate
- # artifact across the whole lifecycle (roadmap/scouts, plan draft/review/
- # fresh-verify, plan-final, impl, impl-review, verify, signoff, sweep-round,
- # arbiter, goal-check). Versioned (-vN), per-feature (Fx-), retained-scout, and
- # per-round artifacts multiply as work proceeds, so a run that is advancing through
- # the pre-build scope phase, which writes roadmap and retained scout evidence
- # long before the first plan-final - bumps the count every relaunch and resets
- # the poison window. A run that relaunches writing NOTHING new keeps the count
- # flat and still trips poison. Counting only plan-final/verify (the old globs)
- # pinned the count at 0 for that whole early phase and KILLED healthy runs.
- frontier_count() {
- if [ "$DRY_RUN" -eq 1 ]; then
- # In dry-run, a poison fake never advances; a healthy fake bumps a counter file.
- if [ "${FAKE_POISON:-0}" = "1" ]; then echo 0; return; fi
- if [ -f "$LEDGER_DIR/.fake-frontier" ]; then cat "$LEDGER_DIR/.fake-frontier"; else echo 0; fi
- return
- fi
- count=0
- # Three artifact layouts must ALL be counted, or a run driven by one of them is
- # invisible to the frontier and a healthy-long run trips POISON:
- # prose/agent (SKILL.md/GATES.md): autoprompt/prompt-NNN-<slug>/artifacts/
- # harness (autoprompt-gate.js ARTIFACT_DIR): autoprompt/.artifacts/<run-tag>/
- # session ledger (SPEC-1 SCRIBE): autoprompt/session_NN/prompt_NN-<slug>/ and
- # its optional artifacts/ subdir. The per-prompt ledger .md files (BRIEF/
- # GATELOG/COVERAGE...) count as forward progress (monotonic; same rationale as
- # the multiplying-artifacts globs), so a run advancing ONLY in the new layout
- # is never falsely poisoned.
- # The leading-dot harness dir is NOT matched by "*" (POSIX glob skips dotfiles),
- # and its nesting differs, so it needs its own glob - which also stops the prose
- # glob from double-counting it. Ledger-root prose files (BRIEF/PLAN/GATELOG...)
- # live ONE level above artifacts/ so they are not counted by the first two globs;
- # the session-ledger glob counts them at their nested depth. The DONE sentinel
- # lives at the ledger root, not under any artifacts/ dir. Plain shell `for` over an
- # unmatched glob leaves the literal pattern (nullglob off); `[ -f ]` filters it.
- for f in "$LEDGER_DIR"/*/artifacts/*.md \
- "$LEDGER_DIR"/.artifacts/*/*.md \
- "$LEDGER_DIR"/session_*/prompt_*/artifacts/*.md \
- "$LEDGER_DIR"/session_*/prompt_*/*.md; do
- [ -f "$f" ] && count=$((count + 1))
- done
- echo "$count"
- }
- # The durable pre-execution clock starts before the roadmap author and remains active
- # through every plan/review/fresh-verify revision. Only real G4 implementation evidence
- # proves execution started; planning artifacts are never execution progress.
- scope_phase_elapsed() {
- if [ "$DRY_RUN" -eq 1 ]; then
- [ -n "${FAKE_SCOPE_ELAPSED:-}" ] && echo "$FAKE_SCOPE_ELAPSED"
- return
- fi
- for f in "$LEDGER_DIR"/.artifacts/*/*-impl-v*.md \
- "$LEDGER_DIR"/*/artifacts/*-impl-v*.md \
- "$LEDGER_DIR"/session_*/prompt_*/artifacts/*-impl-v*.md; do
- [ -f "$f" ] && {
- rm -f "$SCOPE_PHASE_START_FILE" "$SCOPE_RESETS_FILE" \
- "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST" \
- "$LEDGER_DIR/SCOPE-BUDGET-BREACH" 2>/dev/null
- return
- }
- done
- now_s=$(date +%s 2>/dev/null || echo 0)
- start_s=""
- stored_binding=""
- if [ -r "$SCOPE_PHASE_START_FILE" ]; then
- start_s=$(awk 'NR==1{print $1; exit}' "$SCOPE_PHASE_START_FILE" 2>/dev/null || echo)
- stored_binding=$(awk 'NR==1{print $2; exit}' "$SCOPE_PHASE_START_FILE" 2>/dev/null || echo)
- fi
- case "$start_s" in (*[!0-9]*|"") start_s="" ;; esac
- if [ "$stored_binding" != "$SCOPE_MISSION_BINDING" ]; then
- start_s=""
- rm -f "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST" \
- "$LEDGER_DIR/SCOPE-BUDGET-BREACH" "$SCOPE_RESETS_FILE" 2>/dev/null
- fi
- if [ -z "$start_s" ] || [ "$start_s" -le 0 ] 2>/dev/null; then
- start_s="$now_s"
- printf '%s %s\n' "$start_s" "$SCOPE_MISSION_BINDING" \
- > "$SCOPE_PHASE_START_FILE.tmp" 2>/dev/null \
- && mv "$SCOPE_PHASE_START_FILE.tmp" "$SCOPE_PHASE_START_FILE" 2>/dev/null
- fi
- el=$((now_s - start_s))
- [ "$el" -lt 0 ] 2>/dev/null && el=0
- echo "$el"
- }
- # Honest retained scope evidence. New runs expose roadmap-scout-N; legacy resumes
- # expose scope-<key>. Missing evidence stays missing rather than being invented.
- scope_landed_angles() {
- if [ "$DRY_RUN" -eq 1 ]; then
- echo "${FAKE_SCOPE_LANDED:-}"
- return
- fi
- keys=""
- for f in "$LEDGER_DIR"/.artifacts/*/roadmap-scout-*.md \
- "$LEDGER_DIR"/*/artifacts/roadmap-scout-*.md \
- "$LEDGER_DIR"/session_*/prompt_*/artifacts/roadmap-scout-*.md \
- "$LEDGER_DIR"/.artifacts/*/scope-*.md \
- "$LEDGER_DIR"/*/artifacts/scope-*.md \
- "$LEDGER_DIR"/session_*/prompt_*/artifacts/scope-*.md; do
- [ -f "$f" ] || continue
- base=$(basename "$f")
- case "$base" in
- roadmap-scout-*.md) key=$(printf '%s' "$base" | sed -e 's/\.md$//') ;;
- *) key=$(printf '%s' "$base" | sed -e 's/^scope-//' -e 's/-v[0-9]*\.md$//' -e 's/\.md$//') ;;
- esac
- [ -n "$key" ] || continue
- case " $keys " in (*" $key "*) ;; (*) keys="$keys $key" ;; esac
- done
- printf '%s' "$keys" | sed -e 's/^ *//' -e 's/ *$//' -e 's/ */,/g'
- }
- # Age (seconds) of the pending SCOPE-CONVERGE-REQUEST, or 0 when none exists.
- scope_converge_request_age() {
- req="$LEDGER_DIR/SCOPE-CONVERGE-REQUEST"
- [ -r "$req" ] || { echo 0; return; }
- now_s=$(date +%s 2>/dev/null || echo 0)
- req_ts=$(awk 'NR==1{print $1+0; exit}' "$req" 2>/dev/null || echo 0)
- case "$req_ts" in (*[!0-9]*|"") req_ts=0 ;; esac
- age=$((now_s - req_ts))
- [ "$age" -lt 0 ] 2>/dev/null && age=0
- echo "$age"
- }
- # === PLAN-auto-compact-threshold: proactive supervisor-fired compaction ============
- # The supervisor cannot introspect the live CLI's RAM, and the parent cannot /compact
- # itself. So the supervisor OBSERVES the parent's context size from disk (the parent's
- # own session transcript; watermark/ledger-byte fallbacks) and, on crossing COMPACT_AT,
- # writes COMPACT-REQUEST then -- on grace timeout -- fires a process-group kill so the
- # outer relaunch loop RESUMEs a fresh, smaller context that re-reads ANCHOR.md.
- # Canonicalize a path for cross-platform cwd comparison (win32/gitbash AND posix):
- # lowercase; collapse \ and / runs to a single /; map a leading "<drive>:" to "/<drive>".
- # Worked: "/c/Users/x"->"/c/users/x"; "C:\\Users\\x"->"c:\\users\\x"->"c:/users/x"->"/c/users/x".
- canon_path() { # $1 = raw path ; echoes canonical form
- printf '%s' "$1" \
- | tr 'A-Z\\' 'a-z/' \
- | sed -e 's#//*#/#g' -e 's#^\([a-z]\):#/\1#'
- }
- # Find the live parent session .jsonl. Slug-free: matches RUN_CWD against each
- # transcript's embedded "cwd" after canonicalization. Single-level glob excludes nested
- # subagent/tool-result transcripts. Echoes the path of the newest cwd-matching transcript
- # whose mtime is >= the child launch epoch, or nothing.
- find_parent_transcript() { # $1 = child_launch_epoch
- if [ -n "$PARENT_TRANSCRIPT" ] && [ -r "$PARENT_TRANSCRIPT" ]; then echo "$PARENT_TRANSCRIPT"; return; fi
- cfg="${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
- want=$(canon_path "$RUN_CWD")
- newest=""; newest_mt=0
- for f in "$cfg"/projects/*/*.jsonl; do
- [ -f "$f" ] || continue
- mt=$(stat -c %Y "$f" 2>/dev/null || stat -f %m "$f" 2>/dev/null || echo 0)
- [ "$mt" -lt "${1:-0}" ] 2>/dev/null && continue # stale prior session
- tcwd=$(grep -o '"cwd":"[^"]*"' "$f" 2>/dev/null | head -n1 | sed 's/.*"cwd":"//; s/"$//')
- [ -n "$tcwd" ] || continue
- tcwd=$(printf '%s' "$tcwd" | sed 's/\\\\/\\/g') # un-escape JSON doubled backslashes
- [ "$(canon_path "$tcwd")" = "$want" ] || continue # different project session -> skip
- [ "$mt" -gt "$newest_mt" ] 2>/dev/null && { newest="$f"; newest_mt=$mt; }
- done
- [ -n "$newest" ] && echo "$newest"
- }
- # Read the PARENT's context size in three tiers; echoes an integer (0 = unavailable).
- # TIER 1: parse the parent session .jsonl usage fields (real token accounting), with a
- # same-source byte proxy of THAT .jsonl when usage is unparseable.
- # TIER 2: parent-emitted .context-watermark (stale-rejected).
- # TIER 3: coarse ledger-byte proxy (NOT parent context -- last resort).
- # Honors FAKE_WATERMARK in dry-run so the poll loop is testable.
- read_context_estimate() { # $1 = child_launch_epoch (for staleness)
- if [ "$DRY_RUN" -eq 1 ]; then
- if [ -n "${FAKE_WATERMARK:-}" ]; then echo "$FAKE_WATERMARK"; else echo 0; fi
- return
- fi
- tx=$(find_parent_transcript "${1:-0}")
- if [ -n "$tx" ] && [ -r "$tx" ]; then
- if command -v jq >/dev/null 2>&1; then
- est=$(jq -r 'select(.message.usage) | .message.usage
- | ((.input_tokens//0)+(.cache_read_input_tokens//0)+(.cache_creation_input_tokens//0))' \
- "$tx" 2>/dev/null | awk 'NF{v=$1} END{if(v!="")print v}')
- else
- est=$(grep -o '"usage":[^}]*}' "$tx" 2>/dev/null | tail -n1 \
- | grep -oE '"(input_tokens|cache_read_input_tokens|cache_creation_input_tokens)":[0-9]+' \
- | awk -F: '{s+=$2} END{if(s>0)print s}')
- fi
- case "$est" in (*[0-9]*) [ "$est" -gt 0 ] 2>/dev/null && { echo "$est"; return; } ;; esac
- sz=$(wc -c < "$tx" 2>/dev/null || echo 0)
- [ "$sz" -gt 0 ] 2>/dev/null && { echo $((sz / BYTES_PER_TOKEN)); return; }
- fi
- if [ -r "$WATERMARK_FILE" ]; then
- wm_tok=$(awk 'NR==1{print $1; exit}' "$WATERMARK_FILE" 2>/dev/null || echo)
- wm_ts=$(awk 'NR==1{print $2; exit}' "$WATERMARK_FILE" 2>/dev/null || echo)
- case "$wm_tok" in (*[0-9]*) ;; (*) wm_tok="" ;; esac
- if [ -n "$wm_tok" ] && { [ -z "$wm_ts" ] || [ "${wm_ts:-0}" -ge "${1:-0}" ] 2>/dev/null; }; then
- echo "$wm_tok"; return
- fi
- fi
- bytes=0
- for f in "$LEDGER_DIR"/session_*/prompt_*/*.md "$LEDGER_DIR"/session_*/prompt_*/artifacts/*.md "$LEDGER_DIR"/*/artifacts/*.md; do
- [ -f "$f" ] || continue
- sz=$(wc -c < "$f" 2>/dev/null || echo 0); bytes=$((bytes + sz))
- done
- echo $((bytes / BYTES_PER_TOKEN))
- }
- # Detect a harness-fired (~400k) compaction so the supervisor does NOT then double-fire:
- # a sharp estimate DROP across ticks arms the cooldown and clears any pending request.
- # Records "<epoch> <est>" into COMPACT_STATE_FILE each tick. $1=now $2=current_est.
- note_external_compaction() { # $1=now $2=current_est
- prev_est=0
- [ -r "$COMPACT_STATE_FILE" ] && prev_est=$(awk 'NR==1{print $2+0; exit}' "$COMPACT_STATE_FILE" 2>/dev/null || echo 0)
- if [ "${prev_est:-0}" -gt 0 ] 2>/dev/null \
- && [ $(( prev_est - ${2:-0} )) -ge "$EXTERNAL_COMPACT_DELTA" ] 2>/dev/null; then
- printf '%s %s external_compaction\n' "$1" "${2:-0}" > "$COMPACT_STATE_FILE.tmp" 2>/dev/null \
- && mv "$COMPACT_STATE_FILE.tmp" "$COMPACT_STATE_FILE" 2>/dev/null
- rm -f "$COMPACT_REQUEST_FILE" 2>/dev/null || true
- log "EXTERNAL COMPACTION detected: context estimate dropped ${prev_est}->${2:-0} (>=${EXTERNAL_COMPACT_DELTA}) - arming cooldown and clearing any pending COMPACT-REQUEST (no double-fire)."
- return 0
- fi
- # record the current estimate for next tick's drop comparison (keep the last_compact epoch field 0 unless set)
- last_compact=0; [ -r "$COMPACT_STATE_FILE" ] && last_compact=$(awk 'NR==1{print $1+0; exit}' "$COMPACT_STATE_FILE" 2>/dev/null || echo 0)
- printf '%s %s\n' "$last_compact" "${2:-0}" > "$COMPACT_STATE_FILE.tmp" 2>/dev/null \
- && mv "$COMPACT_STATE_FILE.tmp" "$COMPACT_STATE_FILE" 2>/dev/null
- return 1
- }
- # Decide whether to request/force a compaction. Sets COMPACT_FORCE=1 when a written
- # request has gone unhonored past COMPACT_GRACE. Returns 0 when the caller should act
- # (request written OR force due), 1 otherwise. Guards: cooldown, in-flight request,
- # external-compaction detection -- so one context fill triggers at most one compaction.
- maybe_request_compaction() { # $1=child_launch_epoch $2=now
- COMPACT_FORCE=0
- est=$(read_context_estimate "$1")
- note_external_compaction "$2" "$est" && return 1 # harness already compacted -> nothing to do
- last_compact=0; [ -r "$COMPACT_STATE_FILE" ] && last_compact=$(awk 'NR==1{print $1+0; exit}' "$COMPACT_STATE_FILE" 2>/dev/null || echo 0)
- if [ "${last_compact:-0}" -gt 0 ] 2>/dev/null && [ $(( $2 - last_compact )) -lt "$COMPACT_COOLDOWN" ] 2>/dev/null; then
- return 1
- fi
- if [ -f "$COMPACT_REQUEST_FILE" ]; then
- req_ts=$(awk 'NR==1{print $1+0; exit}' "$COMPACT_REQUEST_FILE" 2>/dev/null || echo 0)
- if [ $(( $2 - req_ts )) -ge "$COMPACT_GRACE" ] 2>/dev/null; then COMPACT_FORCE=1; return 0; fi
- return 1
- fi
- if [ "$est" -ge "$COMPACT_AT" ] 2>/dev/null; then
- printf '%s proactive est=%s threshold=%s\n' "$2" "$est" "$COMPACT_AT" > "$COMPACT_REQUEST_FILE.tmp" 2>/dev/null \
- && mv "$COMPACT_REQUEST_FILE.tmp" "$COMPACT_REQUEST_FILE" 2>/dev/null \
- && log "COMPACT-REQUEST written: context est=${est} tokens >= AUTOPROMPT_COMPACT_AT=${COMPACT_AT}. Parent will checkpoint+compact at its next gate boundary (not a wipe, not a stop)."
- return 0
- fi
- return 1
- }
- # Kill the child's whole process GROUP so a wedged parent leaves NO orphaned subagent.
- # SIGTERM the group, escalate to SIGKILL after a short grace. Falls back to a plain PID
- # kill when job control / negative-pgid signaling is unavailable.
- kill_tree() { # $1 = child pid
- pid="$1"
- [ -n "$pid" ] || return 0
- if command -v taskkill.exe >/dev/null 2>&1; then
- win_pid=$(ps -W -p "$pid" -l 2>/dev/null | awk 'NR==2{print $4; exit}')
- case "$win_pid" in (*[!0-9]*|"") win_pid="" ;; esac
- if [ -n "$win_pid" ] && taskkill.exe /T /F /PID "$win_pid" >/dev/null 2>&1; then
- return 0
- fi
- fi
- descendants=""
- pending="$pid"
- while [ -n "$pending" ]; do
- parent=${pending%% *}
- case "$pending" in (*" "*) pending=${pending#* } ;; (*) pending="" ;; esac
- children=$(ps -ef 2>/dev/null | awk -v parent="$parent" 'NR>1 && $3 == parent { print $2 }')
- for child in $children; do
- case " $descendants " in (*" $child "*) ;; (*) descendants="$child $descendants"; pending="$pending $child" ;; esac
- done
- pending=$(printf '%s' "$pending" | sed 's/^ *//')
- done
- for victim in $descendants "$pid"; do kill -TERM "$victim" 2>/dev/null || true; done
- i=0
- while [ "$i" -lt 4 ] && kill -0 "$pid" 2>/dev/null; do sleep 0.5 2>/dev/null || sleep 1; i=$((i + 1)); done
- for victim in $descendants "$pid"; do
- kill -0 "$victim" 2>/dev/null && kill -KILL "$victim" 2>/dev/null || true
- done
- }
- # Run the real or fake launcher once; return its exit code.
- #
- # HEARTBEAT (PLAN-idle-watchdog V3): the child is launched in the BACKGROUND on
- # BOTH the real exec AND the dry-run fake path, so a SINGLE poll loop watches
- # liveness + frontier-COUNT staleness regardless of path (blocker 2: the poll loop
- # is genuinely exercised under --dry-run). While the child is alive, if
- # frontier_count has NOT grown beyond last_seen within IDLE_TIMEOUT and no sentinel
- # exists, the run is ALIVE-BUT-IDLE -> kill the child so the outer relaunch loop
- # RESUMEs it (the automatic CONTINUE for an idle agent). This is DISTINCT from the
- # EXIT-keyed poison guard and FEEDS it: a heartbeat kill that produced no count
- # growth is recorded by the outer loop as a no-progress restart, so a wedged child
- # still trips POISON after MAX_RESTARTS (anti-thrash, §4.5 - no second uncapped
- # relaunch path). LAUNCH_INDEX is incremented in the PARENT scope here, before the
- # fork, so only the exec / fake-work is backgrounded.
- LAUNCH_INDEX=0
- run_launcher() {
- LAUNCH_INDEX=$((LAUNCH_INDEX + 1))
- child_launch_epoch=$(date +%s 2>/dev/null || echo 0)
- if [ "$DRY_RUN" -eq 0 ]; then
- stored_binding=""
- [ -r "$SCOPE_PHASE_START_FILE" ] && stored_binding=$(awk 'NR==1{print $2; exit}' "$SCOPE_PHASE_START_FILE" 2>/dev/null || echo)
- if [ "$stored_binding" != "$SCOPE_MISSION_BINDING" ]; then
- rm -f "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST" \
- "$LEDGER_DIR/SCOPE-BUDGET-BREACH" "$SCOPE_RESETS_FILE" 2>/dev/null
- printf '%s %s\n' "$child_launch_epoch" "$SCOPE_MISSION_BINDING" \
- > "$SCOPE_PHASE_START_FILE.tmp" 2>/dev/null \
- && mv "$SCOPE_PHASE_START_FILE.tmp" "$SCOPE_PHASE_START_FILE" 2>/dev/null
- fi
- fi
- if [ "$DRY_RUN" -eq 1 ]; then
- # Pop the next exit code from FAKE_EXITS in the PARENT (LAUNCH_INDEX-indexed);
- # default 0 once the list is spent. The fork below exits with this code so the
- # parent's `wait` retrieves it.
- set -- ${FAKE_EXITS:-0}
- idx="$LAUNCH_INDEX"
- code=0; n=0
- for c in "$@"; do n=$((n + 1)); if [ "$n" -eq "$idx" ]; then code="$c"; fi; done
- (
- # The backgrounded fake child. Optionally write the sentinel BEFORE exit
- # (models the JANITOR having written it), advance the frontier unless poisoned,
- # then optionally STAY ALIVE (FAKE_CHILD_ALIVE seconds) so the poll loop has a
- # real PID to kill -0 / kill and a real .fake-frontier to read as stale. Exit
- # with the popped code so `wait` recovers it.
- if [ -n "${FAKE_SENTINEL_AFTER:-}" ] && [ "$idx" -ge "$FAKE_SENTINEL_AFTER" ]; then
- printf '{"done": true, "nonce": "FAKE", "verdict": "fake done", "ts": "now"}' \
- > "$LEDGER_DIR/DONE-FAKE.tmp" && mv "$LEDGER_DIR/DONE-FAKE.tmp" "$LEDGER_DIR/DONE-FAKE"
- fi
- if [ "${FAKE_POISON:-0}" != "1" ]; then
- cur=0; [ -f "$LEDGER_DIR/.fake-frontier" ] && cur=$(cat "$LEDGER_DIR/.fake-frontier")
- echo $((cur + 1)) > "$LEDGER_DIR/.fake-frontier"
- fi
- sleep "${FAKE_CHILD_ALIVE:-0}" 2>/dev/null || true
- exit "$code"
- ) &
- else
- # Launch one is fresh unless the operator explicitly invoked this supervisor as a
- # resume. Relaunches always export AUTOPROMPT_RESUME=1.
- # When LAUNCH_CMD is set it is used VERBATIM (word-split into command + args,
- # mission appended) so a fresh user can pass their real CLI; otherwise the
- # bare LAUNCHER label is exec'd as before.
- # Neutralize the operator's CLAUDE_CODE_SUBAGENT_MODEL for the CHILD CLI ONLY.
- # That var has HIGHEST precedence in the harness and force-pins every (even
- # nested) subagent onto a fixed model, defeating the skill's `model: inherit`
- # contract. A child cannot mutate its parent's env, so the LAUNCH layer is the
- # only correct place to strip it: `env -u` removes it from the child's
- # environment WITHOUT touching this supervisor's own env or the operator's
- # shell/profile/CLAUDE.md/settings.json. `inherit` then resolves to the real
- # session/--model selection. Idempotent: env -u of an unset/inherit var is a
- # no-op, never an error. AUTOPROMPT_KEEP_MODEL_PIN=1 opts OUT (keeps the pin).
- (
- export AUTOPROMPT_UNATTENDED=1
- if [ "$LAUNCH_INDEX" -gt 1 ] || [ "$INITIAL_RESUME" -eq 1 ]; then
- export AUTOPROMPT_RESUME=1
- else
- unset AUTOPROMPT_RESUME
- fi
- export AUTOPROMPT_MODE
- if [ "$LEGACY_SENTINEL" != "1" ]; then export AUTOPROMPT_RUN_NONCE="$RUN_NONCE"; fi
- export AUTOPROMPT_LEDGER_CHECK="$LEDGER_CHECK_PATH"
- if [ -n "$AUTOPROMPT_SESSION_TOKEN" ]; then
- export AUTOPROMPT_SESSION_TOKEN
- else
- unset AUTOPROMPT_SESSION_TOKEN
- fi
- if [ "${AUTOPROMPT_KEEP_MODEL_PIN:-0}" != "1" ]; then
- unset CLAUDE_CODE_SUBAGENT_MODEL
- fi
- export AUTOPROMPT_AGENTS="$AGENTS_SELECTOR"
- export AUTOPROMPT_PROVIDER="$CAPABILITY_PROVIDER"
- export AUTOPROMPT_CLI_VERSION="$CAPABILITY_CLI_VERSION"
- export AUTOPROMPT_PERMISSION_PROFILE="$CAPABILITY_PERMISSION_PROFILE"
- export AUTOPROMPT_AGENT_DEFINITIONS_HASH="$CAPABILITY_AGENT_DEFINITIONS_HASH"
- export AUTOPROMPT_CASTING_HASH="$CAPABILITY_CASTING_HASH"
- if [ -n "$AUTOPROMPT_CAPABILITY_ATTESTATION" ]; then
- export AUTOPROMPT_CAPABILITY_ATTESTATION
- else
- unset AUTOPROMPT_CAPABILITY_ATTESTATION
- fi
- if [ "$CASTING_ENABLED" = "true" ]; then
- export AUTOPROMPT_AGENT_CASTING="$CASTING_JSON"
- export ANTHROPIC_DEFAULT_OPUS_MODEL="$CASTING_OPUS"
- export ANTHROPIC_DEFAULT_SONNET_MODEL="$CASTING_SONNET"
- export ANTHROPIC_DEFAULT_HAIKU_MODEL="$CASTING_HAIKU"
- if [ -n "$CASTING_BASE_URL" ]; then export ANTHROPIC_BASE_URL="$CASTING_BASE_URL"; fi
- if [ -n "$CASTING_API_KEY_ENV" ]; then export ANTHROPIC_AUTH_TOKEN="$CASTING_AUTH_TOKEN"; fi
- fi
- if [ -n "$LAUNCH_CMD" ]; then
- # shellcheck disable=SC2086 # operator command is intentionally split into argv.
- set -- $LAUNCH_CMD
- else
- set -- "$LAUNCHER"
- fi
- [ "$#" -gt 0 ] || exit 127
- "$@" --agents "$AGENT_DEFINITIONS_JSON" "$MISSION"
- ) &
- fi
- child_pid=$!
- # NOTE on `date +%s`: used ONLY for the elapsed-wall-clock comparison
- # (now - last_progress), exactly as the existing relaunch loop already does - it is
- # NOT a file probe, and its `|| echo 0` fallback only pins now/last_progress to the
- # same baseline, which can at worst DELAY the timeout, never falsely fire it. The
- # progress decision is purely the integer frontier-count delta (blocker 3: no mtime
- # probe, so a healthy progressing run is NEVER mischaracterized as stale).
- last_progress=$(date +%s 2>/dev/null || echo 0)
- last_seen_count=$(frontier_count)
- # The poll loop wakes on a RESPONSIVE slice (min of HEARTBEAT_INTERVAL and 1s) so a
- # child that EXITS is detected promptly instead of after a full HEARTBEAT_INTERVAL
- # block - the staleness evaluation still only runs once per HEARTBEAT_INTERVAL of
- # elapsed wall-clock. This keeps a fast-exiting (real or dry-run) child from pinning
- # the loop for the whole interval while preserving the exact heartbeat cadence.
- poll_slice="$HEARTBEAT_INTERVAL"; [ "$poll_slice" -gt 1 ] 2>/dev/null && poll_slice=1
- last_eval="$last_progress"
- while kill -0 "$child_pid" 2>/dev/null; do
- sleep "$poll_slice" 2>/dev/null || true
- sentinel_present && break # the run finished while we slept; let the outer loop halt cleanly
- now=$(date +%s 2>/dev/null || echo 0)
- [ $((now - last_eval)) -ge "$HEARTBEAT_INTERVAL" ] || continue # not yet a heartbeat tick
- last_eval="$now"
- cur_count=$(frontier_count)
- if [ "$cur_count" -gt "$last_seen_count" ]; then
- last_seen_count="$cur_count"; last_progress="$now" # frontier advanced -> healthy, reset
- elif [ $((now - last_progress)) -ge "$IDLE_TIMEOUT" ]; then
- log "HEARTBEAT: no frontier progress for >=${IDLE_TIMEOUT}s while alive and no sentinel - killing to relaunch with RESUME (auto-continue an idle agent)."
- kill "$child_pid" 2>/dev/null || true; break
- fi
- # PLAN-auto-compact-threshold: proactive supervisor-fired compaction check. Writes
- # COMPACT-REQUEST when the externally-observed context size crosses COMPACT_AT; on a
- # request unhonored past COMPACT_GRACE (parent wedged) forces the reset.
- if maybe_request_compaction "$child_launch_epoch" "$now"; then
- if [ "$COMPACT_FORCE" -eq 1 ]; then
- log "COMPACT FALLBACK: request unhonored for >=${COMPACT_GRACE}s (parent likely wedged) - recording a .forced-reset marker, then killing the WHOLE child process group so no subagent is orphaned; the outer loop RESUMEs from the SCRIBE-refreshed ANCHOR.md."
- printf '%s forced est_unhonored grace=%s\n' "$now" "$COMPACT_GRACE" > "$COMPACT_STATE_FILE.forced.tmp" 2>/dev/null \
- && mv "$COMPACT_STATE_FILE.forced.tmp" "$LEDGER_DIR/.forced-reset" 2>/dev/null
- printf '%s forced\n' "$now" > "$COMPACT_STATE_FILE.tmp" 2>/dev/null \
- && mv "$COMPACT_STATE_FILE.tmp" "$COMPACT_STATE_FILE" 2>/dev/null
- rm -f "$COMPACT_REQUEST_FILE" 2>/dev/null || true
- kill_tree "$child_pid"
- break
- fi
- fi
- # F-SPEED steer-2 B3: PHASE WALL-CLOCK BUDGET check. Once per tick, when the SCOPE
- # phase is active (ROADMAP/scout evidence present, no build artifact yet), consult phase-budget.js.
- # It is anchored to scope ENTRY and NOT reset by frontier growth, so it fires on the
- # progressing-but-slow 30-min scope IDLE_TIMEOUT can never bound. Fail-open: an absent
- # node/module skips the block (guarded by [ -r ]) and the run proceeds on IDLE_TIMEOUT.
- scope_el=$(scope_phase_elapsed)
- if [ -n "$scope_el" ] && [ -r "$PHASE_BUDGET_PATH" ]; then
- req_age=$(scope_converge_request_age)
- prior=$(awk 'NR==1{print $1+0; exit}' "$SCOPE_RESETS_FILE" 2>/dev/null || echo 0)
- case "$prior" in (*[!0-9]*|"") prior=0 ;; esac
- landed=$(scope_landed_angles)
- node "$PHASE_BUDGET_PATH" --verdict --phase scope --elapsed "$scope_el" \
- --soft "$SCOPE_SOFT_SEC" --hard "$SCOPE_HARD_SEC" --request-age "$req_age" \
- --grace "$SCOPE_GRACE_SEC" --prior-resets "$prior" --max-resets "$MAX_SCOPE_RESETS" \
- --landed "$landed" >/dev/null 2>&1
- case $? in
- 10) # SOFT breach: write the converge heads-up ONCE (idempotent), keep running.
- if [ ! -f "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST" ]; then
- printf '%s soft scope budget: mission=%s elapsed=%ss soft=%ss landed=%s - converge on the landed angles; do NOT fabricate unscoped ones.\n' \
- "$now" "$SCOPE_MISSION_BINDING" "$scope_el" "$SCOPE_SOFT_SEC" "$landed" \
- > "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST.tmp" 2>/dev/null \
- && mv "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST.tmp" "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST" 2>/dev/null
- log "SCOPE BUDGET soft breach at ${scope_el}s (>= ${SCOPE_SOFT_SEC}s, frontier advancing) - wrote SCOPE-CONVERGE-REQUEST (converge on landed=${landed}); child NOT killed."
- fi ;;
- 20) # HARD/grace breach: durable breach marker (honest landed residual), bump the
- # forced-reset counter, then REAL kill->RESUME via the existing idle-kill path.
- printf '%s hard scope budget breach: mission=%s elapsed=%ss hard=%ss landed=%s residual=%s - converge on landed, surface any unscoped angle; DO NOT fabricate.\n' \
- "$now" "$SCOPE_MISSION_BINDING" "$scope_el" "$SCOPE_HARD_SEC" "$landed" "$landed" \
- > "$LEDGER_DIR/SCOPE-BUDGET-BREACH.tmp" 2>/dev/null \
- && mv "$LEDGER_DIR/SCOPE-BUDGET-BREACH.tmp" "$LEDGER_DIR/SCOPE-BUDGET-BREACH" 2>/dev/null
- echo $((prior + 1)) > "$SCOPE_RESETS_FILE.tmp" 2>/dev/null \
- && mv "$SCOPE_RESETS_FILE.tmp" "$SCOPE_RESETS_FILE" 2>/dev/null
- log "SCOPE BUDGET hard breach at ${scope_el}s (frontier was advancing) - wrote SCOPE-BUDGET-BREACH (residual=${landed}); killing the process tree and terminating this supervisor run."
- SCOPE_BUDGET_TERMINAL=1
- kill_tree "$child_pid"; break ;;
- 30) # RE-BREACH past the reset cap: escalate honestly, never fake a roadmap.
- {
- echo "supervisor escalation: scope budget breached past MAX_SCOPE_RESETS=$MAX_SCOPE_RESETS"
- echo "scope_elapsed=$scope_el hard=$SCOPE_HARD_SEC prior_resets=$prior landed=$landed"
- echo "converge unreachable - landed angles surfaced as the honest residual; NO fabricated roadmap"
- echo "ts=$(date 2>/dev/null)"
- } > "$ESCALATE_FILE" 2>/dev/null || true
- log "SCOPE BUDGET escalation at ${scope_el}s - breached past MAX_SCOPE_RESETS=${MAX_SCOPE_RESETS}; landed=${landed} surfaced as residual; killing and exiting 1."
- kill_tree "$child_pid"
- wait "$child_pid" 2>/dev/null
- exit 1 ;;
- esac
- fi
- done
- wait "$child_pid" 2>/dev/null
- exit_code=$?
- [ "$SCOPE_BUDGET_TERMINAL" -eq 1 ] && return 124
- return "$exit_code"
- }
- # EDIT 23: seed the per-conversation session token BEFORE the relaunch loop. The
- # supervisor is the durable producer across relaunches of one conversation; this
- # establishes the token precedence ONCE: an env-supplied token (operator or a prior
- # same-conversation export) wins and is persisted to the durable file; else a
- # previously-harvested token is read back from the file; else the token stays empty
- # and the first SCRIBE-run resolver MINTS one (which we then harvest, below).
- # Fail-soft: an unwritable/unreadable token file never aborts the run - the token
- # just stays empty and the next launch re-mints (worst case a fresh session).
- seed_session_token() {
- if [ -n "$AUTOPROMPT_SESSION_TOKEN" ]; then
- printf '%s\n' "$AUTOPROMPT_SESSION_TOKEN" > "$SESSION_TOKEN_FILE" 2>/dev/null || true
- elif [ -r "$SESSION_TOKEN_FILE" ]; then
- AUTOPROMPT_SESSION_TOKEN=$(head -n1 "$SESSION_TOKEN_FILE" 2>/dev/null || echo)
- fi
- }
- # EDIT 23: HARVEST the resolver-minted token after a launch when the supervisor holds
- # none yet. The SCRIBE-run `--resolve-prompt-dir` CLI writes the marker
- # "$LEDGER_DIR/.session-current" as "session_NN <token>" (two whitespace-separated
- # fields - the EDIT 7 contract). We read the 2nd field and persist it so the NEXT
- # launch re-exports the SAME token and a 2nd prompt rejoins the same session_NN.
- # Fail-soft: an absent/corrupt marker (no 2nd field) leaves the token empty and the
- # next launch mints again - a fresh session, never a crash.
- harvest_session_token() {
- [ -n "$AUTOPROMPT_SESSION_TOKEN" ] && return 0
- marker="$LEDGER_DIR/.session-current"
- [ -r "$marker" ] || return 0
- harvested=$(awk 'NR==1{print $2; exit}' "$marker" 2>/dev/null || echo)
- if [ -n "$harvested" ]; then
- AUTOPROMPT_SESSION_TOKEN="$harvested"
- printf '%s\n' "$AUTOPROMPT_SESSION_TOKEN" > "$SESSION_TOKEN_FILE" 2>/dev/null || true
- fi
- }
- # PLAN-auto-compact-threshold: a discovery-level test sources this script to call
- # canon_path / find_parent_transcript directly. AUTOPROMPT_SOURCE_ONLY=1 stops here,
- # AFTER every function + path var is defined but BEFORE the launch loop runs.
- [ "${AUTOPROMPT_SOURCE_ONLY:-0}" = "1" ] && return 0 2>/dev/null
- # Legacy broad DONE-* matching is a DOWNGRADE honored only for a verified legacy
- # resume: the operator opted in explicitly AND the ledger directory carries
- # physical evidence of a pre-nonce run (legacy governance files a three-file
- # new-format run never creates). A fresh or new-format directory fails closed so
- # the downgrade can never weaken a current-format run. Checked on the launch
- # path only (after the source-only return) so sourced function evaluation is
- # not subjected to launch-time validation.
- if [ "$LEGACY_SENTINEL" = "1" ]; then
- LEGACY_EVIDENCE=0
- for marker in BRIEF.md AGENTS.md bucketlist.md ANCHOR.md; do
- if [ -f "$LEDGER_DIR/$marker" ]; then LEGACY_EVIDENCE=1; break; fi
- done
- if [ "$LEGACY_EVIDENCE" -ne 1 ]; then
- echo "supervisor: AUTOPROMPT_LEGACY_SENTINEL=1 requires a verified legacy resume (legacy governance files under $LEDGER_DIR); unset it for new runs" >&2
- exit 2
- fi
- fi
- if [ -z "$LAUNCHER" ] && [ -z "$LAUNCH_CMD" ] && [ "$DRY_RUN" -eq 0 ]; then
- echo "supervisor: no launch command (use --cmd \"<your CLI>\" / AUTOPROMPT_LAUNCH_CMD, or --launcher apidemo|codexdemo / AUTOPROMPT_LAUNCHER)" >&2
- exit 2
- fi
- resolve_model_casting || exit $?
- resolve_capability_binding || exit $?
- if [ "$DRY_RUN" -eq 0 ]; then
- AGENT_DEFINITIONS_JSON=""
- resolve_agent_definitions_json || exit $?
- fi
- LAUNCH_LABEL="${LAUNCH_CMD:-${LAUNCHER:-<dry-run>}}"
- log "starting: launcher=$LAUNCH_LABEL ledger=$LEDGER_DIR mission=\"$MISSION\""
- log "topology: 5-level L0->L4; mode=$AUTOPROMPT_MODE; per-L3 fan-out=$FANOUT; L3 tracks=$L3_TRACKS; L1 never executes (rule 68); single-block spawns (rule 67) - enforced in the harness."
- # THE stale-sentinel guarantee: snapshot every pre-existing DONE-* PATH BEFORE the
- # first launch and BEFORE quarantine. sentinel_present refuses any path still in
- # this snapshot, so a prior-run sentinel can never halt this mission -- even if the
- # quarantine rename below fails (read-only dir / permissions). ORDER IS LOAD-BEARING:
- # snapshot first (records the dir as it was), THEN quarantine -- which prunes each
- # SUCCESSFULLY-renamed path from the live snapshot so the same-activation
- # DONE-<nonce> can be reclaimed by a genuine fresh sentinel. A path whose rename
- # FAILS stays snapshotted and vetoed. Both run before the first sentinel_present.
- snapshot_pre_existing_sentinels
- # Quarantine renames each stale sentinel aside, emits a loud log line, and prunes
- # every successfully-cleared path from the snapshot so a fresh same-path sentinel is
- # honored; a failed rename leaves the path vetoed and degrades to RELAUNCH.
- quarantine_stale_sentinels
- # EDIT 23: seed the session token once, after the ledger dir exists and before the
- # first launch, so run_launcher can re-export it and harvest_session_token can fill it.
- seed_session_token
- restart_times="" # space-separated epoch seconds of recent restarts (no progress)
- last_frontier=$(frontier_count)
- backoff="$RETRY_BASE"
- while :; do
- if sentinel_present; then
- log "DONE-sentinel present - run complete, halting cleanly."
- exit 0
- fi
- run_launcher
- exit_code=$?
- if [ "$SCOPE_BUDGET_TERMINAL" -eq 1 ]; then
- log "SCOPE BUDGET terminal stop - no same-mission relaunch will consume another worker."
- exit 124
- fi
- if sentinel_present; then
- log "DONE-sentinel present after launch (exit $exit_code) - run complete, halting cleanly."
- exit 0
- fi
- # V5 (MANDATORY terminal caller): the child EXITED with no DONE-sentinel - a
- # TERMINAL boundary for that child. Mark it so a ledger audit treats this as
- # run-ended, then run the terminal IDLE-FINISH audit. RUN-ENDED is the marker
- # autoprompt-ledger-check.js reads to set runEnded=true (§2.3 Edit L1). Written
- # every exit-without-sentinel; idempotent (overwritten each exit). The clean-DONE
- # path short-circuits at the sentinel checks above, so RUN-ENDED is only ever
- # written when the run is genuinely not done.
- printf 'run-ended exit=%s ts=%s\n' "$exit_code" "$(date 2>/dev/null)" > "$LEDGER_DIR/RUN-ENDED" 2>/dev/null || true
- if [ "$DRY_RUN" -eq 0 ] && [ -n "$LEDGER_CHECK_PATH" ] && [ -r "$LEDGER_CHECK_PATH" ]; then
- # Best-effort loud-log: the marker alone is sufficient for the rule to fire on the
- # NEXT audit, so this node call's exit 1 is informational; the relaunch happens regardless.
- if node "$LEDGER_CHECK_PATH" --ledger-dir "$LEDGER_DIR" --transcript-dir "$LEDGER_DIR" --terminal >/dev/null 2>&1; then :; else
- log "IDLE-FINISH terminal audit flagged a P0 (run ended with open work, no live agent) - relaunching with RESUME to re-drive."
- fi
- fi
- now=$(date +%s 2>/dev/null || echo 0)
- cur_frontier=$(frontier_count)
- # EDIT 23: harvest the resolver-minted session token (no-op once we hold one) so
- # the next relaunch re-exports the SAME token and a 2nd prompt rejoins the session.
- harvest_session_token
- log "launcher exited ($exit_code); frontier $last_frontier -> $cur_frontier; no sentinel - relaunching with RESUME."
- if [ "$cur_frontier" -gt "$last_frontier" ]; then
- # Healthy-long: progress was made. Reset the poison window and backoff.
- restart_times=""
- backoff="$RETRY_BASE"
- last_frontier="$cur_frontier"
- else
- # No progress since the last launch. Record this restart in the rolling
- # window and check the poison guard.
- new_times=""
- rapid=1
- for t in $restart_times; do
- if [ $((now - t)) -lt "$WINDOW" ]; then
- new_times="$new_times $t"
- rapid=$((rapid + 1))
- fi
- done
- restart_times="$new_times $now"
- if [ "$rapid" -ge "$MAX_RESTARTS" ]; then
- log "POISON: $rapid restarts within ${WINDOW}s with NO frontier progress - escalating, not relaunching."
- {
- echo "supervisor escalation: crash-loop with no frontier progress"
- echo "restarts_in_window=$rapid window_s=$WINDOW last_exit=$exit_code frontier=$cur_frontier"
- echo "ts=$(date 2>/dev/null)"
- } > "$ESCALATE_FILE"
- exit 1
- fi
- # Exponential backoff, capped, between unproductive relaunches.
- if [ "$backoff" -gt 0 ] 2>/dev/null; then sleep "$backoff" 2>/dev/null || true; fi
- next=$((backoff * 2)); [ "$next" -gt "$RETRY_CAP" ] && next="$RETRY_CAP"
- backoff="$next"
- fi
- done
agents/codex/workflow/windows-appcontainer-probe.js · Bundled script · 126 lines · 1 finding marked
- 'use strict'
- const fs = require('node:fs')
- const path = require('node:path')
- const crypto = require('node:crypto')
- const net = require('node:net')
- const { ensureWindowsPrivateAcl, ensureWindowsDefaultTokenOwner, windowsControllerEnvironment } = require('./safe-run-root.js')
- function failureDiagnostic(error, phase) {
- const details = error && error.details
- // This probe only runs fixed controller diagnostics. Preserve their bounded
- // failure explanation, never arbitrary error properties or environment maps.
- const diagnostic = { phase, message: String(error && error.message || 'Native probe failed').slice(0, 1024) }
- for (const name of ['stage', 'helperPhase', 'cause', 'signal']) {
- if (typeof details?.[name] === 'string' && /^[A-Za-z0-9_-]{1,80}$/.test(details[name])) diagnostic[name] = details[name]
- }
- if (new Set(['open', 'read', 'write', 'lstat', 'stat', 'realpath', 'scandir', 'rm', 'rmdir', 'unlink', 'rename', 'chmod', 'mkdir', 'access']).has(details?.syscall)) diagnostic.syscall = details.syscall
- for (const name of ['status', 'timeoutMs']) if (details?.[name] === null || Number.isSafeInteger(details?.[name])) diagnostic[name] = details[name]
- if (typeof details?.stderr === 'string' && details.stderr) diagnostic.stderr = details.stderr.slice(0, 2048)
- return diagnostic
- }
- function runtimeKey(workerIdentity) {
- const hash = crypto.createHash('sha256')
- for (const name of ['windows-appcontainer.js', 'windows-appcontainer.ps1', 'windows-appcontainer-native.cs', 'windows-appcontainer-command.js', 'windows-appcontainer-probe.js', 'windows-appcontainer-resources.js', 'windows-appcontainer-resources.ps1', 'windows-appcontainer-resources-native.cs', 'windows-helper-deployment.js', 'windows-filesystem.js', 'windows-filesystem.ps1']) hash.update(name).update(fs.readFileSync(path.join(__dirname, name)))
- hash.update(workerIdentity)
- hash.update(fs.readFileSync(process.execPath))
- return hash.update(JSON.stringify([process.pid, process.env.SystemRoot, process.env.LOCALAPPDATA])).digest('hex')
- }
- async function listen(host) {
- const state = { accepted: 0 }
- const server = net.createServer(socket => { state.accepted++; socket.end() })
- await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, host, resolve) })
- return { server, state, host, port: server.address().port, family: host === '::1' ? 6 : 4 }
- }
- async function control(endpoint) {
- await new Promise((resolve, reject) => {
- const socket = net.connect({ host: endpoint.host, port: endpoint.port, family: endpoint.family })
- socket.once('connect', () => { socket.destroy(); resolve() }); socket.once('error', reject)
- socket.setTimeout(1500, () => { socket.destroy(); reject(new Error('CONTROL_TIMEOUT')) })
- })
- await new Promise(resolve => setImmediate(resolve))
- }
- async function probeWindowsAppContainer() {
- return require('./windows-appcontainer-command.js').probeWindowsAppContainer()
- }
- // This fixed fixture cannot grant admission. Only command.js owns that cache and
- // supplies the private tuple-bound executor; external calls receive observations.
- async function runWindowsAppContainerCanary(runWindowsAppContainerCommand, workerIdentity, key) {
- if (process.platform !== 'win32') return { supported: false, backend: 'windows-appcontainer', code: 'COMMAND_SANDBOX_UNSUPPORTED' }
- if (typeof runWindowsAppContainerCommand !== 'function' || !/^[a-f0-9]{64}$/.test(workerIdentity) || key !== runtimeKey(workerIdentity)) throw new Error('CANARY_IDENTITY_MISMATCH')
- ensureWindowsDefaultTokenOwner()
- const controllerEnvironment = windowsControllerEnvironment(process.env.SystemRoot || process.env.WINDIR)
- let base = fs.mkdtempSync(path.join(controllerEnvironment.TEMP, 'autoprompt-appcontainer-probe-'))
- let preserve = false, launcherSessionId = null, nativeExitCode = null, probeFailure = null, primaryError = null, phase = 'private-root'
- const endpoints = []
- try {
- base = fs.realpathSync.native(base)
- ensureWindowsPrivateAcl(base)
- phase = 'private-fixture'
- const controlRoot = path.join(base, 'controller'), target = path.join(base, 'target'), scratch = path.join(base, 'scratch')
- for (const directory of [controlRoot, target, scratch]) { fs.mkdirSync(directory); ensureWindowsPrivateAcl(directory) }
- fs.mkdirSync(path.join(target, '.git')); fs.writeFileSync(path.join(target, '.git', 'guard'), 'controller git')
- fs.writeFileSync(path.join(target, 'allowed'), 'allowed')
- const deletedOriginal = path.join(target, 'delete-original')
- fs.writeFileSync(deletedOriginal, 'controller original', { flag: 'wx' })
- const sentinel = path.join(controlRoot, 'sentinel'); fs.writeFileSync(sentinel, 'controller only')
- phase = 'loopback-control'
- endpoints.push(await listen('127.0.0.1'))
- endpoints.push(await listen('::1'))
- for (const endpoint of endpoints) { await control(endpoint); if (endpoint.state.accepted !== 1) throw new Error('CONTROL_ACCEPT'); endpoint.state.accepted = 0 }
- const targetStat = fs.lstatSync(target, { bigint: true })
- if (!targetStat.isDirectory() || targetStat.isSymbolicLink() || targetStat.dev < 0n || targetStat.dev > 0xffffffffn || targetStat.ino < 1n || targetStat.ino > 0xffffffffffffffffn || !['x64', 'arm64'].includes(process.arch)) throw new Error('CANARY_TARGET_IDENTITY_INVALID')
- const targetIdentity = targetStat.dev.toString(16).padStart(8, '0') + ':' + targetStat.ino.toString(16).padStart(16, '0')
- const fixture = { target, scratch, sentinel, targetIdentity, architecture: process.arch, endpoints: endpoints.map(({host,port,family}) => ({host,port,family})) }
- const source = `const fs=require('node:fs'),net=require('node:net'),cp=require('node:child_process'),path=require('node:path');const f=${JSON.stringify(fixture)};let phase='read';const need=x=>{if(!x)throw Error('PROBE')};const denied=p=>{try{fs.readFileSync(p);return false}catch(e){return e.code==='EACCES'||e.code==='EPERM'}};const request=e=>new Promise(ok=>{let done=false;const finish=v=>{if(done)return;done=true;s.destroy();ok(v)};const s=net.connect(e);s.once('connect',()=>finish(false));s.once('error',e=>finish(['EACCES','EPERM','ETIMEDOUT'].includes(e.code)));s.setTimeout(1500,()=>finish(false))});(async()=>{need(fs.readFileSync(path.join(f.target,'allowed'),'utf8')==='allowed');phase='delete-original';need(fs.readFileSync(path.join(f.target,'delete-original'),'utf8')==='controller original');fs.unlinkSync(path.join(f.target,'delete-original'));phase='write-target';fs.writeFileSync(path.join(f.target,'written'),'worker');phase='write-scratch';fs.writeFileSync(path.join(f.scratch,'written'),'scratch');phase='new-entry-delete';for(const root of [f.target,f.scratch]){const directory=path.join(root,'delete-created'),file=path.join(directory,'child');fs.mkdirSync(directory);fs.writeFileSync(file,'worker');fs.unlinkSync(file);fs.rmdirSync(directory)}phase='sentinel';need(denied(f.sentinel));phase='git-write';let gitDenied=false,gitOutcome='WRITE_SUCCEEDED';try{fs.writeFileSync(path.join(f.target,'.git','guard'),'bad')}catch(e){gitOutcome=/^[A-Z][A-Z0-9_]{0,39}$/.test(String(e.code))?e.code:'OTHER_ERRNO';gitDenied=['EACCES','EPERM'].includes(e.code)}if(!gitDenied){const error=Error('PROBE');error.code='GIT_'+gitOutcome;throw error};phase='git-rename-delete';for(const operation of [()=>fs.renameSync(path.join(f.target,'.git'),path.join(f.target,'moved-git')),()=>fs.unlinkSync(path.join(f.target,'.git','guard'))]){let denied=false;try{operation()}catch(e){denied=['EACCES','EPERM'].includes(e.code)}need(denied)}phase='acl-write';const aclResult=path.join(f.scratch,'acl-result.txt'),aclOutput=fs.openSync(aclResult,'wx');let aclExit;try{const acl=cp.spawn(path.join(path.dirname(process.execPath),'acl-probe.exe'),['--acl-probe',process.env.AUTOPROMPT_APP_CONTAINER_SID,f.target,f.targetIdentity],{cwd:f.scratch,stdio:[0,aclOutput,aclOutput]});aclExit=await new Promise((ok,no)=>{acl.once('error',no);acl.once('exit',ok)})}finally{fs.closeSync(aclOutput)};need(fs.statSync(aclResult).size<=256);const aclBytes=fs.readFileSync(aclResult),aclExpected='bundle-acl-denied-v1:'+f.architecture+':'+f.targetIdentity+':5';need(aclExit===0&&aclBytes.length<=256&&(aclBytes.equals(Buffer.from(aclExpected+'\\r\\n'))||aclBytes.equals(Buffer.from(aclExpected+'\\n'))));phase='descendant';const child=cp.spawn(process.execPath,['-e','setTimeout(()=>process.exit(0),10000)'],{stdio:'inherit'});need(child.pid>0);let childError=false;child.on('error',()=>{childError=true});await new Promise(r=>setTimeout(r,100));phase='network';for(const e of f.endpoints)need(await request(e));phase='child-kill';const exit=new Promise(r=>child.once('exit',r));need(child.kill());await exit;need(!childError);process.stdout.write('APPCONTAINER_PROBE_PASS')})().catch(error=>{process.stderr.write('APPCONTAINER_PROBE_FAILURE:'+phase+':'+String(error.code||'CHECK'));process.exitCode=1})`
- const encoded = Buffer.from(source).toString('base64')
- // Admission must exercise Bash fork/pipe behavior as well as the Node worker.
- // A final simple command can otherwise pass through Bash's exec optimization.
- const command = `ap_parent=$BASHPID; ap_child=$(printf '%s' "$BASHPID") || { printf '%s' 'APPCONTAINER_PROBE_FAILURE:bash-fork:COMMAND_SUBSTITUTION' >&2; exit 91; }; [[ "$ap_parent" =~ ^[0-9]+$ && "$ap_child" =~ ^[0-9]+$ && "$ap_child" != "$ap_parent" ]] || { printf '%s' 'APPCONTAINER_PROBE_FAILURE:bash-fork:CHILD_IDENTITY' >&2; exit 92; }; set -o pipefail && printf '%s\\n' 'APPCONTAINER_PIPE_PROBE' | (read -r ap_line && [[ "$ap_line" == APPCONTAINER_PIPE_PROBE && "$BASHPID" != "$ap_parent" ]]) || { printf '%s' 'APPCONTAINER_PROBE_FAILURE:bash-pipe:CHECK' >&2; exit 93; }; node -e "eval(Buffer.from('${encoded}','base64').toString())"`
- Note: Runs code it decodes (base64, hex, character codes, reversed text or a compressed blob), which hides what runs from a reader
- Line 77 on GitHub
- const policy = { schemaVersion: 1, provider: 'claude', nestedDispatch: false, commandBoundary: true, externalWrites: false, targetPath: target, scratchPath: scratch,
- readableRoots: [target, scratch], writableRoots: [target, scratch], readOnly: false }
- phase = 'command-launch'
- const result = await runWindowsAppContainerCommand(policy, { command, cwd: target, timeoutMs: 15000 }, { controlRoot })
- phase = 'command-result'
- launcherSessionId = result.launcherSessionId; nativeExitCode = result.exitCode; probeFailure = {
- stdout: result.stdout.slice(0, 1024), stderr: result.stderr.slice(0, 1024),
- timedOut: result.timedOut === true, cancelled: result.cancelled === true, truncated: result.truncated === true,
- durationMs: Number.isSafeInteger(result.durationMs) ? result.durationMs : null,
- }
- try { probeFailure.gitGuard = fs.readFileSync(path.join(target, '.git', 'guard'), 'utf8') === 'controller git' ? 'UNCHANGED' : 'CHANGED' } catch { probeFailure.gitGuard = 'UNREADABLE' }
- if (result.workerIdentity !== workerIdentity) throw new Error('WORKER_TUPLE_CHANGED')
- if (result.status !== 'completed' || result.stdout !== 'APPCONTAINER_PROBE_PASS' || result.stderr || fs.readFileSync(path.join(target, '.git', 'guard'), 'utf8') !== 'controller git') throw new Error('NATIVE_PROBE_FAILED')
- phase = 'original-recovery'
- // runTupleCommand returns only after owned drain and validated ACL recovery.
- // This exercises the private TEMP fixture's volume, not arbitrary projects.
- if (result.resourceRecovery?.deletedEntries !== 1) throw new Error('ORIGINAL_RECOVERY_UNPROVEN')
- let originalAbsent = false
- try { fs.lstatSync(deletedOriginal) } catch (error) { if (error.code === 'ENOENT') originalAbsent = true; else throw error }
- if (!originalAbsent) throw new Error('ORIGINAL_DELETE_UNPROVEN')
- for (const root of [target, scratch]) {
- let createdAbsent = false
- try { fs.lstatSync(path.join(root, 'delete-created')) } catch (error) { if (error.code === 'ENOENT') createdAbsent = true; else throw error }
- if (!createdAbsent) throw new Error('CREATED_DELETE_UNPROVEN')
- }
- phase = 'loopback-denial'
- for (const endpoint of endpoints) { if (endpoint.state.accepted !== 0) throw new Error('SANDBOX_CONNECTED'); await control(endpoint); if (endpoint.state.accepted !== 1) throw new Error('CONTROL_ACCEPT') }
- const supported = Object.freeze({ supported: true, backend: 'windows-appcontainer', runtimeSha256: key, workerIdentity, launcherSessionId: result.launcherSessionId,
- resourceRecovery: Object.freeze({ ...result.resourceRecovery }), resourceRecoveryScope: 'pre-existing original deleted and recovered on private TEMP fixture volume',
- networkProof: 'zero sandbox accepts between successful same-listener IPv4/IPv6 controller checks; bounded explicit socket denial', processCleanup: 'owned-job-drained' })
- return supported
- } catch (error) {
- primaryError = error
- preserve = error.cleanupConfirmed === false || error.code === 'APPCONTAINER_CLEANUP_UNCONFIRMED' || Boolean(error.recovery && !error.recoveryResolved)
- return { supported: false, backend: 'windows-appcontainer', code: error.code || 'COMMAND_SANDBOX_UNSUPPORTED', diagnostic: failureDiagnostic(error, phase), launcherSessionId, nativeExitCode, probeFailure, ...(preserve ? { recoveryRoot: base, ...(typeof error.retainedStagingRoot === 'string' ? { retainedStagingRoot: error.retainedStagingRoot } : {}) } : {}) }
- } finally {
- let cleanupFailure
- for (const endpoint of endpoints) { try { endpoint.server.close() } catch (error) { cleanupFailure ||= error } }
- if (!preserve && !cleanupFailure) { try { fs.rmSync(base, { recursive: true, force: true }) } catch (error) { cleanupFailure ||= error } }
- if (cleanupFailure) {
- const error = primaryError || cleanupFailure
- error.cleanupConfirmed = false
- error.recoveryRoot = base
- error.cleanupCode = String(cleanupFailure.code || 'cleanup-failed').slice(0, 64)
- throw error
- }
- }
- }
- module.exports = { probeWindowsAppContainer, failureDiagnostic, canaryKey: runtimeKey, runWindowsAppContainerCanary }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.