Skip to content
Back to search

autoprompt-skill

SkillWorks with Claude CodeGitHub

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.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/spielewoy-autoprompt-skill/badge.svg)](/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

i

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)

  1. <p align="center">
  2. <img src="assets/banner.svg" alt="Autoprompt Skill: pink clouds and flying geese" width="1000"/>
  3. </p>
  4. <p align="center">Autoprompt is a coding-agent workflow that cuts failures by 45% by reviewing, fixing, and rechecking its work.</p>
  5. <p align="center">
  6. <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>
  7. <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>
  8. <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>
  9. <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-965477?style=flat-square&labelColor=302335" alt="License MIT"/></a>
  10. </p>
  11. <p align="center">
  12. <a href="README.md"><b>English</b></a> |
  13. <a href="docs/translations/zh.md">中文</a> |
  14. <a href="docs/translations/ko.md">한국어</a> |
  15. <a href="docs/translations/es.md">Español</a> |
  16. <a href="docs/translations/ar.md">العربية</a>
  17. </p>
  18. ## Contents
  19. [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)
  20. ## Install
  21. Use the CLI below, or download an installer from [GitHub Releases](https://github.com/Spielewoy/autoprompt-skill/releases/latest).
  22. ### 1. Install the CLI
  23. ```bash
  24. npm install -g https://github.com/Spielewoy/autoprompt-skill/releases/download/v2.1.0/autoprompt-skill-2.1.0.tgz
  25. ```
  26. ### 2. Launch the installer
  27. ```bash
  28. autoprompt
  29. ```
  30. ### 3. Install
  31. Choose your coding agent, confirm its path, and install. `N` means enter another path.
  32. For another CLI or IDE, choose `Custom coding agent` and use the [compatibility guide](docs/guides/custom-agent-compatibility.md).
  33. <details>
  34. <summary><strong>Install from source</strong></summary>
  35. ```bash
  36. git clone https://github.com/Spielewoy/autoprompt-skill
  37. cd autoprompt-skill
  38. npm install -g .
  39. autoprompt
  40. ```
  41. </details>
  42. ### Requirements
  43. - [Node.js 20+](https://nodejs.org/en/download)
  44. - [Python 3.11+](https://www.python.org/downloads/) available as `python3` or `python`, with [PyYAML](https://pypi.org/project/PyYAML/)
  45. - [Bash 4.3+](https://www.gnu.org/software/bash/) on macOS or Linux
  46. - 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
  47. - 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.
  48. - [Git](https://git-scm.com/downloads) only for the GitHub checkout method
  49. ### Support
  50. | Status | Coding agent | Tested version | Key |
  51. |---|---|---|---|
  52. | Working | [Claude Code](https://code.claude.com/docs/en/setup) | 2.1.263 | `claude` |
  53. | Working | [Codex](https://github.com/openai/codex) | 0.148.0 | `codex` |
  54. | Working | [OpenCode](https://opencode.ai/docs/agents) | 1.18.29 | `opencode` |
  55. | Working | [Kilo Code](https://kilo.ai/docs/customize/custom-subagents) | 7.5.15 | `kilo` |
  56. | Working | [VS Code](https://code.visualstudio.com/docs/agents/subagents) | 1.136.1 | `vscode` |
  57. | Working | [Prime Agent](https://github.com/PrimeIntellect-ai/prime-agent) | 0.7.2 | `prime` |
  58. | Working | [Oh My Pi](https://omp.sh/) | 18.1.14 | `omp` |
  59. | Working | [DeepSeek Harness](https://deepseek.com/harness/en/) | 0.1.2-rc.1 | `deepseek` |
  60. | Working | [Reasonix](https://reasonix.io/docs/) | 1.30.0 | `reasonix` |
  61. | Working | [Hermes Agent](https://github.com/NousResearch/hermes-agent) | 0.21.1 | `hermes` |
  62. | Working | [Grok Build](https://docs.x.ai/build/overview) | 1.0.13 | `grok` |
  63. These versions passed Linux runs. Model and platform availability varies by provider.
  64. Native Windows execution uses AppContainer isolation and Windows Job process
  65. ownership, with Node 20 or 24 on x64 or ARM64. Native macOS execution uses the
  66. system sandbox and owned-process controls. Windows command tools include the
  67. bundled Bash/MSYS/Node runtime; native paths do not require WSL or a VM.
  68. The ten non-Codex providers can run their local capability checks on Linux,
  69. Windows, and macOS. All eleven checks must pass for the installed runtime before
  70. a mission starts; missing, failed, or skipped checks block activation. Codex uses
  71. its separate canonical validation route. On Windows, that route creates a fresh
  72. offline account and an own-SID Windows Filtering Platform policy for each
  73. activation. Their activation-bound lease is retained for resume. Permanent
  74. cleanup removes the account and policy only after owned Jobs drain; uncertain
  75. verification or cleanup fails closed and retains recovery records. The Linux
  76. version table above does not
  77. certify every provider/platform combination. Installer success and
  78. `doctor --strict` are prerequisite checks; `local-canary-required` means native
  79. validation is still pending. See [configured Linux runtimes](docs/lima-runtime.md)
  80. when a native path is unavailable.
  81. See [support and audit notes](docs/faq/which-coding-agents-are-supported.md).
  82. ### Check, update, or remove an installation
  83. - Check every detected installation: `autoprompt doctor --strict`
  84. - Check one provider: `autoprompt doctor PROVIDER --strict`
  85. - Update or repair: `autoprompt`, then choose an installed provider
  86. - Uninstall interactively: `autoprompt uninstall`
  87. - Uninstall one provider: `autoprompt uninstall PROVIDER`
  88. - Show every command: `autoprompt help`
  89. Replace `PROVIDER` with a key from the support table, such as `claude`, `codex`, or `prime`.
  90. ## Benchmarks
  91. These are **version 1 benchmarks**. Version 2 benchmarks will follow.
  92. <p align="center">
  93. <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."/>
  94. </p>
  95. <details>
  96. <summary><strong>Measured OpenCode comparison</strong></summary>
  97. <p align="center">
  98. <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."/>
  99. </p>
  100. | Track | Solved | Score | Failed |
  101. |---|---:|---:|---:|
  102. | OpenCode | 60/89 | 67.42% | 29 |
  103. | **OpenCode + Autoprompt** | **73/89** | **82.02%** | **16** |
  104. | **Change** | **+13 solves** | **+14.61 points** | **45% fewer** |
  105. </details>
  106. 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).
  107. <details>
  108. <summary><strong>Expected trade-off:</strong> about 3x the time and 2x the tokens.</summary>
  109. 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.
  110. </details>
  111. ## Anatomy of an invocation
  112. ```bash
  113. autoprompt activate PROVIDER --target /absolute/project -- "<goal>"
  114. ```
  115. | Part | What it does |
  116. |---|---|
  117. | `PROVIDER` | A key from the support table, such as `claude`, `codex`, or `grok`. |
  118. | `--target` | The project to work on. Omit it to use the current directory. |
  119. | `--` | Separates launcher options from the request. |
  120. | `<goal>` | The result you want, constraints, and how to check success. |
  121. | `path=` | Optional `auto`, `direct`, `light`, or `roadmap`, before the quoted goal. See [work paths](docs/faq/work-paths.md). |
  122. ```bash
  123. autoprompt activate codex -- path=light "add retries and test the edge cases"
  124. ```
  125. ## Run controls
  126. The same controls apply to all eleven providers. [Custom model setup](docs/faq/how-to-add-custom-models.md)
  127. | Control | What it does |
  128. |---|---|
  129. | `--concurrency tokensaver` | Runs at most six subagents at once. |
  130. | `--concurrency wide` | Starts ready, independent work up to the host limit. |
  131. | `--concurrency custom --max-subs N` | Sets your own concurrency limit. |
  132. | `configure PROVIDER --agents off` | Uses the provider's configured model. |
  133. | `configure PROVIDER --agents MODEL` | Selects one model. Add `--effort LEVEL` where supported. |
  134. | `configure PROVIDER --agents auto --model-map FILE` | Chooses from a measured model registry. A comma-separated model list also requires `--model-map`. |
  135. Pass concurrency controls after `--`, before the quoted goal:
  136. ```bash
  137. autoprompt activate codex -- --concurrency custom --max-subs 4 "add retries and tests"
  138. autoprompt configure claude --agents provider/model --effort low
  139. ```
  140. ## How it works
  141. <p align="center">
  142. <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>
  143. </p>
  144. ## The agents
  145. <p align="center">
  146. <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>
  147. </p>
  148. ## Examples
  149. | Goal | Prompt |
  150. |---|---|
  151. | Fix | `autoprompt activate claude -- "fix the registration race and add a regression test"` |
  152. | Build | `autoprompt activate codex -- --concurrency wide "build the booking flow from API to checkout"` |
  153. | Research | `autoprompt activate hermes -- "compare job queues against this codebase and recommend one"` |
  154. | Limit parallel work | `autoprompt activate grok -- --concurrency custom --max-subs 4 "migrate every model"` |
  155. Run these commands from your project, or supply `--target /absolute/project` before `--`.
  156. ## FAQ
  157. <details>
  158. <summary><strong>Does Autoprompt mean I literally do not have to prompt?</strong></summary>
  159. 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)
  160. </details>
  161. <details>
  162. <summary><strong>How autonomous is Autoprompt?</strong></summary>
  163. 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)
  164. </details>
  165. <details>
  166. <summary><strong>What are the layers for?</strong></summary>
  167. 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)
  168. </details>
  169. <details>
  170. <summary><strong>What are the paths?</strong></summary>
  171. `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)
  172. </details>
  173. <details>
  174. <summary><strong>What do concurrency, models, and paths control?</strong></summary>
  175. `--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)
  176. </details>
  177. <details>
  178. <summary><strong>Why does Autoprompt not start in the background?</strong></summary>
  179. Because it changes cost, time, and workflow. Start it explicitly with `autoprompt activate PROVIDER -- "<goal>"`.
  180. </details>
  181. ## License
  182. [MIT](LICENSE). Copyright 2026 [Spielewoy](https://github.com/Spielewoy).
  183. 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).
  184. ### Contributors
  185. [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
  1. <#
  2. .SYNOPSIS
  3. autoprompt supervisor (Windows PowerShell 5.1 port of supervisor.sh) --
  4. external auto-relaunch for a one-sitting unattended run.
  5. .DESCRIPTION
  6. This is a STANDALONE OS PROCESS, NOT a Claude Code hook. It touches no
  7. settings.json, registers no hook, and is launched by the operator. It honors
  8. the global no-hooks rule.
  9. It relaunches the autoprompt CLI with RESUME on any unexpected exit, loops
  10. until the JANITOR has written the DONE-sentinel (autoprompt/DONE-<nonce>),
  11. and has a crash-loop/poison-restart guard that distinguishes:
  12. - a FINISHED run (sentinel present) -> clean halt (exit 0)
  13. - a HEALTHY-LONG run (frontier advances) -> keep relaunching, no escalation
  14. - a TRULY-STUCK run (no frontier progress) -> escalate, stop relaunching (exit 1)
  15. Behavior-faithful to agents/claude/workflow/supervisor.sh: identical sentinel glob
  16. (autoprompt/DONE-*), identical "done": true check, identical env var names
  17. (AUTOPROMPT_RESUME / AUTOPROMPT_UNATTENDED), identical --launcher selection,
  18. identical backoff schedule and poison guard.
  19. .PARAMETER Launcher
  20. apidemo | codexdemo (or any launcher command on PATH). Defaults to
  21. $env:AUTOPROMPT_LAUNCHER. Exec'd as a bare command name.
  22. .PARAMETER Cmd
  23. Verbatim launch command (e.g. "claude --dangerously-skip-permissions -p"),
  24. word-split with the mission appended. Overrides -Launcher. Defaults to
  25. $env:AUTOPROMPT_LAUNCH_CMD. A fresh user with no apidemo/codexdemo alias
  26. uses --cmd with their real CLI.
  27. .PARAMETER Mission
  28. The mission text passed through to the launch command.
  29. .EXAMPLE
  30. powershell -File supervisor.ps1 --launcher apidemo "<mission>"
  31. .EXAMPLE
  32. powershell -File supervisor.ps1 --cmd "claude --dangerously-skip-permissions -p" "<mission>"
  33. .EXAMPLE
  34. powershell -File supervisor.ps1 --agents "auto:strong,cheap" --model-registry "$HOME\.claude\autoprompt-models.json" --cmd "claude -p" "<mission>"
  35. .NOTES
  36. Env (all optional), mirroring supervisor.sh:
  37. AUTOPROMPT_LAUNCH_CMD verbatim launch command (overrides --launcher)
  38. AUTOPROMPT_LAUNCHER default launcher label if --launcher is omitted
  39. AUTOPROMPT_AGENTS off | auto | <list> | auto:<list> (default off)
  40. AUTOPROMPT_MODEL_REGISTRY optional registry path; defaults to ~/.claude/autoprompt-models.json for auto modes
  41. LEDGER_DIR default "autoprompt"
  42. SENTINEL explicit sentinel glob (default <LEDGER_DIR>/DONE-*).
  43. Passed to Get-ChildItem -Path as ONE pattern (no word-
  44. split), so a single dir-wildcard like 'autoprompt/*/DONE-*'
  45. works but a space-separated MULTI-pattern (a .sh-only escape
  46. hatch) does not -- use one wildcard on PowerShell. When UNSET
  47. (the default -- every real run) the glob is <LEDGER_DIR>/DONE-*
  48. as one quoted path, so a LEDGER_DIR containing spaces (a
  49. Windows path) still matches its own DONE-* sentinel.
  50. MAX_RESTARTS rapid restarts allowed in WINDOW without progress (default 5)
  51. WINDOW rolling window seconds for the poison guard (default 600)
  52. RETRY_BASE base backoff seconds between relaunches (default 5; 0 in tests)
  53. RETRY_CAP max backoff seconds (default 300)
  54. AUTOPROMPT_KEEP_MODEL_PIN when "1", SKIP neutralizing CLAUDE_CODE_SUBAGENT_MODEL
  55. for the child CLI. By DEFAULT (unset) the supervisor strips
  56. CLAUDE_CODE_SUBAGENT_MODEL from the CHILD ONLY so the skill's
  57. `model: inherit` contract resolves to the real session/--model
  58. selection instead of the operator's force-pin. Set to 1 to
  59. preserve the operator's pin and let it reach the child as before.
  60. AUTOPROMPT_MODE tokensaver | wide | billionaire | custom (default tokensaver).
  61. WIDE and BILLIONAIRE share wide semantics. CUSTOM requires a
  62. positive numeric AUTOPROMPT_MAX_CONCURRENT value, floors it
  63. to a whole-agent ceiling, and passes both values through.
  64. The 5-level topology (L0 conductor -> L1 coordinators -> L2 managers -> L3
  65. executors -> L4 leaves) lives in the harness; rule 68 (L1 never executes) and
  66. rule 67 (single-block spawns) are enforced there. This OS-level supervisor only
  67. relaunches the L0 entry process and passes the mode through; it spawns no agents.
  68. Test hooks (only honored with --dry-run):
  69. FAKE_EXITS space-separated exit codes the fake launcher returns in turn
  70. FAKE_SENTINEL_AFTER write the sentinel before the launch with this 1-based index
  71. FAKE_POISON 1 => fake never advances the frontier and always exits non-zero
  72. #>
  73. Set-StrictMode -Version Latest
  74. $ErrorActionPreference = 'Stop'
  75. function Get-EnvOrDefault {
  76. param([string]$Name, $Default)
  77. $value = [Environment]::GetEnvironmentVariable($Name)
  78. if ([string]::IsNullOrEmpty($value)) { return $Default }
  79. return $value
  80. }
  81. function Get-RequiredArgumentValue {
  82. param([string]$Flag, [int]$Index, [string[]]$Arguments)
  83. if ($Index -lt $Arguments.Count) { return $Arguments[$Index] }
  84. [Console]::Error.WriteLine("supervisor: $Flag requires a value")
  85. return $null
  86. }
  87. function ConvertTo-NativeArgument {
  88. param([AllowEmptyString()][string]$Value)
  89. if ($Value.Length -gt 0 -and $Value -notmatch '[\s"]') { return $Value }
  90. $builder = New-Object Text.StringBuilder
  91. $backslash = [char]92
  92. $quote = [char]34
  93. $backslashCount = 0
  94. [void]$builder.Append($quote)
  95. foreach ($character in $Value.ToCharArray()) {
  96. if ($character -eq $backslash) {
  97. $backslashCount += 1
  98. continue
  99. }
  100. if ($character -eq $quote) {
  101. for ($index = 0; $index -lt (($backslashCount * 2) + 1); $index += 1) {
  102. [void]$builder.Append($backslash)
  103. }
  104. [void]$builder.Append($quote)
  105. $backslashCount = 0
  106. continue
  107. }
  108. for ($index = 0; $index -lt $backslashCount; $index += 1) {
  109. [void]$builder.Append($backslash)
  110. }
  111. $backslashCount = 0
  112. [void]$builder.Append($character)
  113. }
  114. for ($index = 0; $index -lt ($backslashCount * 2); $index += 1) {
  115. [void]$builder.Append($backslash)
  116. }
  117. [void]$builder.Append($quote)
  118. return $builder.ToString()
  119. }
  120. function Join-NativeArguments {
  121. param([string[]]$Arguments)
  122. return (($Arguments | ForEach-Object { ConvertTo-NativeArgument -Value $_ }) -join ' ')
  123. }
  124. function Get-AgentDefinitionsHash {
  125. param([string]$ModelCastingPath, [string]$AgentsDirectory)
  126. if (-not (Test-Path -LiteralPath $ModelCastingPath -PathType Leaf) -or
  127. -not (Test-Path -LiteralPath $AgentsDirectory -PathType Container)) {
  128. return 'unknown'
  129. }
  130. $files = @($ModelCastingPath) + @(
  131. Get-ChildItem -LiteralPath $AgentsDirectory -File -Filter 'ap-*.md' |
  132. Sort-Object Name |
  133. ForEach-Object { $_.FullName }
  134. )
  135. $sha = [Security.Cryptography.SHA256]::Create()
  136. try {
  137. foreach ($file in $files) {
  138. $label = [IO.Path]::GetFileName($file)
  139. $labelBytes = [Text.Encoding]::UTF8.GetBytes($label)
  140. $lengthBytes = [Text.Encoding]::UTF8.GetBytes(([string]$labelBytes.Length) + ':')
  141. $null = $sha.TransformBlock($lengthBytes, 0, $lengthBytes.Length, $lengthBytes, 0)
  142. $null = $sha.TransformBlock($labelBytes, 0, $labelBytes.Length, $labelBytes, 0)
  143. $content = [IO.File]::ReadAllBytes($file)
  144. $contentLength = [Text.Encoding]::UTF8.GetBytes(([string]$content.Length) + ':')
  145. $null = $sha.TransformBlock($contentLength, 0, $contentLength.Length, $contentLength, 0)
  146. $null = $sha.TransformBlock($content, 0, $content.Length, $content, 0)
  147. }
  148. $null = $sha.TransformFinalBlock([byte[]]@(), 0, 0)
  149. return 'sha256:' + ([BitConverter]::ToString($sha.Hash) -replace '-', '').ToLowerInvariant()
  150. } finally {
  151. $sha.Dispose()
  152. }
  153. }
  154. function Invoke-Supervisor {
  155. param([string[]]$Argv)
  156. function Test-CapabilityAttestation {
  157. param([string]$Raw, [string[]]$Expected)
  158. try {
  159. $attestation = $Raw | ConvertFrom-Json -ErrorAction Stop
  160. } catch {
  161. return $false
  162. }
  163. $bindings = @(
  164. 'provider', 'cliVersion', 'permissionProfile', 'agentSelector',
  165. 'agentDefinitionsHash', 'castingHash', 'effortStatus', 'effortSource'
  166. )
  167. for ($index = 0; $index -lt $bindings.Count; $index += 1) {
  168. $property = $attestation.PSObject.Properties[$bindings[$index]]
  169. if ($null -eq $property -or
  170. $property.Value -isnot [string] -or
  171. $property.Value -cne $Expected[$index]) {
  172. return $false
  173. }
  174. }
  175. $schemaVersion = $attestation.PSObject.Properties['schemaVersion']
  176. $proofKind = $attestation.PSObject.Properties['proofKind']
  177. $proofHash = $attestation.PSObject.Properties['proofHash']
  178. $proofBytes = $attestation.PSObject.Properties['proofBytes']
  179. if ($null -eq $schemaVersion -or
  180. $schemaVersion.Value -isnot [int] -or
  181. $schemaVersion.Value -ne 4 -or
  182. $null -eq $proofKind -or
  183. $proofKind.Value -isnot [string] -or
  184. $proofKind.Value -cne 'disposable-scratch' -or
  185. $null -eq $proofHash -or
  186. $proofHash.Value -isnot [string] -or
  187. $proofHash.Value -cnotmatch '^sha256:[a-f0-9]{64}$') {
  188. return $false
  189. }
  190. # The proof hash must recompute from the inspectable scratch bytes the
  191. # attestation carries; a bare well-formed hash string proves nothing.
  192. if ($null -eq $proofBytes -or
  193. $proofBytes.Value -isnot [string] -or
  194. $proofBytes.Value.Length -eq 0 -or
  195. $proofBytes.Value.Length -gt 4096) {
  196. return $false
  197. }
  198. $sha = [Security.Cryptography.SHA256]::Create()
  199. try {
  200. $recomputed = 'sha256:' + ([BitConverter]::ToString(
  201. $sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($proofBytes.Value))
  202. ) -replace '-', '').ToLowerInvariant()
  203. } finally {
  204. $sha.Dispose()
  205. }
  206. if ($recomputed -cne $proofHash.Value) {
  207. return $false
  208. }
  209. foreach ($name in @('run', 'read', 'write')) {
  210. $property = $attestation.PSObject.Properties[$name]
  211. if ($null -eq $property -or
  212. $property.Value -isnot [bool] -or
  213. $property.Value -ne $true) {
  214. return $false
  215. }
  216. }
  217. return $true
  218. }
  219. $launcher = Get-EnvOrDefault 'AUTOPROMPT_LAUNCHER' ''
  220. $launchCmd = Get-EnvOrDefault 'AUTOPROMPT_LAUNCH_CMD' ''
  221. $agentsSelector = Get-EnvOrDefault 'AUTOPROMPT_AGENTS' 'off'
  222. $modelRegistry = Get-EnvOrDefault 'AUTOPROMPT_MODEL_REGISTRY' ''
  223. $providerCapability = Get-EnvOrDefault 'AUTOPROMPT_PROVIDER_CAPABILITY' ''
  224. $ledgerDir = Get-EnvOrDefault 'LEDGER_DIR' 'autoprompt'
  225. $maxRestarts = [int](Get-EnvOrDefault 'MAX_RESTARTS' 5)
  226. $window = [int](Get-EnvOrDefault 'WINDOW' 600)
  227. $retryBase = [int](Get-EnvOrDefault 'RETRY_BASE' 5)
  228. $retryCap = [int](Get-EnvOrDefault 'RETRY_CAP' 300)
  229. # P1 (PLAN-idle-watchdog) - heartbeat env defaults, IDENTICAL to supervisor.sh.
  230. # IDLE_TIMEOUT defaults to 1800s (30 min) so a long-but-progressing build/test does
  231. # NOT trip the heartbeat (the frontier count grows on ANY artifact write and resets
  232. # the timer); operators with long atomic steps raise AUTOPROMPT_IDLE_TIMEOUT.
  233. $idleTimeout = [int](Get-EnvOrDefault 'AUTOPROMPT_IDLE_TIMEOUT' 1800)
  234. $heartbeatInterval = [int](Get-EnvOrDefault 'AUTOPROMPT_HEARTBEAT_INTERVAL' 60)
  235. # PLAN-auto-compact-threshold: proactive, SUPERVISOR-FIRED compaction below the
  236. # harness ~400k ceiling. IDENTICAL semantics + knobs to supervisor.sh. The supervisor
  237. # observes the parent's context size from OUTSIDE (parent session transcript;
  238. # watermark/ledger-byte fallbacks) and, on crossing $compactAt, writes COMPACT-REQUEST,
  239. # then on grace timeout fires the kill->RESUME (the parent cannot /compact itself).
  240. $compactAt = Get-EnvOrDefault 'AUTOPROMPT_COMPACT_AT' '200000'
  241. $parsedCompactAt = 0
  242. if (-not [int]::TryParse([string]$compactAt, [ref]$parsedCompactAt) -or $parsedCompactAt -le 0 -or $parsedCompactAt -ge 10000000) {
  243. $parsedCompactAt = 200000 # absurd/non-numeric -> default (never disables the guard, never fires every tick)
  244. }
  245. $compactAt = $parsedCompactAt
  246. $bytesPerToken = [int](Get-EnvOrDefault 'AUTOPROMPT_BYTES_PER_TOKEN' 4)
  247. if ($bytesPerToken -le 0) { $bytesPerToken = 4 }
  248. $compactCooldown = [int](Get-EnvOrDefault 'AUTOPROMPT_COMPACT_COOLDOWN' 120)
  249. $compactGrace = [int](Get-EnvOrDefault 'AUTOPROMPT_COMPACT_GRACE' 180)
  250. $externalCompactDelta = [int](Get-EnvOrDefault 'AUTOPROMPT_EXTERNAL_COMPACT_DELTA' 50000)
  251. # Execution mode selects the 5-level topology's wave cap. Unknown modes retain
  252. # the safe tokensaver fallback. CUSTOM is an explicit request for a caller-supplied
  253. # ceiling, so a missing or invalid value fails closed.
  254. $autopromptMode = Get-EnvOrDefault 'AUTOPROMPT_MODE' 'tokensaver'
  255. switch -CaseSensitive ($autopromptMode) {
  256. 'tokensaver' { $fanout = 'up to 6 live per wave'; $l3Tracks = 'parallel' }
  257. 'wide' { $fanout = 'wide up to the runtime ceiling'; $l3Tracks = 'parallel' }
  258. 'billionaire' { $fanout = 'wide up to the runtime ceiling'; $l3Tracks = 'parallel' }
  259. 'custom' {
  260. $rawCustomMax = Get-EnvOrDefault 'AUTOPROMPT_MAX_CONCURRENT' ''
  261. [double]$parsedCustomMax = 0
  262. $validCustomMax = [double]::TryParse(
  263. [string]$rawCustomMax,
  264. [Globalization.NumberStyles]::Float,
  265. [Globalization.CultureInfo]::InvariantCulture,
  266. [ref]$parsedCustomMax
  267. )
  268. if (-not $validCustomMax -or [double]::IsNaN($parsedCustomMax) -or
  269. [double]::IsInfinity($parsedCustomMax) -or $parsedCustomMax -lt 1) {
  270. [Console]::Error.WriteLine('supervisor: custom mode requires a positive numeric AUTOPROMPT_MAX_CONCURRENT')
  271. return 2
  272. }
  273. $customMax = [Math]::Floor($parsedCustomMax)
  274. $env:AUTOPROMPT_MAX_CONCURRENT = [string]$customMax
  275. $fanout = "up to $customMax live per wave (AUTOPROMPT_MAX_CONCURRENT)"
  276. $l3Tracks = 'parallel'
  277. }
  278. default { $autopromptMode = 'tokensaver'; $fanout = 'up to 6 live per wave'; $l3Tracks = 'parallel' }
  279. }
  280. # Scope wall-clock budget, with semantics matching supervisor.sh. A slow scope can
  281. # keep producing ROADMAP.md and roadmap-scout-*.md checkpoints, resetting the idle
  282. # clock while never converging. This budget is anchored to scope entry, not frontier
  283. # growth. Each knob is validated with [int]::TryParse (like $compactAt): an absurd or
  284. # non-numeric value falls back to the default (never disables the guard).
  285. $scopeSoftSec = 60
  286. if (-not [int]::TryParse([string](Get-EnvOrDefault 'AUTOPROMPT_SCOPE_SOFT_SEC' '60'), [ref]$scopeSoftSec) -or $scopeSoftSec -le 0) { $scopeSoftSec = 60 }
  287. $scopeHardSec = 300
  288. if (-not [int]::TryParse([string](Get-EnvOrDefault 'AUTOPROMPT_SCOPE_HARD_SEC' '300'), [ref]$scopeHardSec) -or $scopeHardSec -le 0) { $scopeHardSec = 300 }
  289. $scopeGraceSec = 60
  290. if (-not [int]::TryParse([string](Get-EnvOrDefault 'AUTOPROMPT_SCOPE_GRACE' '60'), [ref]$scopeGraceSec) -or $scopeGraceSec -lt 0) { $scopeGraceSec = 60 }
  291. $maxScopeResets = 1
  292. if (-not [int]::TryParse([string](Get-EnvOrDefault 'AUTOPROMPT_MAX_SCOPE_RESETS' '1'), [ref]$maxScopeResets) -or $maxScopeResets -lt 0) { $maxScopeResets = 1 }
  293. $dryRun = $false
  294. $mission = ''
  295. # EDIT 23a: the supervisor sits in .../workflow/ next to autoprompt-ledger-check.js,
  296. # so derive that resolver's absolute path from its own location and export it to the
  297. # child (gate.js EDIT 4a reads AUTOPROMPT_LEDGER_CHECK; the SCRIBE/JANITOR briefs
  298. # interpolate it). An operator override wins; else the script-dir sibling is used.
  299. # $PSCommandPath is the .ps1's own full path (this script), the analog of the .sh $0.
  300. $scriptDir = Split-Path -Parent $PSCommandPath
  301. $ledgerCheckPath = if ($env:AUTOPROMPT_LEDGER_CHECK) { $env:AUTOPROMPT_LEDGER_CHECK } else { Join-Path $scriptDir 'autoprompt-ledger-check.js' }
  302. $modelCastingPath = if ($env:AUTOPROMPT_MODEL_CASTING) { $env:AUTOPROMPT_MODEL_CASTING } else { Join-Path $scriptDir 'model-casting.js' }
  303. $agentDefinitionsPath = if ($env:AUTOPROMPT_AGENT_DEFINITIONS_DIR) { $env:AUTOPROMPT_AGENT_DEFINITIONS_DIR } else { Join-Path (Split-Path -Parent $scriptDir) 'agents' }
  304. $agentDefinitionsCli = if ($env:AUTOPROMPT_AGENT_DEFINITIONS_CLI) { $env:AUTOPROMPT_AGENT_DEFINITIONS_CLI } else { Join-Path $scriptDir 'agent-definitions-cli.js' }
  305. # F-SPEED steer-2 B3: the phase-budget verdict CLI sits next to the ledger-check.
  306. # An operator override wins; the Test-Path guard at the call site fail-opens if
  307. # node/module are absent (same posture as the ledger-check).
  308. $phaseBudgetPath = if ($env:AUTOPROMPT_PHASE_BUDGET) { $env:AUTOPROMPT_PHASE_BUDGET } else { Join-Path $scriptDir 'phase-budget.js' }
  309. # EDIT 23: per-conversation session token. The supervisor is the durable producer
  310. # across relaunches of one conversation: seed it (env > file > empty) before the
  311. # loop, re-export the held token to each child, and HARVEST the resolver-minted
  312. # marker token after each launch so a 2nd prompt rejoins the same session_NN.
  313. $sessionToken = Get-EnvOrDefault 'AUTOPROMPT_SESSION_TOKEN' ''
  314. $initialResume = (Get-EnvOrDefault 'AUTOPROMPT_RESUME' '').Trim().ToLowerInvariant() -in @('1', 'true', 'yes')
  315. $runNonce = Get-EnvOrDefault 'AUTOPROMPT_RUN_NONCE' ''
  316. $legacySentinel = (Get-EnvOrDefault 'AUTOPROMPT_LEGACY_SENTINEL' '0') -eq '1'
  317. # --- arg parse (mirrors the .sh case loop) ----------------------------------
  318. $i = 0
  319. while ($i -lt $Argv.Count) {
  320. $arg = $Argv[$i]
  321. switch -CaseSensitive ($arg) {
  322. '--launcher' {
  323. $value = Get-RequiredArgumentValue -Flag $arg -Index ($i + 1) -Arguments $Argv
  324. if ($null -eq $value) { return 2 }
  325. $launcher = $value; $i += 2; continue
  326. }
  327. '--cmd' {
  328. $value = Get-RequiredArgumentValue -Flag $arg -Index ($i + 1) -Arguments $Argv
  329. if ($null -eq $value) { return 2 }
  330. $launchCmd = $value; $i += 2; continue
  331. }
  332. '--agents' {
  333. $value = Get-RequiredArgumentValue -Flag $arg -Index ($i + 1) -Arguments $Argv
  334. if ($null -eq $value) { return 2 }
  335. $agentsSelector = $value; $i += 2; continue
  336. }
  337. '--model-registry' {
  338. $value = Get-RequiredArgumentValue -Flag $arg -Index ($i + 1) -Arguments $Argv
  339. if ($null -eq $value) { return 2 }
  340. $modelRegistry = $value; $i += 2; continue
  341. }
  342. '--provider-capability' {
  343. $value = Get-RequiredArgumentValue -Flag $arg -Index ($i + 1) -Arguments $Argv
  344. if ($null -eq $value) { return 2 }
  345. $providerCapability = $value; $i += 2; continue
  346. }
  347. '--dry-run' { $dryRun = $true; $i += 1; continue }
  348. '--ledger-dir' {
  349. $value = Get-RequiredArgumentValue -Flag $arg -Index ($i + 1) -Arguments $Argv
  350. if ($null -eq $value) { return 2 }
  351. $ledgerDir = $value; $i += 2; continue
  352. }
  353. '--' {
  354. # A trailing bare '--' with no following tokens yields an EMPTY
  355. # mission (matches supervisor.sh `shift; MISSION="$*"`). Only build
  356. # the slice when there is at least one token after '--', else the
  357. # range reverses (e.g. 2..1) and throws "index out of range".
  358. if (($i + 1) -lt $Argv.Count) {
  359. $mission = ($Argv[($i + 1)..($Argv.Count - 1)] -join ' ')
  360. } else {
  361. $mission = ''
  362. }
  363. $i = $Argv.Count; continue
  364. }
  365. default {
  366. if ($arg -like '-*') {
  367. [Console]::Error.WriteLine("supervisor: unknown flag $arg")
  368. return 2
  369. }
  370. $mission = $arg; $i += 1; continue
  371. }
  372. }
  373. }
  374. $missionBytes = [Text.Encoding]::UTF8.GetBytes($mission)
  375. $missionSha = [Security.Cryptography.SHA256]::Create()
  376. try {
  377. $scopeMissionBinding = 'sha256:' + ([BitConverter]::ToString($missionSha.ComputeHash($missionBytes)) -replace '-', '').ToLowerInvariant()
  378. } finally {
  379. $missionSha.Dispose()
  380. }
  381. if (-not $legacySentinel) {
  382. if ([string]::IsNullOrEmpty($runNonce)) {
  383. $nonceBytes = New-Object byte[] 16
  384. $generator = [Security.Cryptography.RandomNumberGenerator]::Create()
  385. try { $generator.GetBytes($nonceBytes) } finally { $generator.Dispose() }
  386. $runNonce = 'NONCE-' + ([BitConverter]::ToString($nonceBytes) -replace '-', '').ToLowerInvariant()
  387. } elseif ($runNonce -cnotmatch '^NONCE-[A-Za-z0-9_-]+$') {
  388. [Console]::Error.WriteLine('supervisor: AUTOPROMPT_RUN_NONCE is malformed')
  389. return 2
  390. }
  391. }
  392. $casting = $null
  393. $castingJson = ''
  394. $castingEnabled = $false
  395. $castingBaseUrl = ''
  396. $castingApiKeyEnv = ''
  397. $castingAuthToken = ''
  398. $capabilityProvider = 'claude-code'
  399. $capabilityCliVersion = 'unknown'
  400. $capabilityPermissionProfile = 'default'
  401. $capabilityAgentDefinitionsHash = 'unknown'
  402. $capabilityCastingHash = 'none'
  403. $capabilityEffortStatus = 'inherited-only'
  404. $capabilityEffortSource = 'session-inheritance'
  405. $suppliedCapabilityAttestation = Get-EnvOrDefault 'AUTOPROMPT_CAPABILITY_ATTESTATION' ''
  406. $capabilityAttestation = $null
  407. $selectorControl = $agentsSelector.Trim().ToLowerInvariant()
  408. if (-not [string]::IsNullOrEmpty($selectorControl) -and $selectorControl -ne 'off') {
  409. if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
  410. [Console]::Error.WriteLine('supervisor: model casting requires node on PATH')
  411. return 2
  412. }
  413. if (-not (Test-Path -LiteralPath $modelCastingPath -PathType Leaf)) {
  414. [Console]::Error.WriteLine("supervisor: model casting resolver is not readable: $modelCastingPath")
  415. return 2
  416. }
  417. $nodeArgs = @($modelCastingPath, '--selector', $agentsSelector)
  418. if (-not [string]::IsNullOrEmpty($modelRegistry)) {
  419. $nodeArgs += @('--registry', $modelRegistry)
  420. }
  421. if (-not [string]::IsNullOrEmpty($providerCapability)) {
  422. $nodeArgs += @('--provider-capability', $providerCapability)
  423. }
  424. $previousErrorActionPreference = $ErrorActionPreference
  425. try {
  426. $ErrorActionPreference = 'Continue'
  427. $castingOutput = @(& node @nodeArgs 2>&1)
  428. $castingExitCode = $LASTEXITCODE
  429. } finally {
  430. $ErrorActionPreference = $previousErrorActionPreference
  431. }
  432. $castingJson = ($castingOutput | ForEach-Object { [string]$_ }) -join [Environment]::NewLine
  433. if ($castingExitCode -ne 0) {
  434. [Console]::Error.WriteLine($castingJson.Trim())
  435. return 2
  436. }
  437. try {
  438. $casting = $castingJson | ConvertFrom-Json -ErrorAction Stop
  439. } catch {
  440. [Console]::Error.WriteLine("supervisor: model casting resolver returned invalid JSON: $($_.Exception.Message)")
  441. return 2
  442. }
  443. $castingEnabled = [bool]$casting.enabled
  444. if ($castingEnabled) {
  445. $keepModelPin = (Get-EnvOrDefault 'AUTOPROMPT_KEEP_MODEL_PIN' '0') -eq '1'
  446. if ($keepModelPin -and -not [string]::IsNullOrEmpty($env:CLAUDE_CODE_SUBAGENT_MODEL)) {
  447. [Console]::Error.WriteLine('supervisor: AUTOPROMPT_KEEP_MODEL_PIN=1 conflicts with model casting because CLAUDE_CODE_SUBAGENT_MODEL is set')
  448. return 2
  449. }
  450. $baseUrlProperty = $casting.endpoint.PSObject.Properties['baseUrl']
  451. if ($null -ne $baseUrlProperty) { $castingBaseUrl = [string]$baseUrlProperty.Value }
  452. $apiKeyProperty = $casting.endpoint.PSObject.Properties['apiKeyEnv']
  453. if ($null -ne $apiKeyProperty) { $castingApiKeyEnv = [string]$apiKeyProperty.Value }
  454. if (-not [string]::IsNullOrEmpty($castingApiKeyEnv)) {
  455. $castingAuthToken = [Environment]::GetEnvironmentVariable($castingApiKeyEnv)
  456. if ([string]::IsNullOrEmpty($castingAuthToken)) {
  457. [Console]::Error.WriteLine("supervisor: model casting credential environment variable is unset or empty: $castingApiKeyEnv")
  458. return 2
  459. }
  460. }
  461. }
  462. }
  463. if (Get-Command node -ErrorAction SilentlyContinue) {
  464. $configuredVersion = Get-EnvOrDefault 'AUTOPROMPT_CLI_VERSION' ''
  465. if (-not [string]::IsNullOrEmpty($configuredVersion)) {
  466. $capabilityCliVersion = $configuredVersion
  467. } else {
  468. $cliCommand = if (-not [string]::IsNullOrEmpty($launchCmd)) { ($launchCmd -split '\s+')[0] } else { $launcher }
  469. if (-not [string]::IsNullOrEmpty($cliCommand) -and (Get-Command $cliCommand -ErrorAction SilentlyContinue)) {
  470. try { $capabilityCliVersion = [string]((& $cliCommand --version 2>$null | Select-Object -First 1)) } catch {}
  471. }
  472. }
  473. if ($launchCmd -match '(?:^|\s)--dangerously-skip-permissions(?:\s|$)') {
  474. $capabilityPermissionProfile = 'bypass-permissions'
  475. } else {
  476. $capabilityPermissionProfile = Get-EnvOrDefault 'AUTOPROMPT_PERMISSION_PROFILE' 'default'
  477. }
  478. $capabilityAgentDefinitionsHash = Get-AgentDefinitionsHash `
  479. -ModelCastingPath $modelCastingPath `
  480. -AgentsDirectory $agentDefinitionsPath
  481. if ($castingEnabled) {
  482. $bytes = [Text.Encoding]::UTF8.GetBytes($castingJson)
  483. $sha = [Security.Cryptography.SHA256]::Create()
  484. try { $capabilityCastingHash = 'sha256:' + ([BitConverter]::ToString($sha.ComputeHash($bytes)) -replace '-', '').ToLowerInvariant() }
  485. finally { $sha.Dispose() }
  486. $capabilityEffortStatus = [string]$casting.effort.status
  487. $capabilityEffortSource = [string]$casting.effort.source
  488. }
  489. if ($capabilityCliVersion -ne 'unknown' -and
  490. $capabilityAgentDefinitionsHash -ne 'unknown' -and
  491. -not [string]::IsNullOrEmpty($suppliedCapabilityAttestation)) {
  492. $expectedBindings = @(
  493. $capabilityProvider,
  494. $capabilityCliVersion,
  495. $capabilityPermissionProfile,
  496. $agentsSelector,
  497. $capabilityAgentDefinitionsHash,
  498. $capabilityCastingHash,
  499. $capabilityEffortStatus,
  500. $capabilityEffortSource
  501. )
  502. if (Test-CapabilityAttestation `
  503. -Raw $suppliedCapabilityAttestation `
  504. -Expected $expectedBindings) {
  505. $capabilityAttestation = $suppliedCapabilityAttestation
  506. }
  507. }
  508. }
  509. $agentDefinitionsJson = ''
  510. if (-not $dryRun) {
  511. if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
  512. [Console]::Error.WriteLine('supervisor: activation-scoped agents require node on PATH')
  513. return 2
  514. }
  515. if (-not (Test-Path -LiteralPath $agentDefinitionsCli -PathType Leaf)) {
  516. [Console]::Error.WriteLine("supervisor: agent-definition converter is not readable: $agentDefinitionsCli")
  517. return 2
  518. }
  519. $previousErrorActionPreference = $ErrorActionPreference
  520. try {
  521. $ErrorActionPreference = 'Continue'
  522. $agentDefinitionsOutput = @(
  523. & node $agentDefinitionsCli $agentDefinitionsPath 2>&1
  524. )
  525. $agentDefinitionsExitCode = $LASTEXITCODE
  526. } finally {
  527. $ErrorActionPreference = $previousErrorActionPreference
  528. }
  529. if ($agentDefinitionsExitCode -ne 0) {
  530. [Console]::Error.WriteLine(($agentDefinitionsOutput | ForEach-Object { [string]$_ }) -join [Environment]::NewLine)
  531. return 2
  532. }
  533. $agentDefinitionsJson = $agentDefinitionsOutput -join [Environment]::NewLine
  534. if ([string]::IsNullOrEmpty($agentDefinitionsJson)) {
  535. [Console]::Error.WriteLine('supervisor: agent-definition converter returned an empty cast')
  536. return 2
  537. }
  538. }
  539. $sentinelGlob = Get-EnvOrDefault 'SENTINEL' (Join-Path $ledgerDir 'DONE-*')
  540. $escalateFile = Join-Path $ledgerDir 'SUPERVISOR-ESCALATE'
  541. $snapshotFile = Join-Path $ledgerDir '.sentinel-snapshot'
  542. # EDIT 23: durable session-token store under the ledger dir, surviving across
  543. # relaunches of one conversation. Seeded before the loop, harvested after launches.
  544. $sessionTokenFile = Join-Path $ledgerDir '.session-token'
  545. # PLAN-auto-compact-threshold path vars. Discovery is CWD-AGNOSTIC and slug-free: it
  546. # matches the supervisor's own run cwd against each transcript's embedded "cwd" after
  547. # normalization -- NO slug derivation, NO launcher edit. Identical to supervisor.sh.
  548. $runCwd = (Get-EnvOrDefault 'RUN_CWD' (Get-Location).Path)
  549. $parentTranscript = Get-EnvOrDefault 'AUTOPROMPT_PARENT_TRANSCRIPT' ''
  550. $watermarkFile = Join-Path $ledgerDir '.context-watermark'
  551. $compactRequestFile = Join-Path $ledgerDir 'COMPACT-REQUEST'
  552. $compactStateFile = Join-Path $ledgerDir '.compaction-state'
  553. # Scope-budget state survives relaunches. The start epoch does not reset on
  554. # frontier growth; the reset counter clears once build evidence lands.
  555. $scopePhaseStartFile = Join-Path $ledgerDir '.scope-phase-start'
  556. $scopeResetsFile = Join-Path $ledgerDir '.scope-forced-resets'
  557. if (-not (Test-Path -LiteralPath $ledgerDir)) {
  558. New-Item -ItemType Directory -Path $ledgerDir -Force | Out-Null
  559. }
  560. # Supervisor start time (captured BEFORE the first launch). It is no longer part
  561. # of the stale-sentinel guarantee (see below) -- it is kept only to name the
  562. # quarantine target (superseded-<epoch>-...). Get-Date cannot fail here.
  563. $startTime = Get-Date
  564. # THE stale-sentinel guarantee is a LIVE STARTUP SNAPSHOT, not LastWriteTime.
  565. # Before the first launch we record every pre-existing DONE-* PATH into
  566. # $snapshotFile. Test-SentinelPresent REFUSES any DONE-* whose path is in that
  567. # snapshot -- regardless of LastWriteTime. As quarantine SUCCESSFULLY renames each
  568. # stale occupant aside it PRUNES that path from the snapshot, so a path is vetoed
  569. # IFF its stale occupant still physically exists. A DONE-* counts as THIS run's
  570. # completion if its path was NOT present at startup OR was present but has since
  571. # been cleared by a successful quarantine (the launcher then wrote a FRESH one
  572. # there -- the same-activation DONE-<nonce> case). A failed quarantine
  573. # rename leaves the path vetoed -> RELAUNCH, never a false halt. The
  574. # LastWriteTime>=start belt is gone -- it could not backstop the same-second
  575. # class, which is the whole reason this defense exists. FAIL-SAFE: if the snapshot
  576. # cannot be written or read, ALL DONE-* are treated as suspect -> relaunch.
  577. $script:state = @{
  578. DryRun = $dryRun
  579. LedgerDir = $ledgerDir
  580. SentinelGlob = $sentinelGlob
  581. LaunchIndex = 0
  582. StartTime = $startTime
  583. SnapshotFile = $snapshotFile
  584. SnapshotOk = $false
  585. SnapshotPaths = @{}
  586. ScopeEscalate = $false
  587. ScopeTerminal = $false
  588. }
  589. function Write-SupLog {
  590. param([string]$Message)
  591. $ts = (Get-Date).ToString('yyyy-MM-ddTHH:mm:ss')
  592. Write-Host "[supervisor $ts] $Message"
  593. }
  594. # Take the startup snapshot of pre-existing DONE-* PATHS, BEFORE the first
  595. # launch and BEFORE any sentinel check or quarantine. Each path is written on
  596. # its own line to $snapshotFile and held in a hashtable for O(1) lookup.
  597. # SnapshotOk=$true marks a trustworthy snapshot; if writing fails we leave it
  598. # $false, and Test-SentinelPresent then treats EVERY DONE-* as suspect
  599. # (relaunch), the fail-safe direction.
  600. function Save-PreExistingSentinels {
  601. $script:state.SnapshotOk = $false
  602. $script:state.SnapshotPaths = @{}
  603. try {
  604. $found = @(Get-ChildItem -Path $script:state.SentinelGlob -ErrorAction SilentlyContinue)
  605. $lines = New-Object System.Collections.Generic.List[string]
  606. foreach ($file in $found) {
  607. $lines.Add($file.FullName)
  608. $script:state.SnapshotPaths[$file.FullName] = $true
  609. }
  610. Set-Content -LiteralPath $script:state.SnapshotFile -Value $lines -Encoding ascii -ErrorAction Stop
  611. $script:state.SnapshotOk = $true
  612. } catch {
  613. $script:state.SnapshotOk = $false
  614. }
  615. }
  616. # Is $Path one of the paths recorded in the startup snapshot? If the snapshot is
  617. # not trustworthy (SnapshotOk=$false) we answer YES for every path -> every
  618. # DONE-* is treated as pre-existing -> never halts -> relaunch. That is the
  619. # deliberate fail-safe: a missing/unreadable snapshot must never permit a halt.
  620. function Test-PathInSnapshot {
  621. param([string]$Path)
  622. if (-not $script:state.SnapshotOk) { return $true }
  623. return $script:state.SnapshotPaths.ContainsKey($Path)
  624. }
  625. # Drop one path from the live snapshot so a genuinely-fresh sentinel can later
  626. # reclaim it. Called by quarantine ONLY after a SUCCESSFUL rename: once the stale
  627. # occupant has been moved aside, the path is empty, so the ONLY thing that can
  628. # appear there is a fresh sentinel written by THIS run. The activation nonce is
  629. # minted once (CSPRNG) and re-exported unchanged to every relaunched child (no
  630. # clock), so a re-launch of
  631. # the SAME activation writes the SAME path the snapshot recorded -- if the snapshot
  632. # kept vetoing it, that fresh sentinel would be refused forever and the supervisor
  633. # would relaunch without end (the livelock). We drop it from the in-memory set AND
  634. # rewrite $SnapshotFile so a mid-run re-read agrees. If the rewrite fails we KEEP
  635. # the path in memory (over-veto = relaunch, never a false halt). A path whose
  636. # rename FAILED is never pruned, so it stays vetoed while its occupant still exists.
  637. function Remove-PathFromSnapshot {
  638. param([string]$Path)
  639. if (-not $script:state.SnapshotOk) { return }
  640. $script:state.SnapshotPaths.Remove($Path) | Out-Null
  641. try {
  642. $lines = New-Object System.Collections.Generic.List[string]
  643. foreach ($key in $script:state.SnapshotPaths.Keys) { $lines.Add($key) }
  644. Set-Content -LiteralPath $script:state.SnapshotFile -Value $lines -Encoding ascii -ErrorAction Stop
  645. } catch {
  646. # Rewrite failed: the in-memory set already dropped the path (the source of
  647. # truth for this process); the on-disk copy is only for a mid-run re-read,
  648. # which this port does not do. Leaving it stale cannot cause a false halt.
  649. }
  650. }
  651. # A DONE-sentinel counts as THIS run's completion iff it exists, carries the
  652. # done marker, AND its path is NOT in the LIVE startup snapshot. The snapshot
  653. # starts as every pre-existing DONE-* path and is pruned as quarantine clears
  654. # each one, so a path is vetoed IFF its stale occupant still physically exists;
  655. # a fresh sentinel at a cleared path is honored. Mirrors the .sh for-loop glob +
  656. # grep '"done"\s*:\s*true'.
  657. function Test-SentinelPresent {
  658. if (-not $legacySentinel) {
  659. $sentinelPath = Join-Path $script:state.LedgerDir "DONE-$runNonce"
  660. if (-not (Test-Path -LiteralPath $sentinelPath -PathType Leaf) -or
  661. (Test-PathInSnapshot $sentinelPath)) {
  662. return $false
  663. }
  664. try {
  665. $sentinel = Get-Content -LiteralPath $sentinelPath -Raw -ErrorAction Stop |
  666. ConvertFrom-Json -ErrorAction Stop
  667. $done = $sentinel.PSObject.Properties['done']
  668. $nonce = $sentinel.PSObject.Properties['nonce']
  669. return $null -ne $done -and $done.Value -is [bool] -and $done.Value -eq $true -and
  670. $null -ne $nonce -and $nonce.Value -is [string] -and $nonce.Value -ceq $runNonce
  671. } catch {
  672. return $false
  673. }
  674. }
  675. $found = @(Get-ChildItem -Path $script:state.SentinelGlob -File -ErrorAction SilentlyContinue)
  676. foreach ($file in $found) {
  677. $content = Get-Content -LiteralPath $file.FullName -Raw -ErrorAction SilentlyContinue
  678. if ($null -ne $content -and $content -match '"done"\s*:\s*true') {
  679. if (-not (Test-PathInSnapshot $file.FullName)) {
  680. return $true
  681. }
  682. }
  683. }
  684. return $false
  685. }
  686. # At startup, BEFORE the first launch, QUARANTINE every pre-existing done:true
  687. # DONE-* sentinel: rename it aside to <dir>\superseded-<start-epoch>-<name> so
  688. # the new name no longer starts with DONE- and thus no longer matches the live
  689. # DONE-* glob -- it cannot halt this fresh mission. (Prefixing, NOT suffixing: a
  690. # DONE-X.superseded-N name would STILL match DONE-* and re-trip the same-second
  691. # halt, so the leading DONE- must be displaced.) This is the PRIMARY fix for the
  692. # whole stale-sentinel class -- after quarantine there is no leftover sentinel
  693. # left to race, so a same-second / sub-second LastWriteTime collision is moot.
  694. # We RENAME, never delete (deleting artifacts is the JANITOR's job; never
  695. # silently remove operator files) and log a loud line naming each quarantined
  696. # file. On a SUCCESSFUL rename the path is pruned from the live snapshot so a
  697. # genuine fresh same-activation DONE-<nonce> (the minted nonce is re-exported to
  698. # every relaunched child, no clock) can reclaim it -- else the snapshot would veto
  699. # that fresh sentinel forever and the supervisor would relaunch without end
  700. # (livelock). If a rename FAILS (read-only dir / permissions / clobber) the
  701. # leftover DONE-* still matches the live glob, its path is NOT pruned, and
  702. # Test-SentinelPresent unconditionally refuses it. A failed rename degrades to
  703. # RELAUNCH, never a halt. Net invariant: the snapshot vetoes a path IFF its stale
  704. # occupant still exists.
  705. function Move-StaleSentinelAside {
  706. $startEpoch = [int64][Math]::Floor(([DateTimeOffset]$script:state.StartTime).ToUnixTimeSeconds())
  707. $found = @(Get-ChildItem -Path $script:state.SentinelGlob -File -ErrorAction SilentlyContinue)
  708. foreach ($file in $found) {
  709. $content = Get-Content -LiteralPath $file.FullName -Raw -ErrorAction SilentlyContinue
  710. if ($null -ne $content -and $content -match '"done"\s*:\s*true') {
  711. $quarantined = Join-Path $file.DirectoryName "superseded-$startEpoch-$($file.Name)"
  712. try {
  713. Move-Item -LiteralPath $file.FullName -Destination $quarantined -Force -ErrorAction Stop
  714. # The stale occupant is gone, so this path can no longer hold
  715. # anything but a FRESH this-run sentinel. Drop it from the live
  716. # snapshot so the same-activation DONE-<nonce> is
  717. # reclaimable -- otherwise the snapshot would veto the genuine
  718. # fresh sentinel forever (the livelock).
  719. Remove-PathFromSnapshot $file.FullName
  720. 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."
  721. } catch {
  722. 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."
  723. }
  724. }
  725. }
  726. }
  727. # The frontier marker is a monotonic forward-progress counter, not a success
  728. # counter. In real runs it counts roadmap/scout, plan, build, assurance, sweep,
  729. # arbitration, and goal-check artifacts. Versioned, per-feature, retained-scout,
  730. # and per-round files multiply as work proceeds, so an advancing pre-build scope
  731. # that writes roadmap and retained scout evidence long
  732. # before any plan-final -- bumps the count every relaunch and resets the
  733. # poison window; a run writing nothing new stays flat and still trips poison.
  734. function Get-FrontierCount {
  735. if ($script:state.DryRun) {
  736. if ((Get-EnvOrDefault 'FAKE_POISON' '0') -eq '1') { return 0 }
  737. $counterFile = Join-Path $script:state.LedgerDir '.fake-frontier'
  738. if (Test-Path -LiteralPath $counterFile) {
  739. return [int]((Get-Content -LiteralPath $counterFile -Raw).Trim())
  740. }
  741. return 0
  742. }
  743. $count = 0
  744. # Three artifact layouts must ALL be counted, or a run driven by one of them
  745. # is invisible to the frontier and a healthy-long run trips POISON:
  746. # prose/agent (SKILL.md/GATES.md): autoprompt/prompt-NNN-<slug>/artifacts/
  747. # harness (autoprompt-gate.js ARTIFACT_DIR): autoprompt/.artifacts/<run-tag>/
  748. # session ledger (SPEC-1 SCRIBE): autoprompt/session_NN/prompt_NN-<slug>/ and
  749. # its optional artifacts/ subdir. The per-prompt ledger .md files
  750. # (BRIEF/GATELOG/COVERAGE...) count as forward progress (monotonic; same
  751. # rationale as the multiplying-artifacts globs), so a run advancing ONLY in
  752. # the new layout is never falsely poisoned.
  753. # The leading-dot harness dir is not matched by the prose "*" wildcard and its
  754. # nesting differs, so it needs its own glob -- which also stops the prose glob
  755. # from double-counting it. Ledger-root prose files (BRIEF/PLAN/GATELOG...) live
  756. # one level above artifacts/ so they are not counted by the first two globs; the
  757. # session-ledger glob counts them at their nested depth. The DONE sentinel lives
  758. # at the ledger root, not under any artifacts/ dir.
  759. $proseArtifacts = Join-Path (Join-Path $script:state.LedgerDir '*') 'artifacts'
  760. $harnessArtifacts = Join-Path (Join-Path $script:state.LedgerDir '.artifacts') '*'
  761. $artifactGlobs = @(
  762. (Join-Path $proseArtifacts '*.md')
  763. (Join-Path $harnessArtifacts '*.md')
  764. (Join-Path (Join-Path (Join-Path $script:state.LedgerDir 'session_*') 'prompt_*') (Join-Path 'artifacts' '*.md'))
  765. (Join-Path (Join-Path (Join-Path $script:state.LedgerDir 'session_*') 'prompt_*') '*.md')
  766. )
  767. $count += @(Get-ChildItem -Path $artifactGlobs -File -ErrorAction SilentlyContinue).Count
  768. return $count
  769. }
  770. # Scope wall-clock budget starts at launch, before the author can emit an artifact,
  771. # and goes dormant only when build evidence lands.
  772. function Get-ScopePhaseElapsed {
  773. if ($script:state.DryRun) {
  774. $fse = Get-EnvOrDefault 'FAKE_SCOPE_ELAPSED' ''
  775. if (-not [string]::IsNullOrEmpty($fse)) { return [int]$fse }
  776. return $null
  777. }
  778. $ld = $script:state.LedgerDir
  779. $buildGlobs = @(
  780. (Join-Path (Join-Path (Join-Path $ld '.artifacts') '*') '*-impl-v*.md')
  781. (Join-Path (Join-Path (Join-Path $ld '*') 'artifacts') '*-impl-v*.md')
  782. (Join-Path (Join-Path (Join-Path (Join-Path $ld 'session_*') 'prompt_*') 'artifacts') '*-impl-v*.md')
  783. )
  784. if (@(Get-ChildItem -Path $buildGlobs -File -ErrorAction SilentlyContinue).Count -gt 0) {
  785. Remove-Item -LiteralPath $scopePhaseStartFile -Force -ErrorAction SilentlyContinue
  786. Remove-Item -LiteralPath $scopeResetsFile -Force -ErrorAction SilentlyContinue
  787. Remove-Item -LiteralPath (Join-Path $ld 'SCOPE-CONVERGE-REQUEST') -Force -ErrorAction SilentlyContinue
  788. Remove-Item -LiteralPath (Join-Path $ld 'SCOPE-BUDGET-BREACH') -Force -ErrorAction SilentlyContinue
  789. return $null
  790. }
  791. $nowS = [int64][Math]::Floor(([DateTimeOffset](Get-Date)).ToUnixTimeSeconds())
  792. $startS = 0
  793. $storedBinding = ''
  794. if (Test-Path -LiteralPath $scopePhaseStartFile) {
  795. try {
  796. $first = (Get-Content -LiteralPath $scopePhaseStartFile -First 1 -ErrorAction Stop)
  797. if ($null -ne $first) {
  798. $fields = ([string]$first).Trim() -split '\s+'
  799. if ($fields.Count -ge 1) { [void][int64]::TryParse($fields[0], [ref]$startS) }
  800. if ($fields.Count -ge 2) { $storedBinding = $fields[1] }
  801. }
  802. } catch { $startS = 0; $storedBinding = '' }
  803. }
  804. if ($storedBinding -cne $scopeMissionBinding) {
  805. $startS = 0
  806. Remove-Item -LiteralPath (Join-Path $ld 'SCOPE-CONVERGE-REQUEST') -Force -ErrorAction SilentlyContinue
  807. Remove-Item -LiteralPath (Join-Path $ld 'SCOPE-BUDGET-BREACH') -Force -ErrorAction SilentlyContinue
  808. Remove-Item -LiteralPath $scopeResetsFile -Force -ErrorAction SilentlyContinue
  809. }
  810. if ($startS -le 0) {
  811. $startS = $nowS
  812. try {
  813. $tmp = "$scopePhaseStartFile.tmp"
  814. "$startS $scopeMissionBinding" | Set-Content -LiteralPath $tmp -Encoding ascii
  815. Move-Item -LiteralPath $tmp -Destination $scopePhaseStartFile -Force
  816. } catch { }
  817. }
  818. $elapsed = $nowS - $startS
  819. if ($elapsed -lt 0) { $elapsed = 0 }
  820. return [int]$elapsed
  821. }
  822. # Honest retained scope evidence: roadmap-scout-N on new runs, scope-<key> on
  823. # legacy resumes. Missing evidence stays missing rather than being invented.
  824. function Get-ScopeLandedAngles {
  825. if ($script:state.DryRun) { return (Get-EnvOrDefault 'FAKE_SCOPE_LANDED' '') }
  826. $ld = $script:state.LedgerDir
  827. $scopeGlobs = @(
  828. (Join-Path (Join-Path (Join-Path $ld '.artifacts') '*') 'roadmap-scout-*.md')
  829. (Join-Path (Join-Path (Join-Path $ld '*') 'artifacts') 'roadmap-scout-*.md')
  830. (Join-Path (Join-Path (Join-Path (Join-Path $ld 'session_*') 'prompt_*') 'artifacts') 'roadmap-scout-*.md')
  831. (Join-Path (Join-Path (Join-Path $ld '.artifacts') '*') 'scope-*.md')
  832. (Join-Path (Join-Path (Join-Path $ld '*') 'artifacts') 'scope-*.md')
  833. (Join-Path (Join-Path (Join-Path (Join-Path $ld 'session_*') 'prompt_*') 'artifacts') 'scope-*.md')
  834. )
  835. $keys = New-Object System.Collections.Generic.List[string]
  836. foreach ($file in @(Get-ChildItem -Path $scopeGlobs -File -ErrorAction SilentlyContinue)) {
  837. $key = if ($file.Name -like 'roadmap-scout-*.md') {
  838. $file.Name -replace '\.md$', ''
  839. } else {
  840. $file.Name -replace '^scope-', '' -replace '-v[0-9]+\.md$', '' -replace '\.md$', ''
  841. }
  842. if (-not [string]::IsNullOrEmpty($key) -and -not $keys.Contains($key)) { $keys.Add($key) }
  843. }
  844. return ($keys -join ',')
  845. }
  846. # Age (seconds) of the pending SCOPE-CONVERGE-REQUEST, or 0 when none exists.
  847. function Get-ScopeConvergeRequestAge {
  848. $req = Join-Path $script:state.LedgerDir 'SCOPE-CONVERGE-REQUEST'
  849. if (-not (Test-Path -LiteralPath $req)) { return 0 }
  850. $nowS = [int64][Math]::Floor(([DateTimeOffset](Get-Date)).ToUnixTimeSeconds())
  851. $reqTs = 0
  852. try {
  853. $first = (Get-Content -LiteralPath $req -First 1 -ErrorAction Stop)
  854. if ($null -ne $first) { $f = ([string]$first).Trim() -split '\s+'; if ($f.Count -ge 1) { [void][int64]::TryParse($f[0], [ref]$reqTs) } }
  855. } catch { $reqTs = 0 }
  856. $age = $nowS - $reqTs
  857. if ($age -lt 0) { $age = 0 }
  858. return [int]$age
  859. }
  860. # === PLAN-auto-compact-threshold: proactive supervisor-fired compaction ==========
  861. # The PowerShell port of canon_path / find_parent_transcript / read_context_estimate
  862. # / note_external_compaction / maybe_request_compaction / kill_tree. The slug-free
  863. # discovery rule (single-level glob + embedded-cwd match + newest-since-launch) is
  864. # BYTE-FOR-BYTE the same decision as supervisor.sh -- there is no slug to diverge on.
  865. # Canonicalize a path for cross-platform cwd comparison (win32 AND posix): lowercase;
  866. # collapse \ and / runs to a single /; map a leading "<drive>:" to "/<drive>".
  867. function Get-CanonPath {
  868. param([string]$Path)
  869. if ($null -eq $Path) { return '' }
  870. $p = $Path.ToLowerInvariant() -replace '\\', '/'
  871. $p = $p -replace '/+', '/'
  872. $p = $p -replace '^([a-z]):', '/$1'
  873. return $p
  874. }
  875. # Find the live parent session .jsonl. Slug-free: matches $runCwd against each
  876. # transcript's embedded "cwd" after canonicalization. Single-level glob excludes
  877. # nested subagent/tool-result transcripts. Returns the path or $null.
  878. function Find-ParentTranscript {
  879. param([long]$LaunchEpoch)
  880. if (-not [string]::IsNullOrEmpty($parentTranscript) -and (Test-Path -LiteralPath $parentTranscript)) {
  881. return $parentTranscript
  882. }
  883. $cfg = Get-EnvOrDefault 'CLAUDE_CONFIG_DIR' (Join-Path $HOME '.claude')
  884. $want = Get-CanonPath $runCwd
  885. $glob = Join-Path (Join-Path $cfg 'projects') (Join-Path '*' '*.jsonl')
  886. $newest = $null; $newestMt = [long]0
  887. foreach ($f in @(Get-ChildItem -Path $glob -File -ErrorAction SilentlyContinue)) {
  888. $mt = [int64][Math]::Floor(([DateTimeOffset]$f.LastWriteTimeUtc).ToUnixTimeSeconds())
  889. if ($mt -lt $LaunchEpoch) { continue } # stale prior session
  890. $tcwd = $null
  891. try {
  892. foreach ($line in [System.IO.File]::ReadLines($f.FullName)) {
  893. $m = [regex]::Match($line, '"cwd":"([^"]*)"')
  894. if ($m.Success) { $tcwd = $m.Groups[1].Value; break }
  895. }
  896. } catch { $tcwd = $null }
  897. if ([string]::IsNullOrEmpty($tcwd)) { continue }
  898. $tcwd = $tcwd -replace '\\\\', '\' # un-escape JSON doubled backslashes
  899. if ((Get-CanonPath $tcwd) -ne $want) { continue }
  900. if ($mt -gt $newestMt) { $newest = $f.FullName; $newestMt = $mt }
  901. }
  902. return $newest
  903. }
  904. # Read the PARENT's context size in three tiers; returns an integer (0 = unavailable).
  905. # TIER 1 parse transcript usage (byte proxy on parse failure); TIER 2 watermark
  906. # (stale-rejected); TIER 3 coarse ledger-byte proxy. Honors FAKE_WATERMARK in dry-run.
  907. function Read-ContextEstimate {
  908. param([long]$LaunchEpoch)
  909. if ($script:state.DryRun) {
  910. $fw = Get-EnvOrDefault 'FAKE_WATERMARK' ''
  911. if (-not [string]::IsNullOrEmpty($fw)) { return [int]$fw }
  912. return 0
  913. }
  914. $tx = Find-ParentTranscript -LaunchEpoch $LaunchEpoch
  915. if (-not [string]::IsNullOrEmpty($tx) -and (Test-Path -LiteralPath $tx)) {
  916. $lastUsage = $null
  917. try {
  918. foreach ($line in [System.IO.File]::ReadLines($tx)) {
  919. if ($line -notmatch '"usage"') { continue }
  920. try {
  921. $obj = $line | ConvertFrom-Json
  922. if ($obj.message -and $obj.message.usage) { $lastUsage = $obj.message.usage }
  923. } catch { }
  924. }
  925. } catch { $lastUsage = $null }
  926. if ($null -ne $lastUsage) {
  927. $sum = 0
  928. foreach ($k in @('input_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens')) {
  929. $v = $lastUsage.$k
  930. if ($null -ne $v) { $sum += [int]$v }
  931. }
  932. if ($sum -gt 0) { return $sum }
  933. }
  934. try {
  935. $sz = (Get-Item -LiteralPath $tx).Length
  936. if ($sz -gt 0) { return [int]([math]::Floor($sz / $bytesPerToken)) }
  937. } catch { }
  938. }
  939. if (Test-Path -LiteralPath $watermarkFile) {
  940. try {
  941. $first = (Get-Content -LiteralPath $watermarkFile -First 1 -ErrorAction Stop)
  942. if ($null -ne $first) {
  943. $fields = ([string]$first).Trim() -split '\s+'
  944. $wmTok = 0
  945. if ($fields.Count -ge 1 -and [int]::TryParse($fields[0], [ref]$wmTok)) {
  946. $wmTs = $null
  947. if ($fields.Count -ge 2) { $parsedTs = [long]0; if ([long]::TryParse($fields[1], [ref]$parsedTs)) { $wmTs = $parsedTs } }
  948. if ($null -eq $wmTs -or $wmTs -ge $LaunchEpoch) { return $wmTok }
  949. }
  950. }
  951. } catch { }
  952. }
  953. $bytes = [long]0
  954. $ledgerGlobs = @(
  955. (Join-Path (Join-Path (Join-Path $script:state.LedgerDir 'session_*') 'prompt_*') '*.md')
  956. (Join-Path (Join-Path (Join-Path $script:state.LedgerDir 'session_*') 'prompt_*') (Join-Path 'artifacts' '*.md'))
  957. (Join-Path (Join-Path $script:state.LedgerDir '*') (Join-Path 'artifacts' '*.md'))
  958. )
  959. foreach ($g in $ledgerGlobs) {
  960. foreach ($f in @(Get-ChildItem -Path $g -File -ErrorAction SilentlyContinue)) { $bytes += $f.Length }
  961. }
  962. return [int]([math]::Floor($bytes / $bytesPerToken))
  963. }
  964. # Detect a harness-fired compaction (a sharp estimate DROP across ticks): arm the
  965. # cooldown and clear any pending request so the supervisor does NOT double-fire.
  966. # Returns $true when an external compaction was detected.
  967. function Note-ExternalCompaction {
  968. param([long]$Now, [int]$CurrentEst)
  969. $prevEst = 0; $lastCompact = 0
  970. if (Test-Path -LiteralPath $compactStateFile) {
  971. try {
  972. $first = (Get-Content -LiteralPath $compactStateFile -First 1 -ErrorAction Stop)
  973. if ($null -ne $first) {
  974. $f = ([string]$first).Trim() -split '\s+'
  975. if ($f.Count -ge 1) { [void][int]::TryParse($f[0], [ref]$lastCompact) }
  976. if ($f.Count -ge 2) { [void][int]::TryParse($f[1], [ref]$prevEst) }
  977. }
  978. } catch { }
  979. }
  980. if ($prevEst -gt 0 -and (($prevEst - $CurrentEst) -ge $externalCompactDelta)) {
  981. try {
  982. $tmp = "$compactStateFile.tmp"
  983. "$Now $CurrentEst external_compaction" | Set-Content -LiteralPath $tmp -Encoding ascii
  984. Move-Item -LiteralPath $tmp -Destination $compactStateFile -Force
  985. } catch { }
  986. if (Test-Path -LiteralPath $compactRequestFile) { Remove-Item -LiteralPath $compactRequestFile -Force -ErrorAction SilentlyContinue }
  987. Write-SupLog "EXTERNAL COMPACTION detected: context estimate dropped $prevEst->$CurrentEst (>=$externalCompactDelta) -- arming cooldown and clearing any pending COMPACT-REQUEST (no double-fire)."
  988. return $true
  989. }
  990. try {
  991. $tmp = "$compactStateFile.tmp"
  992. "$lastCompact $CurrentEst" | Set-Content -LiteralPath $tmp -Encoding ascii
  993. Move-Item -LiteralPath $tmp -Destination $compactStateFile -Force
  994. } catch { }
  995. return $false
  996. }
  997. # Decide whether to request/force a compaction. Returns @{Requested=$bool; Force=$bool}.
  998. # Guards: cooldown, in-flight request, external-compaction detection.
  999. function Request-CompactionIfNeeded {
  1000. param([long]$LaunchEpoch, [long]$Now)
  1001. $result = @{ Requested = $false; Force = $false }
  1002. $est = Read-ContextEstimate -LaunchEpoch $LaunchEpoch
  1003. if (Note-ExternalCompaction -Now $Now -CurrentEst $est) { return $result }
  1004. $lastCompact = 0
  1005. if (Test-Path -LiteralPath $compactStateFile) {
  1006. try {
  1007. $first = (Get-Content -LiteralPath $compactStateFile -First 1 -ErrorAction Stop)
  1008. if ($null -ne $first) { $f = ([string]$first).Trim() -split '\s+'; if ($f.Count -ge 1) { [void][int]::TryParse($f[0], [ref]$lastCompact) } }
  1009. } catch { }
  1010. }
  1011. if ($lastCompact -gt 0 -and (($Now - $lastCompact) -lt $compactCooldown)) { return $result }
  1012. if (Test-Path -LiteralPath $compactRequestFile) {
  1013. $reqTs = 0
  1014. try {
  1015. $first = (Get-Content -LiteralPath $compactRequestFile -First 1 -ErrorAction Stop)
  1016. if ($null -ne $first) { $f = ([string]$first).Trim() -split '\s+'; if ($f.Count -ge 1) { [void][int]::TryParse($f[0], [ref]$reqTs) } }
  1017. } catch { }
  1018. if (($Now - $reqTs) -ge $compactGrace) { $result.Force = $true; $result.Requested = $true }
  1019. return $result
  1020. }
  1021. if ($est -ge $compactAt) {
  1022. try {
  1023. $tmp = "$compactRequestFile.tmp"
  1024. "$Now proactive est=$est threshold=$compactAt" | Set-Content -LiteralPath $tmp -Encoding ascii
  1025. Move-Item -LiteralPath $tmp -Destination $compactRequestFile -Force
  1026. 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)."
  1027. } catch { }
  1028. $result.Requested = $true
  1029. }
  1030. return $result
  1031. }
  1032. # Kill the child process AND every descendant so a wedged parent leaves NO orphaned
  1033. # subagent (the ps1 analog of the .sh process-group kill_tree). Walks Win32_Process
  1034. # ParentProcessId, killing leaves-first, then the root.
  1035. function Stop-ProcessTree {
  1036. param($Proc)
  1037. if ($null -eq $Proc) { return }
  1038. $rootId = $null
  1039. try { $rootId = $Proc.Id } catch { $rootId = $null }
  1040. if ($null -ne $rootId) {
  1041. try {
  1042. & taskkill.exe /T /F /PID $rootId 2>$null | Out-Null
  1043. if ($LASTEXITCODE -eq 0) { return }
  1044. } catch { }
  1045. # Fallback: manual descendant walk if taskkill is unavailable or fails.
  1046. try {
  1047. $all = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue
  1048. $toKill = New-Object System.Collections.Generic.List[int]
  1049. $queue = New-Object System.Collections.Generic.Queue[int]
  1050. $queue.Enqueue([int]$rootId)
  1051. while ($queue.Count -gt 0) {
  1052. $procId = $queue.Dequeue(); $toKill.Add($procId)
  1053. foreach ($c in @($all | Where-Object { $_.ParentProcessId -eq $procId })) { $queue.Enqueue([int]$c.ProcessId) }
  1054. }
  1055. foreach ($victim in ($toKill.ToArray() | Sort-Object -Descending)) {
  1056. try { Stop-Process -Id $victim -Force -ErrorAction SilentlyContinue } catch { }
  1057. }
  1058. } catch { }
  1059. }
  1060. try { $Proc.Kill() } catch { }
  1061. }
  1062. # Run the real or fake launcher once; return its exit code.
  1063. #
  1064. # HEARTBEAT (PLAN-idle-watchdog P3, behavior-parallel to supervisor.sh V3): the
  1065. # child is launched in the BACKGROUND on BOTH the real exec AND the dry-run fake
  1066. # path (via Start-Process -PassThru), so a SINGLE poll loop watches liveness +
  1067. # frontier-COUNT staleness regardless of path (blocker 2: the poll loop is genuinely
  1068. # exercised under --dry-run against a real process handle). While the child is alive,
  1069. # if Get-FrontierCount has NOT grown beyond last-seen within $idleTimeout and no
  1070. # sentinel exists, the run is ALIVE-BUT-IDLE -> Stop-Process so the outer relaunch
  1071. # loop RESUMEs it (the automatic CONTINUE). DISTINCT from the EXIT-keyed poison guard
  1072. # and FEEDS it: a heartbeat kill that produced no count growth is a no-progress
  1073. # restart for the outer loop, so a wedged child still trips POISON after MAX_RESTARTS
  1074. # (anti-thrash). The model-pin / session-token save -> set -> restore-in-finally
  1075. # quartet wraps the Start-Process so the child inherits the neutralized env and this
  1076. # supervisor's own env is restored after the child fully exits.
  1077. function Invoke-Launcher {
  1078. $script:state.LaunchIndex += 1
  1079. $idx = $script:state.LaunchIndex
  1080. $childLaunchEpoch = [int64][Math]::Floor(([DateTimeOffset](Get-Date)).ToUnixTimeSeconds())
  1081. if (-not $script:state.DryRun) {
  1082. $storedBinding = ''
  1083. if (Test-Path -LiteralPath $scopePhaseStartFile) {
  1084. try {
  1085. $first = Get-Content -LiteralPath $scopePhaseStartFile -First 1 -ErrorAction Stop
  1086. if ($null -ne $first) {
  1087. $fields = ([string]$first).Trim() -split '\s+'
  1088. if ($fields.Count -ge 2) { $storedBinding = $fields[1] }
  1089. }
  1090. } catch { $storedBinding = '' }
  1091. }
  1092. if ($storedBinding -cne $scopeMissionBinding) {
  1093. Remove-Item -LiteralPath (Join-Path $ledgerDir 'SCOPE-CONVERGE-REQUEST') -Force -ErrorAction SilentlyContinue
  1094. Remove-Item -LiteralPath (Join-Path $ledgerDir 'SCOPE-BUDGET-BREACH') -Force -ErrorAction SilentlyContinue
  1095. Remove-Item -LiteralPath $scopeResetsFile -Force -ErrorAction SilentlyContinue
  1096. try {
  1097. $tmp = "$scopePhaseStartFile.tmp"
  1098. "$childLaunchEpoch $scopeMissionBinding" | Set-Content -LiteralPath $tmp -Encoding ascii
  1099. Move-Item -LiteralPath $tmp -Destination $scopePhaseStartFile -Force
  1100. } catch {}
  1101. }
  1102. }
  1103. $absLedger = $script:state.LedgerDir
  1104. if (-not [System.IO.Path]::IsPathRooted($absLedger)) {
  1105. $absLedger = Join-Path (Get-Location).Path $absLedger
  1106. }
  1107. if ($script:state.DryRun) {
  1108. # Compute everything in the PARENT (idx-indexed), then background a generated
  1109. # fake-child script via Start-Process so the poll loop has a real handle. The
  1110. # fake writes the sentinel / advances the frontier / optionally stays alive
  1111. # (FAKE_CHILD_ALIVE seconds) then exits with the popped code - exactly the
  1112. # work the old synchronous fake did, now in a real backgrounded process.
  1113. $sentinelAfter = Get-EnvOrDefault 'FAKE_SENTINEL_AFTER' ''
  1114. $writeSentinel = (-not [string]::IsNullOrEmpty($sentinelAfter) -and $idx -ge [int]$sentinelAfter)
  1115. $advance = ((Get-EnvOrDefault 'FAKE_POISON' '0') -ne '1')
  1116. $alive = [int](Get-EnvOrDefault 'FAKE_CHILD_ALIVE' 0)
  1117. $fakeExits = (Get-EnvOrDefault 'FAKE_EXITS' '0').Trim()
  1118. $codes = @($fakeExits -split '\s+' | Where-Object { $_ -ne '' })
  1119. $code = 0
  1120. if ($idx -ge 1 -and $idx -le $codes.Count) { $code = [int]$codes[$idx - 1] }
  1121. $fakeChild = Join-Path $absLedger '.fake-child.ps1'
  1122. @(
  1123. 'param($Ledger,$WriteSentinel,$Advance,$Alive,$Code)'
  1124. 'if ($WriteSentinel -eq "1") {'
  1125. ' $done = Join-Path $Ledger "DONE-FAKE"'
  1126. ' $tmp = "$done.tmp"'
  1127. ' ''{"done": true, "nonce": "FAKE", "verdict": "fake done", "ts": "now"}'' | Set-Content -LiteralPath $tmp -Encoding ascii -NoNewline'
  1128. ' Move-Item -LiteralPath $tmp -Destination $done -Force'
  1129. '}'
  1130. 'if ($Advance -eq "1") {'
  1131. ' $cf = Join-Path $Ledger ".fake-frontier"'
  1132. ' $cur = 0; if (Test-Path -LiteralPath $cf) { $cur = [int]((Get-Content -LiteralPath $cf -Raw).Trim()) }'
  1133. ' ($cur + 1) | Set-Content -LiteralPath $cf -Encoding ascii -NoNewline'
  1134. '}'
  1135. 'if ($Alive -gt 0) { Start-Sleep -Seconds $Alive }'
  1136. 'exit $Code'
  1137. ) -join "`n" | Set-Content -LiteralPath $fakeChild -Encoding ascii
  1138. $wsArg = if ($writeSentinel) { '1' } else { '0' }
  1139. $advArg = if ($advance) { '1' } else { '0' }
  1140. $proc = Start-Process -FilePath 'powershell' `
  1141. -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $fakeChild, $absLedger, $wsArg, $advArg, "$alive", "$code") `
  1142. -PassThru -NoNewWindow -WorkingDirectory (Get-Location).Path
  1143. return (Wait-ChildWithHeartbeat -Proc $proc)
  1144. }
  1145. # Launch one is fresh unless the operator explicitly requested resume.
  1146. # Relaunches always export AUTOPROMPT_RESUME=1.
  1147. # When $launchCmd is set it is used VERBATIM (word-split into command +
  1148. # args, mission appended) so a fresh user can pass their real CLI;
  1149. # otherwise the bare $launcher label is exec'd as before.
  1150. # Neutralize the operator's CLAUDE_CODE_SUBAGENT_MODEL for the CHILD CLI
  1151. # ONLY. That var has HIGHEST precedence in the harness and force-pins every
  1152. # (even nested) subagent onto a fixed model, defeating the skill's
  1153. # `model: inherit` contract. PowerShell env is process-scoped, so the
  1154. # faithful analog of the .sh `env -u` is save -> set $null -> restore in
  1155. # `finally`: the backgrounded child inherits the var UNSET while this
  1156. # supervisor process's own value (and the operator's shell/profile) is
  1157. # restored intact after the child exits. `inherit` then resolves to the real
  1158. # session/--model selection. Idempotent: a null/inherit/unset prior value
  1159. # round-trips with no error. AUTOPROMPT_KEEP_MODEL_PIN=1 opts OUT.
  1160. $keepModelPin = (Get-EnvOrDefault 'AUTOPROMPT_KEEP_MODEL_PIN' '0') -eq '1'
  1161. $previousSubagentModel = $env:CLAUDE_CODE_SUBAGENT_MODEL
  1162. $previousUnattended = $env:AUTOPROMPT_UNATTENDED
  1163. $previousResume = $env:AUTOPROMPT_RESUME
  1164. $previousMode = $env:AUTOPROMPT_MODE
  1165. $previousRunNonce = $env:AUTOPROMPT_RUN_NONCE
  1166. $previousLedgerCheck = $env:AUTOPROMPT_LEDGER_CHECK
  1167. $previousSessionToken = $env:AUTOPROMPT_SESSION_TOKEN
  1168. $previousAgents = $env:AUTOPROMPT_AGENTS
  1169. $previousAgentCasting = $env:AUTOPROMPT_AGENT_CASTING
  1170. $previousCapabilityAttestation = $env:AUTOPROMPT_CAPABILITY_ATTESTATION
  1171. $previousProvider = $env:AUTOPROMPT_PROVIDER
  1172. $previousCliVersion = $env:AUTOPROMPT_CLI_VERSION
  1173. $previousPermissionProfile = $env:AUTOPROMPT_PERMISSION_PROFILE
  1174. $previousAgentDefinitionsHash = $env:AUTOPROMPT_AGENT_DEFINITIONS_HASH
  1175. $previousCastingHash = $env:AUTOPROMPT_CASTING_HASH
  1176. $previousOpusModel = $env:ANTHROPIC_DEFAULT_OPUS_MODEL
  1177. $previousSonnetModel = $env:ANTHROPIC_DEFAULT_SONNET_MODEL
  1178. $previousHaikuModel = $env:ANTHROPIC_DEFAULT_HAIKU_MODEL
  1179. $previousBaseUrl = $env:ANTHROPIC_BASE_URL
  1180. $previousAuthToken = $env:ANTHROPIC_AUTH_TOKEN
  1181. $env:AUTOPROMPT_UNATTENDED = '1'
  1182. if ($idx -gt 1 -or $initialResume) {
  1183. $env:AUTOPROMPT_RESUME = '1'
  1184. } else {
  1185. $env:AUTOPROMPT_RESUME = $null
  1186. }
  1187. $env:AUTOPROMPT_MODE = $autopromptMode
  1188. if (-not $legacySentinel) { $env:AUTOPROMPT_RUN_NONCE = $runNonce }
  1189. $env:AUTOPROMPT_LEDGER_CHECK = $ledgerCheckPath
  1190. if (-not [string]::IsNullOrEmpty($sessionToken)) {
  1191. $env:AUTOPROMPT_SESSION_TOKEN = $sessionToken
  1192. } else {
  1193. $env:AUTOPROMPT_SESSION_TOKEN = $null
  1194. }
  1195. if (-not $keepModelPin) { $env:CLAUDE_CODE_SUBAGENT_MODEL = $null }
  1196. $env:AUTOPROMPT_AGENTS = $agentsSelector
  1197. $env:AUTOPROMPT_PROVIDER = $capabilityProvider
  1198. $env:AUTOPROMPT_CLI_VERSION = $capabilityCliVersion
  1199. $env:AUTOPROMPT_PERMISSION_PROFILE = $capabilityPermissionProfile
  1200. $env:AUTOPROMPT_AGENT_DEFINITIONS_HASH = $capabilityAgentDefinitionsHash
  1201. $env:AUTOPROMPT_CASTING_HASH = $capabilityCastingHash
  1202. $env:AUTOPROMPT_CAPABILITY_ATTESTATION = $capabilityAttestation
  1203. if ($castingEnabled) {
  1204. $env:AUTOPROMPT_AGENT_CASTING = $castingJson
  1205. $env:ANTHROPIC_DEFAULT_OPUS_MODEL = [string]$casting.aliases.opus
  1206. $env:ANTHROPIC_DEFAULT_SONNET_MODEL = [string]$casting.aliases.sonnet
  1207. $env:ANTHROPIC_DEFAULT_HAIKU_MODEL = [string]$casting.aliases.haiku
  1208. if (-not [string]::IsNullOrEmpty($castingBaseUrl)) {
  1209. $env:ANTHROPIC_BASE_URL = $castingBaseUrl
  1210. }
  1211. if (-not [string]::IsNullOrEmpty($castingApiKeyEnv)) {
  1212. $env:ANTHROPIC_AUTH_TOKEN = $castingAuthToken
  1213. }
  1214. }
  1215. try {
  1216. $launchWorkingDirectory = (Get-Location).Path
  1217. if (-not [string]::IsNullOrEmpty($launchCmd)) {
  1218. $parts = @($launchCmd -split '\s+' | Where-Object { $_ -ne '' })
  1219. $exe = $parts[0]
  1220. $rest = @($parts | Select-Object -Skip 1)
  1221. $procArgs = @($rest + @('--agents', $agentDefinitionsJson, $mission))
  1222. } else {
  1223. $exe = $launcher
  1224. $procArgs = @('--agents', $agentDefinitionsJson, $mission)
  1225. }
  1226. $nativeArguments = Join-NativeArguments -Arguments $procArgs
  1227. $proc = Start-Process -FilePath $exe `
  1228. -ArgumentList $nativeArguments -PassThru -NoNewWindow `
  1229. -WorkingDirectory $launchWorkingDirectory
  1230. return (Wait-ChildWithHeartbeat -Proc $proc)
  1231. } catch {
  1232. # A launcher that cannot be executed (a bad --cmd/--launcher: user typo
  1233. # or missing alias) throws a TERMINATING error under 'Stop'. Mirror the
  1234. # bash exit 127 so it feeds the SAME poison-guard/relaunch path instead
  1235. # of unwinding the loop and crashing the supervisor with a stack trace.
  1236. Write-SupLog "launch failed: $($_.Exception.Message)"
  1237. return 127
  1238. } finally {
  1239. $env:AUTOPROMPT_UNATTENDED = $previousUnattended
  1240. $env:AUTOPROMPT_RESUME = $previousResume
  1241. $env:AUTOPROMPT_MODE = $previousMode
  1242. $env:AUTOPROMPT_RUN_NONCE = $previousRunNonce
  1243. $env:AUTOPROMPT_LEDGER_CHECK = $previousLedgerCheck
  1244. $env:AUTOPROMPT_SESSION_TOKEN = $previousSessionToken
  1245. $env:AUTOPROMPT_AGENTS = $previousAgents
  1246. $env:AUTOPROMPT_AGENT_CASTING = $previousAgentCasting
  1247. $env:AUTOPROMPT_CAPABILITY_ATTESTATION = $previousCapabilityAttestation
  1248. $env:AUTOPROMPT_PROVIDER = $previousProvider
  1249. $env:AUTOPROMPT_CLI_VERSION = $previousCliVersion
  1250. $env:AUTOPROMPT_PERMISSION_PROFILE = $previousPermissionProfile
  1251. $env:AUTOPROMPT_AGENT_DEFINITIONS_HASH = $previousAgentDefinitionsHash
  1252. $env:AUTOPROMPT_CASTING_HASH = $previousCastingHash
  1253. $env:ANTHROPIC_DEFAULT_OPUS_MODEL = $previousOpusModel
  1254. $env:ANTHROPIC_DEFAULT_SONNET_MODEL = $previousSonnetModel
  1255. $env:ANTHROPIC_DEFAULT_HAIKU_MODEL = $previousHaikuModel
  1256. $env:ANTHROPIC_BASE_URL = $previousBaseUrl
  1257. $env:ANTHROPIC_AUTH_TOKEN = $previousAuthToken
  1258. $env:CLAUDE_CODE_SUBAGENT_MODEL = $previousSubagentModel
  1259. $restoredModelPin = $env:CLAUDE_CODE_SUBAGENT_MODEL
  1260. if ([string]::IsNullOrEmpty($restoredModelPin)) { $restoredModelPin = 'UNSET' }
  1261. Write-SupLog "model-pin restored to $restoredModelPin"
  1262. if ($castingEnabled) { Write-SupLog 'model-casting environment restored' }
  1263. }
  1264. }
  1265. # Wait-ChildWithHeartbeat: poll a backgrounded child process for liveness +
  1266. # frontier-COUNT staleness, killing it on an idle-timeout so the outer relaunch
  1267. # loop RESUMEs it. Behavior-parallel to the supervisor.sh poll loop. Returns the
  1268. # child's exit code (or 0 if a heartbeat kill pre-empted a clean exit code - the
  1269. # outer loop then sees no count growth and treats it as a no-progress restart).
  1270. # The poll wakes on a RESPONSIVE 200ms slice so a fast-exiting child is detected
  1271. # promptly; the staleness evaluation runs only once per $heartbeatInterval of
  1272. # elapsed wall-clock, preserving the exact heartbeat cadence.
  1273. function Wait-ChildWithHeartbeat {
  1274. param($Proc)
  1275. $handle = $Proc.Handle # cache the OS handle so .ExitCode populates on exit
  1276. $nowEpoch = { [int64][Math]::Floor(([DateTimeOffset](Get-Date)).ToUnixTimeSeconds()) }
  1277. $childLaunchEpoch = & $nowEpoch
  1278. $lastProgress = & $nowEpoch
  1279. $lastEval = $lastProgress
  1280. $lastSeenCount = Get-FrontierCount
  1281. while (-not $Proc.HasExited) {
  1282. Start-Sleep -Milliseconds 200
  1283. if (Test-SentinelPresent) { break }
  1284. $now = & $nowEpoch
  1285. if (($now - $lastEval) -lt $heartbeatInterval) { continue }
  1286. $lastEval = $now
  1287. $curCount = Get-FrontierCount
  1288. if ($curCount -gt $lastSeenCount) {
  1289. $lastSeenCount = $curCount; $lastProgress = $now
  1290. } elseif (($now - $lastProgress) -ge $idleTimeout) {
  1291. Write-SupLog "HEARTBEAT: no frontier progress for >=${idleTimeout}s while alive and no sentinel -- killing to relaunch with RESUME (auto-continue an idle agent)."
  1292. Stop-ProcessTree -Proc $Proc
  1293. break
  1294. }
  1295. # PLAN-auto-compact-threshold: proactive supervisor-fired compaction check.
  1296. $compact = Request-CompactionIfNeeded -LaunchEpoch $childLaunchEpoch -Now $now
  1297. if ($compact.Force) {
  1298. 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."
  1299. try {
  1300. $tmp = (Join-Path $ledgerDir '.forced-reset.tmp')
  1301. "$now forced est_unhonored grace=$compactGrace" | Set-Content -LiteralPath $tmp -Encoding ascii
  1302. Move-Item -LiteralPath $tmp -Destination (Join-Path $ledgerDir '.forced-reset') -Force
  1303. } catch { }
  1304. try {
  1305. $tmp2 = "$compactStateFile.tmp"
  1306. "$now forced" | Set-Content -LiteralPath $tmp2 -Encoding ascii
  1307. Move-Item -LiteralPath $tmp2 -Destination $compactStateFile -Force
  1308. } catch { }
  1309. if (Test-Path -LiteralPath $compactRequestFile) { Remove-Item -LiteralPath $compactRequestFile -Force -ErrorAction SilentlyContinue }
  1310. Stop-ProcessTree -Proc $Proc
  1311. break
  1312. }
  1313. # F-SPEED steer-2 B3: PHASE WALL-CLOCK BUDGET check. Once per tick, when the
  1314. # SCOPE phase is active, consult phase-budget.js. Anchored to scope ENTRY, NOT
  1315. # reset by frontier growth. Fail-open: an absent node/module skips the block.
  1316. $scopeEl = Get-ScopePhaseElapsed
  1317. if ($null -ne $scopeEl -and (Test-Path -LiteralPath $phaseBudgetPath)) {
  1318. $reqAge = Get-ScopeConvergeRequestAge
  1319. $prior = 0
  1320. if (Test-Path -LiteralPath $scopeResetsFile) {
  1321. try {
  1322. $pf = (Get-Content -LiteralPath $scopeResetsFile -First 1 -ErrorAction Stop)
  1323. if ($null -ne $pf) { [void][int]::TryParse(([string]$pf).Trim(), [ref]$prior) }
  1324. } catch { $prior = 0 }
  1325. }
  1326. $landed = Get-ScopeLandedAngles
  1327. & node $phaseBudgetPath --verdict --phase scope --elapsed $scopeEl `
  1328. --soft $scopeSoftSec --hard $scopeHardSec --request-age $reqAge `
  1329. --grace $scopeGraceSec --prior-resets $prior --max-resets $maxScopeResets `
  1330. --landed $landed *> $null
  1331. $verdictCode = $LASTEXITCODE
  1332. $convergeReqFile = Join-Path $ledgerDir 'SCOPE-CONVERGE-REQUEST'
  1333. if ($verdictCode -eq 10) {
  1334. # SOFT breach: write the converge heads-up ONCE (idempotent), keep running.
  1335. if (-not (Test-Path -LiteralPath $convergeReqFile)) {
  1336. try {
  1337. $tmp = "$convergeReqFile.tmp"
  1338. "$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
  1339. Move-Item -LiteralPath $tmp -Destination $convergeReqFile -Force
  1340. } catch { }
  1341. Write-SupLog "SCOPE BUDGET soft breach at ${scopeEl}s (>= ${scopeSoftSec}s, frontier advancing) -- wrote SCOPE-CONVERGE-REQUEST (converge on landed=$landed); child NOT killed."
  1342. }
  1343. } elseif ($verdictCode -eq 20) {
  1344. # HARD/grace breach: durable marker (honest landed residual), bump counter, kill->RESUME.
  1345. try {
  1346. $breachFile = Join-Path $ledgerDir 'SCOPE-BUDGET-BREACH'
  1347. $tmp = "$breachFile.tmp"
  1348. "$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
  1349. Move-Item -LiteralPath $tmp -Destination $breachFile -Force
  1350. } catch { }
  1351. try {
  1352. $tmpR = "$scopeResetsFile.tmp"
  1353. "$($prior + 1)" | Set-Content -LiteralPath $tmpR -Encoding ascii
  1354. Move-Item -LiteralPath $tmpR -Destination $scopeResetsFile -Force
  1355. } catch { }
  1356. 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."
  1357. $script:state.ScopeTerminal = $true
  1358. Stop-ProcessTree -Proc $Proc
  1359. break
  1360. } elseif ($verdictCode -eq 30) {
  1361. # RE-BREACH past the reset cap: escalate honestly, never fake a roadmap.
  1362. try {
  1363. $lines = @(
  1364. "supervisor escalation: scope budget breached past MAX_SCOPE_RESETS=$maxScopeResets"
  1365. "scope_elapsed=$scopeEl hard=$scopeHardSec prior_resets=$prior landed=$landed"
  1366. 'converge unreachable -- landed angles surfaced as the honest residual; NO fabricated roadmap'
  1367. "ts=$((Get-Date).ToString())"
  1368. )
  1369. $lines -join [Environment]::NewLine | Set-Content -LiteralPath $escalateFile -Encoding ascii
  1370. } catch { }
  1371. Write-SupLog "SCOPE BUDGET escalation at ${scopeEl}s -- breached past MAX_SCOPE_RESETS=$maxScopeResets; landed=$landed surfaced as residual; killing and exiting 1."
  1372. $script:state.ScopeEscalate = $true
  1373. Stop-ProcessTree -Proc $Proc
  1374. break
  1375. }
  1376. }
  1377. }
  1378. try { $Proc.WaitForExit() } catch {}
  1379. $exit = 0
  1380. try { if ($Proc.HasExited) { $exit = $Proc.ExitCode } } catch { $exit = 0 }
  1381. if ($null -eq $exit) { $exit = 0 }
  1382. return $exit
  1383. }
  1384. # Legacy broad DONE-* matching is a DOWNGRADE honored only for a verified
  1385. # legacy resume: the operator opted in explicitly AND the ledger directory
  1386. # carries physical evidence of a pre-nonce run (legacy governance files a
  1387. # three-file new-format run never creates). A fresh or new-format directory
  1388. # fails closed so the downgrade can never weaken a current-format run.
  1389. if ($legacySentinel) {
  1390. $legacyEvidence = $false
  1391. foreach ($marker in @('BRIEF.md', 'AGENTS.md', 'bucketlist.md', 'ANCHOR.md')) {
  1392. if (Test-Path -LiteralPath (Join-Path $ledgerDir $marker) -PathType Leaf) {
  1393. $legacyEvidence = $true
  1394. break
  1395. }
  1396. }
  1397. if (-not $legacyEvidence) {
  1398. [Console]::Error.WriteLine("supervisor: AUTOPROMPT_LEGACY_SENTINEL=1 requires a verified legacy resume (legacy governance files under $ledgerDir); unset it for new runs")
  1399. return 2
  1400. }
  1401. }
  1402. if ([string]::IsNullOrEmpty($launcher) -and [string]::IsNullOrEmpty($launchCmd) -and -not $dryRun) {
  1403. [Console]::Error.WriteLine('supervisor: no launch command (use --cmd "<your CLI>" / AUTOPROMPT_LAUNCH_CMD, or --launcher apidemo|codexdemo / AUTOPROMPT_LAUNCHER)')
  1404. return 2
  1405. }
  1406. $launcherLabel =
  1407. if (-not [string]::IsNullOrEmpty($launchCmd)) { $launchCmd }
  1408. elseif (-not [string]::IsNullOrEmpty($launcher)) { $launcher }
  1409. else { '<dry-run>' }
  1410. Write-SupLog "starting: launcher=$launcherLabel ledger=$ledgerDir mission=`"$mission`""
  1411. 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."
  1412. # Snapshot pre-existing DONE-* PATHS FIRST, THEN quarantine. Order matters: the
  1413. # snapshot must see the dir as it was before any rename, so a failed rename still
  1414. # leaves the path recorded (and vetoed). Quarantine prunes each SUCCESSFULLY
  1415. # renamed path back out of the snapshot, so the net invariant after this pair is:
  1416. # a path is vetoed IFF its stale occupant still physically exists.
  1417. Save-PreExistingSentinels
  1418. Move-StaleSentinelAside
  1419. # EDIT 23: seed the per-conversation session token ONCE, before the relaunch loop.
  1420. # An env-supplied token (operator or a prior same-conversation export) wins and is
  1421. # persisted to the durable file; else a previously-harvested token is read back;
  1422. # else the token stays empty and the first SCRIBE-run resolver MINTS one. Fail-soft:
  1423. # an unwritable/unreadable token file never aborts the run.
  1424. if (-not [string]::IsNullOrEmpty($sessionToken)) {
  1425. try { Set-Content -LiteralPath $sessionTokenFile -Value $sessionToken -Encoding ascii -ErrorAction Stop } catch {}
  1426. } elseif (Test-Path -LiteralPath $sessionTokenFile) {
  1427. try {
  1428. $fileToken = (Get-Content -LiteralPath $sessionTokenFile -First 1 -ErrorAction Stop)
  1429. if ($null -ne $fileToken) { $sessionToken = ([string]$fileToken).Trim() }
  1430. } catch {}
  1431. }
  1432. [long[]]$restartTimes = @() # epoch seconds of recent restarts (no progress)
  1433. $lastFrontier = Get-FrontierCount
  1434. $backoff = $retryBase
  1435. while ($true) {
  1436. if (Test-SentinelPresent) {
  1437. Write-SupLog 'DONE-sentinel present -- run complete, halting cleanly.'
  1438. return 0
  1439. }
  1440. $exitCode = Invoke-Launcher
  1441. # Scope budget termination is checked before sentinels so a breach cannot be
  1442. # masked by output written during the same tick or poison-relaunch the mission.
  1443. if ($script:state.ScopeEscalate) {
  1444. return 1
  1445. }
  1446. if ($script:state.ScopeTerminal) {
  1447. Write-SupLog 'SCOPE BUDGET terminal stop -- no same-mission relaunch will consume another worker.'
  1448. return 124
  1449. }
  1450. if (Test-SentinelPresent) {
  1451. Write-SupLog "DONE-sentinel present after launch (exit $exitCode) -- run complete, halting cleanly."
  1452. return 0
  1453. }
  1454. # P4 (MANDATORY terminal caller, behavior-parallel to supervisor.sh V5): the
  1455. # child EXITED with no DONE-sentinel -- a TERMINAL boundary for that child. Write
  1456. # the RUN-ENDED marker so a ledger audit treats this as run-ended, then (real-run
  1457. # only) run a best-effort terminal IDLE-FINISH audit. RUN-ENDED is the marker
  1458. # autoprompt-ledger-check.js reads to set runEnded=true. Written every exit-
  1459. # without-sentinel; idempotent (overwritten each exit). The clean-DONE path
  1460. # short-circuits at the sentinel checks above, so RUN-ENDED is only ever written
  1461. # when the run is genuinely not done.
  1462. try {
  1463. "run-ended exit=$exitCode ts=$(Get-Date)" | Set-Content -LiteralPath (Join-Path $ledgerDir 'RUN-ENDED') -Encoding ascii
  1464. } catch {}
  1465. if (-not $dryRun -and (Test-Path -LiteralPath $ledgerCheckPath)) {
  1466. # Best-effort loud-log: the marker alone is sufficient for the rule to fire on
  1467. # the NEXT audit, so this node call's non-zero exit is informational; the
  1468. # relaunch happens regardless.
  1469. try {
  1470. & node $ledgerCheckPath --ledger-dir $ledgerDir --transcript-dir $ledgerDir --terminal *> $null
  1471. if ($LASTEXITCODE -ne 0) {
  1472. Write-SupLog 'IDLE-FINISH terminal audit flagged a P0 (run ended with open work, no live agent) -- relaunching with RESUME to re-drive.'
  1473. }
  1474. } catch {}
  1475. }
  1476. $now = [int64][Math]::Floor(([DateTimeOffset](Get-Date)).ToUnixTimeSeconds())
  1477. $curFrontier = Get-FrontierCount
  1478. # EDIT 23: HARVEST the resolver-minted session token after a launch when the
  1479. # supervisor holds none yet. The SCRIBE-run --resolve-prompt-dir CLI writes the
  1480. # marker "<LedgerDir>/.session-current" as "session_NN <token>" (two
  1481. # whitespace-separated fields -- the EDIT 7 contract). Read the 2nd field and
  1482. # persist it so the NEXT launch re-exports the SAME token and a 2nd prompt
  1483. # rejoins the same session_NN. Fail-soft: an absent/corrupt marker (no 2nd
  1484. # field) leaves the token empty and the next launch mints again.
  1485. if ([string]::IsNullOrEmpty($sessionToken)) {
  1486. $markerPath = Join-Path $ledgerDir '.session-current'
  1487. if (Test-Path -LiteralPath $markerPath) {
  1488. try {
  1489. $markerLine = (Get-Content -LiteralPath $markerPath -First 1 -ErrorAction Stop)
  1490. if ($null -ne $markerLine) {
  1491. $fields = ([string]$markerLine).Trim() -split '\s+'
  1492. if ($fields.Count -ge 2 -and -not [string]::IsNullOrEmpty($fields[1])) {
  1493. $sessionToken = $fields[1]
  1494. try { Set-Content -LiteralPath $sessionTokenFile -Value $sessionToken -Encoding ascii -ErrorAction Stop } catch {}
  1495. }
  1496. }
  1497. } catch {}
  1498. }
  1499. }
  1500. Write-SupLog "launcher exited ($exitCode); frontier $lastFrontier -> $curFrontier; no sentinel -- relaunching with RESUME."
  1501. if ($curFrontier -gt $lastFrontier) {
  1502. # Healthy-long: progress was made. Reset the poison window and backoff.
  1503. $restartTimes = @()
  1504. $backoff = $retryBase
  1505. $lastFrontier = $curFrontier
  1506. } else {
  1507. # No progress since the last launch. Record this restart in the rolling
  1508. # window and check the poison guard.
  1509. $newTimes = New-Object System.Collections.Generic.List[long]
  1510. $rapid = 1
  1511. foreach ($t in $restartTimes) {
  1512. if (($now - $t) -lt $window) {
  1513. $newTimes.Add($t)
  1514. $rapid += 1
  1515. }
  1516. }
  1517. $newTimes.Add($now)
  1518. $restartTimes = $newTimes.ToArray()
  1519. if ($rapid -ge $maxRestarts) {
  1520. Write-SupLog "POISON: $rapid restarts within ${window}s with NO frontier progress -- escalating, not relaunching."
  1521. $escalateTs = (Get-Date).ToString()
  1522. $lines = @(
  1523. 'supervisor escalation: crash-loop with no frontier progress'
  1524. "restarts_in_window=$rapid window_s=$window last_exit=$exitCode frontier=$curFrontier"
  1525. "ts=$escalateTs"
  1526. )
  1527. $lines -join [Environment]::NewLine | Set-Content -LiteralPath $escalateFile -Encoding ascii
  1528. return 1
  1529. }
  1530. # Exponential backoff, capped, between unproductive relaunches.
  1531. if ($backoff -gt 0) { Start-Sleep -Seconds $backoff }
  1532. $next = $backoff * 2
  1533. if ($next -gt $retryCap) { $next = $retryCap }
  1534. $backoff = $next
  1535. }
  1536. }
  1537. }
  1538. # Only auto-run when invoked as a script, not when dot-sourced by the test suite.
  1539. if ($MyInvocation.InvocationName -ne '.') {
  1540. $exit = Invoke-Supervisor -Argv $args
  1541. exit $exit
  1542. }
agents/claude/workflow/supervisor.sh · Bundled script · 1,272 lines · 1 finding marked
  1. #!/bin/sh
  2. # autoprompt supervisor - external auto-relaunch for a one-sitting unattended run.
  3. #
  4. # This is a STANDALONE OS PROCESS, NOT a Claude Code hook. It touches no
  5. # settings.json, registers no hook, and is launched by the operator (or a
  6. # tmux/nohup line). It honors the global no-hooks rule.
  7. #
  8. # It relaunches the autoprompt CLI with RESUME on any unexpected exit, loops
  9. # until the JANITOR has written the DONE-sentinel (autoprompt/DONE-<nonce>),
  10. # and has a crash-loop/poison-restart guard that distinguishes:
  11. # - a FINISHED run (sentinel present) -> clean halt
  12. # - a HEALTHY-LONG run (frontier advances) -> keep relaunching, no escalation
  13. # - a TRULY-STUCK run (no frontier progress) -> escalate, stop relaunching
  14. #
  15. # Usage:
  16. # supervisor.sh --launcher apidemo|codexdemo "<mission>"
  17. # supervisor.sh --cmd "claude --dangerously-skip-permissions -p" "<mission>"
  18. # supervisor.sh --agents "auto:strong,cheap" --model-registry ~/.claude/autoprompt-models.json --cmd "claude -p" "<mission>"
  19. #
  20. # The launch command is resolved in this precedence:
  21. # 1. --cmd "<command>" / AUTOPROMPT_LAUNCH_CMD (used VERBATIM, word-split,
  22. # with the mission appended) -- the explicit, copy-pasteable escape hatch.
  23. # 2. --launcher <label> / AUTOPROMPT_LAUNCHER (the bare command name, e.g.
  24. # apidemo|codexdemo, exec'd directly -- requires that name to be on PATH).
  25. # A fresh user with no apidemo/codexdemo alias uses --cmd with their real CLI.
  26. # Env (all optional):
  27. # AUTOPROMPT_LAUNCH_CMD verbatim launch command (overrides --launcher)
  28. # AUTOPROMPT_LAUNCHER default launcher label if --launcher is omitted
  29. # AUTOPROMPT_AGENTS off | auto | <list> | auto:<list> (default off)
  30. # AUTOPROMPT_MODEL_REGISTRY optional registry path; defaults to ~/.claude/autoprompt-models.json for auto modes
  31. # LEDGER_DIR default "autoprompt"
  32. # SENTINEL explicit sentinel glob/patterns (default <LEDGER_DIR>/DONE-*).
  33. # When SET, the value is WORD-SPLIT into one-or-more shell
  34. # globs (an explicit multi-pattern escape hatch) and so MUST
  35. # NOT contain spaces in any single path. When UNSET (the
  36. # default -- every real run) the glob is "$LEDGER_DIR"/DONE-*
  37. # with the DIR QUOTED and only the * unquoted, so a LEDGER_DIR
  38. # containing spaces (e.g. a Windows path) still matches its
  39. # DONE-* sentinel. NOTE: the .ps1 port passes an explicit
  40. # SENTINEL as ONE Get-ChildItem -Path pattern (no word-split),
  41. # so a space-separated multi-pattern SENTINEL is a .sh-only
  42. # feature; on PowerShell use a single dir-wildcard instead.
  43. # MAX_RESTARTS rapid restarts allowed in WINDOW without progress (default 5)
  44. # WINDOW rolling window seconds for the poison guard (default 600)
  45. # RETRY_BASE base backoff seconds between relaunches (default 5; 0 in tests)
  46. # RETRY_CAP max backoff seconds (default 300)
  47. # AUTOPROMPT_KEEP_MODEL_PIN when "1", SKIP neutralizing CLAUDE_CODE_SUBAGENT_MODEL
  48. # for the child CLI. By DEFAULT (unset) the supervisor strips
  49. # CLAUDE_CODE_SUBAGENT_MODEL from the CHILD ONLY (env -u) so the
  50. # skill's `model: inherit` contract resolves to the real session/
  51. # --model selection instead of the operator's force-pin. Set to 1
  52. # to preserve the operator's pin and let it reach the child as before.
  53. # AUTOPROMPT_MODE tokensaver | wide | billionaire | custom (default
  54. # tokensaver). WIDE and BILLIONAIRE share wide semantics.
  55. # CUSTOM requires a positive numeric
  56. # AUTOPROMPT_MAX_CONCURRENT value, floors it to a whole-agent
  57. # ceiling, and passes both values through to the harness.
  58. # The 5-level topology (L0 conductor -> L1 coordinators -> L2 managers -> L3
  59. # executors -> L4 leaves) lives in the harness; rule 68 (L1 never executes) and
  60. # rule 67 (single-block spawns) are enforced there. This OS-level supervisor only
  61. # relaunches the L0 entry process and passes the mode through; it spawns no agents.
  62. # Test hooks (only honored with --dry-run):
  63. # FAKE_EXITS space-separated exit codes the fake launcher returns in turn
  64. # FAKE_SENTINEL_AFTER write the sentinel before the launch with this 1-based index
  65. # FAKE_POISON 1 => fake never advances the frontier and always exits non-zero
  66. set -u
  67. LAUNCHER="${AUTOPROMPT_LAUNCHER:-}"
  68. LAUNCH_CMD="${AUTOPROMPT_LAUNCH_CMD:-}"
  69. AGENTS_SELECTOR="${AUTOPROMPT_AGENTS:-off}"
  70. MODEL_REGISTRY="${AUTOPROMPT_MODEL_REGISTRY:-}"
  71. PROVIDER_CAPABILITY="${AUTOPROMPT_PROVIDER_CAPABILITY:-}"
  72. LEDGER_DIR="${LEDGER_DIR:-autoprompt}"
  73. MAX_RESTARTS="${MAX_RESTARTS:-5}"
  74. WINDOW="${WINDOW:-600}"
  75. RETRY_BASE="${RETRY_BASE:-5}"
  76. RETRY_CAP="${RETRY_CAP:-300}"
  77. IDLE_TIMEOUT="${AUTOPROMPT_IDLE_TIMEOUT:-1800}" # seconds of frontier-count staleness while alive -> kill -> relaunch (continue)
  78. HEARTBEAT_INTERVAL="${AUTOPROMPT_HEARTBEAT_INTERVAL:-60}" # poll cadence while the child is alive
  79. # V4 (long-tool-call guard): IDLE_TIMEOUT defaults to 1800s (30 min) precisely so a
  80. # long-but-progressing build/test does NOT trip the heartbeat - the frontier count
  81. # grows when ANY artifact is written, so a progressing run resets the timer well before
  82. # 30 min. Operators with long single atomic steps raise AUTOPROMPT_IDLE_TIMEOUT.
  83. # PLAN-auto-compact-threshold: proactive, SUPERVISOR-FIRED compaction below the harness
  84. # ~400k ceiling. The supervisor observes the parent's context size from OUTSIDE (it
  85. # parses the parent's own Claude Code session transcript; watermark/ledger-byte
  86. # fallbacks) and, when it crosses COMPACT_AT, writes COMPACT-REQUEST (a heads-up so the
  87. # parent checkpoints + STOPS its subagents at the next gate boundary) and, on grace
  88. # timeout, fires the kill->RESUME itself (the parent cannot /compact itself).
  89. COMPACT_AT="${AUTOPROMPT_COMPACT_AT:-200000}" # proactive compaction watermark (tokens); below the harness ~400k ceiling
  90. BYTES_PER_TOKEN="${AUTOPROMPT_BYTES_PER_TOKEN:-4}" # bytes->tokens divisor for the fallback proxies
  91. COMPACT_COOLDOWN="${AUTOPROMPT_COMPACT_COOLDOWN:-120}" # seconds after a compaction before another may be requested
  92. COMPACT_GRACE="${AUTOPROMPT_COMPACT_GRACE:-180}" # seconds to let the parent honor a request before the forced fallback
  93. EXTERNAL_COMPACT_DELTA="${AUTOPROMPT_EXTERNAL_COMPACT_DELTA:-50000}" # an estimate DROP >= this across ticks = a harness-fired compaction
  94. # Validate COMPACT_AT to a positive integer; an absurd/non-numeric value falls back to
  95. # the default (never disables the guard, never fires every tick -- the zero-threshold trap).
  96. case "$COMPACT_AT" in (*[!0-9]*|"") COMPACT_AT=200000 ;; esac
  97. [ "$COMPACT_AT" -gt 0 ] 2>/dev/null || COMPACT_AT=200000
  98. [ "$COMPACT_AT" -lt 10000000 ] 2>/dev/null || COMPACT_AT=200000
  99. case "$BYTES_PER_TOKEN" in (*[!0-9]*|""|0) BYTES_PER_TOKEN=4 ;; esac
  100. # F-SPEED steer-2 B3: PHASE WALL-CLOCK BUDGET for the SCOPE phase. IDLE_TIMEOUT
  101. # (above) fires only on frontier STALENESS; a slow scope can keep producing
  102. # ROADMAP.md and roadmap-scout-*.md checkpoints, resetting the idle clock while never
  103. # bounded. This budget is anchored to scope-phase ENTRY and NOT reset by frontier
  104. # growth - the exact hole IDLE_TIMEOUT leaves. Soft => a converge REQUEST; hard (or an
  105. # unhonored converge past grace) => a durable breach marker + REAL kill->RESUME on the
  106. # honest landed set; a re-breach past the reset cap => SUPERVISOR-ESCALATE. It NEVER
  107. # fabricates a roadmap. Each knob is validated with the SAME positive-integer idiom as
  108. # COMPACT_AT: an absurd/non-numeric value falls back to the default (never disables the
  109. # guard, never a zero-budget trap that fires every tick).
  110. SCOPE_SOFT_SEC="${AUTOPROMPT_SCOPE_SOFT_SEC:-60}" # bounded scope target
  111. SCOPE_HARD_SEC="${AUTOPROMPT_SCOPE_HARD_SEC:-300}" # ordinary multi-surface ceiling
  112. SCOPE_GRACE_SEC="${AUTOPROMPT_SCOPE_GRACE:-60}" # converge-request grace
  113. MAX_SCOPE_RESETS="${AUTOPROMPT_MAX_SCOPE_RESETS:-1}" # budget-forced scope resets before escalation
  114. case "$SCOPE_SOFT_SEC" in (*[!0-9]*|"") SCOPE_SOFT_SEC=60 ;; esac
  115. [ "$SCOPE_SOFT_SEC" -gt 0 ] 2>/dev/null || SCOPE_SOFT_SEC=60
  116. case "$SCOPE_HARD_SEC" in (*[!0-9]*|"") SCOPE_HARD_SEC=300 ;; esac
  117. [ "$SCOPE_HARD_SEC" -gt 0 ] 2>/dev/null || SCOPE_HARD_SEC=300
  118. case "$SCOPE_GRACE_SEC" in (*[!0-9]*|"") SCOPE_GRACE_SEC=60 ;; esac
  119. [ "$SCOPE_GRACE_SEC" -ge 0 ] 2>/dev/null || SCOPE_GRACE_SEC=60
  120. case "$MAX_SCOPE_RESETS" in (*[!0-9]*|"") MAX_SCOPE_RESETS=1 ;; esac
  121. [ "$MAX_SCOPE_RESETS" -ge 0 ] 2>/dev/null || MAX_SCOPE_RESETS=1
  122. # Execution mode selects the 5-level topology's wave cap. Unknown modes retain the
  123. # safe tokensaver fallback. CUSTOM is different: it is an explicit request for a
  124. # caller-supplied ceiling, so a missing or invalid ceiling fails closed.
  125. AUTOPROMPT_MODE="${AUTOPROMPT_MODE:-tokensaver}"
  126. case "$AUTOPROMPT_MODE" in
  127. tokensaver) FANOUT="up to 6 live per wave"; L3_TRACKS="parallel" ;;
  128. wide|billionaire) FANOUT="wide up to the runtime ceiling"; L3_TRACKS="parallel" ;;
  129. custom)
  130. CUSTOM_MAX=$(awk -v raw="${AUTOPROMPT_MAX_CONCURRENT:-}" 'BEGIN {
  131. if (raw ~ /^[+]?[0-9]+([.][0-9]+)?$/ && (raw + 0) >= 1) printf "%d", int(raw + 0)
  132. }')
  133. if [ -z "$CUSTOM_MAX" ]; then
  134. echo "supervisor: custom mode requires a positive numeric AUTOPROMPT_MAX_CONCURRENT" >&2
  135. exit 2
  136. fi
  137. AUTOPROMPT_MAX_CONCURRENT="$CUSTOM_MAX"
  138. export AUTOPROMPT_MAX_CONCURRENT
  139. FANOUT="up to $CUSTOM_MAX live per wave (AUTOPROMPT_MAX_CONCURRENT)"
  140. L3_TRACKS="parallel"
  141. ;;
  142. *) AUTOPROMPT_MODE="tokensaver"; FANOUT="up to 6 live per wave"; L3_TRACKS="parallel" ;;
  143. esac
  144. # EDIT 23a: the supervisor sits in .../workflow/ next to autoprompt-ledger-check.js,
  145. # so it derives that resolver's ABSOLUTE path from its own location and exports it to
  146. # the child (gate.js EDIT 4a reads AUTOPROMPT_LEDGER_CHECK; the SCRIBE/JANITOR briefs
  147. # interpolate it to RUN `node "$AUTOPROMPT_LEDGER_CHECK" --resolve-prompt-dir ...`).
  148. # An operator override wins; otherwise the script-dir sibling is used. CDPATH= guards
  149. # a hostile CDPATH from redirecting the cd, and -- ends option parsing for odd $0.
  150. SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
  151. LEDGER_CHECK_PATH="${AUTOPROMPT_LEDGER_CHECK:-$SCRIPT_DIR/autoprompt-ledger-check.js}"
  152. MODEL_CASTING_PATH="${AUTOPROMPT_MODEL_CASTING:-$SCRIPT_DIR/model-casting.js}"
  153. AGENT_DEFINITIONS_PATH="${AUTOPROMPT_AGENT_DEFINITIONS_DIR:-$SCRIPT_DIR/../agents}"
  154. AGENT_DEFINITIONS_CLI="${AUTOPROMPT_AGENT_DEFINITIONS_CLI:-$SCRIPT_DIR/agent-definitions-cli.js}"
  155. # F-SPEED steer-2 B3: the phase-budget verdict CLI sits next to the ledger-check in
  156. # .../workflow/. An operator override wins; otherwise the script-dir sibling is used.
  157. # Consulted once per heartbeat tick, scope-phase only, and guarded by [ -r ] so an
  158. # absent node/module fail-opens to IDLE_TIMEOUT alone (same posture as the ledger-check).
  159. PHASE_BUDGET_PATH="${AUTOPROMPT_PHASE_BUDGET:-$SCRIPT_DIR/phase-budget.js}"
  160. # EDIT 23: per-conversation session token, defaulted here for `set -u` safety. The
  161. # supervisor is the durable producer across relaunches of one conversation: it seeds
  162. # this token (env > file > empty) before the loop and HARVESTs the resolver-minted
  163. # marker token after each launch, re-exporting the SAME token so a 2nd prompt lands
  164. # in the SAME session_NN (SPEC-1 S2). RESUME is always same-session regardless.
  165. AUTOPROMPT_SESSION_TOKEN="${AUTOPROMPT_SESSION_TOKEN:-}"
  166. INITIAL_RESUME="${AUTOPROMPT_RESUME:-}"
  167. case "$(printf '%s' "$INITIAL_RESUME" | tr '[:upper:]' '[:lower:]')" in
  168. 1|true|yes) INITIAL_RESUME=1 ;;
  169. *) INITIAL_RESUME=0 ;;
  170. esac
  171. SCOPE_MISSION_BINDING="unbound"
  172. RUN_NONCE="${AUTOPROMPT_RUN_NONCE:-}"
  173. LEGACY_SENTINEL="${AUTOPROMPT_LEGACY_SENTINEL:-0}"
  174. SCOPE_BUDGET_TERMINAL=0
  175. DRY_RUN=0
  176. MISSION=""
  177. require_flag_value() {
  178. [ "$2" -ge 2 ] && return 0
  179. echo "supervisor: $1 requires a value" >&2
  180. exit 2
  181. }
  182. while [ $# -gt 0 ]; do
  183. case "$1" in
  184. --launcher) require_flag_value "$1" "$#"; LAUNCHER="$2"; shift 2 ;;
  185. --cmd) require_flag_value "$1" "$#"; LAUNCH_CMD="$2"; shift 2 ;;
  186. --agents) require_flag_value "$1" "$#"; AGENTS_SELECTOR="$2"; shift 2 ;;
  187. --model-registry) require_flag_value "$1" "$#"; MODEL_REGISTRY="$2"; shift 2 ;;
  188. --provider-capability) require_flag_value "$1" "$#"; PROVIDER_CAPABILITY="$2"; shift 2 ;;
  189. --dry-run) DRY_RUN=1; shift ;;
  190. --ledger-dir) require_flag_value "$1" "$#"; LEDGER_DIR="$2"; shift 2 ;;
  191. --) shift; MISSION="$*"; break ;;
  192. -*) echo "supervisor: unknown flag $1" >&2; exit 2 ;;
  193. *) MISSION="$1"; shift ;;
  194. esac
  195. done
  196. if command -v node >/dev/null 2>&1; then
  197. SCOPE_MISSION_BINDING=$(printf '%s' "$MISSION" | node -e '
  198. const crypto = require("crypto")
  199. let input = ""
  200. process.stdin.setEncoding("utf8")
  201. process.stdin.on("data", chunk => { input += chunk })
  202. process.stdin.on("end", () => process.stdout.write("sha256:" + crypto.createHash("sha256").update(input, "utf8").digest("hex")))
  203. ' 2>/dev/null || echo unbound)
  204. fi
  205. if [ "$LEGACY_SENTINEL" != "1" ]; then
  206. case "$RUN_NONCE" in
  207. NONCE-[A-Za-z0-9_-]*) ;;
  208. "")
  209. if command -v node >/dev/null 2>&1; then
  210. RUN_NONCE="NONCE-$(node -e 'process.stdout.write(require("crypto").randomBytes(16).toString("hex"))' 2>/dev/null || true)"
  211. fi
  212. case "$RUN_NONCE" in
  213. NONCE-[A-Za-z0-9_-]*) ;;
  214. *) echo "supervisor: could not mint a cryptographically strong activation nonce" >&2; exit 2 ;;
  215. esac
  216. ;;
  217. *) echo "supervisor: AUTOPROMPT_RUN_NONCE is malformed" >&2; exit 2 ;;
  218. esac
  219. fi
  220. # Sentinel matching has two modes. DEFAULT (SENTINEL unset -- every real run):
  221. # the glob is "$LEDGER_DIR"/DONE-* iterated with the DIR QUOTED and only the *
  222. # unquoted, so a LEDGER_DIR containing spaces (a Windows path) still matches its
  223. # own DONE-* sentinel. EXPLICIT (SENTINEL set): the value is word-split into one
  224. # or more shell globs -- an intentional multi-pattern escape hatch -- so no single
  225. # path in it may contain spaces. SENTINEL_SET records which mode is active; the
  226. # unquoted word-split is confined to the explicit case where the user opted in.
  227. if [ -n "${SENTINEL:-}" ]; then
  228. SENTINEL_SET=1
  229. SENTINEL_GLOB="$SENTINEL"
  230. else
  231. SENTINEL_SET=0
  232. SENTINEL_GLOB="$LEDGER_DIR/DONE-*" # reference/logging only; never iterated unquoted
  233. fi
  234. ESCALATE_FILE="$LEDGER_DIR/SUPERVISOR-ESCALATE"
  235. SNAPSHOT_FILE="$LEDGER_DIR/.sentinel-snapshot"
  236. # EDIT 23: the durable session-token store, under the ledger dir so it survives across
  237. # relaunches of one conversation. Seeded before the loop, harvested after each launch.
  238. SESSION_TOKEN_FILE="$LEDGER_DIR/.session-token"
  239. # PLAN-auto-compact-threshold path vars. Discovery is CWD-AGNOSTIC and slug-free: it
  240. # matches the supervisor's own RUN_CWD (POSIX on gitbash) against each transcript's
  241. # embedded OS-native "cwd" after normalization -- NO slug derivation, NO launcher edit.
  242. RUN_CWD="${RUN_CWD:-$PWD}" # run cwd; matched against each transcript's embedded "cwd"
  243. PARENT_TRANSCRIPT="${AUTOPROMPT_PARENT_TRANSCRIPT:-}" # OPTIONAL explicit override of the parent .jsonl path
  244. WATERMARK_FILE="$LEDGER_DIR/.context-watermark" # FALLBACK: parent-emitted watermark (only when transcript unreadable)
  245. COMPACT_REQUEST_FILE="$LEDGER_DIR/COMPACT-REQUEST"
  246. COMPACT_STATE_FILE="$LEDGER_DIR/.compaction-state" # holds: last_compact_epoch + last seen estimate (for cooldown + drop-detection)
  247. # Scope-budget state under the ledger dir, durable across relaunches. The start epoch
  248. # does not reset on frontier growth; the reset counter clears once build evidence lands.
  249. SCOPE_PHASE_START_FILE="$LEDGER_DIR/.scope-phase-start"
  250. SCOPE_RESETS_FILE="$LEDGER_DIR/.scope-forced-resets"
  251. SNAPSHOT_OK=0
  252. mkdir -p "$LEDGER_DIR" 2>/dev/null || true
  253. # Supervisor start epoch (captured BEFORE the first launch). It is no longer part
  254. # of the stale-sentinel guarantee (see below) -- it is kept only to name the
  255. # quarantine target (superseded-<epoch>-...) and is read fail-safe: if `date +%s`
  256. # fails we leave it EMPTY (not 0), so the quarantine name degrades to
  257. # superseded-unknown-... rather than colliding on a fixed "0".
  258. SUPERVISOR_START_EPOCH=$(date +%s 2>/dev/null || echo)
  259. # THE stale-sentinel guarantee is a STARTUP SNAPSHOT, not mtime. Before the first
  260. # launch we record every pre-existing DONE-* PATH into $SNAPSHOT_FILE.
  261. # sentinel_present then REFUSES any DONE-* whose path is still in that snapshot --
  262. # regardless of mtime. THE LIVE INVARIANT: a path stays in the snapshot IFF its
  263. # stale occupant still physically exists. Quarantine renames each pre-existing
  264. # done:true sentinel aside; on a SUCCESSFUL rename the path is now empty, so it is
  265. # PRUNED from the snapshot -- the only thing that can later appear there is a
  266. # genuinely fresh this-run sentinel, which must be honored (otherwise the
  267. # same-activation DONE-<nonce> - the supervisor-minted CSPRNG nonce re-exported
  268. # unchanged to every relaunched child, with NO clock - would be vetoed forever
  269. # and the supervisor would relaunch without end --
  270. # the livelock). A path whose rename FAILED is NOT pruned: its stale occupant is
  271. # still there, so it stays vetoed and a failed quarantine degrades to RELAUNCH,
  272. # never a false halt. The mtime `>=start` belt is gone -- it could not backstop
  273. # the same-second class, which is the whole reason this defense exists. FAIL-SAFE:
  274. # if the snapshot cannot be written or read, ALL DONE-* are treated as suspect ->
  275. # relaunch, never halt.
  276. log() { echo "[supervisor $(date '+%Y-%m-%dT%H:%M:%S' 2>/dev/null)] $*"; }
  277. CASTING_ENABLED=0
  278. CASTING_JSON=""
  279. CASTING_OPUS=""
  280. CASTING_SONNET=""
  281. CASTING_HAIKU=""
  282. CASTING_BASE_URL=""
  283. CASTING_API_KEY_ENV=""
  284. CASTING_AUTH_TOKEN=""
  285. CAPABILITY_PROVIDER="claude-code"
  286. CAPABILITY_CLI_VERSION="unknown"
  287. CAPABILITY_PERMISSION_PROFILE="default"
  288. CAPABILITY_AGENT_DEFINITIONS_HASH="unknown"
  289. CAPABILITY_CASTING_HASH="unknown"
  290. CAPABILITY_EFFORT_STATUS="inherited-only"
  291. CAPABILITY_EFFORT_SOURCE="session-inheritance"
  292. AUTOPROMPT_CAPABILITY_ATTESTATION="${AUTOPROMPT_CAPABILITY_ATTESTATION:-}"
  293. casting_json_field() {
  294. field="$1"
  295. printf '%s' "$CASTING_JSON" | node -e '
  296. let input = ""
  297. process.stdin.setEncoding("utf8")
  298. process.stdin.on("data", chunk => { input += chunk })
  299. process.stdin.on("end", () => {
  300. let value = JSON.parse(input)
  301. for (const key of process.argv[1].split(".")) value = value == null ? undefined : value[key]
  302. if (value != null) process.stdout.write(String(value))
  303. })
  304. ' "$field"
  305. }
  306. resolve_model_casting() {
  307. control=$(printf '%s' "$AGENTS_SELECTOR" | tr '[:upper:]' '[:lower:]')
  308. [ -z "$control" ] || [ "$control" = "off" ] || {
  309. command -v node >/dev/null 2>&1 || {
  310. echo "supervisor: model casting requires node on PATH" >&2
  311. return 2
  312. }
  313. [ -r "$MODEL_CASTING_PATH" ] || {
  314. echo "supervisor: model casting resolver is not readable: $MODEL_CASTING_PATH" >&2
  315. return 2
  316. }
  317. set -- "$MODEL_CASTING_PATH" --selector "$AGENTS_SELECTOR"
  318. if [ -n "$MODEL_REGISTRY" ]; then
  319. set -- "$@" --registry "$MODEL_REGISTRY"
  320. fi
  321. if [ -n "$PROVIDER_CAPABILITY" ]; then
  322. set -- "$@" --provider-capability "$PROVIDER_CAPABILITY"
  323. fi
  324. CASTING_JSON=$(node "$@") || return 2
  325. CASTING_ENABLED=$(casting_json_field enabled) || return 2
  326. [ "$CASTING_ENABLED" = "true" ] || return 0
  327. CASTING_OPUS=$(casting_json_field aliases.opus) || return 2
  328. CASTING_SONNET=$(casting_json_field aliases.sonnet) || return 2
  329. CASTING_HAIKU=$(casting_json_field aliases.haiku) || return 2
  330. CASTING_BASE_URL=$(casting_json_field endpoint.baseUrl) || return 2
  331. CASTING_API_KEY_ENV=$(casting_json_field endpoint.apiKeyEnv) || return 2
  332. if [ "${AUTOPROMPT_KEEP_MODEL_PIN:-0}" = "1" ] && [ -n "${CLAUDE_CODE_SUBAGENT_MODEL:-}" ]; then
  333. echo "supervisor: AUTOPROMPT_KEEP_MODEL_PIN=1 conflicts with model casting because CLAUDE_CODE_SUBAGENT_MODEL is set" >&2
  334. return 2
  335. fi
  336. if [ -n "$CASTING_API_KEY_ENV" ]; then
  337. CASTING_AUTH_TOKEN=$(printenv "$CASTING_API_KEY_ENV" 2>/dev/null || true)
  338. [ -n "$CASTING_AUTH_TOKEN" ] || {
  339. echo "supervisor: model casting credential environment variable is unset or empty: $CASTING_API_KEY_ENV" >&2
  340. return 2
  341. }
  342. fi
  343. }
  344. }
  345. sha256_file() {
  346. file="$1"
  347. node -e '
  348. const fs = require("fs")
  349. const crypto = require("crypto")
  350. const file = process.argv[1]
  351. process.stdout.write("sha256:" + crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"))
  352. ' "$file"
  353. }
  354. sha256_text() {
  355. node -e '
  356. const crypto = require("crypto")
  357. process.stdin.setEncoding("utf8")
  358. let input = ""
  359. process.stdin.on("data", chunk => { input += chunk })
  360. process.stdin.on("end", () => process.stdout.write("sha256:" + crypto.createHash("sha256").update(input, "utf8").digest("hex")))
  361. '
  362. }
  363. hash_agent_definitions() {
  364. agents_dir=$(CDPATH= cd -- "$AGENT_DEFINITIONS_PATH" 2>/dev/null && pwd) || return 1
  365. node -e '
  366. const crypto = require("crypto")
  367. const fs = require("fs")
  368. const path = require("path")
  369. const [castingPath, agentsDir] = process.argv.slice(1)
  370. const files = [castingPath, ...fs.readdirSync(agentsDir)
  371. .filter(name => /^ap-.*\.md$/.test(name))
  372. .sort()
  373. .map(name => path.join(agentsDir, name))]
  374. const hash = crypto.createHash("sha256")
  375. for (const file of files) {
  376. const label = path.basename(file)
  377. hash.update(String(Buffer.byteLength(label, "utf8"))).update(":").update(label)
  378. const content = fs.readFileSync(file)
  379. hash.update(String(content.length)).update(":").update(content)
  380. }
  381. process.stdout.write("sha256:" + hash.digest("hex"))
  382. ' "$MODEL_CASTING_PATH" "$agents_dir"
  383. }
  384. resolve_agent_definitions_json() {
  385. command -v node >/dev/null 2>&1 || {
  386. echo "supervisor: activation-scoped agents require node on PATH" >&2
  387. return 2
  388. }
  389. [ -r "$AGENT_DEFINITIONS_CLI" ] || {
  390. echo "supervisor: agent-definition converter is not readable: $AGENT_DEFINITIONS_CLI" >&2
  391. return 2
  392. }
  393. AGENT_DEFINITIONS_JSON=$(node "$AGENT_DEFINITIONS_CLI" "$AGENT_DEFINITIONS_PATH") || return 2
  394. [ -n "$AGENT_DEFINITIONS_JSON" ] || {
  395. echo "supervisor: agent-definition converter returned an empty cast" >&2
  396. return 2
  397. }
  398. }
  399. resolve_capability_binding() {
  400. supplied_attestation="$AUTOPROMPT_CAPABILITY_ATTESTATION"
  401. AUTOPROMPT_CAPABILITY_ATTESTATION=""
  402. command -v node >/dev/null 2>&1 || return 0
  403. CAPABILITY_CLI_VERSION="${AUTOPROMPT_CLI_VERSION:-}"
  404. if [ -z "$CAPABILITY_CLI_VERSION" ]; then
  405. cli_cmd="${LAUNCH_CMD%% *}"
  406. [ -n "$cli_cmd" ] || cli_cmd="$LAUNCHER"
  407. if [ -n "$cli_cmd" ] && command -v "$cli_cmd" >/dev/null 2>&1; then
  408. CAPABILITY_CLI_VERSION=$($cli_cmd --version 2>/dev/null | head -n1 || true)
  409. fi
  410. fi
  411. [ -n "$CAPABILITY_CLI_VERSION" ] || CAPABILITY_CLI_VERSION="unknown"
  412. case " $LAUNCH_CMD " in
  413. *" --dangerously-skip-permissions "*) CAPABILITY_PERMISSION_PROFILE="bypass-permissions" ;;
  414. *) CAPABILITY_PERMISSION_PROFILE="${AUTOPROMPT_PERMISSION_PROFILE:-default}" ;;
  415. esac
  416. if [ -r "$MODEL_CASTING_PATH" ]; then
  417. CAPABILITY_AGENT_DEFINITIONS_HASH=$(hash_agent_definitions 2>/dev/null || echo unknown)
  418. fi
  419. CAPABILITY_CASTING_HASH="none"
  420. if [ "$CASTING_ENABLED" = "true" ]; then
  421. CAPABILITY_CASTING_HASH=$(printf '%s' "$CASTING_JSON" | sha256_text) || return 2
  422. CAPABILITY_EFFORT_STATUS=$(casting_json_field effort.status) || return 2
  423. CAPABILITY_EFFORT_SOURCE=$(casting_json_field effort.source) || return 2
  424. fi
  425. if [ "$CAPABILITY_CLI_VERSION" = "unknown" ] || [ "$CAPABILITY_AGENT_DEFINITIONS_HASH" = "unknown" ] || [ -z "$supplied_attestation" ]; then
  426. return 0
  427. fi
  428. AUTOPROMPT_CAPABILITY_ATTESTATION=$(node -e '
  429. const crypto = require("crypto")
  430. const raw = process.argv[1]
  431. const expected = process.argv.slice(2)
  432. let attestation
  433. try { attestation = JSON.parse(raw) } catch { process.exit(1) }
  434. const bindings = [
  435. "provider", "cliVersion", "permissionProfile", "agentSelector",
  436. "agentDefinitionsHash", "castingHash", "effortStatus", "effortSource",
  437. ]
  438. const proofBytesOk = typeof attestation.proofBytes === "string" &&
  439. attestation.proofBytes !== "" && attestation.proofBytes.length <= 4096
  440. const proofOk = proofBytesOk &&
  441. "sha256:" + crypto.createHash("sha256").update(attestation.proofBytes, "utf8").digest("hex") === attestation.proofHash
  442. const valid = attestation && attestation.schemaVersion === 4 &&
  443. attestation.run === true && attestation.read === true && attestation.write === true &&
  444. attestation.proofKind === "disposable-scratch" &&
  445. typeof attestation.proofHash === "string" && /^sha256:[a-f0-9]{64}$/.test(attestation.proofHash) &&
  446. proofOk &&
  447. bindings.every((field, index) => attestation[field] === expected[index])
  448. if (!valid) process.exit(1)
  449. process.stdout.write(JSON.stringify(attestation))
  450. ' "$supplied_attestation" "$CAPABILITY_PROVIDER" "$CAPABILITY_CLI_VERSION" \
  451. "$CAPABILITY_PERMISSION_PROFILE" "$AGENTS_SELECTOR" "$CAPABILITY_AGENT_DEFINITIONS_HASH" \
  452. "$CAPABILITY_CASTING_HASH" "$CAPABILITY_EFFORT_STATUS" "$CAPABILITY_EFFORT_SOURCE" 2>/dev/null) || {
  453. AUTOPROMPT_CAPABILITY_ATTESTATION=""
  454. return 0
  455. }
  456. }
  457. # Take the startup snapshot of pre-existing DONE-* PATHS, BEFORE the first launch
  458. # and BEFORE any sentinel check or quarantine. Each path is written on its own
  459. # line to $SNAPSHOT_FILE. SNAPSHOT_OK=1 marks a trustworthy snapshot; if writing
  460. # fails we leave it 0, and sentinel_present then treats EVERY DONE-* as suspect
  461. # (relaunch), the fail-safe direction. The snapshot is the authoritative record
  462. # of "what was already here", so it is taken from the live glob exactly once.
  463. snapshot_pre_existing_sentinels() {
  464. SNAPSHOT_OK=0
  465. # `:` is a POSIX SPECIAL builtin: under dash a redirection error on it aborts
  466. # the whole non-interactive shell BEFORE `|| return` can run (bash only
  467. # returns). Wrapping it in a subshell isolates the abort to the subshell, so
  468. # an unwritable snapshot file degrades to RELAUNCH (fail-safe) under dash too.
  469. ( : > "$SNAPSHOT_FILE" ) 2>/dev/null || return
  470. if [ "$SENTINEL_SET" -eq 1 ]; then set -- $SENTINEL_GLOB; else set -- "$LEDGER_DIR"/DONE-*; fi
  471. for f in "$@"; do
  472. [ -e "$f" ] || continue
  473. printf '%s\n' "$f" >> "$SNAPSHOT_FILE" 2>/dev/null || return
  474. done
  475. SNAPSHOT_OK=1
  476. }
  477. # Is $1 one of the paths recorded in the startup snapshot? Exact whole-line match.
  478. # If the snapshot is not trustworthy (SNAPSHOT_OK=0) we answer YES for every path
  479. # -> every DONE-* is treated as pre-existing -> never halts -> relaunch. That is
  480. # the deliberate fail-safe: a missing/unreadable snapshot must never permit a halt.
  481. path_in_snapshot() {
  482. [ "$SNAPSHOT_OK" -eq 1 ] 2>/dev/null || return 0
  483. # If the snapshot file became unreadable/removed after SNAPSHOT_OK was set, the
  484. # read loop below would never run and we would fall through to `return 1` (= not
  485. # snapshotted = halt ALLOWED) -- fail-OPEN. The header contract says a snapshot
  486. # that cannot be READ makes every path suspect, so veto here too (return 0).
  487. [ -r "$SNAPSHOT_FILE" ] || return 0
  488. while IFS= read -r line; do
  489. [ "$line" = "$1" ] && return 0
  490. done < "$SNAPSHOT_FILE" 2>/dev/null
  491. return 1
  492. }
  493. # Drop one path from the live snapshot (in $SNAPSHOT_FILE) so a genuinely-fresh
  494. # sentinel can later reclaim it. Called by quarantine ONLY after a SUCCESSFUL
  495. # rename: once the stale occupant has been moved aside, the path is empty, so the
  496. # ONLY thing that can appear there is a fresh sentinel written by THIS run. The
  497. # activation nonce is minted once (CSPRNG) and re-exported unchanged to every
  498. # relaunched child (no clock), so a re-launch of the SAME activation writes the
  499. # SAME path the snapshot recorded -- if
  500. # the snapshot kept vetoing it, that fresh sentinel would be refused forever and
  501. # the supervisor would relaunch without end (the livelock). Rewrite is atomic via
  502. # a temp file. If the rewrite itself fails we KEEP the path (over-veto = relaunch,
  503. # never a false halt) -- the safe direction. A path whose rename FAILED is never
  504. # pruned, so it stays vetoed while its stale occupant still physically exists.
  505. prune_path_from_snapshot() {
  506. [ "$SNAPSHOT_OK" -eq 1 ] 2>/dev/null || return 0
  507. pruned="$SNAPSHOT_FILE.prune"
  508. ( : > "$pruned" ) 2>/dev/null || return 0
  509. while IFS= read -r line; do
  510. [ "$line" = "$1" ] && continue
  511. printf '%s\n' "$line" >> "$pruned" 2>/dev/null || { rm -f "$pruned" 2>/dev/null; return 0; }
  512. done < "$SNAPSHOT_FILE" 2>/dev/null
  513. mv "$pruned" "$SNAPSHOT_FILE" 2>/dev/null || rm -f "$pruned" 2>/dev/null
  514. }
  515. sentinel_json_matches() {
  516. file="$1"
  517. expected_nonce="$2"
  518. node -e '
  519. const fs = require("fs")
  520. let value
  521. try { value = JSON.parse(fs.readFileSync(process.argv[1], "utf8")) }
  522. catch { process.exit(1) }
  523. process.exit(value && value.done === true && value.nonce === process.argv[2] ? 0 : 1)
  524. ' "$file" "$expected_nonce" >/dev/null 2>&1
  525. }
  526. sentinel_present() {
  527. if [ "$LEGACY_SENTINEL" != "1" ]; then
  528. f="$LEDGER_DIR/DONE-$RUN_NONCE"
  529. [ -f "$f" ] || return 1
  530. path_in_snapshot "$f" && return 1
  531. sentinel_json_matches "$f" "$RUN_NONCE"
  532. return $?
  533. fi
  534. if [ "$SENTINEL_SET" -eq 1 ]; then set -- $SENTINEL_GLOB; else set -- "$LEDGER_DIR"/DONE-*; fi
  535. for f in "$@"; do
  536. [ -f "$f" ] || continue
  537. grep -q '"done"[[:space:]]*:[[:space:]]*true' "$f" 2>/dev/null || continue
  538. path_in_snapshot "$f" && continue
  539. return 0
  540. done
  541. return 1
  542. }
  543. # At startup, BEFORE the first launch, QUARANTINE every pre-existing done:true
  544. # DONE-* sentinel: rename it aside to <dir>/superseded-<start-epoch>-<name> so the
  545. # new name no longer starts with DONE- and thus no longer matches the live DONE-*
  546. # glob -- it cannot halt this fresh mission. (Prefixing, NOT suffixing: a
  547. # DONE-X.superseded-N name would STILL match DONE-* and re-trip the same-second
  548. # halt, so the leading DONE- must be displaced.) This is the PRIMARY fix for the
  549. # whole stale-sentinel class -- after quarantine there is no leftover sentinel
  550. # left to race, so a same-second / zero-epoch / sub-second mtime collision is
  551. # moot. We RENAME, never delete (deleting artifacts is the JANITOR's job; never
  552. # silently rm operator files) and log a loud line naming each quarantined file.
  553. # On a SUCCESSFUL rename the path is pruned from the live snapshot so a genuine
  554. # fresh same-activation DONE-<nonce> (the minted nonce is re-exported to every
  555. # relaunched child, no clock) can reclaim it -- else the snapshot would veto that
  556. # fresh sentinel forever and the supervisor would relaunch without end (livelock).
  557. # If a rename FAILS (read-only dir / permissions / clobber) the leftover DONE-*
  558. # still matches the live glob, its path is NOT pruned, and sentinel_present
  559. # unconditionally refuses it. A failed rename degrades to RELAUNCH, never a halt.
  560. # Net invariant: the snapshot vetoes a path IFF its stale occupant still exists.
  561. quarantine_stale_sentinels() {
  562. if [ "$SENTINEL_SET" -eq 1 ]; then set -- $SENTINEL_GLOB; else set -- "$LEDGER_DIR"/DONE-*; fi
  563. for f in "$@"; do
  564. [ -f "$f" ] || continue
  565. if grep -q '"done"[[:space:]]*:[[:space:]]*true' "$f" 2>/dev/null; then
  566. dir=$(dirname "$f"); base=$(basename "$f")
  567. quarantined="$dir/superseded-${SUPERVISOR_START_EPOCH:-unknown}-$base"
  568. if mv "$f" "$quarantined" 2>/dev/null; then
  569. # The stale occupant is gone, so this path can no longer hold anything
  570. # but a FRESH this-run sentinel. Drop it from the live snapshot so the
  571. # same-activation DONE-<nonce> is reclaimable -- otherwise the
  572. # snapshot would veto the genuine fresh sentinel forever (the livelock).
  573. prune_path_from_snapshot "$f"
  574. 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."
  575. else
  576. 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."
  577. fi
  578. fi
  579. done
  580. }
  581. # The frontier marker: how much forward progress exists on disk. It is a
  582. # MONOTONIC progress counter, not a success counter - it counts EVERY gate
  583. # artifact across the whole lifecycle (roadmap/scouts, plan draft/review/
  584. # fresh-verify, plan-final, impl, impl-review, verify, signoff, sweep-round,
  585. # arbiter, goal-check). Versioned (-vN), per-feature (Fx-), retained-scout, and
  586. # per-round artifacts multiply as work proceeds, so a run that is advancing through
  587. # the pre-build scope phase, which writes roadmap and retained scout evidence
  588. # long before the first plan-final - bumps the count every relaunch and resets
  589. # the poison window. A run that relaunches writing NOTHING new keeps the count
  590. # flat and still trips poison. Counting only plan-final/verify (the old globs)
  591. # pinned the count at 0 for that whole early phase and KILLED healthy runs.
  592. frontier_count() {
  593. if [ "$DRY_RUN" -eq 1 ]; then
  594. # In dry-run, a poison fake never advances; a healthy fake bumps a counter file.
  595. if [ "${FAKE_POISON:-0}" = "1" ]; then echo 0; return; fi
  596. if [ -f "$LEDGER_DIR/.fake-frontier" ]; then cat "$LEDGER_DIR/.fake-frontier"; else echo 0; fi
  597. return
  598. fi
  599. count=0
  600. # Three artifact layouts must ALL be counted, or a run driven by one of them is
  601. # invisible to the frontier and a healthy-long run trips POISON:
  602. # prose/agent (SKILL.md/GATES.md): autoprompt/prompt-NNN-<slug>/artifacts/
  603. # harness (autoprompt-gate.js ARTIFACT_DIR): autoprompt/.artifacts/<run-tag>/
  604. # session ledger (SPEC-1 SCRIBE): autoprompt/session_NN/prompt_NN-<slug>/ and
  605. # its optional artifacts/ subdir. The per-prompt ledger .md files (BRIEF/
  606. # GATELOG/COVERAGE...) count as forward progress (monotonic; same rationale as
  607. # the multiplying-artifacts globs), so a run advancing ONLY in the new layout
  608. # is never falsely poisoned.
  609. # The leading-dot harness dir is NOT matched by "*" (POSIX glob skips dotfiles),
  610. # and its nesting differs, so it needs its own glob - which also stops the prose
  611. # glob from double-counting it. Ledger-root prose files (BRIEF/PLAN/GATELOG...)
  612. # live ONE level above artifacts/ so they are not counted by the first two globs;
  613. # the session-ledger glob counts them at their nested depth. The DONE sentinel
  614. # lives at the ledger root, not under any artifacts/ dir. Plain shell `for` over an
  615. # unmatched glob leaves the literal pattern (nullglob off); `[ -f ]` filters it.
  616. for f in "$LEDGER_DIR"/*/artifacts/*.md \
  617. "$LEDGER_DIR"/.artifacts/*/*.md \
  618. "$LEDGER_DIR"/session_*/prompt_*/artifacts/*.md \
  619. "$LEDGER_DIR"/session_*/prompt_*/*.md; do
  620. [ -f "$f" ] && count=$((count + 1))
  621. done
  622. echo "$count"
  623. }
  624. # The durable pre-execution clock starts before the roadmap author and remains active
  625. # through every plan/review/fresh-verify revision. Only real G4 implementation evidence
  626. # proves execution started; planning artifacts are never execution progress.
  627. scope_phase_elapsed() {
  628. if [ "$DRY_RUN" -eq 1 ]; then
  629. [ -n "${FAKE_SCOPE_ELAPSED:-}" ] && echo "$FAKE_SCOPE_ELAPSED"
  630. return
  631. fi
  632. for f in "$LEDGER_DIR"/.artifacts/*/*-impl-v*.md \
  633. "$LEDGER_DIR"/*/artifacts/*-impl-v*.md \
  634. "$LEDGER_DIR"/session_*/prompt_*/artifacts/*-impl-v*.md; do
  635. [ -f "$f" ] && {
  636. rm -f "$SCOPE_PHASE_START_FILE" "$SCOPE_RESETS_FILE" \
  637. "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST" \
  638. "$LEDGER_DIR/SCOPE-BUDGET-BREACH" 2>/dev/null
  639. return
  640. }
  641. done
  642. now_s=$(date +%s 2>/dev/null || echo 0)
  643. start_s=""
  644. stored_binding=""
  645. if [ -r "$SCOPE_PHASE_START_FILE" ]; then
  646. start_s=$(awk 'NR==1{print $1; exit}' "$SCOPE_PHASE_START_FILE" 2>/dev/null || echo)
  647. stored_binding=$(awk 'NR==1{print $2; exit}' "$SCOPE_PHASE_START_FILE" 2>/dev/null || echo)
  648. fi
  649. case "$start_s" in (*[!0-9]*|"") start_s="" ;; esac
  650. if [ "$stored_binding" != "$SCOPE_MISSION_BINDING" ]; then
  651. start_s=""
  652. rm -f "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST" \
  653. "$LEDGER_DIR/SCOPE-BUDGET-BREACH" "$SCOPE_RESETS_FILE" 2>/dev/null
  654. fi
  655. if [ -z "$start_s" ] || [ "$start_s" -le 0 ] 2>/dev/null; then
  656. start_s="$now_s"
  657. printf '%s %s\n' "$start_s" "$SCOPE_MISSION_BINDING" \
  658. > "$SCOPE_PHASE_START_FILE.tmp" 2>/dev/null \
  659. && mv "$SCOPE_PHASE_START_FILE.tmp" "$SCOPE_PHASE_START_FILE" 2>/dev/null
  660. fi
  661. el=$((now_s - start_s))
  662. [ "$el" -lt 0 ] 2>/dev/null && el=0
  663. echo "$el"
  664. }
  665. # Honest retained scope evidence. New runs expose roadmap-scout-N; legacy resumes
  666. # expose scope-<key>. Missing evidence stays missing rather than being invented.
  667. scope_landed_angles() {
  668. if [ "$DRY_RUN" -eq 1 ]; then
  669. echo "${FAKE_SCOPE_LANDED:-}"
  670. return
  671. fi
  672. keys=""
  673. for f in "$LEDGER_DIR"/.artifacts/*/roadmap-scout-*.md \
  674. "$LEDGER_DIR"/*/artifacts/roadmap-scout-*.md \
  675. "$LEDGER_DIR"/session_*/prompt_*/artifacts/roadmap-scout-*.md \
  676. "$LEDGER_DIR"/.artifacts/*/scope-*.md \
  677. "$LEDGER_DIR"/*/artifacts/scope-*.md \
  678. "$LEDGER_DIR"/session_*/prompt_*/artifacts/scope-*.md; do
  679. [ -f "$f" ] || continue
  680. base=$(basename "$f")
  681. case "$base" in
  682. roadmap-scout-*.md) key=$(printf '%s' "$base" | sed -e 's/\.md$//') ;;
  683. *) key=$(printf '%s' "$base" | sed -e 's/^scope-//' -e 's/-v[0-9]*\.md$//' -e 's/\.md$//') ;;
  684. esac
  685. [ -n "$key" ] || continue
  686. case " $keys " in (*" $key "*) ;; (*) keys="$keys $key" ;; esac
  687. done
  688. printf '%s' "$keys" | sed -e 's/^ *//' -e 's/ *$//' -e 's/ */,/g'
  689. }
  690. # Age (seconds) of the pending SCOPE-CONVERGE-REQUEST, or 0 when none exists.
  691. scope_converge_request_age() {
  692. req="$LEDGER_DIR/SCOPE-CONVERGE-REQUEST"
  693. [ -r "$req" ] || { echo 0; return; }
  694. now_s=$(date +%s 2>/dev/null || echo 0)
  695. req_ts=$(awk 'NR==1{print $1+0; exit}' "$req" 2>/dev/null || echo 0)
  696. case "$req_ts" in (*[!0-9]*|"") req_ts=0 ;; esac
  697. age=$((now_s - req_ts))
  698. [ "$age" -lt 0 ] 2>/dev/null && age=0
  699. echo "$age"
  700. }
  701. # === PLAN-auto-compact-threshold: proactive supervisor-fired compaction ============
  702. # The supervisor cannot introspect the live CLI's RAM, and the parent cannot /compact
  703. # itself. So the supervisor OBSERVES the parent's context size from disk (the parent's
  704. # own session transcript; watermark/ledger-byte fallbacks) and, on crossing COMPACT_AT,
  705. # writes COMPACT-REQUEST then -- on grace timeout -- fires a process-group kill so the
  706. # outer relaunch loop RESUMEs a fresh, smaller context that re-reads ANCHOR.md.
  707. # Canonicalize a path for cross-platform cwd comparison (win32/gitbash AND posix):
  708. # lowercase; collapse \ and / runs to a single /; map a leading "<drive>:" to "/<drive>".
  709. # Worked: "/c/Users/x"->"/c/users/x"; "C:\\Users\\x"->"c:\\users\\x"->"c:/users/x"->"/c/users/x".
  710. canon_path() { # $1 = raw path ; echoes canonical form
  711. printf '%s' "$1" \
  712. | tr 'A-Z\\' 'a-z/' \
  713. | sed -e 's#//*#/#g' -e 's#^\([a-z]\):#/\1#'
  714. }
  715. # Find the live parent session .jsonl. Slug-free: matches RUN_CWD against each
  716. # transcript's embedded "cwd" after canonicalization. Single-level glob excludes nested
  717. # subagent/tool-result transcripts. Echoes the path of the newest cwd-matching transcript
  718. # whose mtime is >= the child launch epoch, or nothing.
  719. find_parent_transcript() { # $1 = child_launch_epoch
  720. if [ -n "$PARENT_TRANSCRIPT" ] && [ -r "$PARENT_TRANSCRIPT" ]; then echo "$PARENT_TRANSCRIPT"; return; fi
  721. cfg="${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
  722. want=$(canon_path "$RUN_CWD")
  723. newest=""; newest_mt=0
  724. for f in "$cfg"/projects/*/*.jsonl; do
  725. [ -f "$f" ] || continue
  726. mt=$(stat -c %Y "$f" 2>/dev/null || stat -f %m "$f" 2>/dev/null || echo 0)
  727. [ "$mt" -lt "${1:-0}" ] 2>/dev/null && continue # stale prior session
  728. tcwd=$(grep -o '"cwd":"[^"]*"' "$f" 2>/dev/null | head -n1 | sed 's/.*"cwd":"//; s/"$//')
  729. [ -n "$tcwd" ] || continue
  730. tcwd=$(printf '%s' "$tcwd" | sed 's/\\\\/\\/g') # un-escape JSON doubled backslashes
  731. [ "$(canon_path "$tcwd")" = "$want" ] || continue # different project session -> skip
  732. [ "$mt" -gt "$newest_mt" ] 2>/dev/null && { newest="$f"; newest_mt=$mt; }
  733. done
  734. [ -n "$newest" ] && echo "$newest"
  735. }
  736. # Read the PARENT's context size in three tiers; echoes an integer (0 = unavailable).
  737. # TIER 1: parse the parent session .jsonl usage fields (real token accounting), with a
  738. # same-source byte proxy of THAT .jsonl when usage is unparseable.
  739. # TIER 2: parent-emitted .context-watermark (stale-rejected).
  740. # TIER 3: coarse ledger-byte proxy (NOT parent context -- last resort).
  741. # Honors FAKE_WATERMARK in dry-run so the poll loop is testable.
  742. read_context_estimate() { # $1 = child_launch_epoch (for staleness)
  743. if [ "$DRY_RUN" -eq 1 ]; then
  744. if [ -n "${FAKE_WATERMARK:-}" ]; then echo "$FAKE_WATERMARK"; else echo 0; fi
  745. return
  746. fi
  747. tx=$(find_parent_transcript "${1:-0}")
  748. if [ -n "$tx" ] && [ -r "$tx" ]; then
  749. if command -v jq >/dev/null 2>&1; then
  750. est=$(jq -r 'select(.message.usage) | .message.usage
  751. | ((.input_tokens//0)+(.cache_read_input_tokens//0)+(.cache_creation_input_tokens//0))' \
  752. "$tx" 2>/dev/null | awk 'NF{v=$1} END{if(v!="")print v}')
  753. else
  754. est=$(grep -o '"usage":[^}]*}' "$tx" 2>/dev/null | tail -n1 \
  755. | grep -oE '"(input_tokens|cache_read_input_tokens|cache_creation_input_tokens)":[0-9]+' \
  756. | awk -F: '{s+=$2} END{if(s>0)print s}')
  757. fi
  758. case "$est" in (*[0-9]*) [ "$est" -gt 0 ] 2>/dev/null && { echo "$est"; return; } ;; esac
  759. sz=$(wc -c < "$tx" 2>/dev/null || echo 0)
  760. [ "$sz" -gt 0 ] 2>/dev/null && { echo $((sz / BYTES_PER_TOKEN)); return; }
  761. fi
  762. if [ -r "$WATERMARK_FILE" ]; then
  763. wm_tok=$(awk 'NR==1{print $1; exit}' "$WATERMARK_FILE" 2>/dev/null || echo)
  764. wm_ts=$(awk 'NR==1{print $2; exit}' "$WATERMARK_FILE" 2>/dev/null || echo)
  765. case "$wm_tok" in (*[0-9]*) ;; (*) wm_tok="" ;; esac
  766. if [ -n "$wm_tok" ] && { [ -z "$wm_ts" ] || [ "${wm_ts:-0}" -ge "${1:-0}" ] 2>/dev/null; }; then
  767. echo "$wm_tok"; return
  768. fi
  769. fi
  770. bytes=0
  771. for f in "$LEDGER_DIR"/session_*/prompt_*/*.md "$LEDGER_DIR"/session_*/prompt_*/artifacts/*.md "$LEDGER_DIR"/*/artifacts/*.md; do
  772. [ -f "$f" ] || continue
  773. sz=$(wc -c < "$f" 2>/dev/null || echo 0); bytes=$((bytes + sz))
  774. done
  775. echo $((bytes / BYTES_PER_TOKEN))
  776. }
  777. # Detect a harness-fired (~400k) compaction so the supervisor does NOT then double-fire:
  778. # a sharp estimate DROP across ticks arms the cooldown and clears any pending request.
  779. # Records "<epoch> <est>" into COMPACT_STATE_FILE each tick. $1=now $2=current_est.
  780. note_external_compaction() { # $1=now $2=current_est
  781. prev_est=0
  782. [ -r "$COMPACT_STATE_FILE" ] && prev_est=$(awk 'NR==1{print $2+0; exit}' "$COMPACT_STATE_FILE" 2>/dev/null || echo 0)
  783. if [ "${prev_est:-0}" -gt 0 ] 2>/dev/null \
  784. && [ $(( prev_est - ${2:-0} )) -ge "$EXTERNAL_COMPACT_DELTA" ] 2>/dev/null; then
  785. printf '%s %s external_compaction\n' "$1" "${2:-0}" > "$COMPACT_STATE_FILE.tmp" 2>/dev/null \
  786. && mv "$COMPACT_STATE_FILE.tmp" "$COMPACT_STATE_FILE" 2>/dev/null
  787. rm -f "$COMPACT_REQUEST_FILE" 2>/dev/null || true
  788. 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)."
  789. return 0
  790. fi
  791. # record the current estimate for next tick's drop comparison (keep the last_compact epoch field 0 unless set)
  792. last_compact=0; [ -r "$COMPACT_STATE_FILE" ] && last_compact=$(awk 'NR==1{print $1+0; exit}' "$COMPACT_STATE_FILE" 2>/dev/null || echo 0)
  793. printf '%s %s\n' "$last_compact" "${2:-0}" > "$COMPACT_STATE_FILE.tmp" 2>/dev/null \
  794. && mv "$COMPACT_STATE_FILE.tmp" "$COMPACT_STATE_FILE" 2>/dev/null
  795. return 1
  796. }
  797. # Decide whether to request/force a compaction. Sets COMPACT_FORCE=1 when a written
  798. # request has gone unhonored past COMPACT_GRACE. Returns 0 when the caller should act
  799. # (request written OR force due), 1 otherwise. Guards: cooldown, in-flight request,
  800. # external-compaction detection -- so one context fill triggers at most one compaction.
  801. maybe_request_compaction() { # $1=child_launch_epoch $2=now
  802. COMPACT_FORCE=0
  803. est=$(read_context_estimate "$1")
  804. note_external_compaction "$2" "$est" && return 1 # harness already compacted -> nothing to do
  805. last_compact=0; [ -r "$COMPACT_STATE_FILE" ] && last_compact=$(awk 'NR==1{print $1+0; exit}' "$COMPACT_STATE_FILE" 2>/dev/null || echo 0)
  806. if [ "${last_compact:-0}" -gt 0 ] 2>/dev/null && [ $(( $2 - last_compact )) -lt "$COMPACT_COOLDOWN" ] 2>/dev/null; then
  807. return 1
  808. fi
  809. if [ -f "$COMPACT_REQUEST_FILE" ]; then
  810. req_ts=$(awk 'NR==1{print $1+0; exit}' "$COMPACT_REQUEST_FILE" 2>/dev/null || echo 0)
  811. if [ $(( $2 - req_ts )) -ge "$COMPACT_GRACE" ] 2>/dev/null; then COMPACT_FORCE=1; return 0; fi
  812. return 1
  813. fi
  814. if [ "$est" -ge "$COMPACT_AT" ] 2>/dev/null; then
  815. printf '%s proactive est=%s threshold=%s\n' "$2" "$est" "$COMPACT_AT" > "$COMPACT_REQUEST_FILE.tmp" 2>/dev/null \
  816. && mv "$COMPACT_REQUEST_FILE.tmp" "$COMPACT_REQUEST_FILE" 2>/dev/null \
  817. && 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)."
  818. return 0
  819. fi
  820. return 1
  821. }
  822. # Kill the child's whole process GROUP so a wedged parent leaves NO orphaned subagent.
  823. # SIGTERM the group, escalate to SIGKILL after a short grace. Falls back to a plain PID
  824. # kill when job control / negative-pgid signaling is unavailable.
  825. kill_tree() { # $1 = child pid
  826. pid="$1"
  827. [ -n "$pid" ] || return 0
  828. if command -v taskkill.exe >/dev/null 2>&1; then
  829. win_pid=$(ps -W -p "$pid" -l 2>/dev/null | awk 'NR==2{print $4; exit}')
  830. case "$win_pid" in (*[!0-9]*|"") win_pid="" ;; esac
  831. if [ -n "$win_pid" ] && taskkill.exe /T /F /PID "$win_pid" >/dev/null 2>&1; then
  832. return 0
  833. fi
  834. fi
  835. descendants=""
  836. pending="$pid"
  837. while [ -n "$pending" ]; do
  838. parent=${pending%% *}
  839. case "$pending" in (*" "*) pending=${pending#* } ;; (*) pending="" ;; esac
  840. children=$(ps -ef 2>/dev/null | awk -v parent="$parent" 'NR>1 && $3 == parent { print $2 }')
  841. for child in $children; do
  842. case " $descendants " in (*" $child "*) ;; (*) descendants="$child $descendants"; pending="$pending $child" ;; esac
  843. done
  844. pending=$(printf '%s' "$pending" | sed 's/^ *//')
  845. done
  846. for victim in $descendants "$pid"; do kill -TERM "$victim" 2>/dev/null || true; done
  847. i=0
  848. while [ "$i" -lt 4 ] && kill -0 "$pid" 2>/dev/null; do sleep 0.5 2>/dev/null || sleep 1; i=$((i + 1)); done
  849. for victim in $descendants "$pid"; do
  850. kill -0 "$victim" 2>/dev/null && kill -KILL "$victim" 2>/dev/null || true
  851. done
  852. }
  853. # Run the real or fake launcher once; return its exit code.
  854. #
  855. # HEARTBEAT (PLAN-idle-watchdog V3): the child is launched in the BACKGROUND on
  856. # BOTH the real exec AND the dry-run fake path, so a SINGLE poll loop watches
  857. # liveness + frontier-COUNT staleness regardless of path (blocker 2: the poll loop
  858. # is genuinely exercised under --dry-run). While the child is alive, if
  859. # frontier_count has NOT grown beyond last_seen within IDLE_TIMEOUT and no sentinel
  860. # exists, the run is ALIVE-BUT-IDLE -> kill the child so the outer relaunch loop
  861. # RESUMEs it (the automatic CONTINUE for an idle agent). This is DISTINCT from the
  862. # EXIT-keyed poison guard and FEEDS it: a heartbeat kill that produced no count
  863. # growth is recorded by the outer loop as a no-progress restart, so a wedged child
  864. # still trips POISON after MAX_RESTARTS (anti-thrash, §4.5 - no second uncapped
  865. # relaunch path). LAUNCH_INDEX is incremented in the PARENT scope here, before the
  866. # fork, so only the exec / fake-work is backgrounded.
  867. LAUNCH_INDEX=0
  868. run_launcher() {
  869. LAUNCH_INDEX=$((LAUNCH_INDEX + 1))
  870. child_launch_epoch=$(date +%s 2>/dev/null || echo 0)
  871. if [ "$DRY_RUN" -eq 0 ]; then
  872. stored_binding=""
  873. [ -r "$SCOPE_PHASE_START_FILE" ] && stored_binding=$(awk 'NR==1{print $2; exit}' "$SCOPE_PHASE_START_FILE" 2>/dev/null || echo)
  874. if [ "$stored_binding" != "$SCOPE_MISSION_BINDING" ]; then
  875. rm -f "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST" \
  876. "$LEDGER_DIR/SCOPE-BUDGET-BREACH" "$SCOPE_RESETS_FILE" 2>/dev/null
  877. printf '%s %s\n' "$child_launch_epoch" "$SCOPE_MISSION_BINDING" \
  878. > "$SCOPE_PHASE_START_FILE.tmp" 2>/dev/null \
  879. && mv "$SCOPE_PHASE_START_FILE.tmp" "$SCOPE_PHASE_START_FILE" 2>/dev/null
  880. fi
  881. fi
  882. if [ "$DRY_RUN" -eq 1 ]; then
  883. # Pop the next exit code from FAKE_EXITS in the PARENT (LAUNCH_INDEX-indexed);
  884. # default 0 once the list is spent. The fork below exits with this code so the
  885. # parent's `wait` retrieves it.
  886. set -- ${FAKE_EXITS:-0}
  887. idx="$LAUNCH_INDEX"
  888. code=0; n=0
  889. for c in "$@"; do n=$((n + 1)); if [ "$n" -eq "$idx" ]; then code="$c"; fi; done
  890. (
  891. # The backgrounded fake child. Optionally write the sentinel BEFORE exit
  892. # (models the JANITOR having written it), advance the frontier unless poisoned,
  893. # then optionally STAY ALIVE (FAKE_CHILD_ALIVE seconds) so the poll loop has a
  894. # real PID to kill -0 / kill and a real .fake-frontier to read as stale. Exit
  895. # with the popped code so `wait` recovers it.
  896. if [ -n "${FAKE_SENTINEL_AFTER:-}" ] && [ "$idx" -ge "$FAKE_SENTINEL_AFTER" ]; then
  897. printf '{"done": true, "nonce": "FAKE", "verdict": "fake done", "ts": "now"}' \
  898. > "$LEDGER_DIR/DONE-FAKE.tmp" && mv "$LEDGER_DIR/DONE-FAKE.tmp" "$LEDGER_DIR/DONE-FAKE"
  899. fi
  900. if [ "${FAKE_POISON:-0}" != "1" ]; then
  901. cur=0; [ -f "$LEDGER_DIR/.fake-frontier" ] && cur=$(cat "$LEDGER_DIR/.fake-frontier")
  902. echo $((cur + 1)) > "$LEDGER_DIR/.fake-frontier"
  903. fi
  904. sleep "${FAKE_CHILD_ALIVE:-0}" 2>/dev/null || true
  905. exit "$code"
  906. ) &
  907. else
  908. # Launch one is fresh unless the operator explicitly invoked this supervisor as a
  909. # resume. Relaunches always export AUTOPROMPT_RESUME=1.
  910. # When LAUNCH_CMD is set it is used VERBATIM (word-split into command + args,
  911. # mission appended) so a fresh user can pass their real CLI; otherwise the
  912. # bare LAUNCHER label is exec'd as before.
  913. # Neutralize the operator's CLAUDE_CODE_SUBAGENT_MODEL for the CHILD CLI ONLY.
  914. # That var has HIGHEST precedence in the harness and force-pins every (even
  915. # nested) subagent onto a fixed model, defeating the skill's `model: inherit`
  916. # contract. A child cannot mutate its parent's env, so the LAUNCH layer is the
  917. # only correct place to strip it: `env -u` removes it from the child's
  918. # environment WITHOUT touching this supervisor's own env or the operator's
  919. # shell/profile/CLAUDE.md/settings.json. `inherit` then resolves to the real
  920. # session/--model selection. Idempotent: env -u of an unset/inherit var is a
  921. # no-op, never an error. AUTOPROMPT_KEEP_MODEL_PIN=1 opts OUT (keeps the pin).
  922. (
  923. export AUTOPROMPT_UNATTENDED=1
  924. if [ "$LAUNCH_INDEX" -gt 1 ] || [ "$INITIAL_RESUME" -eq 1 ]; then
  925. export AUTOPROMPT_RESUME=1
  926. else
  927. unset AUTOPROMPT_RESUME
  928. fi
  929. export AUTOPROMPT_MODE
  930. if [ "$LEGACY_SENTINEL" != "1" ]; then export AUTOPROMPT_RUN_NONCE="$RUN_NONCE"; fi
  931. export AUTOPROMPT_LEDGER_CHECK="$LEDGER_CHECK_PATH"
  932. if [ -n "$AUTOPROMPT_SESSION_TOKEN" ]; then
  933. export AUTOPROMPT_SESSION_TOKEN
  934. else
  935. unset AUTOPROMPT_SESSION_TOKEN
  936. fi
  937. if [ "${AUTOPROMPT_KEEP_MODEL_PIN:-0}" != "1" ]; then
  938. unset CLAUDE_CODE_SUBAGENT_MODEL
  939. fi
  940. export AUTOPROMPT_AGENTS="$AGENTS_SELECTOR"
  941. export AUTOPROMPT_PROVIDER="$CAPABILITY_PROVIDER"
  942. export AUTOPROMPT_CLI_VERSION="$CAPABILITY_CLI_VERSION"
  943. export AUTOPROMPT_PERMISSION_PROFILE="$CAPABILITY_PERMISSION_PROFILE"
  944. export AUTOPROMPT_AGENT_DEFINITIONS_HASH="$CAPABILITY_AGENT_DEFINITIONS_HASH"
  945. export AUTOPROMPT_CASTING_HASH="$CAPABILITY_CASTING_HASH"
  946. if [ -n "$AUTOPROMPT_CAPABILITY_ATTESTATION" ]; then
  947. export AUTOPROMPT_CAPABILITY_ATTESTATION
  948. else
  949. unset AUTOPROMPT_CAPABILITY_ATTESTATION
  950. fi
  951. if [ "$CASTING_ENABLED" = "true" ]; then
  952. export AUTOPROMPT_AGENT_CASTING="$CASTING_JSON"
  953. export ANTHROPIC_DEFAULT_OPUS_MODEL="$CASTING_OPUS"
  954. export ANTHROPIC_DEFAULT_SONNET_MODEL="$CASTING_SONNET"
  955. export ANTHROPIC_DEFAULT_HAIKU_MODEL="$CASTING_HAIKU"
  956. if [ -n "$CASTING_BASE_URL" ]; then export ANTHROPIC_BASE_URL="$CASTING_BASE_URL"; fi
  957. if [ -n "$CASTING_API_KEY_ENV" ]; then export ANTHROPIC_AUTH_TOKEN="$CASTING_AUTH_TOKEN"; fi
  958. fi
  959. if [ -n "$LAUNCH_CMD" ]; then
  960. # shellcheck disable=SC2086 # operator command is intentionally split into argv.
  961. set -- $LAUNCH_CMD
  962. else
  963. set -- "$LAUNCHER"
  964. fi
  965. [ "$#" -gt 0 ] || exit 127
  966. "$@" --agents "$AGENT_DEFINITIONS_JSON" "$MISSION"
  967. ) &
  968. fi
  969. child_pid=$!
  970. # NOTE on `date +%s`: used ONLY for the elapsed-wall-clock comparison
  971. # (now - last_progress), exactly as the existing relaunch loop already does - it is
  972. # NOT a file probe, and its `|| echo 0` fallback only pins now/last_progress to the
  973. # same baseline, which can at worst DELAY the timeout, never falsely fire it. The
  974. # progress decision is purely the integer frontier-count delta (blocker 3: no mtime
  975. # probe, so a healthy progressing run is NEVER mischaracterized as stale).
  976. last_progress=$(date +%s 2>/dev/null || echo 0)
  977. last_seen_count=$(frontier_count)
  978. # The poll loop wakes on a RESPONSIVE slice (min of HEARTBEAT_INTERVAL and 1s) so a
  979. # child that EXITS is detected promptly instead of after a full HEARTBEAT_INTERVAL
  980. # block - the staleness evaluation still only runs once per HEARTBEAT_INTERVAL of
  981. # elapsed wall-clock. This keeps a fast-exiting (real or dry-run) child from pinning
  982. # the loop for the whole interval while preserving the exact heartbeat cadence.
  983. poll_slice="$HEARTBEAT_INTERVAL"; [ "$poll_slice" -gt 1 ] 2>/dev/null && poll_slice=1
  984. last_eval="$last_progress"
  985. while kill -0 "$child_pid" 2>/dev/null; do
  986. sleep "$poll_slice" 2>/dev/null || true
  987. sentinel_present && break # the run finished while we slept; let the outer loop halt cleanly
  988. now=$(date +%s 2>/dev/null || echo 0)
  989. [ $((now - last_eval)) -ge "$HEARTBEAT_INTERVAL" ] || continue # not yet a heartbeat tick
  990. last_eval="$now"
  991. cur_count=$(frontier_count)
  992. if [ "$cur_count" -gt "$last_seen_count" ]; then
  993. last_seen_count="$cur_count"; last_progress="$now" # frontier advanced -> healthy, reset
  994. elif [ $((now - last_progress)) -ge "$IDLE_TIMEOUT" ]; then
  995. log "HEARTBEAT: no frontier progress for >=${IDLE_TIMEOUT}s while alive and no sentinel - killing to relaunch with RESUME (auto-continue an idle agent)."
  996. kill "$child_pid" 2>/dev/null || true; break
  997. fi
  998. # PLAN-auto-compact-threshold: proactive supervisor-fired compaction check. Writes
  999. # COMPACT-REQUEST when the externally-observed context size crosses COMPACT_AT; on a
  1000. # request unhonored past COMPACT_GRACE (parent wedged) forces the reset.
  1001. if maybe_request_compaction "$child_launch_epoch" "$now"; then
  1002. if [ "$COMPACT_FORCE" -eq 1 ]; then
  1003. 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."
  1004. printf '%s forced est_unhonored grace=%s\n' "$now" "$COMPACT_GRACE" > "$COMPACT_STATE_FILE.forced.tmp" 2>/dev/null \
  1005. && mv "$COMPACT_STATE_FILE.forced.tmp" "$LEDGER_DIR/.forced-reset" 2>/dev/null
  1006. printf '%s forced\n' "$now" > "$COMPACT_STATE_FILE.tmp" 2>/dev/null \
  1007. && mv "$COMPACT_STATE_FILE.tmp" "$COMPACT_STATE_FILE" 2>/dev/null
  1008. rm -f "$COMPACT_REQUEST_FILE" 2>/dev/null || true
  1009. kill_tree "$child_pid"
  1010. break
  1011. fi
  1012. fi
  1013. # F-SPEED steer-2 B3: PHASE WALL-CLOCK BUDGET check. Once per tick, when the SCOPE
  1014. # phase is active (ROADMAP/scout evidence present, no build artifact yet), consult phase-budget.js.
  1015. # It is anchored to scope ENTRY and NOT reset by frontier growth, so it fires on the
  1016. # progressing-but-slow 30-min scope IDLE_TIMEOUT can never bound. Fail-open: an absent
  1017. # node/module skips the block (guarded by [ -r ]) and the run proceeds on IDLE_TIMEOUT.
  1018. scope_el=$(scope_phase_elapsed)
  1019. if [ -n "$scope_el" ] && [ -r "$PHASE_BUDGET_PATH" ]; then
  1020. req_age=$(scope_converge_request_age)
  1021. prior=$(awk 'NR==1{print $1+0; exit}' "$SCOPE_RESETS_FILE" 2>/dev/null || echo 0)
  1022. case "$prior" in (*[!0-9]*|"") prior=0 ;; esac
  1023. landed=$(scope_landed_angles)
  1024. node "$PHASE_BUDGET_PATH" --verdict --phase scope --elapsed "$scope_el" \
  1025. --soft "$SCOPE_SOFT_SEC" --hard "$SCOPE_HARD_SEC" --request-age "$req_age" \
  1026. --grace "$SCOPE_GRACE_SEC" --prior-resets "$prior" --max-resets "$MAX_SCOPE_RESETS" \
  1027. --landed "$landed" >/dev/null 2>&1
  1028. case $? in
  1029. 10) # SOFT breach: write the converge heads-up ONCE (idempotent), keep running.
  1030. if [ ! -f "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST" ]; then
  1031. printf '%s soft scope budget: mission=%s elapsed=%ss soft=%ss landed=%s - converge on the landed angles; do NOT fabricate unscoped ones.\n' \
  1032. "$now" "$SCOPE_MISSION_BINDING" "$scope_el" "$SCOPE_SOFT_SEC" "$landed" \
  1033. > "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST.tmp" 2>/dev/null \
  1034. && mv "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST.tmp" "$LEDGER_DIR/SCOPE-CONVERGE-REQUEST" 2>/dev/null
  1035. 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."
  1036. fi ;;
  1037. 20) # HARD/grace breach: durable breach marker (honest landed residual), bump the
  1038. # forced-reset counter, then REAL kill->RESUME via the existing idle-kill path.
  1039. 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' \
  1040. "$now" "$SCOPE_MISSION_BINDING" "$scope_el" "$SCOPE_HARD_SEC" "$landed" "$landed" \
  1041. > "$LEDGER_DIR/SCOPE-BUDGET-BREACH.tmp" 2>/dev/null \
  1042. && mv "$LEDGER_DIR/SCOPE-BUDGET-BREACH.tmp" "$LEDGER_DIR/SCOPE-BUDGET-BREACH" 2>/dev/null
  1043. echo $((prior + 1)) > "$SCOPE_RESETS_FILE.tmp" 2>/dev/null \
  1044. && mv "$SCOPE_RESETS_FILE.tmp" "$SCOPE_RESETS_FILE" 2>/dev/null
  1045. 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."
  1046. SCOPE_BUDGET_TERMINAL=1
  1047. kill_tree "$child_pid"; break ;;
  1048. 30) # RE-BREACH past the reset cap: escalate honestly, never fake a roadmap.
  1049. {
  1050. echo "supervisor escalation: scope budget breached past MAX_SCOPE_RESETS=$MAX_SCOPE_RESETS"
  1051. echo "scope_elapsed=$scope_el hard=$SCOPE_HARD_SEC prior_resets=$prior landed=$landed"
  1052. echo "converge unreachable - landed angles surfaced as the honest residual; NO fabricated roadmap"
  1053. echo "ts=$(date 2>/dev/null)"
  1054. } > "$ESCALATE_FILE" 2>/dev/null || true
  1055. 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."
  1056. kill_tree "$child_pid"
  1057. wait "$child_pid" 2>/dev/null
  1058. exit 1 ;;
  1059. esac
  1060. fi
  1061. done
  1062. wait "$child_pid" 2>/dev/null
  1063. exit_code=$?
  1064. [ "$SCOPE_BUDGET_TERMINAL" -eq 1 ] && return 124
  1065. return "$exit_code"
  1066. }
  1067. # EDIT 23: seed the per-conversation session token BEFORE the relaunch loop. The
  1068. # supervisor is the durable producer across relaunches of one conversation; this
  1069. # establishes the token precedence ONCE: an env-supplied token (operator or a prior
  1070. # same-conversation export) wins and is persisted to the durable file; else a
  1071. # previously-harvested token is read back from the file; else the token stays empty
  1072. # and the first SCRIBE-run resolver MINTS one (which we then harvest, below).
  1073. # Fail-soft: an unwritable/unreadable token file never aborts the run - the token
  1074. # just stays empty and the next launch re-mints (worst case a fresh session).
  1075. seed_session_token() {
  1076. if [ -n "$AUTOPROMPT_SESSION_TOKEN" ]; then
  1077. printf '%s\n' "$AUTOPROMPT_SESSION_TOKEN" > "$SESSION_TOKEN_FILE" 2>/dev/null || true
  1078. elif [ -r "$SESSION_TOKEN_FILE" ]; then
  1079. AUTOPROMPT_SESSION_TOKEN=$(head -n1 "$SESSION_TOKEN_FILE" 2>/dev/null || echo)
  1080. fi
  1081. }
  1082. # EDIT 23: HARVEST the resolver-minted token after a launch when the supervisor holds
  1083. # none yet. The SCRIBE-run `--resolve-prompt-dir` CLI writes the marker
  1084. # "$LEDGER_DIR/.session-current" as "session_NN <token>" (two whitespace-separated
  1085. # fields - the EDIT 7 contract). We read the 2nd field and persist it so the NEXT
  1086. # launch re-exports the SAME token and a 2nd prompt rejoins the same session_NN.
  1087. # Fail-soft: an absent/corrupt marker (no 2nd field) leaves the token empty and the
  1088. # next launch mints again - a fresh session, never a crash.
  1089. harvest_session_token() {
  1090. [ -n "$AUTOPROMPT_SESSION_TOKEN" ] && return 0
  1091. marker="$LEDGER_DIR/.session-current"
  1092. [ -r "$marker" ] || return 0
  1093. harvested=$(awk 'NR==1{print $2; exit}' "$marker" 2>/dev/null || echo)
  1094. if [ -n "$harvested" ]; then
  1095. AUTOPROMPT_SESSION_TOKEN="$harvested"
  1096. printf '%s\n' "$AUTOPROMPT_SESSION_TOKEN" > "$SESSION_TOKEN_FILE" 2>/dev/null || true
  1097. fi
  1098. }
  1099. # PLAN-auto-compact-threshold: a discovery-level test sources this script to call
  1100. # canon_path / find_parent_transcript directly. AUTOPROMPT_SOURCE_ONLY=1 stops here,
  1101. # AFTER every function + path var is defined but BEFORE the launch loop runs.
  1102. [ "${AUTOPROMPT_SOURCE_ONLY:-0}" = "1" ] && return 0 2>/dev/null
  1103. # Legacy broad DONE-* matching is a DOWNGRADE honored only for a verified legacy
  1104. # resume: the operator opted in explicitly AND the ledger directory carries
  1105. # physical evidence of a pre-nonce run (legacy governance files a three-file
  1106. # new-format run never creates). A fresh or new-format directory fails closed so
  1107. # the downgrade can never weaken a current-format run. Checked on the launch
  1108. # path only (after the source-only return) so sourced function evaluation is
  1109. # not subjected to launch-time validation.
  1110. if [ "$LEGACY_SENTINEL" = "1" ]; then
  1111. LEGACY_EVIDENCE=0
  1112. for marker in BRIEF.md AGENTS.md bucketlist.md ANCHOR.md; do
  1113. if [ -f "$LEDGER_DIR/$marker" ]; then LEGACY_EVIDENCE=1; break; fi
  1114. done
  1115. if [ "$LEGACY_EVIDENCE" -ne 1 ]; then
  1116. echo "supervisor: AUTOPROMPT_LEGACY_SENTINEL=1 requires a verified legacy resume (legacy governance files under $LEDGER_DIR); unset it for new runs" >&2
  1117. exit 2
  1118. fi
  1119. fi
  1120. if [ -z "$LAUNCHER" ] && [ -z "$LAUNCH_CMD" ] && [ "$DRY_RUN" -eq 0 ]; then
  1121. echo "supervisor: no launch command (use --cmd \"<your CLI>\" / AUTOPROMPT_LAUNCH_CMD, or --launcher apidemo|codexdemo / AUTOPROMPT_LAUNCHER)" >&2
  1122. exit 2
  1123. fi
  1124. resolve_model_casting || exit $?
  1125. resolve_capability_binding || exit $?
  1126. if [ "$DRY_RUN" -eq 0 ]; then
  1127. AGENT_DEFINITIONS_JSON=""
  1128. resolve_agent_definitions_json || exit $?
  1129. fi
  1130. LAUNCH_LABEL="${LAUNCH_CMD:-${LAUNCHER:-<dry-run>}}"
  1131. log "starting: launcher=$LAUNCH_LABEL ledger=$LEDGER_DIR mission=\"$MISSION\""
  1132. 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."
  1133. # THE stale-sentinel guarantee: snapshot every pre-existing DONE-* PATH BEFORE the
  1134. # first launch and BEFORE quarantine. sentinel_present refuses any path still in
  1135. # this snapshot, so a prior-run sentinel can never halt this mission -- even if the
  1136. # quarantine rename below fails (read-only dir / permissions). ORDER IS LOAD-BEARING:
  1137. # snapshot first (records the dir as it was), THEN quarantine -- which prunes each
  1138. # SUCCESSFULLY-renamed path from the live snapshot so the same-activation
  1139. # DONE-<nonce> can be reclaimed by a genuine fresh sentinel. A path whose rename
  1140. # FAILS stays snapshotted and vetoed. Both run before the first sentinel_present.
  1141. snapshot_pre_existing_sentinels
  1142. # Quarantine renames each stale sentinel aside, emits a loud log line, and prunes
  1143. # every successfully-cleared path from the snapshot so a fresh same-path sentinel is
  1144. # honored; a failed rename leaves the path vetoed and degrades to RELAUNCH.
  1145. quarantine_stale_sentinels
  1146. # EDIT 23: seed the session token once, after the ledger dir exists and before the
  1147. # first launch, so run_launcher can re-export it and harvest_session_token can fill it.
  1148. seed_session_token
  1149. restart_times="" # space-separated epoch seconds of recent restarts (no progress)
  1150. last_frontier=$(frontier_count)
  1151. backoff="$RETRY_BASE"
  1152. while :; do
  1153. if sentinel_present; then
  1154. log "DONE-sentinel present - run complete, halting cleanly."
  1155. exit 0
  1156. fi
  1157. run_launcher
  1158. exit_code=$?
  1159. if [ "$SCOPE_BUDGET_TERMINAL" -eq 1 ]; then
  1160. log "SCOPE BUDGET terminal stop - no same-mission relaunch will consume another worker."
  1161. exit 124
  1162. fi
  1163. if sentinel_present; then
  1164. log "DONE-sentinel present after launch (exit $exit_code) - run complete, halting cleanly."
  1165. exit 0
  1166. fi
  1167. # V5 (MANDATORY terminal caller): the child EXITED with no DONE-sentinel - a
  1168. # TERMINAL boundary for that child. Mark it so a ledger audit treats this as
  1169. # run-ended, then run the terminal IDLE-FINISH audit. RUN-ENDED is the marker
  1170. # autoprompt-ledger-check.js reads to set runEnded=true (§2.3 Edit L1). Written
  1171. # every exit-without-sentinel; idempotent (overwritten each exit). The clean-DONE
  1172. # path short-circuits at the sentinel checks above, so RUN-ENDED is only ever
  1173. # written when the run is genuinely not done.
  1174. printf 'run-ended exit=%s ts=%s\n' "$exit_code" "$(date 2>/dev/null)" > "$LEDGER_DIR/RUN-ENDED" 2>/dev/null || true
  1175. if [ "$DRY_RUN" -eq 0 ] && [ -n "$LEDGER_CHECK_PATH" ] && [ -r "$LEDGER_CHECK_PATH" ]; then
  1176. # Best-effort loud-log: the marker alone is sufficient for the rule to fire on the
  1177. # NEXT audit, so this node call's exit 1 is informational; the relaunch happens regardless.
  1178. if node "$LEDGER_CHECK_PATH" --ledger-dir "$LEDGER_DIR" --transcript-dir "$LEDGER_DIR" --terminal >/dev/null 2>&1; then :; else
  1179. log "IDLE-FINISH terminal audit flagged a P0 (run ended with open work, no live agent) - relaunching with RESUME to re-drive."
  1180. fi
  1181. fi
  1182. now=$(date +%s 2>/dev/null || echo 0)
  1183. cur_frontier=$(frontier_count)
  1184. # EDIT 23: harvest the resolver-minted session token (no-op once we hold one) so
  1185. # the next relaunch re-exports the SAME token and a 2nd prompt rejoins the session.
  1186. harvest_session_token
  1187. log "launcher exited ($exit_code); frontier $last_frontier -> $cur_frontier; no sentinel - relaunching with RESUME."
  1188. if [ "$cur_frontier" -gt "$last_frontier" ]; then
  1189. # Healthy-long: progress was made. Reset the poison window and backoff.
  1190. restart_times=""
  1191. backoff="$RETRY_BASE"
  1192. last_frontier="$cur_frontier"
  1193. else
  1194. # No progress since the last launch. Record this restart in the rolling
  1195. # window and check the poison guard.
  1196. new_times=""
  1197. rapid=1
  1198. for t in $restart_times; do
  1199. if [ $((now - t)) -lt "$WINDOW" ]; then
  1200. new_times="$new_times $t"
  1201. rapid=$((rapid + 1))
  1202. fi
  1203. done
  1204. restart_times="$new_times $now"
  1205. if [ "$rapid" -ge "$MAX_RESTARTS" ]; then
  1206. log "POISON: $rapid restarts within ${WINDOW}s with NO frontier progress - escalating, not relaunching."
  1207. {
  1208. echo "supervisor escalation: crash-loop with no frontier progress"
  1209. echo "restarts_in_window=$rapid window_s=$WINDOW last_exit=$exit_code frontier=$cur_frontier"
  1210. echo "ts=$(date 2>/dev/null)"
  1211. } > "$ESCALATE_FILE"
  1212. exit 1
  1213. fi
  1214. # Exponential backoff, capped, between unproductive relaunches.
  1215. if [ "$backoff" -gt 0 ] 2>/dev/null; then sleep "$backoff" 2>/dev/null || true; fi
  1216. next=$((backoff * 2)); [ "$next" -gt "$RETRY_CAP" ] && next="$RETRY_CAP"
  1217. backoff="$next"
  1218. fi
  1219. done
agents/codex/workflow/windows-appcontainer-probe.js · Bundled script · 126 lines · 1 finding marked
  1. 'use strict'
  2. const fs = require('node:fs')
  3. const path = require('node:path')
  4. const crypto = require('node:crypto')
  5. const net = require('node:net')
  6. const { ensureWindowsPrivateAcl, ensureWindowsDefaultTokenOwner, windowsControllerEnvironment } = require('./safe-run-root.js')
  7. function failureDiagnostic(error, phase) {
  8. const details = error && error.details
  9. // This probe only runs fixed controller diagnostics. Preserve their bounded
  10. // failure explanation, never arbitrary error properties or environment maps.
  11. const diagnostic = { phase, message: String(error && error.message || 'Native probe failed').slice(0, 1024) }
  12. for (const name of ['stage', 'helperPhase', 'cause', 'signal']) {
  13. if (typeof details?.[name] === 'string' && /^[A-Za-z0-9_-]{1,80}$/.test(details[name])) diagnostic[name] = details[name]
  14. }
  15. if (new Set(['open', 'read', 'write', 'lstat', 'stat', 'realpath', 'scandir', 'rm', 'rmdir', 'unlink', 'rename', 'chmod', 'mkdir', 'access']).has(details?.syscall)) diagnostic.syscall = details.syscall
  16. for (const name of ['status', 'timeoutMs']) if (details?.[name] === null || Number.isSafeInteger(details?.[name])) diagnostic[name] = details[name]
  17. if (typeof details?.stderr === 'string' && details.stderr) diagnostic.stderr = details.stderr.slice(0, 2048)
  18. return diagnostic
  19. }
  20. function runtimeKey(workerIdentity) {
  21. const hash = crypto.createHash('sha256')
  22. 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)))
  23. hash.update(workerIdentity)
  24. hash.update(fs.readFileSync(process.execPath))
  25. return hash.update(JSON.stringify([process.pid, process.env.SystemRoot, process.env.LOCALAPPDATA])).digest('hex')
  26. }
  27. async function listen(host) {
  28. const state = { accepted: 0 }
  29. const server = net.createServer(socket => { state.accepted++; socket.end() })
  30. await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, host, resolve) })
  31. return { server, state, host, port: server.address().port, family: host === '::1' ? 6 : 4 }
  32. }
  33. async function control(endpoint) {
  34. await new Promise((resolve, reject) => {
  35. const socket = net.connect({ host: endpoint.host, port: endpoint.port, family: endpoint.family })
  36. socket.once('connect', () => { socket.destroy(); resolve() }); socket.once('error', reject)
  37. socket.setTimeout(1500, () => { socket.destroy(); reject(new Error('CONTROL_TIMEOUT')) })
  38. })
  39. await new Promise(resolve => setImmediate(resolve))
  40. }
  41. async function probeWindowsAppContainer() {
  42. return require('./windows-appcontainer-command.js').probeWindowsAppContainer()
  43. }
  44. // This fixed fixture cannot grant admission. Only command.js owns that cache and
  45. // supplies the private tuple-bound executor; external calls receive observations.
  46. async function runWindowsAppContainerCanary(runWindowsAppContainerCommand, workerIdentity, key) {
  47. if (process.platform !== 'win32') return { supported: false, backend: 'windows-appcontainer', code: 'COMMAND_SANDBOX_UNSUPPORTED' }
  48. if (typeof runWindowsAppContainerCommand !== 'function' || !/^[a-f0-9]{64}$/.test(workerIdentity) || key !== runtimeKey(workerIdentity)) throw new Error('CANARY_IDENTITY_MISMATCH')
  49. ensureWindowsDefaultTokenOwner()
  50. const controllerEnvironment = windowsControllerEnvironment(process.env.SystemRoot || process.env.WINDIR)
  51. let base = fs.mkdtempSync(path.join(controllerEnvironment.TEMP, 'autoprompt-appcontainer-probe-'))
  52. let preserve = false, launcherSessionId = null, nativeExitCode = null, probeFailure = null, primaryError = null, phase = 'private-root'
  53. const endpoints = []
  54. try {
  55. base = fs.realpathSync.native(base)
  56. ensureWindowsPrivateAcl(base)
  57. phase = 'private-fixture'
  58. const controlRoot = path.join(base, 'controller'), target = path.join(base, 'target'), scratch = path.join(base, 'scratch')
  59. for (const directory of [controlRoot, target, scratch]) { fs.mkdirSync(directory); ensureWindowsPrivateAcl(directory) }
  60. fs.mkdirSync(path.join(target, '.git')); fs.writeFileSync(path.join(target, '.git', 'guard'), 'controller git')
  61. fs.writeFileSync(path.join(target, 'allowed'), 'allowed')
  62. const deletedOriginal = path.join(target, 'delete-original')
  63. fs.writeFileSync(deletedOriginal, 'controller original', { flag: 'wx' })
  64. const sentinel = path.join(controlRoot, 'sentinel'); fs.writeFileSync(sentinel, 'controller only')
  65. phase = 'loopback-control'
  66. endpoints.push(await listen('127.0.0.1'))
  67. endpoints.push(await listen('::1'))
  68. for (const endpoint of endpoints) { await control(endpoint); if (endpoint.state.accepted !== 1) throw new Error('CONTROL_ACCEPT'); endpoint.state.accepted = 0 }
  69. const targetStat = fs.lstatSync(target, { bigint: true })
  70. 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')
  71. const targetIdentity = targetStat.dev.toString(16).padStart(8, '0') + ':' + targetStat.ino.toString(16).padStart(16, '0')
  72. const fixture = { target, scratch, sentinel, targetIdentity, architecture: process.arch, endpoints: endpoints.map(({host,port,family}) => ({host,port,family})) }
  73. 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})`
  74. const encoded = Buffer.from(source).toString('base64')
  75. // Admission must exercise Bash fork/pipe behavior as well as the Node worker.
  76. // A final simple command can otherwise pass through Bash's exec optimization.
  77. 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
  78. const policy = { schemaVersion: 1, provider: 'claude', nestedDispatch: false, commandBoundary: true, externalWrites: false, targetPath: target, scratchPath: scratch,
  79. readableRoots: [target, scratch], writableRoots: [target, scratch], readOnly: false }
  80. phase = 'command-launch'
  81. const result = await runWindowsAppContainerCommand(policy, { command, cwd: target, timeoutMs: 15000 }, { controlRoot })
  82. phase = 'command-result'
  83. launcherSessionId = result.launcherSessionId; nativeExitCode = result.exitCode; probeFailure = {
  84. stdout: result.stdout.slice(0, 1024), stderr: result.stderr.slice(0, 1024),
  85. timedOut: result.timedOut === true, cancelled: result.cancelled === true, truncated: result.truncated === true,
  86. durationMs: Number.isSafeInteger(result.durationMs) ? result.durationMs : null,
  87. }
  88. try { probeFailure.gitGuard = fs.readFileSync(path.join(target, '.git', 'guard'), 'utf8') === 'controller git' ? 'UNCHANGED' : 'CHANGED' } catch { probeFailure.gitGuard = 'UNREADABLE' }
  89. if (result.workerIdentity !== workerIdentity) throw new Error('WORKER_TUPLE_CHANGED')
  90. 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')
  91. phase = 'original-recovery'
  92. // runTupleCommand returns only after owned drain and validated ACL recovery.
  93. // This exercises the private TEMP fixture's volume, not arbitrary projects.
  94. if (result.resourceRecovery?.deletedEntries !== 1) throw new Error('ORIGINAL_RECOVERY_UNPROVEN')
  95. let originalAbsent = false
  96. try { fs.lstatSync(deletedOriginal) } catch (error) { if (error.code === 'ENOENT') originalAbsent = true; else throw error }
  97. if (!originalAbsent) throw new Error('ORIGINAL_DELETE_UNPROVEN')
  98. for (const root of [target, scratch]) {
  99. let createdAbsent = false
  100. try { fs.lstatSync(path.join(root, 'delete-created')) } catch (error) { if (error.code === 'ENOENT') createdAbsent = true; else throw error }
  101. if (!createdAbsent) throw new Error('CREATED_DELETE_UNPROVEN')
  102. }
  103. phase = 'loopback-denial'
  104. 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') }
  105. const supported = Object.freeze({ supported: true, backend: 'windows-appcontainer', runtimeSha256: key, workerIdentity, launcherSessionId: result.launcherSessionId,
  106. resourceRecovery: Object.freeze({ ...result.resourceRecovery }), resourceRecoveryScope: 'pre-existing original deleted and recovered on private TEMP fixture volume',
  107. networkProof: 'zero sandbox accepts between successful same-listener IPv4/IPv6 controller checks; bounded explicit socket denial', processCleanup: 'owned-job-drained' })
  108. return supported
  109. } catch (error) {
  110. primaryError = error
  111. preserve = error.cleanupConfirmed === false || error.code === 'APPCONTAINER_CLEANUP_UNCONFIRMED' || Boolean(error.recovery && !error.recoveryResolved)
  112. 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 } : {}) } : {}) }
  113. } finally {
  114. let cleanupFailure
  115. for (const endpoint of endpoints) { try { endpoint.server.close() } catch (error) { cleanupFailure ||= error } }
  116. if (!preserve && !cleanupFailure) { try { fs.rmSync(base, { recursive: true, force: true }) } catch (error) { cleanupFailure ||= error } }
  117. if (cleanupFailure) {
  118. const error = primaryError || cleanupFailure
  119. error.cleanupConfirmed = false
  120. error.recoveryRoot = base
  121. error.cleanupCode = String(cleanupFailure.code || 'cleanup-failed').slice(0, 64)
  122. throw error
  123. }
  124. }
  125. }
  126. module.exports = { probeWindowsAppContainer, failureDiagnostic, canaryKey: runtimeKey, runWindowsAppContainerCanary }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.