diff --git a/DECISIONS.md b/DECISIONS.md index 0005e61..bd8eb0d 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -230,3 +230,5 @@ Status: **decided** (owner agreed), **adopted** (recommended and taken; confirm | S-220 | **The channel and the MCP router are MCP servers on the environment module; the channel connects as its own login** (2026-11-27; `docs/parts.md` "Order" step 2, second part). (a) **The channel** (`environment/channel.py`, stdio, started by the harness) was already an MCP server reading the environment's queues, but it connected as Postgres's superuser. It now connects with `DATABASE_URL`, its own login `mcp_channel` (role `env_agent`: publish, act through the gates, read and acknowledge the queues it subscribed; it cannot decide, set a gate or read another's queue), password `MCP_CHANNEL_DB_PASSWORD` (`deploy/secrets.txt`, made by `scripts/settings.sh`, the login by `scripts/db.py init`). `scripts/assistant.sh` writes it into the channel's MCP entry (`.state/assistant/mcp.json`, mode 600, beside the token it already held); `013_review_lane.sql` gives the login the assistant's queues made before. Without `DATABASE_URL` it still falls back to `ENV_URL`, `STORE_URL`, then the superuser, for a person at the command line. It stays in the `environment` package: it is a few lines over the module's functions, not a part with code of its own. (b) **The router** (`mcp-router/`, Go) is already a compose-service MCP server whose registry (`env.mcp_server`, `env.mcp_tool`, `env.mcp_policy`) and gates are the environment module's schema; it now decides nothing (S-219 c). S-205 (g)'s question, whether it moves into the kernel's core, stays open. (c) **The catalog:** `component:environment` is now a service with its compose service, `component:channel` is new. (d) **Checked:** four new checks in `scripts/tests/test_environment.py` (the channel's session runs on an `env_agent` login; that login may not decide, set a gate or read a queue it did not subscribe), and the channel started from `assistant.sh`'s dry-run settings on the throwaway stack initialised as `mcp_channel` and acted through the gates. | adopted | | S-221 | **The assistant's conversation is already a view in the kernel's desktop; nothing more is built for it until a use case asks, and `ui/` stays** (2026-11-27; `docs/parts.md` "Order" step 2, third part: "built as far as a use case needs"). The Assistant view (`desktop/view-assistant/`, a view module in the kernel's contract, mounted into the kernel's container, S-206) and its messages as signals in `env` (`011_desktop.sql`) are the target shape already; its server `desktop/server.py` is an MCP server through the router, as S-213 (a) wants. What it lacks (a chat library picked with the `research` skill, S-208) waits for the next use of the assistant. `ui/` is not retired: the kernel's Map view draws one map, and Substrate's many maps (S-207: a map as an item, one marked self) are not in the kernel yet. | adopted | | S-222 | **A preview release, v0.1.0-preview.1: images pinned to the release, a fresh install tested, a second copy on one machine possible** (2026-11-27; the owner wants projects released, Morphogen first, Substrate as a clearly labelled preview while the re-cut is under way; numbered after the re-cut's S-219 to S-221, PR #32). (a) **Versions:** `VERSION` holds the release (`0.1.0-preview.1`); `deploy/compose.yaml`'s image defaults, `image_ref` in `scripts/lib.sh` (`SUBSTRATE_VERSION`, `KERNEL_VERSION`) and `.env.example` name it and the kernel release it pins (`0.1.0`, the kernel's tag on `e4ed8e2`'s code), no longer `main`; `scripts/tests/test_release.py` keeps them equal, checks the images workflow publishes `v*` tags (it already did: the tag as pushed and the version without the v) and that release notes exist (`docs/release-notes/`). A kernel image that does not pull is built from its tag `v`; `scripts/build.sh` pulls or builds the router's image too. A working checkout that wants `main` sets the tags in `.env` (an existing `.env` keeps what it has). (b) **The fresh install** (a clone in a temporary folder, the README only, beside other stacks on the owner's machine): it failed three ways, each fixed: the desktop's framed-app ports 8081 to 8083 were fixed and taken on this machine (now `DESKTOP_GATEWAY_PORT`, `DESKTOP_MAPS_PORT`, `DESKTOP_ROUTER_PORT`: compose maps them to Caddy's fixed 8081 to 8083, the Caddyfile's frame-src names them, `apps.json` is rendered by Caddy's `templates` with `{{env}}`, `check.sh` and `assistant.sh` read them); a first `up.sh` stopped in `gateway.py prune` while Bifrost was still making its tables (prune now waits for none of them: with any missing there is nothing stale); and a second copy would have shared the first one's data and tools container (`COMPOSE_PROJECT_NAME`, `TOOLS_CONTAINER`, `KERNEL_ARTIFACTS_VOLUME` are settings beside `DB_VOLUME` and `OLLAMA_VOLUME`; `tools.sh` refuses to replace another checkout's container, which it did before: the test removed the owner's stopped `substrate-tools`, which `scripts/tools.sh start` recreates). `bootstrap.sh` checks for curl (rule 6 names it). With those, bootstrap, up, check and every test suite passed on the fresh clone. (c) **The README** says what the preview is, what works, what is moving and what it needs; release notes are `docs/release-notes/v0.1.0-preview.1.md`. (d) **The owner releases** (not done here): the kernel's `v0.1.0` first, then this repository's `v0.1.0-preview.1`, each pushed tag publishing its images. | adopted — confirm | +| S-223 | **A manager agent: a router with a ledger, which knows every project, hands work to workers and never does it itself; the design is `docs/manager-agent.md`** (2026-11-27; the owner wants a main agent that acts like a project manager, aware of all projects, delegating to workers, staying responsive, with a UI in the kernel's desktop: "yes, start the manager agent design"). S-223 because #32 takes S-219 to S-221 and #33 S-222; builds on #32's design (the environment as a kernel module, `propose` in the kernel's review lane, the channel and router as MCP servers), not its code. (a) **The portfolio** in the environment module (`env.project`, `env.worker`, `env.decision`, a new `014_portfolio.sql`), written only through a portfolio MCP server behind the router that checks each caller's token, with a files-only mirror as Backstage entities (`portfolio/`, Morphogen's format, S-209). The manager cannot set a project done, set its class, write a worker's state or answer a decision; a worker reports only on itself; the supervisor cannot answer. (b) **The manager** is a Claude Code session on Haiku in its own container (as the companion, S-136, S-144) with no built-in tools (`--tools ''`, so no Bash, edits or Agent tool), only the channel and the router, a hook that caps a turn at 8 tool calls, and its calls metered at the gateway as `manager:session`. Haiku, not `fast` (S-170): the manager needs Claude Code's loop with about ten tools and writes the briefs workers succeed or fail by; its routing choices are recorded so they can be replayed against `fast`. (c) **Workers** start through actuators `pm.start` (free: an `own` project on the subscription or a quota) and `pm.start_gated` (propose: client work, containers for a client, cloud, past a budget or quota), the gate chosen by the server from the project's class, never by the manager. Runners: `local` (`claude --bg` in a worktree) first, then `container` (`claude -p --output-format stream-json --max-budget-usd`), `kaggle` (MetaSoar's `job.py`), `scheduled` (pg_cron); `cloud` not in v1. Workers report through one tool, `pm_report` (kind, a summary of at most 300 words, refs: branch, PR, commit, results), never a transcript. Workers are background sessions, never subagents: today's two agents stopped at the usage limit were subagents, which `claude agents --json` does not list (seen 2026-11-27, Claude Code 2.1.332). (d) **The supervisor**, on the host (`uv run`, its own login `pm_supervisor`), outside the manager's reach, applies the actuators and watches every runner, publishing `pm.worker.` (working, needs_input, stalled, limited, finished, failed, stopped) and respawning a session stopped by the usage limit at its reset, one at a time. The trial `scripts/trials/manager/watch.py` is its watch half with no database; run once it read the one background session as `pm.worker.finished`. (e) **Decisions:** gated actions stay in the review lane (#32); questions and notices are `env.decision` rows the person accepts, edits, responds to or ignores; notifications only on needs-input, failed or stalled, a verdict, over budget. "Done" is a `judge` worker's verdict with a clean context (`morphogen change` or `judge`, or Morphogen's reviewer), never the worker's; the person merges. (f) **The UI** is a view module `desktop/view-manager/` (projects, workers with peek, log and stop, the inbox; spend from the gateway's meter), beside the Assistant window, where the manager now answers. (g) **First trial, PM-1**, registered here, also a model comparison (the owner: "Haiku-5.5 would be nice for cost efficacy, but might not be the most reliable - something worth testing"): Haiku 5.5 and Sonnet 5.5 as the manager, the local `fast` model on routing only, the same workers. PM-1a replays 43 labelled scenarios (`scripts/trials/manager/scenarios.json`, paraphrases of the owner's requests across the four projects, with recovery cases: a usage-limit stop, a merge conflict, a stall) three times per arm with a stub portfolio; PM-1b is nine live messages in three rounds across two scratch repositories while workers run, once per arm. The lean manager is falsified by more than one reply later than 30 s, any work attempt, more than one of six requests misrouted or not delegated, the manager's tokens over 10% of the workers', a worker's needs-input or finish reaching the inbox later than 60 s, or a worker lost. "Haiku is reliable enough" is refuted by routing-and-delegation accuracy more than 5 points below Sonnet's with the paired 95% interval wholly below zero (5: about the manager's share of tokens, which is all Haiku can save), more than one work attempt, more than one must-escalate case missed that Sonnet catches, or two or more fewer workers finishing without coming back to ask; then the manager runs on Sonnet. No public benchmark tests this role; MS-Eval's delegation subset and τ²-bench's published scores are sanity checks only. Build order and the owner's open questions (privacy of the manager's stream, whether it replaces the assistant, which projects are `own`, workers' defaults, cloud work, automatic resume, where the mirror lives) are in the document. | proposed | +| S-224 | **The manager's prompt is a Morphogen cell, optimised with GEPA on held-out scenarios; the first run is refused and the prompt stays** (2026-11-27; the owner: "if our agent environments are supposed to assist with optimization, we should be able to optimize the manager/operator/delegator against its goals and feedback"; builds on S-223 and S-193, S-216; branch `claude/manager-agent`, PR #34). (a) **Scoring frozen:** PM-1a's `score.py`, `stub_pm.py`, `portfolio_fixture.json`, `scenarios.json` and the split files are hashed in `scripts/trials/manager/results/pm1a-scoring-frozen.json` (checked by `freeze.py` before every optimisation and judgement, and by the test); no change after seeing results, a change is a new version. Baseline before and after PM-1a's own rule change recorded together in `pm1a-scoring-frozen.md`: 67% (first rules, never committed, cannot be recomputed) and 81.4% (frozen rules, the saved traces rescored). (b) **Split,** fixed seed 20261127, stratified by expected action with the r-series recovery cases as a stratum: 20 train, 10 dev, 13 held out (`split.py`, `split.json`). The optimiser reads `scenarios-search.json` (train and dev) only; the held-out labels and cases live outside the repository in two directories named in the uncommitted `morphogen.local.yaml` (Morphogen's convention: `private` for the scorer alone, `inputs` for the workload). They are not isolated from the owner's user or from an agent running as them (only a second Unix user, Morphogen's `morphogen-judge`, would do that), and `scenarios.json` still holds all 43 as PM-1a's record, so the held-out text is in git history: the held-out set is blind to GEPA, not to the authors, and the feedback loop (`docs/manager-agent.md`, "Optimising the prompt") supplies fresh held-out cases. (c) **The cell,** `catalog/component-manager-prompt.yaml` (Morphogen reads it: `spec.morphogen`): `change` is `scripts/trials/manager/manager.md` only; `run`/`score` are `cell.py run` and `cell.py score`; primary metric **routing accuracy** (the figure PM-1's falsifier 1 is stated in; it covers project and action, so a manager that answers instead of delegating loses it), minimum gain 5 points absolute; constraints that are never traded for score: **did the work itself** may not rise above 0 (falsifier 2), **delegation recall** may not fall by more than 10 points (a guard: a prompt can raise routing by asking more and delegating less); tokens and latency `observe`d through Claude Code's own OpenTelemetry export (`PM_PASS_TELEMETRY=1`); `autonomy` stays at its default, `review`: the owner merges a new prompt. Not run through `morphogen judge`: an agent cell needs `sandbox: none` and its sign test (p at most 0.01) needs more rounds than 13 scenarios and this budget allow, so `judge.py` applies the cell's rule with the same scorer, paired, 3 runs per arm, written before any held-out run. (d) **GEPA** `gepa==0.1.4` standalone (`optimise.py`, a custom adapter: Haiku 5.5 through the PM-1a `claude -p` driver is the task, Sonnet 5.5 through `claude -p --model sonnet` with no tools is the reflection, the subscription only). Budget used: 100 Haiku runs and 8 Sonnet calls in the run, 52 more Haiku runs lost to a bug of mine (no reflection ran) and a smoke test; 78 in the judgement. (e) **Verdict: refused.** Dev: seed 9/10, best candidate 10/10 (selection-biased, one scenario); held-out, 3 paired runs: routing 71.8% baseline, 69.2% candidate, paired 95% [-10.3, +5.1] points; work itself 0; delegation recall equal; the manager's prompt is unchanged. The result says little either way: dev had one failure to learn from and 13 held-out scenarios cannot show less than 8 points. (f) **Feedback loop, design only:** corrections, "you should have delegated that" and decisions overturned in the review lane become scenarios (message, portfolio state, owner's label, confirmed by the owner), added 2 to 1 to train and dev, with about a third of every fourth batch moved to held-out; scoring versions change only with the old and new scores recorded together. | proposed | diff --git a/catalog/catalog-info.yaml b/catalog/catalog-info.yaml index 0729691..8da10f9 100644 --- a/catalog/catalog-info.yaml +++ b/catalog/catalog-info.yaml @@ -34,6 +34,7 @@ spec: - ./component-llm.yaml - ./component-mcp-desktop.yaml - ./component-mcp-kernel.yaml + - ./component-manager-prompt.yaml - ./component-mcp-router.yaml - ./component-ollama.yaml - ./component-ui.yaml diff --git a/catalog/component-manager-prompt.yaml b/catalog/component-manager-prompt.yaml new file mode 100644 index 0000000..670967d --- /dev/null +++ b/catalog/component-manager-prompt.yaml @@ -0,0 +1,40 @@ +# A catalog entry (S-176) that is also a Morphogen cell (S-224): the manager agent's system prompt, optimised with GEPA +# and judged on held-out scenarios. `change` names the prompt file alone; the scorer is PM-1a's, frozen by hash +# (scripts/trials/manager/results/pm1a-scoring-frozen.json). The held-out scenarios are not in this repository: the +# operator names them in the uncommitted morphogen.local.yaml (see docs/manager-agent.md, "Optimising the prompt"). +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: manager-prompt + title: The manager agent's system prompt + description: The prompt of the manager, a router with a ledger over the portfolio (docs/manager-agent.md); one text file, optimised against PM-1a's labelled scenarios and judged on held-out ones. + annotations: + substrate.dev/source: scripts/trials/manager/manager.md + substrate.dev/decision: S-223, S-224 +spec: + type: prompt + lifecycle: experimental + owner: owner + system: substrate + morphogen: + description: Haiku 5.5 as the manager, through a stripped-down claude -p session on the subscription, on 13 held-out PM-1a scenarios. + change: scripts/trials/manager/manager.md + run: python3 -I scripts/trials/manager/cell.py run + score: python3 -I scripts/trials/manager/cell.py score + # The primary metric is routing accuracy (project and action both right), the thing falsifier 1 of PM-1 is stated in. + # Constraints, never traded for score: the manager does the work itself in no scenario, and delegation recall (start, + # message or stop when one was expected) does not fall by more than 10 points. A pass needs routing to gain 5 points. + better: + routing_accuracy: {higher: true, min: 0.05, gain: absolute, aggregate: mean} + work_itself: {lower: true, max_regression: 0, gain: absolute, aggregate: mean} + delegation_recall: {higher: true, max_regression: 0.1, gain: absolute, aggregate: mean} + # Tokens and latency, collected by Claude Code's own telemetry outside the workload (PM_PASS_TELEMETRY=1 lets the + # driver pass the variable on); recorded with the verdict, not a condition of it. + observe: + type: otel + collected: outside + metrics: + output_tokens: {metric: claude_code.token.usage, where: {type: output}} + input_tokens: {metric: claude_code.token.usage, where: {type: input}} + api_ms: {event: claude_code.api_request, field: duration_ms} + tests: python3 -I scripts/tests/test_manager_trial.py diff --git a/docs/manager-agent.md b/docs/manager-agent.md new file mode 100644 index 0000000..8bfb954 --- /dev/null +++ b/docs/manager-agent.md @@ -0,0 +1,634 @@ +# The manager agent (S-223, proposed) + +A design, not a build. The owner (2026-11-27) wants a main agent that acts like a project manager: it knows every +project, hands work to worker agents, never does the work itself, and stays free to answer, because a Claude Code +session doing long work itself cannot take new messages until it finishes. It should have a UI, ideally a view in the +kernel's desktop. The owner: "yes, start the manager agent design". + +This builds on the shape of PR #32 (the environment as a kernel module, proposals decided in the kernel's review lane, +the channel and the router as MCP servers), not on its code, which is not merged. Its decision is S-223 in +`DECISIONS.md` (#32 takes S-219 to S-221, #33 takes S-222). The research behind it, with sources, was done on +2026-11-27 and is summarised where it is used. The only code here is a trial, `scripts/trials/manager/watch.py`: the +supervisor's watch over Claude Code's background sessions, which prints what it would publish. PM-1's scenario set +(`scripts/trials/manager/scenarios.json`) is data for the trial in section 8. + +## In one paragraph + +The manager is a router with a ledger. It is a lean Claude Code session on Haiku, fed by the channel, with no +built-in tools at all: it can read and write the portfolio, start, message and stop workers, and talk to the person, +all through the MCP router, and nothing else. Anything that would take more than a few tool calls becomes a worker. +Workers are ordinary Claude Code runs (a background session in a worktree first; later a container, Kaggle or a +schedule), started by actuators behind gates. They report through one tool, with references (branch, pull request, +results file) and a short summary, never a transcript. A supervisor outside the manager's reach watches every runner +and publishes each change of state, including stalls and stops at the usage limit, which it resumes on its own after +the reset. The person sees one view in the kernel's desktop: the projects, the workers, and an inbox of decisions. +"Done" is decided by a judge with a clean context, never by the worker that did the work. + +## What the research says, in short + +- **The product exists, but in the cloud.** Claude Code Projects (public beta) is exactly this loop: one + conversation coordinates threads, an Overview groups them as *Ready for review, Waiting on you, Working*, and the + conversation "sees what threads report back, not every step they take" (code.claude.com/docs/en/claude-projects). + Its threads are cloud sessions on github.com repositories; they do not load a repository's `.mcp.json` or hooks, + and reach local things (the stack, local models, Podman, Kaggle's CLI) only as Remote Control sessions. Substrate's + privacy rule also argues against making it the only home (`docs/privacy.md`). +- **The parts exist locally.** `claude --bg` and `claude agents --json` (agent view, research preview), + cross-session messaging, channels (research preview), and cloud scheduled tasks with an API trigger. +- **The manager must be unable to work.** Agent teams' docs say the lead "sometimes starts implementing tasks itself + instead of waiting"; CrewAI's hierarchical mode is widely reported to do the same. An instruction does not hold; + taking the tools away does. +- **State outside the manager; references, not transcripts.** Every system that scales keeps the plan and status in a + ledger, board or issue tracker, and passes back references (Anthropic's multi-agent research post: artifacts on the + filesystem and "lightweight references", to avoid a game of telephone; Magentic-One's task and progress ledgers). +- **This is the favourable case for many agents.** Workers act on separate repositories, so the work is parallel with + no shared writes; centralised coordination gained 80.8% on parallel tasks and lost on sequential ones (Kim et al., + arXiv 2512.08296). The rule that follows: **one writer per project at a time, the manager never writes project + code, a reviewer gets a clean context** (Cognition, "Multi-agents: what's actually working", 2026). +- **The UI has converged:** a board with one state per item, an inbox of decisions (notify, question, review; accept, + edit, respond, ignore: LangChain's Agent Inbox), peek before attach, notifications only on transitions. +- **No public benchmark tests this role.** Some test parts of it: whether to delegate (MS-Eval), which peer to hand to + (DecisionBench), when to hand to a human (τ²-bench), tool choice (BFCL, the MCP benchmarks). None tests routing + across projects, brief quality, or recovery from a worker that stops. So the model is chosen by PM-1, our own + replayable trial (section 8), and a public benchmark is at most a sanity check. + +Prior work here: the companion (S-136, S-144, S-145) was this loop's core, a Haiku session in its own container on +the channel with a `task` actuator that ran `claude -p`. S-171 found its one worker "takes one task at a time, so a +reminder would wait behind a long job". S-195 removed the code; it is in commits `1f36971` and `e231ee2`. + +## 1. The portfolio + +One record of the projects, the workers and the decisions, that the manager, the supervisor and the view all read. +It lives in the environment module (a new `environment/sql/014_portfolio.sql`, after #32's `013`), with a files-only +mirror so it also works with no kernel running. + +### The tables + +| Table | One row per | Columns | +| --- | --- | --- | +| `env.project` | project | `id` (slug, e.g. `substrate`), `repo` (path and remote), `goal` (one line, the person's), `class` (`own` or `client`: decides the gates, set by a person only), `status` (`active`, `paused`, `done`), `next_step` (one line), `entity` (its Backstage entity ref, when it has a catalog), `judge` (how "done" is checked: `morphogen-change`, `morphogen-cell:`, `review`), `budget_tokens_day`, `updated_by`, `updated_at` | +| `env.worker` | started run | `id`, `project`, `runner` (`local`, `container`, `kaggle`, `scheduled`, later `cloud`), `kind` (`work` or `judge`), `brief` (the text it was started with), `handle` (the runner's own id: a background session's id and session id, a container's name, a Kaggle notebook), `branch`, `state` (below), `state_at`, `last_report` (the latest summary), `refs` (jsonb: branch, PR, commit, results file), `tokens` (from the meter), `resumes` (how many times the supervisor resumed it), `started_by` (the action that started it) | +| `env.decision` | thing waiting on the person | `id`, `project`, `worker`, `kind` (`notify`, `question`, `review`), `text`, `options` (jsonb), `proposed` (the action proposed, if any), `action` (the `env.action` id when it is a gated proposal in the review lane), `state` (`open`, `answered`, `ignored`, `expired`), `answer` (jsonb: accept, edit, respond or ignore, and the text), `answered_by`, `answered_at` | + +Worker states use the vocabulary the products converged on, mapped from each runner's own: `starting`, `working`, +`needs_input`, `stalled`, `limited` (stopped by the usage limit, resume due), `finished` (the worker says done), +`judging`, `verified` or `rejected` (the judge's verdict), `failed`, `stopped`. Each change is also a signal +`pm.worker.` with the worker's id, so the record of what happened is `env.signal`, as for everything else. + +### Who may write what + +Enforced by Postgres logins and security-definer functions granted by name, as in `006_logins.sql` and #32's +`013_review_lane.sql`. A process that runs a model can never decide, answer for a person, or mark its own work done. + +| Login (role) | Is | May | May not | +| --- | --- | --- | --- | +| `mcp_pm` (`env_pm`) | the portfolio's MCP server (below), which checks the caller's kernel token on every call, so its functions take the caller's role as an argument and the server is the only writer | everything below on behalf of a caller whose role allows it | anything with no caller | +| caller `agent_manager` | the manager, through the router | read all; set a project's `next_step` and `status` `active` or `paused`; open a `notify` or `question` decision; call the start, message and stop actuators | set `class`, `goal` or `status` `done`; answer, edit or close a decision; write a worker's state; change a gate | +| caller `agent_worker` | any worker, through the router | report on its own worker id (the server checks the id against the token's `worker` claim, minted per worker by the supervisor) | report on another worker; report a `verdict` unless its worker's `kind` is `judge`; read other projects | +| `pm_supervisor` (`env_supervisor`) | the supervisor | write a worker's `state`, `handle`, `tokens`, `resumes`; publish `pm.worker.*`; read and apply the start, message and stop actuators' queues (`env.done`) | open or answer decisions; write projects | +| `person_` | a person, in the view or with `kk`/`psql` | everything, including `class`, `goal`, answering decisions; gated actions are still decided in the review lane (#32) | approve their own proposal (the kernel and the environment both refuse it) | + +### The files-only mirror + +`portfolio/` in a repository the owner picks (Substrate's own, by default), Backstage entity files in Morphogen's +format (S-209): one `kind: Component` per project with `spec.lifecycle` for its status and the rest under +`spec.morphogen.project` (repo, goal, class, judge, next step), and a `portfolio/catalog-info.yaml` Location. Workers +and decisions are not in the files: they change by the minute and belong to the live record. `scripts/portfolio.py +export|import` writes the files from the tables and reads them back; a person may edit the files and import them, +and with no kernel the manager reads them directly (read-only). The kernel's `encoder-backstage` ingests them like +any catalog when search is wanted. + +## 2. The manager + +### What it is + +A Claude Code session kept open in a container of its own (the companion's arrangement, S-136: its own home volume, +the owner logs in once, no host changes), started by `scripts/manager.sh` in the way `scripts/assistant.sh` starts +the assistant today: + + claude --model claude-haiku-5-5 --effort low --tools '' --strict-mcp-config --mcp-config \ + --append-system-prompt "$(cat manager.md)" --dangerously-load-development-channels server:pm + +- **No built-in tools** (`--tools ''`, S-144's lean profile): no Bash, Read, Edit, Write, WebFetch, and no Agent + tool, so it cannot run a subagent to do the work inline either. `ENABLE_TOOL_SEARCH=false` (S-145). +- **Its MCP servers are the channel and the router only** (`--strict-mcp-config`). Through the router, its tools are + `desktop_say`, `desktop_show`, `desktop_ask` (the conversation, S-206), `pm_portfolio`, `pm_project_note`, + `pm_decision_open`, `pm_worker_start`, `pm_worker_message`, `pm_worker_stop`, and the kernel's read tools + (search, explain) so it can answer "what did we decide about X". Each call is an action, recorded with its caller. +- **A turn cap** as a hook (`PreToolUse`, in the container's settings): more than 8 tool calls in one turn are denied + with "hand this to a worker". The cap is the guard; the count of denials is a measure (section 7). +- Its model calls go through the gateway's pass-through route with its own key, caller `manager:session` (S-144, + S-145), so its share of tokens is the gateway's count, not its own. + +### The model: Haiku, and why not the local fast model yet + +The owner's rule is to use the local model when it can do the job (S-170). For the manager it cannot yet: + +1. **The manager must run in a harness that takes a channel and MCP tools,** and Claude Code is the one Substrate + uses (S-211). Claude Code's agent loop on LFM3 1.7B (`fast`) is untried; the voice router got the 1.7B model to + 12/12 only with three forced tools and a tuned prompt (S-170), and the manager has about ten tools and must write + briefs. +2. **The brief is where multi-agent systems fail most** (MAST: specification and system-design failures are the + largest group; Anthropic: vague briefs gave duplicated work). A worse brief costs a worker's whole run; a better + manager costs a few hundred tokens a turn. +3. **Its turns are short,** so Haiku's cost is small next to the workers' (Sonnet or Opus), and the trial measures + that share (section 8). + +Haiku is the default, not a settled choice. The owner: "Haiku-5.5 would be nice for cost efficacy, but might not be +the most reliable - something worth testing". PM-1 compares Haiku 5.5 with Sonnet 5.5 as the manager on the same +scenarios and workers (section 8). The same reason that makes Haiku cheap enough also makes the saving small: the +manager's share of all tokens is a few percent, and one misrouted request or one vague brief costs a whole worker +run. So Haiku has to be nearly as accurate as Sonnet to be worth it, not just good. The falsifier says how near. + +The local model keeps a path in: every routing choice the manager makes is a recorded action (project, runner, the +brief), so the choices can be replayed against `fast` offline, as MetaSoar's E-04a replayed decisions. If `fast` +matches Haiku on them, the routing step moves to it. Privacy: the owner's messages to the manager and the projects' +summaries reach Anthropic, as S-136 allowed for the companion's stream; the workers send code to Anthropic already. +This needs the owner's confirmation for this stream (open question 1). + +### What it hears + +Its queue `pm_manager` is bound to: + +| Pattern | From | +| --- | --- | +| `desktop.person_owner.message` | the person, in the desktop | +| `pm.worker.#` | the supervisor (state changes) and the workers (reports, through the portfolio server) | +| `pm.decision.answered` | the view, when the person answers a decision | +| `env.review.decided` | the review lane (#32), for a gated start or a worker's gated proposal | +| `pm.meter.#` | the supervisor's reading of the gateway's meter (`over_budget`) | +| `pm.clock.daily` | pg_cron in the database (already in Substrate's Postgres image), once a morning | + +### What it does with each + +Every turn ends in at most a few tool calls; "a few" is the cap above. The prompt (`deploy/manager/manager.md`) lists +these, and nothing in it describes how to do a project's work. + +| Message | It does | Notifies the person? | +| --- | --- | --- | +| The person asks about status ("where is E-19?") | `pm_portfolio`, then `desktop_say` with the project's state, its workers and open decisions | it is the answer | +| The person asks for work | picks the project (or asks which, with `desktop_ask`, if two fit); writes a brief (objective, output, boundaries, done-when, section 3's report contract); `pm_worker_start`; `desktop_say` "started W-12 on MetaSoar: ...; I'll tell you when it needs you" | it is the answer | +| The person says something to a worker ("tell the Substrate worker to use port 8180") | `pm_worker_message` | a one-line acknowledgement | +| A question the manager can answer from the portfolio or the kernel | answers it | it is the answer | +| A worker's progress report | `pm_project_note` (next step) if it changed; `ack` | no | +| A worker needs input | `pm_decision_open` (kind `question`, the worker's question, its options, a proposed answer when the brief settles it) | yes | +| A worker finished | starts a `judge` worker when the project has a judge; otherwise opens a `review` decision with the branch and PR | only when there is something to review | +| The judge's verdict | `pm_project_note`; opens a `review` decision with the verdict and the PR (the person merges) | yes | +| A decision answered | `pm_worker_message` with the answer, or `pm_worker_start` if it was a proposed start | no | +| A worker failed or stalled | opens a `question`: resume, re-brief, or stop | yes | +| A worker limited, or resumed | nothing (the supervisor handles it); a second failed resume arrives as `failed` | no | +| Over budget | the supervisor has already set the start actuators to `propose`; opens a `notify` | yes | +| The morning tick | `desktop_say` a digest, only of what changed since yesterday | only if something changed | + +After each event it calls `ack`. An event it does not handle comes back after the channel's visibility timeout, with +its delivery count, so a restart loses nothing (`environment/channel.py`). + +### Why it stays responsive + +Three things together: every turn is short (no tool can run long, and the hook caps the count); everything long is a +worker, a separate process the manager never waits on; and its memory is the portfolio, so it can be restarted or +compacted at any time without losing track. Channel events that arrive during a turn wait for it, seconds at most. + +## 3. Workers and how they start + +### The actuators + +| Actuator | Gate | Input | Applied by | +| --- | --- | --- | --- | +| `pm.start` | `free` | `{project, runner, brief, model?, effort?}` | the supervisor | +| `pm.start_gated` | `propose` | the same | the supervisor, once a person approves in the review lane | +| `pm.message` | `free` | `{worker, text}` | the supervisor | +| `pm.stop` | `free` | `{worker, why}` | the supervisor | + +The manager never chooses the gate. The portfolio server's `pm_worker_start` sends a start to `pm.start` only when +the project's `class` is `own` and the runner spends nothing beyond the subscription and its quotas (`local`, +`scheduled` on the machine, `kaggle` within the week's GPU hours); a `client` project, a container that runs a +client's code, a cloud runner, a Kaggle run past the quota, or a project over its token budget goes to +`pm.start_gated`. The server is code the manager cannot change, and the gate itself is the database's. + +### The runners + +| Runner | Starts with | State from | Stop | Resume | First? | +| --- | --- | --- | --- | --- | --- | +| `local`: a background session in a worktree | `cd && claude --bg --name pm- --model sonnet --permission-mode auto --mcp-config --append-system-prompt ""`; it moves into `.claude/worktrees/` before editing and opens a draft PR when it finishes (agent view, v2.1.198) | `claude agents --json --all`: `state` working, blocked, done, failed, stopped; `waitingFor` | `claude stop ` | `claude respawn `, or `claude --resume --bg ""` (continues in place, v2.1.257) | yes | +| `container`: `claude -p` in a container | `podman run` of a worker image (the companion's `deploy/companion` Containerfile, revived) with `claude -p --output-format stream-json --max-budget-usd ` over a clone; for client code or anything that should not touch the host | the stream: `system/api_retry` events (`error: rate_limit`), the `result` message (`total_cost_usd`, `session_id`, `is_error`); the container's exit | `podman stop` (SIGTERM ends the turn unfinished, exit 143) | `claude -p --resume "continue"` | second | +| `kaggle` | MetaSoar's `trials/kaggle/job.py NAME --commit SHA ... --no-wait` (the owner: all experiments on Kaggle) | `kaggle kernels status`; the outputs when it ends | the Kaggle CLI's `kernels` commands have no cancel (its help, 2026-11-27); stop is the person's, on Kaggle's page | `job.py --resume NAME` (copies the earlier job's outputs first) | third | +| `scheduled` | a schedule row; pg_cron publishes `pm.schedule..due` and the supervisor starts a `local` worker with the saved brief | as `local` | as `local` | as `local` | third | +| `cloud` | a cloud scheduled task's API trigger (`POST .../routines//fire`, beta header `experimental-cc-routine-2026-04-01`, claude.ai only, research preview), or a Projects thread | no supported way for a script to read a cloud session's state was found; the task's own report is the only signal | the task's page | n/a | not in v1 (open question 5) | + +Workers on the host run as the owner, with the owner's git, `gh` and Kaggle credentials, in auto mode, so their +boundaries are their brief's and Claude Code's permission rules', as in any session the owner starts today. Each +`local` worker's settings put its model calls through the gateway (an `env` block with the pass-through route and +the key of caller `pm:worker`, since a background session takes the gateway only from settings or its supervisor's +shell, per agent view's docs), with the worker's id in a custom header so the meter can count it. Whether Bifrost +keeps that header per call is checked in build step 3; if not, a worker's tokens come from its transcript's usage. + +Use background sessions, not subagents. A session's background subagents (the Agent tool) are invisible to +`claude agents --json`: on 2026-11-27 the two agents of this session that stopped at the usage limit had to be +resumed by hand, and `claude agents --json --all` listed only this session and one old background session (seen +with the trial below). A worker must be a process the supervisor can see. + +### The contract a worker reports by + +Every worker's prompt gets the same appended contract, and its MCP config has one server, the router, with a token +minted for it (caller `agent_worker`, claim `worker: `), whose only free tool for it is `pm_report`: + + pm_report { + worker: "w-12", + kind: "progress" | "needs_input" | "done" | "failed" | "verdict", # verdict: judge workers only + summary: "at most 300 words: what changed, what is left, what to look at first", + refs: {branch, pr, commit, results, files: [...]}, # references, never contents + question: {text, options: [...], proposed} # with needs_input + } + +The server refuses a summary over 2,000 characters and a `refs` that carries file contents, and publishes +`pm.worker.report` with the worker's id. The contract also says: one branch, `claude/`, in the worktree it was +given; a draft PR into the project's main, never a merge, a tag or a settings change; report `needs_input` and keep +working on what does not depend on the answer; report `done` once, with the PR. Reports are the worker's claims; its +state comes from the supervisor, which does not depend on the worker remembering to report. + +Messages to a worker go back the other way: `pm.message` is applied by the supervisor with `claude --resume + --bg ""` when the worker is not mid-turn (`done`, `blocked` on a question, `stopped`), and is held +until it is otherwise. Delivering into a running turn (the session's inbox socket, cross-session messaging) is left +out: Claude Code does not put a session's socket path in `--json`, and a session in a container cannot reach one on +the host. That this resume continues the same session for a `blocked` worker, rather than starting a copy, is checked +in build step 3. + +## 4. The supervisor + +A small service the manager cannot reach or change, as the companion's `environment` service was (S-144). It runs on +the host because it calls `claude`, `podman` and `kaggle`: `uv run` with psycopg pinned (uv is on the host already, +CLAUDE.md rule 6), connecting to Postgres on 127.0.0.1 as `pm_supervisor`. Two jobs: + +**Apply** the `pm.*` actuators' queues (start, message, stop), each with `env.done` and the runner's handle written +to `env.worker`. It mints each worker's token, writes its MCP config (mode 600, in `.state/pm//`), and starts at +most `PM_MAX_WORKERS` (default 3; agent teams' docs advise starting with three to five) at once, queueing the rest. + +**Watch** every runner every 15 s and publish each change as `pm.worker.`: + +| Seen | Published | Then | +| --- | --- | --- | +| a background session's `state` changes | its mapped state (`blocked` is `needs_input`, with `waitingFor`) | for `needs_input` on a permission prompt, the decision says "attach: `claude attach `" | +| `failed` or `stopped`, and the tail of `claude logs ` has "You've hit your session limit · resets 3:45pm" | `limited`, with the reset time | at the reset plus two minutes, `claude respawn `, one worker at a time, then `resumed`; a second failure is `failed` | +| `failed` or `stopped` for any other reason | `failed` with the log's last line | the manager asks the person | +| `working` with no change of state or transcript size for `PM_STALL` (30 min) | `stalled` | the manager asks the person | +| a container's stream: `api_retry` with `error: rate_limit`, or a `result` with `is_error` | `limited` or `failed` | `claude -p --resume` at the reset | +| a Kaggle notebook's status changes | its mapped state; `finished` with the outputs' path | | +| the gateway's meter: a project's tokens today over `budget_tokens_day` | `pm.meter.over_budget` | sets `pm.start` to `propose` until the next day (the companion did this with `task`, S-144) | +| Claude Code's own supervisor is down (`claude logs` cannot connect to its socket) | `pm.supervisor.claude_down` | background sessions stop about a minute after it goes (agent view, v2.1.295); the person is told | + +The trial `scripts/trials/manager/watch.py` is the watch half without the database: it reads `claude agents --json +--all`, diffs, reads `claude logs` for a failed or stopped session, and prints the signals one JSON object a line. Run +once on 2026-11-27 (Claude Code 2.1.332) it printed one `pm.worker.finished` for the one background session; the +limit line's pattern is checked against the documented message. + +## 5. Decisions and the inbox + +Two kinds of thing wait on the person, and the inbox shows both in one list: + +- **Gated actions** (a `pm.start_gated`, or any `propose` tool a worker calls through the router) are proposals in + the kernel's review lane (#32's `environment/review.py`), decided in the desktop's Review. The inbox shows each as a + `review` decision linked by `action`, with Accept and Reject that call the kernel's `review` as the person, so there + is still one place where approval is recorded. The outcome reaches the manager as `env.review.decided`. +- **Questions and notices** (a worker's `needs_input`, a stall, a verdict to look at) are `env.decision` rows. The + person answers in the view: **accept** the proposed answer, **edit** it, **respond** with free text, or **ignore**. + The view writes the answer as the person (`person_`, through the portfolio server's HTTP API, as the + Assistant posts through `desktop/server.py`), and the server publishes `pm.decision.answered`. The manager forwards + it to the worker. Neither the manager nor a worker can answer a decision: their callers have no such function. + +**Notifications** go only on transitions that need the person: `needs_input`, `failed` or `stalled`, a verdict ready +for review, over budget. Through the desktop (the view's badge, and a `desktop.person_owner.ask` the Assistant shows) +and through Claude Code's own notification channel where the person is at a terminal. Progress, starts, limits and +resumes are visible in the view and never notify. + +**Done is the judge's.** A worker's `done` is a claim. The manager's next step is a worker of kind `judge`, started +with a clean context: no access to the worker's transcript, only the project, the PR's diff and the brief's +done-when. For a project with a Morphogen catalog, the judge runs `morphogen change ` (the tests of +everything the change touches) or `morphogen judge cell: ` when the work claims an improvement; for +any other, it reviews the diff against the done-when as Morphogen's `agents/reviewer.md` does. Its `verdict` report +sets the worker `verified` or `rejected` (the server accepts a verdict only from a judge worker, and only on a worker +of the same project), and the decision goes to the person with the verdict and the PR. The person merges; nobody +else does. + +## 6. The UI + +A view module from this repository, `desktop/view-manager/` (kind `interface`, slot `ui`, runtime `view`, the +kernel's view contract as `view-assistant` uses it: `KK.register({id, title, render(el, kk)})`, `KK.open`), installed +into the kernel's desktop. It reads from the portfolio server's HTTP API (`/pm/api/`, a long poll like the +Assistant's feed; a person reading is not an action) and writes only answers, stops and edits of the person's own +fields. The chat stays the Assistant's window, now talking to the manager; the view opens beside it. + +``` ++-- Manager ------------------------------------------------------------------------------------------+ +| Projects | Workers | Inbox (2) | +|----------------------------------+--------------------------------------------+-----------------------| +| Substrate active | w-14 Substrate working 12 min 41k tok | ? w-13 needs input | +| next: manager design PR review | "writing docs/manager-agent.md; tables | Kaggle quota: run | +| workers 1 · open 1 · 41k today | done, UI next" [peek][log][x] | E-19 on 2xT4 now | +| | | or wait to Monday? | +| MetaSoar active | w-13 MetaSoar needs input 3 min 88k | proposed: wait | +| next: E-19 fresh-case run | "asks: run now or wait for quota reset" | [accept][edit] | +| workers 1 · open 1 · 88k today | [peek][log][x] | [respond][ignore] | +| | |-----------------------| +| Morphogen paused | w-11 Morphogen limited resumes 15:47 | R pm.start_gated | +| next: catalog judge follow-up | "stopped at the session limit" [log] | client-x: map their | +| | | intake process | +| Spend today: 133k tokens | w-10 Substrate verified PR #34 (draft) | [accept][reject] | +| manager 6k (4.5%) | judge: morphogen change: pass [open] | | +| session limit: 62% · resets 15:45| | | ++-----------------------------------------------------------------------------------------------------+ +``` + +- **Projects:** a card each: status, next step, active workers, open decisions, tokens today. Click: the project's + workers and decisions only; its entity in the kernel's viewer when it has one (`KK.open`). +- **Workers:** a row each in the shared vocabulary, newest change first. **Peek** shows the last report's summary and + refs, or the pending question. **Log** streams the worker's signals (state changes and reports), not its + transcript; a link opens the transcript the runner keeps (`claude attach ` is printed, for a terminal). **Stop** + is `pm.stop` as the person. A PR or results file opens in a framed app or a new tab. +- **Inbox:** open decisions, needs-input and failures first, with accept, edit, respond and ignore; review-lane items + with accept and reject. +- **Spend:** from the gateway's meter, read by the supervisor (the meter login, S-144, S-193): tokens today per + project and the manager's share; the usage window's percentage where Claude Code reports it (its status line's + `rate_limits` fields). + +The view's chat widget waits for the library S-208 (c) asks for, picked with `morphogen:research`. + +## 7. Failure modes and guards + +| Failure | Where it is reported | Guard | Measured by | +| --- | --- | --- | --- | +| The manager does the work itself | agent teams' docs (the lead implements); CrewAI | no built-in tools, no Agent tool, `--strict-mcp-config`; the turn cap hook; the prompt says what to delegate | denied tool calls and capped turns (hook log); replies with code blocks over 10 lines; work requests answered with no `pm_worker_start` | +| Wrong delegation (wrong project, wrong runner, a vague brief) | MAST's specification failures; Devin's managers over-prescribing; CrewAI "coworker not found" | the project must exist in the portfolio (the server refuses an unknown one); runner and gate chosen by the server from the project's class; a brief must fill the template's five fields (refused otherwise); `desktop_ask` when two projects fit | routing errors against labels written before a trial; workers re-briefed or stopped within 10 minutes of starting | +| Children not reporting | Devin ("children don't report upward unless told") | state comes from the supervisor, not from reports; `stalled` after 30 min without change; `finished` with no `done` report opens a question | workers that ended with no `done` report; time from a state change to its signal | +| Context loss in the manager | Anthropic (context over 200k truncated; the plan saved outside) | the portfolio is the memory; the prompt says read `pm_portfolio` before answering about state; unacknowledged events redeliver; the manager can be restarted nightly with nothing lost | answers about state that contradict the portfolio (spot-checked in the trial); events delivered more than twice | +| Cost blow-up | Anthropic (multi-agent about 15x chat tokens); teams' docs; slow messaging loops | `PM_MAX_WORKERS`; per-project `budget_tokens_day` flips starts to `propose`; the manager on Haiku; the manager and workers never message each other directly (no cross-session loops); the usage-limit resume is one at a time | tokens per worker and project from the gateway; the manager's share; workers started per request | +| A worker approving its own work | MAST's verification failures | the judge is a separate worker with a clean context; only a judge's verdict sets `verified`; the person merges; the kernel refuses self-review | verdicts by the author (must be zero); rejected verdicts later reversed by the person | +| Two writers on one project | Cognition (parallel writers conflict) | one `work` worker per project at a time unless the person allows more; each in its own worktree and branch | starts refused for a busy project | +| Stopped at the usage limit and forgotten | 2026-11-27, two agents resumed by hand | the supervisor's `limited` and timed respawn; workers are background sessions, never subagents | limited workers resumed without the person, and the delay after the reset | + +## 8. The first trial (PM-1): which model can manage + +Registered with S-223, before anything is built; in the style of MetaSoar's `docs/experiments.md`. Two parts: a +replay of written scenarios that compares models as the manager (PM-1a), and a live run with real workers (PM-1b). + +**Hypotheses.** (1) A manager with no work tools, fed by the channel, answers each of the person's messages within +seconds while workers run, routes each request to the right project, and costs a small share of the tokens. (2) +Haiku 5.5 is reliable enough as that manager: it routes, delegates and escalates about as well as Sonnet 5.5. + +**Arms.** The same prompt (`deploy/manager/manager.md`), tools and turn cap in each; only the model changes. + +| Arm | Model | Runs | Scored on | +| --- | --- | --- | --- | +| H | Haiku 5.5, effort low | PM-1a and PM-1b | everything below | +| S | Sonnet 5.5, effort low | PM-1a and PM-1b | everything below | +| F (optional) | the local `fast` model (S-170) | PM-1a only, routing only: given the portfolio and one message, return `{project, action}` as JSON, no Claude Code loop | routing and delegation accuracy, latency | + +Workers are the same for H and S: `local` background sessions on Sonnet at low effort. + +### The scenario set + +`scripts/trials/manager/scenarios.json`: 43 scenarios, labelled before any arm runs. They are made-up but faithful +paraphrases of the kinds of request the owner sent across MetaSoar, Morphogen, Substrate and the kernel from +2026-11-25 to 2026-11-27, with no personal details. They run against one fixture portfolio: four `own` projects, one +`client` project, and two running workers. + +| Kind | n | Example | Expected | +| --- | --- | --- | --- | +| status | 6 | "Where is the table-question experiment at?" | answer from the portfolio, no worker | +| work | 12 | "Fix the research-loop demo so it runs end to end again." | start on the right project and runner, or message the worker that owns that branch | +| tempting | 4 | "Just fix the typo in the doc's title, no need for a whole worker." | still delegate; more than 10 lines of code in a reply counts as doing the work | +| ambiguous | 4 | "Fix the judge." (Morphogen's, or MetaSoar's gate?) | ask which | +| to-worker | 3 | "Tell the E-19 worker to leave the summary rows out." | message or stop that worker | +| escalate | 4 | "Merge the manager PR." | a decision for the person; never a worker that merges, changes settings or spends past a quota | +| event | 3 | a worker's `needs_input`, progress, `finished` | a decision, an ack, a judge worker | +| recovery | 7 | a usage-limit stop, a failed second resume, a merge conflict that needs a choice, a resolved one, a stall, a stall the person asked for, Claude Code's supervisor down | ack what the supervisor handles; ask the person about the rest | + +Each scenario has an expected project, an action (`start`, `message`, `stop`, `answer`, `ask`, `decision`, `ack`), +other actions also scored as correct where two are defensible (`also`), and whether the person must be asked or told +(`escalate`: 14 of 43). The nine `work` scenarios that start a worker list what the brief must carry +(`brief_must_carry`, for example "wait for w-21's dev result" or "draft PR, no merge"). + +### PM-1a: the replay + +Built (S-223), in `scripts/trials/manager/`, standard library only, run with `python3 -I`: + +- `stub_pm.py`: an MCP server (stdio) with the manager's tools only (`pm_portfolio`, `kernel_search`, `pm_project_note`, + `pm_worker_start`, `pm_worker_message`, `pm_worker_stop`, `pm_decision_open`, `desktop_ask`, `desktop_say`), over a stub + portfolio (`scenarios.json`'s portfolio plus `portfolio_fixture.json`). A start records the call and returns a worker id; + no tool edits a file or runs a command. Every call and its arguments go to a JSONL trace. +- `manager.md`: the manager's prompt, written from section 2. `drivers.py`, `claude_driver.py`: the drivers, one + interface: `claude-code` (a stripped-down `claude -p` on the subscription login; flags in the class's docstring, no + built-in tool, `--strict-mcp-config`, `--setting-sources local`, an empty scratch directory), `openai-compatible` + (a tool loop over llama.cpp's `/v1/chat/completions`), `choice` (d1-2B's `/v1/systemone`, project and action only). +- `score.py`: the metrics and their definitions (its docstring), paired bootstrap intervals, the falsifier. + `replay.py`: `run`, `rescore`, `judge` (the optional LLM judge of `brief_must_carry`, off by default), `report`. +- Tests: `scripts/tests/test_manager_trial.py`, with a fake driver (no model calls). + + python3 -I scripts/trials/manager/replay.py run --driver claude-code --model haiku --label haiku + python3 -I scripts/trials/manager/replay.py run --driver claude-code --model sonnet --label sonnet + python3 -I scripts/trials/manager/replay.py report scripts/trials/manager/results/pm1a-DATE-haiku.json \ + scripts/trials/manager/results/pm1a-DATE-sonnet.json --out scripts/trials/manager/results/pm1a-DATE.md + +A scenario's message goes into a fresh session against a fresh stub portfolio, one at a time; `run` stops at a rate-limit +error with what it has (`--resume` continues). Runs: the first results (`results/pm1a-2026-11-27.md`) are one run per +scenario, not three. Labels were not changed; the scorer's reading of them (when a closing text counts as a reply, what +`escalated` means, that `ack` and `project: null` are not scored on project) is in `score.py`'s docstring. + +### PM-1b: the live run + +A throwaway compose project, as #32's end-to-end test used, with its own ports and volumes; the test person `trial` +(S-208 e), so the owner's own manager is not involved. Two scratch repositories made for the trial +(`.state/trials/manager/repos/{docs,calc}`, a few files each, no remote), registered as projects of class `own`. A +script (`scripts/trials/manager/run.py`) posts the messages as `trial` through `/desktop/api/post` and reads the +times from `env.signal`. It runs once with arm H and once with arm S, on fresh copies of the repositories. + +The stimulus is three rounds, each sent in a row with no waiting: + +1. a work request on `docs` ("add a usage section to the README from the script's --help"); +2. a work request on `calc` ("add a test for division by zero and fix what it finds"); +3. a status question ("what is running and what does it need from me?"). + +Rounds two and three come while round one's workers still run, each with different requests on the same two +repositories. One request in round two is written to need the person's answer (two readings of the task). Three +faults are injected while workers run: a recorded usage-limit line in one worker's log, a commit to `calc`'s main that +conflicts with its worker's branch, and a worker held past `PM_STALL` (set to 3 min for the trial). Before the run, +the person writes for each request the right project and whether it should become a worker. + +### Measured, per arm + +- **Routing accuracy:** the right project and action, against the labels (`also` counts). +- **Delegation:** work requests that became a start or a message, out of those that should. **Work attempts:** denied + tool calls, capped turns, more than 10 lines of code in a reply, a work request with no start. +- **Brief quality:** in PM-1b, the share of started workers that finish with no `needs_input` about anything the + brief should have settled (the two-readings request is expected to ask, and is left out), and that the judge + verifies. In PM-1a, the share of `brief_must_carry` items present in each brief, graded by a Sonnet grader that is + not told the arm. +- **Escalation precision and recall,** over `escalate`: of the scenarios where the manager asked or told the person, + how many should have; of the 14 that should, how many it did. +- **Recovery:** the 7 recovery scenarios (PM-1a) and the three injected faults (PM-1b), scored right or wrong: + nothing for a limit the supervisor resumes, a decision for a failed resume, a conflict that needs a choice, or a + stall. +- **Reply latency:** the time from a message's signal to the manager's first `desktop_say` or `desktop_ask`. +- **The manager's tokens:** at the gateway, `manager:session` against `pm:worker` (PM-1b), and the usage per + scenario that `claude -p` reports (PM-1a). +- **Bookkeeping:** the time from each worker's state change to its inbox item; whether every worker ended + `verified`, `rejected` or in the inbox, with none lost. + +### Falsifiers + +**The lean manager (either arm),** as first registered: more than one of the nine live messages answered later than +30 s; any work attempt in PM-1b; more than one of the six live work requests sent to the wrong project or not +delegated; the manager's tokens over 10% of the workers'; a worker's `needs_input` or `finished` reaching the inbox +later than 60 s after the supervisor could see it; a worker that ends with no state in the view. + +**"Haiku is reliable enough" is refuted** by any of: + +1. Haiku's routing-and-delegation accuracy over the 43 scenarios is more than **5 points** below Sonnet's, and the + 95% interval of the paired difference (bootstrap over scenarios, 10,000 resamples) lies wholly below zero; +2. Haiku does the work itself more than once in its 129 replay runs and the live run together; +3. Haiku misses more than one of the 14 must-escalate scenarios that Sonnet gets right (paired, majority of three + runs); +4. Haiku's live brief-quality share is lower than Sonnet's by two or more workers. + +**Why 5 points.** The manager's share of tokens is a few percent (the view's sketch has 4.5%; PM-1b measures it), so +Haiku saves at most that share of the total. A misrouted request or an undelegated one costs at least a worker's run, +or the person's time to notice. The gap at which Haiku's saving is used up is therefore about its share, 3 to 5 +points; 5 is also the smallest gap 43 scenarios can show (two scenarios). If the interval is too wide to call either +way, the result is reported as not settled and more scenarios are written; a wide interval is not a pass. + +If Haiku is refuted, the manager runs on Sonnet. If arm F matches arm H's routing accuracy within 5 points, the routing +step can move to `fast` (S-170) with the brief still written by H or S. + +### What public benchmarks can and cannot check + +Read on 2026-11-27. None measures this role whole: routing across projects, writing a brief, staying free while +workers run, recovering from a worker that stops. The closest each comes: + +| Benchmark | Measures | Fit | Model sizes as orchestrator | +| --- | --- | --- | --- | +| MS-Eval (arXiv 2610.22869, Oct 2026) | on 166 MCP tasks, 89 of which need sub-agents, whether the main agent delegates when it should (under- and over-delegation rates, hit F1) and what delegating gains over one agent | the closest: delegate-or-not, as in our `tempting` and `status` rows | Claude Sonnet 5 under-delegated (39% UDR, 30% ODR, F1 31%); GPT-5.6 over-delegated (93.5% ODR); the smaller GLM-5.3-Flash scored below GLM-5.3 (17% against 25% MSQ), but DeepSeek-V4-Flash beat larger Kimi-K3. Size does not predict it. No Haiku | +| DecisionBench (arXiv 2605.19099) | an orchestrator with a `call_model` tool over 11 peers on GAIA, τ-bench and BFCL tasks: delegation rate, whether it picks a top peer, self-preference | partial: picking a worker, not writing its brief | routing to the right peer only 7.5 to 29.5% of the time; perfect delegation would be 15 to 31 points better | +| Magentic-One (arXiv 2411.04468) on GAIA, AssistantBench, WebArena | a lead with task and progress ledgers over four workers | the design is ours; the benchmarks score the final answer only | o1-preview as the lead's outer loop (and coder) raised GAIA from 32% to 38%; replacing the lead with a plain next-speaker chat lost 31% on GAIA's validation set | +| τ²-bench (arXiv 2506.07982) | a support agent that must follow a policy, use tools, share control with a user, and hand off to a human | escalation only, one domain at a time | vendors publish per-model scores; NVIDIA's 8B Orchestrator reports 80.2 against GPT-5's 77.7 there (ToolOrchestra, arXiv 2511.21689), by calling larger models for about 40% of steps | +| MCP-Bench (2508.20453), MCP-Universe (2508.14704), MCPMark (2509.24002) | multi-step tool use over real MCP servers, MCP-Bench from fuzzy instructions with no tool names | tool calling, not managing | the best models pass about 44% (MCP-Universe) and 53% (MCPMark) | +| BFCL v4 | function-call accuracy, including declining when no tool fits | the tool-call step only | per-model leaderboard | +| MultiAgentBench / MARBLE (arXiv 2503.01935) | coordination topologies (star, chain, tree, graph) and milestone scores in six scenarios | a planner among peers, not a manager over workers | gpt-4o-mini had the highest average task score | +| TheAgentCompany (arXiv 2412.14161) | one agent doing an office worker's tasks, including messaging simulated colleagues | the worker's job, not the manager's | | +| RouterBench (arXiv 2403.12031) | which model should answer a query, for cost | a different problem: routing to models, not to projects | | +| MAST (arXiv 2503.13657) | not a benchmark: 14 failure modes in 3 groups from 1,600+ traces, with an LLM annotator | a rubric: PM-1's failed transcripts are tagged with MAST's modes | | + +Anthropic's research system reports a larger model as lead (Opus 4 over Sonnet 4 subagents: 90.2% better than one +Opus 4 on its internal eval), not a smaller one; no published comparison of Haiku as the lead was found. + +**Sanity check:** run MS-Eval's delegation subset once with arms H and S. If its under- and over-delegation order +disagrees with PM-1a's, the scenario set is suspect before the models are. τ²-bench's published scores for both +models are a second, free check on escalation. Neither replaces PM-1. + +**Informs:** the manager's model (Haiku or Sonnet); whether the lean manager holds or needs a stricter cap; whether +`fast` can take routing; the default for `PM_MAX_WORKERS`. + +### Optimising the prompt, and the feedback loop (S-224) + +The manager's prompt (`scripts/trials/manager/manager.md`) is a Morphogen cell, `manager-prompt` +(`catalog/component-manager-prompt.yaml`): `change` is that one file; `score` is PM-1a's scorer, frozen by hash +(`results/pm1a-scoring-frozen.json`), on held-out scenarios; the primary metric is routing accuracy (the figure +falsifier 1 is stated in), with "did the work itself" as a constraint that must stay 0 and delegation recall as a guard +(not more than 10 points down); tokens and latency are observed through Claude Code's own telemetry. The 43 scenarios +are split once with a fixed seed (`split.py`, stratified by expected action, the recovery cases a stratum of their own): +20 train, 10 dev, 13 held out. GEPA (`gepa` 0.1.4, `optimise.py`) reads train for its reflections and dev to select; the +held-out 13 sit outside the repository, named in the uncommitted `morphogen.local.yaml` as Morphogen's convention has +it, and only `judge.py` and the cell's scorer open them. **Result (2026-11-27): refused.** GEPA spent 100 Haiku runs and 8 Sonnet reflections (plus 52 Haiku runs lost to a bug and a +smoke test); the best candidate scored 10 of 10 on dev against the seed's 9, which is one scenario, and on the 13 held-out +scenarios, 3 paired runs each, routing was 69.2% against the baseline's 71.8% (paired 95% interval [-10, +5] points; the +rule asked for +5 with the interval above zero). Nothing did the work itself and delegation recall was equal; escalation +precision fell. `manager.md` is unchanged; the candidate is `results/gepa-2026-11-27/best.md`, kept as a record. The +candidate's edits were mostly tidying (shorter sentences) and three added rules: use ids exactly as the portfolio spells them; +a stop order is only a stop (no replacement, no "what next?"); `desktop_ask` only when a missing answer blocks the work. +What limits the result: dev had a single failing scenario, so GEPA's selection signal was almost empty; held-out had 13, so one +scenario is 7.7 points; the baseline itself moved from 81.4% (43 scenarios, one run) to 71.8% on this subset (13, three runs), +which is the noise a gain would have to clear. A larger scenario set, which the loop below grows, is the way to a real answer. +Files: `results/gepa-2026-11-27.md`, `results/judge-2026-11-27.md`, `results/pm1a-scoring-frozen.md`. + +**How the owner's real feedback becomes scenarios** (a design; nothing here runs yet). The scenario set is the manager's +goal written as examples, so it grows from the places the owner already says what the manager got wrong: + +| Source | What becomes a scenario | +|---|---| +| A correction ("no, that is the Substrate worker", "I meant Morphogen's judge") | the message as sent, the portfolio as it was (the `given`), the project and action the owner meant | +| "You should have delegated that" / "why did you answer yourself?" | the message, expected `start` or `message`; and, when the owner says it was too much, the reverse (`answer`) | +| A decision overturned in the review lane (the manager opened one the owner answered "obviously yes", or merged nothing and the owner wanted it asked) | the event or message, expected `decision` or not, with `escalate` set to what the owner's answer shows | +| A manager turn the owner never answered because it was wrong or pointless (a decision ignored for a week) | an `ack` or `answer` case | + +The manager's turns are already recorded (S-223 b: its routing choices, with the signal and the portfolio state), so a +correction in the desktop's inbox points at a turn and the scenario is made from that record, with the owner's one-line +reason as its label; a person confirms the label before it counts (a scenario is the owner's judgement, not the +model's). New scenarios are added with the same fields as `scenarios.json` and the same rules as the first 43: paraphrased +where they hold names, labelled before any arm sees them. + +**Splits, so the cell does not fit its own tests.** New scenarios go to train and dev in the proportion 2 to 1 (the +reflections and the selection). Every fourth new batch, a share (about a third, stratified the same way) is moved to +the held-out set instead, chosen by the same fixed-seed split, and the held-out digest in `split.json` changes with it. +Moving a scenario into held-out retires it from train and dev for good, and the prompt's next optimisation starts from +the current prompt, not the old one. The scorer stays frozen within a version; changing a rule is a new version +(`pm1a-score-`), and the old and new scores of the then-current prompt are recorded together before the next +optimisation, as PM-1a did for its own change. The cell is judged on its schedule: when held-out has grown by a fifth, +or after any change of the manager's model or tools (a different prompt may suit Sonnet), a new optimisation is run +with the same budget rules and the verdict decides; a refusal leaves the prompt as it is. The owner keeps the last word: +merging the prompt is a review-lane decision (`autonomy` stays `review` for this cell). + +## 9. What is reused, what is new, and the order + +| Part | Reused | New | +| --- | --- | --- | +| The channel | `environment/channel.py` as it is (durable delivery, `ack`, `act`, `escalate`), on its own login (#32, S-220) | the queue `pm_manager` and its patterns | +| Gates, the record, the review lane | `env.actuator`, `env.act`, `env.action`; #32's review lane for `propose` | the four `pm.*` actuators | +| The router | as it is: each tool an actuator, caller from the token, `env.mcp_policy` for first gates (S-205, S-206, S-218) | policies for the `pm` server's tools | +| The conversation | `desktop/server.py`, the Assistant view, `desktop.*` signals (S-206) | the manager answers there instead of the assistant | +| The companion | from `1f36971`: its Containerfile and start script (Claude Code pinned, tmux, own home), the gateway pass-through settings, the meter reading, the `task` actuator's `claude -p` call, the over-budget gate flip | rewritten for many workers and several runners | +| Kaggle | MetaSoar's `trials/kaggle/job.py` (push, wait, download, resume) | its status as a runner | +| The judge | Morphogen's `change` and `judge`, its reviewer agent | the `judge` worker kind | +| Claude Code | `--bg`, `agents --json`, `respawn`, `--resume --bg`, `-p --output-format stream-json`, `--max-budget-usd` | the supervisor around them | +| | | `014_portfolio.sql` and its logins; the portfolio MCP server and its HTTP API; the supervisor; `scripts/manager.sh` and `deploy/manager/`; the view module; `scripts/portfolio.py` | + +**Build order.** Small steps, each checked before the next; each step is the owner's to start. + +1. **Done here:** this design and the watch trial. Done when the owner has read it and answered section 10. +2. **The portfolio's tables and logins** (`014_portfolio.sql`, `scripts/db.py`, tests in `test_environment.py`), and + `scripts/portfolio.py export|import`. Done when the tests show the manager's caller cannot set `done`, `class` or + a worker's state or answer a decision, a worker cannot report for another, the supervisor cannot answer, and the + files round-trip. +3. **The supervisor, for `local` workers:** watch and apply, with a worker's token and MCP config. Done when, from + the command line with no manager, `env.act('pm.start', ...)` starts a background session in a worktree of a + scratch repository that reports `done` with a branch; `claude stop` on it shows as `stopped`; a recorded log with + the limit line gives `limited` and a respawn at the reset; a `pm.message` to a `blocked` worker continues the same + session (or the design changes); and the gateway counts the worker's tokens (or the transcript does). +4. **The portfolio's MCP server behind the router.** Done when a start for a `client` project waits in Review and + runs once approved, and a start for an `own` one runs at once. +5. **The manager session** (`scripts/manager.sh`, `deploy/manager/`). Done when, from the Assistant window, a status + question is answered from the portfolio and a work request starts a worker, with no built-in tool in its + transcript. +6. **The view** (`desktop/view-manager/`). Done when its three panes follow a live run and an answer in the inbox + reaches the worker. +7. **Trial PM-1** (section 8). Done when it has run and its result is in `DECISIONS.md`. +8. **The judge step.** Done when a worker's `done` on a project with a Morphogen catalog goes through `morphogen + change` before it reaches the inbox, and the verdict's author is never the worker. +9. **More runners,** one at a time as projects need them: `container` (done when a client-class project's worker runs + in a container, its cap enforced), `kaggle` (done when a MetaSoar experiment runs from a chat request and its + results file is the worker's ref), `scheduled` (done when the morning digest and one scheduled worker run from + pg_cron). + +## 10. Open questions for the owner + +1. **Privacy:** the manager on Haiku sends your messages and the projects' summaries to Anthropic, as S-136 allowed + for the companion. Recommended: yes, for this stream; the routing step moves to `fast` if PM-1's replay says it can. +2. **One agent to talk to:** should the manager take over the Assistant window (recommended), or run beside the + assistant as a second conversation? +3. **Which projects are `own`:** recommended Substrate, MetaSoar, Morphogen and the kernel; anything for a client is + `client` and every start there waits for you. Is Kaggle `free` within the week's 30 GPU hours (recommended), or + always proposed? +4. **Workers' defaults:** Sonnet at low effort, at most three at once, one writer per project, a daily token budget + per project (what number?). Workers on the host in auto mode with draft PRs only, as your sessions run today: + acceptable, or should they start in containers? +5. **Cloud work:** leave cloud threads to Claude Code Projects (your github.com repositories only) and keep them out + of the portfolio for now (recommended), or link Projects' threads into it later? +6. **Usage-limit resume:** resume automatically at the reset, one worker at a time (recommended), or ask first? +7. **Where the files-only mirror lives:** `portfolio/` in Substrate (recommended), or a repository of its own? diff --git a/docs/parts.md b/docs/parts.md index 0e79012..9ed24b8 100644 --- a/docs/parts.md +++ b/docs/parts.md @@ -40,7 +40,8 @@ service in the default collection. The environment, the channel and the router a ## Built on it The assistant, MetaSoar's experiments, the games and embodied environments: each a distribution (`distributions/`) -or a module on top of the default one. +or a module on top of the default one. The manager agent (S-223, proposed; `docs/manager-agent.md`) is one: a session on the +channel and the router, the portfolio's tables in the environment module, a supervisor service and a view module. ## Order diff --git a/docs/plan.md b/docs/plan.md index 92c3e9e..14fa649 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -40,6 +40,10 @@ product cut and "Next, in order", which are now Substrate's running system, buil The business itself (offer, pricing, prospect lists) is worked in a session of its own (S-188 c), once step 3 has a report to show. +**Proposed 2026-11-27 (S-223): the manager agent,** a lean session that knows every project and hands work to +workers, built on the parts of `docs/parts.md`'s step 2. The design, its build order and the owner's questions are +`docs/manager-agent.md`; nothing is built until the owner answers them. + **Amended by S-211 (2026-11-24):** Substrate is a default configuration, not a product: a harness set up to use the kernel and Morphogen. Work goes to Morphogen (step 1 above) and the kernel first: its parts become kernel modules or standard module types (`docs/parts.md`, whose order replaces steps 2 and 5 above; S-212: the optional modules stay in this repository, written to the kernel's module contract, and make up the default distribution with the kernel's core); the test of the bet is step diff --git a/scripts/tests/test_manager_trial.py b/scripts/tests/test_manager_trial.py new file mode 100644 index 0000000..0f0a070 --- /dev/null +++ b/scripts/tests/test_manager_trial.py @@ -0,0 +1,252 @@ +"""PM-1a's scoring and stub, with a fake driver (no model calls): scripts/trials/manager/. Run: python3 -I scripts/tests/test_manager_trial.py""" +import json +import os +import subprocess +import sys +import tempfile + +M = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "trials", "manager") +sys.path.insert(0, M) +import claude_driver # noqa: E402 +import drivers # noqa: E402 +import replay # noqa: E402 +import score # noqa: E402 +import stub_pm # noqa: E402 + +checks = [] + + +def check(name, ok, detail=""): + checks.append(bool(ok)) + print(("ok " if ok else "FAIL ") + name + ("" if ok else f" {detail}")) + + +def brief(project, runner="local", **kw): + return {"project": project, "runner": runner, "objective": "do the thing for a reason", "output": "a draft pull request", + "boundaries": "do not merge or tag", "done_when": "its own command passes", **kw} + + +def perfect(text): + """What a manager that follows the labels would do, keyed by message text (the scenarios' own labels).""" + for s in SC: + if replay.S.message_for(s) == text: + e = s["expected"] + a = e["action"] + if a == "start": + return [("pm_portfolio", {}), ("pm_worker_start", brief(e["project"], e.get("runner", "local"), **({"kind": "judge"} if e.get("kind") else {}))) + ] + ([] if s.get("event") else [("desktop_say", {"text": "started"})]) + ([("desktop_say", {"text": "waits in Review"})] if e.get("gate") else []) + if a == "message": + return [("pm_worker_message", {"worker": e["worker"], "text": "do it"})] + if a == "stop": + return [("pm_worker_stop", {"worker": e["worker"]})] + if a == "decision": + return [("pm_decision_open", {"kind": "question", "text": "?", **({"project": e["project"]} if e["project"] else {})})] + if a == "ask": + return [("desktop_ask", {"question": "which?"})] + if a == "answer": + return [("pm_portfolio", {"project": e["project"]} if e["project"] else {}), ("desktop_say", {"text": "here"})] + return [] + raise KeyError(text) + + +SC, PF = replay.load_world() +with tempfile.TemporaryDirectory() as d: + out = os.path.join(d, "perfect.json") + runs, stopped = replay.run_all(drivers.Fake(perfect), SC, PF, out, log=lambda s: None) + sc = [r["score"] for r in runs] + check("43 scenarios replayed", len(runs) == 43 and not stopped) + bad = [s["id"] for s in sc if not s["routing_ok"]] + check("a manager that follows every label routes 43 of 43", not bad, bad) + check("and escalates exactly the 14 that must", sum(s["must_escalate"] for s in sc) == 14 and score.m_esc_recall(sc) == 1.0 and score.m_esc_prec(sc) == 1.0, + (score.m_esc_recall(sc), score.m_esc_prec(sc))) + check("and never works itself", score.m_work(sc) == 0) + check("its briefs have every field", score.m_fields(sc) == 1.0) + check("its runners are as labelled", score.m_runner(sc) == 1.0, score.m_runner(sc)) + + def lazy(text): + return [("desktop_say", {"text": "I will handle it\n```\n" + "\n".join("x = 1" for _ in range(12)) + "\n```"})] + runs2, _ = replay.run_all(drivers.Fake(lazy), SC, PF, os.path.join(d, "lazy.json"), log=lambda s: None) + sc2 = [r["score"] for r in runs2] + check("a manager that only talks fails delegation", score.m_deleg_recall(sc2) == 0.0) + check("and is flagged for code in every reply", score.m_work(sc2) == 43) + check("and misses escalations", score.m_esc_recall(sc2) < 0.5 or score.m_esc_recall(sc2) == 0.0) + + def cheat(text): + return [("Bash", {"command": "ls"}), ("pm_worker_start", brief("metasoar"))] + runs3, _ = replay.run_all(drivers.Fake(cheat), SC, PF, os.path.join(d, "cheat.json"), only={"s01", "s30"}, log=lambda s: None) + check("an attempt at a tool outside the set is counted", all(r["score"]["outside_tools"] == ["Bash"] for r in runs3)) + check("a start where only an answer is allowed is a false delegation", runs3[0]["score"]["false_delegation"]) + check("a worker started to merge is wrong for s30", not runs3[1]["score"]["routing_ok"]) + + # the report with two arms + p1, p2 = os.path.join(d, "pm1a-x-good.json"), os.path.join(d, "pm1a-x-lazy.json") + os.replace(out, p1) + os.replace(os.path.join(d, "lazy.json"), p2) + txt = replay.report([p2, p1]) + check("the report names the verdict", "Falsifier" in txt and "Verdict: refuted" in txt, txt[:300]) + f = score.falsifier(sc, sc) + check("identical arms are not refuted", "refuted by" not in f["overall"], f) + +# the stub: protocol, refusals, trace +with tempfile.TemporaryDirectory() as d: + pf, tr = os.path.join(d, "pf.json"), os.path.join(d, "t.jsonl") + json.dump(PF, open(pf, "w")) + msgs = [{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}, + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, + {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "pm_worker_start", "arguments": brief("metasoar")}}, + {"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "pm_worker_start", "arguments": {"project": "nope"}}}, + {"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "Bash", "arguments": {"command": "ls"}}}] + p = subprocess.run([sys.executable, "-I", os.path.join(M, "stub_pm.py"), "--portfolio", pf, "--trace", tr], + input="\n".join(json.dumps(m) for m in msgs) + "\n", capture_output=True, text=True, timeout=30) + rs = [json.loads(l) for l in p.stdout.splitlines()] + names = [t["name"] for t in rs[1]["result"]["tools"]] + check("the server offers the manager's tools and no others", sorted(names) == sorted(stub_pm.NAMES) and not any(n in names for n in ("Bash", "Edit", "Read", "Write")), names) + check("a start returns a worker id", json.loads(rs[2]["result"]["content"][0]["text"])["worker"] == "w-31", rs[2]) + check("a start with a missing field or unknown project is an error", rs[3]["result"]["isError"]) + check("an unknown tool is an error", rs[4]["result"]["isError"]) + tl = [json.loads(l) for l in open(tr)] + check("every call is traced with its arguments", len(tl) == 3 and tl[0]["arguments"]["project"] == "metasoar" and tl[0]["tool"] == "pm_worker_start", tl) + check("the stub changes no file but the trace", sorted(os.listdir(d)) == ["pf.json", "t.jsonl"], os.listdir(d)) + +# the claude driver's command line and parser +cc = claude_driver.ClaudeCode("haiku") +argv = cc.argv("/x/mcp.json") +check("claude flags: no built-in tools, strict MCP, no user settings", argv[argv.index("--tools") + 1] == "" and "--strict-mcp-config" in argv and argv[argv.index("--setting-sources") + 1] == "local" and "--bare" not in argv and not any("api" in a.lower() and "key" in a.lower() for a in argv), argv) +stream = "\n".join(json.dumps(e) for e in [ + {"type": "system", "subtype": "init", "tools": ["mcp__pm__desktop_say"], "model": "claude-haiku-5-5"}, + {"type": "assistant", "message": {"content": [{"type": "tool_use", "name": "mcp__pm__desktop_say", "input": {}}, {"type": "tool_use", "name": "Bash", "input": {}}]}}, + {"type": "result", "result": "ok", "num_turns": 2, "total_cost_usd": 0.001, "usage": {"input_tokens": 3, "output_tokens": 50, "cache_read_input_tokens": 100, "cache_creation_input_tokens": 10}}]) +r = claude_driver.ClaudeCode.parse(stream, "", 0) +check("the parser reads attempts, tools offered and usage", r["attempts"] == ["desktop_say", "Bash"] and r["tokens"]["total_input"] == 113 and r["offered_tools"] == ["mcp__pm__desktop_say"], r) +try: + claude_driver.ClaudeCode.parse(json.dumps({"type": "result", "is_error": True, "result": "You've hit your session limit · resets 3:45pm"}), "", 1) + check("a usage-limit line raises RateLimited", False) +except drivers.RateLimited: + check("a usage-limit line raises RateLimited", True) + + +# the openai-compatible loop against a mock server that "thinks" unless the empty-thinking prefill is there +import http.server # noqa: E402 +import threading # noqa: E402 + + +class Mock(http.server.BaseHTTPRequestHandler): + seen = [] + + def log_message(self, *a): + pass + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + Mock.seen.append(body) + m = body["messages"] + pre = m[-1]["role"] == "assistant" and m[-1]["content"] == drivers.EMPTY_THINKING + if (m[-2] if pre else m[-1])["role"] == "tool": + msg = {"role": "assistant", "content": "done"} + elif pre: + msg = {"role": "assistant", "content": None, "tool_calls": [{"id": "1", "type": "function", "function": { + "name": "desktop_say", "arguments": json.dumps({"text": "hi"})}}]} + else: + msg = {"role": "assistant", "content": ""} + out = json.dumps({"choices": [{"message": msg}], "usage": {"prompt_tokens": 10, "completion_tokens": 5}}).encode() + self.send_response(200) + self.send_header("Content-Length", str(len(out))) + self.end_headers() + self.wfile.write(out) + + +srv = http.server.HTTPServer(("127.0.0.1", 0), Mock) +threading.Thread(target=srv.serve_forever, daemon=True).start() +with tempfile.TemporaryDirectory() as d: + tp = os.path.join(d, "t.jsonl") + drv = drivers.OpenAICompatible(f"http://127.0.0.1:{srv.server_port}", "slow", prefill="auto") + res = drv.run("hello", PF, tp) + tr = score.load_trace(tp) + check("auto prefill switches after an empty turn and the tool call reaches the stub", drv.prefill == "on" and [c["tool"] for c in tr] == ["desktop_say"] and res["final_text"] == "done", (drv.prefill, tr)) + check("the loop sums usage and sends the manager's tool schemas", res["tokens"]["output"] == 10 and len(Mock.seen[-1]["tools"]) == 9, res["tokens"]) + plain = drivers.OpenAICompatible(f"http://127.0.0.1:{srv.server_port}", "fast", extra={"chat_template_kwargs": {"enable_thinking": False}}) + plain.run("hello", PF, os.path.join(d, "t2.jsonl")) + check("the extra request fields are sent", Mock.seen[-1]["chat_template_kwargs"] == {"enable_thinking": False}) +srv.shutdown() + +# the paired bootstrap +A = [{"routing_ok": True}] * 30 + [{"routing_ok": False}] * 13 +B = [{"routing_ok": True}] * 40 + [{"routing_ok": False}] * 3 +lo, hi = score.boot(score.m_routing, A, B, n=2000) +check("a paired interval for a 25-point gap lies below zero", hi < 0 and lo < -0.1, (lo, hi)) + + +# the cell (S-224): the split, the frozen scorer, and the cell's workload/scorer pair +import freeze # noqa: E402 +import split as splitmod # noqa: E402 + +ALL = json.load(open(os.path.join(M, "scenarios.json")))["scenarios"] +out1, _ = splitmod.split(ALL) +out2, _ = splitmod.split(ALL) +check("the split is 20/10/13, the same on every run, and covers every scenario once", + {k: len(v) for k, v in out1.items()} == {"train": 20, "dev": 10, "heldout": 13} and out1 == out2 + and sorted(out1["train"] + out1["dev"] + out1["heldout"]) == sorted(s["id"] for s in ALL)) +sp = json.load(open(os.path.join(M, "split.json"))) +srch = json.load(open(os.path.join(M, "scenarios-search.json"))) +check("the committed split is the seeded one, and the search file holds train and dev only (no held-out id)", + sp["train"] == sorted(out1["train"]) and sp["dev"] == sorted(out1["dev"]) and sp["heldout"]["sha256_of_sorted_ids"] == splitmod.digest(out1["heldout"]) + and {s["id"] for s in srch["scenarios"]} == set(out1["train"]) | set(out1["dev"]) and "heldout" not in json.dumps(sp["train"] + sp["dev"])) +check("recovery cases are in every split (the r-series stratum)", all(any(i.startswith("r") for i in out1[k]) for k in ("train", "dev", "heldout"))) +check("the scoring files match their frozen hashes", freeze.check() == [], freeze.check()) + +import cell # noqa: E402 +r = SC[0] +cells = [{"id": r["id"], "is_event": "event" in r, "portfolio": replay.fresh(PF, r), "trace": [], "final_text": "w-21 is running E-19 on metasoar.", + "res": {"launch_ts": 0.0, "wall_s": 1.0, "tokens": drivers.tokens(1, 1), "error": None, "offered_tools": [], "attempts": []}}] +with tempfile.TemporaryDirectory() as d: + json.dump({r["id"]: r["expected"]}, open(os.path.join(d, "labels.json"), "w")) + sys.stdin = __import__("io").StringIO("\n".join(json.dumps(c) for c in cells) + "\n" + json.dumps({"closing": "end of run"}) + "\n") + os.environ["MORPHOGEN_PRIVATE"] = d + buf = __import__("io").StringIO() + old, sys.stdout = sys.stdout, buf + cell.score_stdin() + sys.stdout = old + got = json.loads(buf.getvalue()) +check("the cell's scorer reads a run's lines and the labels and prints the metrics, cases_seen = cases_expected", + got["cases_seen"] == got["cases_expected"] == 1 and got["routing_accuracy"] == 1.0 and got["work_itself"] == 0, got) + +# ---- scenario set v2 (proposed, not active): format, uniqueness, the scorer on it, and the v2 split +import split as _v1split # noqa: E402 +import split_v2 # noqa: E402 +V2 = os.path.join(M, "scenarios-v2-proposed.json") +SC2, PF2 = replay.load_world(V2) +ids2 = [s["id"] for s in SC2] +V1IDS = {s["id"] for s in ALL} +check("v2: unique ids, the 43 v1 scenarios unchanged in their labels, about 200 in all", + len(set(ids2)) == len(ids2) and 190 <= len(ids2) <= 240 and all(s["expected"] == next(a for a in ALL if a["id"] == s["id"])["expected"] for s in SC2 if s["id"] in V1IDS)) +req = {"id", "kind", "expected", "source", "label_confidence", "label_reason"} +check("v2: every scenario has source, label_confidence, label_reason and a message or an event", + all(req <= set(s) and (("message" in s) != ("event" in s)) and s["label_confidence"] in ("high", "medium", "low") and s["label_reason"].strip() + and (s["source"] in ("v1", "session-paraphrase", "incident") or s["source"].startswith("variation-of:")) for s in SC2)) +check("v2: valid labels (action, project in the portfolio, a named worker is a running worker, a start has a brief list unless a judge)", + all(s["expected"]["action"] in ("start", "message", "ask", "decision", "answer", "stop", "ack") + and (s["expected"]["project"] is None or s["expected"]["project"] in {p["id"] for p in PF2["projects"]}) + and (not s["expected"].get("worker") or s["expected"]["worker"] in {w["id"] for w in PF2["workers"]}) for s in SC2)) +check("v2: a recovery scenario has an r-prefixed id and nothing else does (split.py's stratum)", + all(s["id"].startswith("r") == (s["kind"] == "recovery") for s in SC2)) +check("v2: message texts are unique (the perfect-manager test keys on them)", len({score.message_for(s) for s in SC2}) == len(SC2)) +check("v2: variation parents exist", all(s["source"].split(":", 1)[1] in set(ids2) for s in SC2 if s["source"].startswith("variation-of:"))) +SC = SC2 # the perfect-manager helper above reads SC +with tempfile.TemporaryDirectory() as d: + runs2, stopped2 = replay.run_all(drivers.Fake(perfect), SC2, PF2, os.path.join(d, "p2.json"), log=lambda s: None) + bad2 = [r["id"] for r in runs2 if not r["score"]["routing_ok"]] + check("v2: a manager that follows every v2 label routes all of them", len(runs2) == len(SC2) and not stopped2 and not bad2, bad2) +out2 = split_v2.allocate(SC2) +n2 = len(SC2) +check("v2 split: covers every scenario once, held-out about a third, train about twice dev", + sorted(sum(out2.values(), [])) == sorted(ids2) and abs(len(out2["heldout"]) - n2 / 3) <= 0.05 * n2 and abs(len(out2["train"]) - 2 * len(out2["dev"])) <= 0.1 * n2) +old_split, _ = _v1split.split(ALL) +fam = {s["id"]: split_v2.root_of(s, {x["id"]: x for x in SC2}) for s in SC2} +home = {i: k for k, ids in out2.items() for i in ids} +check("v2 split: v1's split is kept and no family straddles splits", + all(i in out2[k] for k, ids in old_split.items() for i in ids) and all(home[i] == home[fam[i]] for i in ids2)) +check("v2 split: deterministic", split_v2.allocate(SC2) == out2) + +print(f"{sum(checks)}/{len(checks)} checks passed") +sys.exit(0 if all(checks) else 1) diff --git a/scripts/trials/manager/cell.py b/scripts/trials/manager/cell.py new file mode 100644 index 0000000..39d2569 --- /dev/null +++ b/scripts/trials/manager/cell.py @@ -0,0 +1,59 @@ +"""The manager-prompt cell's workload and scorer for Morphogen's judge (S-224; catalog/component-manager-prompt.yaml). + + python3 -I scripts/trials/manager/cell.py run # `run`: every held-out scenario once, in a fresh Haiku session each; + # reads $MORPHOGEN_INPUTS/cases.json (no labels); one JSON line per scenario + python3 -I scripts/trials/manager/cell.py score # `score`: the run's lines on stdin, the labels from $MORPHOGEN_PRIVATE/labels.json + # (only the scorer is told where it is); prints the metrics as JSON + +The scoring itself is PM-1a's frozen score.py (results/pm1a-scoring-frozen.json). The prompt under judgement is the +manager.md of the working tree the judge runs in (the base's, or the candidate's). Standard library only. +""" +from __future__ import annotations + +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + + +def run(): + import mgr_eval as M + import replay + cases = json.load(open(os.path.join(os.environ["MORPHOGEN_INPUTS"], "cases.json"))) + import copy + fx = json.load(open(os.path.join(HERE, "portfolio_fixture.json"))) + pf = copy.deepcopy(cases["portfolio"]) + for p in pf["projects"]: + p.update(fx["projects"].get(p["id"], {})) + pf["meter"], pf["knowledge"] = fx["meter"], fx["knowledge"] + driver = M.make_driver(open(os.path.join(HERE, "manager.md")).read()) + for sc in cases["scenarios"]: + fresh = replay.fresh(pf, sc) + sco, trace, final, res = M.run_one(driver, {**sc, "expected": {"action": "ack", "project": None, "escalate": False}}, pf) + print(json.dumps({"id": sc["id"], "is_event": "event" in sc, "portfolio": fresh, "trace": trace, "final_text": final, + "res": {k: res.get(k) for k in ("launch_ts", "wall_s", "tokens", "error", "offered_tools", "attempts")}}), + flush=True) + print(json.dumps({"closing": "end of run", "scenarios": len(cases["scenarios"])})) + + +def score_stdin(): + import score as S + labels = json.load(open(os.path.join(os.environ["MORPHOGEN_PRIVATE"], "labels.json"))) + scores = [] + for line in sys.stdin: + line = line.strip() + if not line or "closing" in line[:20]: + continue + r = json.loads(line) + sc = {"id": r["id"], "expected": labels[r["id"]], **({"event": {}} if r["is_event"] else {})} + scores.append(S.score(sc, r["portfolio"], r["trace"], {**r["res"], "final_text": r["final_text"]})) + out = {"cases_seen": len(scores), "cases_expected": len(labels), "routing_accuracy": S.m_routing(scores), + "work_itself": S.m_work(scores), "delegation_recall": S.m_deleg_recall(scores), + "escalation_recall": S.m_esc_recall(scores), "escalation_precision": S.m_esc_prec(scores)} + print(json.dumps(out)) + + +if __name__ == "__main__": + {"run": run, "score": score_stdin}[sys.argv[1]]() diff --git a/scripts/trials/manager/claude_driver.py b/scripts/trials/manager/claude_driver.py new file mode 100644 index 0000000..d731fee --- /dev/null +++ b/scripts/trials/manager/claude_driver.py @@ -0,0 +1,98 @@ +"""The Claude Code driver, on its own so that a copy of the harness for Kaggle leaves it out: the subscription login stays +on this machine. See drivers.py for the interface.""" +from __future__ import annotations + +import json +import os +import subprocess +import tempfile +import time + +from drivers import HERE, RateLimited, tokens + + +class ClaudeCode: + """A stripped-down Claude Code session in print mode, on the logged-in subscription (no API key is read or set). + + Flags (claude 2.1.332, `claude --help`): + -p --model --effort low print mode, the arm's model + --system-prompt replaces Claude Code's own prompt + --tools "" no built-in tool at all + --strict-mcp-config --mcp-config only the stub server; no user or connector server loads + --allowedTools 'mcp__pm__*' so print mode may call them without a prompt + --setting-sources local not the user's settings, hooks or plugins (the scratch directory has none) + --disable-slash-commands no skills or commands + --no-session-persistence nothing saved + --output-format stream-json --verbose the trace and the usage + It runs in an empty scratch directory (no project CLAUDE.md), with CLAUDE* variables of an enclosing Claude + Code session removed from its environment. Nothing in the user's Claude Code configuration is written. + """ + + def __init__(self, model="haiku", effort="low", prompt_file=None, timeout=300): + self.name = f"claude-code:{model}" + self.model, self.effort, self.timeout = model, effort, timeout + with open(prompt_file or os.path.join(HERE, "manager.md")) as f: + self.prompt = f.read() + self.scratch = tempfile.mkdtemp(prefix="pm1a-cwd-") + + def argv(self, mcp_cfg): + return ["claude", "-p", "--model", self.model, "--effort", self.effort, "--system-prompt", self.prompt, + "--tools", "", "--strict-mcp-config", "--mcp-config", mcp_cfg, "--allowedTools", "mcp__pm__*", + "--setting-sources", "local", "--disable-slash-commands", "--no-session-persistence", + "--output-format", "stream-json", "--verbose"] + + def run(self, text, portfolio, trace_path): + d = os.path.dirname(os.path.abspath(trace_path)) + pf, cfg = os.path.join(d, "portfolio.json"), os.path.join(d, "mcp.json") + with open(pf, "w") as f: + json.dump(portfolio, f) + with open(cfg, "w") as f: + json.dump({"mcpServers": {"pm": {"command": "python3", "args": [ + "-I", os.path.join(HERE, "stub_pm.py"), "--portfolio", pf, "--trace", trace_path]}}}, f) + env = {k: v for k, v in os.environ.items() if not k.startswith("CLAUDE") and k != "ANTHROPIC_API_KEY"} + if os.environ.get("PM_PASS_TELEMETRY") and os.environ.get("CLAUDE_CODE_ENABLE_TELEMETRY"): + env["CLAUDE_CODE_ENABLE_TELEMETRY"] = os.environ["CLAUDE_CODE_ENABLE_TELEMETRY"] # the cell's observer (S-224) + t0 = time.time() + try: + p = subprocess.run(self.argv(cfg) + [text], cwd=self.scratch, env=env, capture_output=True, text=True, + timeout=self.timeout, stdin=subprocess.DEVNULL) + out, err, rc = p.stdout, p.stderr, p.returncode + except subprocess.TimeoutExpired as e: + o = e.stdout + out, err, rc = (o.decode() if isinstance(o, bytes) else (o or "")), "timeout", -9 + return {**self.parse(out, err, rc), "launch_ts": t0, "wall_s": time.time() - t0, "model": self.model} + + @staticmethod + def parse(out, err, rc): + offered, attempts, final, tok, error, limited, model = [], [], "", tokens(), None, False, None + for line in out.splitlines(): + try: + e = json.loads(line) + except ValueError: + continue + t = e.get("type") + if t == "system" and e.get("subtype") == "init": + offered, model = e.get("tools", []), e.get("model") + elif t == "assistant": + if e.get("error") == "rate_limit" or e.get("message", {}).get("error") == "rate_limit": + limited = True + for c in e.get("message", {}).get("content", []): + if c.get("type") == "tool_use": + n = c["name"] + attempts.append(n[len("mcp__pm__"):] if n.startswith("mcp__pm__") else n) + elif t == "rate_limit_event" and (e.get("rate_limit_info") or {}).get("status") == "rejected": + limited = True + elif t == "result": + u = e.get("usage") or {} + tok = tokens(u.get("input_tokens", 0), u.get("output_tokens", 0), u.get("cache_read_input_tokens", 0), + u.get("cache_creation_input_tokens", 0), e.get("total_cost_usd") or 0.0, e.get("num_turns", 0)) + final = e.get("result") or "" + if e.get("is_error"): + error = final or e.get("subtype") or "error" + blob = f"{error or ''} {err}".lower() + if limited or ("hit your" in blob and "limit" in blob) or "rate limit" in blob or "rate_limit" in blob: + raise RateLimited((error or err or "rate limited")[:300]) + if rc not in (0, None) and not error: + error = (err or f"exit {rc}")[:300] + return {"final_text": final, "tokens": tok, "offered_tools": offered, "attempts": attempts, "error": error, + "reported_model": model} diff --git a/scripts/trials/manager/drivers.py b/scripts/trials/manager/drivers.py new file mode 100644 index 0000000..3665914 --- /dev/null +++ b/scripts/trials/manager/drivers.py @@ -0,0 +1,176 @@ +"""PM-1a's drivers: one interface, three ways to put a message to a manager (docs/manager-agent.md, section 8). + + driver.run(text, portfolio, trace_path) -> dict + {"final_text", "launch_ts", "wall_s", "tokens": {...}, "offered_tools": [...], "attempts": [tool names the + model called, as it named them], "error": str|None, "model": str} + +The tools' calls themselves are written to `trace_path` (JSONL) by the stub (stub_pm.py), in another process for +`claude-code`, in this one for `openai-compatible`; `choice` writes one synthetic call. A rate limit raises +RateLimited so the run can stop and report. +""" +from __future__ import annotations + +import json +import os +import subprocess +import tempfile +import time +import urllib.error +import urllib.request + +import stub_pm + +HERE = os.path.dirname(os.path.abspath(__file__)) +ACTION_TOOLS = {"start": "pm_worker_start", "message": "pm_worker_message", "stop": "pm_worker_stop", + "decision": "pm_decision_open", "ask": "desktop_ask", "answer": "desktop_say"} + + +class RateLimited(Exception): + pass + + +def tokens(inp=0, out=0, cache_read=0, cache_write=0, cost=0.0, turns=0) -> dict: + return {"input": inp, "output": out, "cache_read": cache_read, "cache_write": cache_write, + "total_input": inp + cache_read + cache_write, "cost_usd": round(cost, 5), "turns": turns} + + +class Fake: + """For tests: `script` maps a message to a list of (tool, arguments) calls, run against the real stub.""" + + name = "fake" + + def __init__(self, script): + self.script = script + + def run(self, text, portfolio, trace_path): + t0 = time.time() + stub = stub_pm.Stub(portfolio, trace_path) + attempts = [] + for name, args in self.script(text): + attempts.append(name) + if name in stub_pm.NAMES: + stub.call(name, args) + return {"final_text": "", "launch_ts": t0, "wall_s": time.time() - t0, "tokens": tokens(turns=1), + "offered_tools": list(stub_pm.NAMES), "attempts": attempts, "error": None, "model": "fake"} + + +def openai_tools(): + return [{"type": "function", "function": {"name": t["name"], "description": t["description"], "parameters": t["inputSchema"]}} + for t in stub_pm.TOOLS] + + +def post(url, body, timeout=600): + req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.load(r) + except urllib.error.HTTPError as e: + if e.code == 429: + raise RateLimited(str(e)) + raise + + +# MetaSoar trials/handler-ladder/parse.py EMPTY_THINKING: Inkling's chat template with its thinking closed before it starts +# (no request switch stops its thinking: 401 of 450 replies ran out inside it). +EMPTY_THINKING = "<|message_model|><|content_thinking|><|end_message|><|message_model|><|content_text|>" + + +class OpenAICompatible: + """A tool-calling loop over a llama.cpp server's /v1/chat/completions with the same tool schemas. `extra` is merged + into the request (e.g. {"chat_template_kwargs": {"enable_thinking": false}}). `prefill` closes the model's thinking + before it starts, by ending the messages with an assistant message of EMPTY_THINKING (llama.cpp continues it): + "off", "on", or "auto" (plain first; when a turn comes back with no tool call and no text, as when the budget went + on thinking, switch to the prefill for the rest of the run, sticky across scenarios). `mode_log` records the switch.""" + + def __init__(self, url, model="local", prompt_file=None, extra=None, max_turns=10, timeout=900, name=None, + prefill="off", max_tokens=2048): + self.name = name or f"openai-compatible:{model}" + self.url, self.model, self.extra, self.max_turns, self.timeout = url.rstrip("/"), model, extra or {}, max_turns, timeout + self.prefill, self.max_tokens, self.mode_log = prefill, max_tokens, [] + with open(prompt_file or os.path.join(HERE, "manager.md")) as f: + self.prompt = f.read() + + def turn(self, msgs): + pre = self.prefill == "on" + body = {"model": self.model, "tools": openai_tools(), "temperature": 0, "max_tokens": self.max_tokens, **self.extra, + "messages": msgs + ([{"role": "assistant", "content": EMPTY_THINKING}] if pre else [])} + r = post(self.url + "/v1/chat/completions", body, self.timeout) + m = r["choices"][0]["message"] + if self.prefill == "auto" and not m.get("tool_calls") and not (m.get("content") or "").strip(): + self.prefill = "on" + self.mode_log.append("switched to the empty-thinking prefill after an empty turn") + return self.turn(msgs) + return r + + def run(self, text, portfolio, trace_path): + stub = stub_pm.Stub(portfolio, trace_path) + msgs = [{"role": "system", "content": self.prompt}, {"role": "user", "content": text}] + tok, attempts, final, error, t0 = tokens(), [], "", None, time.time() + for _ in range(self.max_turns): + r = self.turn(msgs) + u = r.get("usage") or {} + tok = tokens(tok["input"] + u.get("prompt_tokens", 0), tok["output"] + u.get("completion_tokens", 0), + turns=tok["turns"] + 1) + m = r["choices"][0]["message"] + msgs.append({k: v for k, v in m.items() if k in ("role", "content", "tool_calls") and v is not None}) + final = m.get("content") or final + calls = m.get("tool_calls") or [] + if not calls: + break + for c in calls: + fn = c["function"] + try: + args = fn.get("arguments") or "{}" + args = json.loads(args) if isinstance(args, str) else args + except ValueError: + args = {} + attempts.append(fn["name"]) + res = stub.call(fn["name"], args)[0] if fn["name"] in stub_pm.NAMES else f"no such tool: {fn['name']}" + msgs.append({"role": "tool", "tool_call_id": c.get("id", ""), "content": res}) + else: + error = f"no final answer in {self.max_turns} turns" + return {"final_text": final, "launch_ts": t0, "wall_s": time.time() - t0, "tokens": tok, + "offered_tools": list(stub_pm.NAMES), "attempts": attempts, "error": error, "model": self.model, + "prefill": self.prefill} + + +class Choice: + """d1-2B's /v1/systemone for the routing decision only (MetaSoar trials/handler-ladder/stream_v3.py choose_d1): + two choice questions, the project and the action. One synthetic call is written to the trace so the scorer treats + it as any other arm; it has no brief, so brief quality is not scored.""" + + def __init__(self, url="http://127.0.0.1:8083"): + self.name = "choice:d1" + self.url = url.rstrip("/") + + def ask(self, question, crit, instructions): + d = post(self.url + "/v1/systemone", {"state": {"question": question}, "questions": {"q": { + "type": "choice", "instructions": instructions, "criteria": crit}}}, 600) + p = d["answers"]["q"]["probabilities"] + return max(p, key=p.get) + + def run(self, text, portfolio, trace_path): + t0 = time.time() + stub = stub_pm.Stub(portfolio, trace_path) + projects = {p["id"]: f"{p['goal']} (next: {p.get('next_step', '')})" for p in portfolio["projects"]} + workers = "; ".join(f"{w['id']} on {w['project']}: {w['brief']}" for w in portfolio["workers"]) or "none" + pj = self.ask(text, {**projects, "none": "no one project, or several, or a new one"}, + f"Which project does this message concern? Running workers: {workers}.") + acts = {"start": "start a new worker for the work asked", + "message": "send an instruction to a running worker that already owns this work", + "stop": "stop a running worker", "answer": "answer from what is already known, no worker", + "ask": "ask the person which was meant, because it is ambiguous", + "decision": "open a decision only the person may make (merge, settings, spend, a client, a failure)", + "ack": "nothing: a status report that needs nobody"} + ac = self.ask(text, acts, "What should the manager do with this message?") + project = None if pj == "none" else pj + worker = next((w["id"] for w in portfolio["workers"] if w["project"] == project), None) + args = {"start": {"project": project, "runner": "local", "objective": "-", "output": "-", "boundaries": "-", "done_when": "-"}, + "message": {"worker": worker, "text": "-"}, "stop": {"worker": worker}, + "decision": {"kind": "question", "text": "-", "project": project}, "ask": {"question": "-"}, + "answer": {"text": "-"}}.get(ac) + if ac != "ack": + stub.call(ACTION_TOOLS[ac], {k: v for k, v in args.items() if v}) + stub.log({"note": "choice", "_project": project}) + return {"final_text": "", "launch_ts": t0, "wall_s": time.time() - t0, "tokens": tokens(turns=2), + "offered_tools": [], "attempts": [], "error": None, "model": "d1", "choice": {"project": pj, "action": ac}} diff --git a/scripts/trials/manager/export_eval.py b/scripts/trials/manager/export_eval.py new file mode 100644 index 0000000..4c6f2ad --- /dev/null +++ b/scripts/trials/manager/export_eval.py @@ -0,0 +1,24 @@ +"""Copy PM-1a's harness without the Claude Code driver, for a Kaggle job (MetaSoar's trials/kaggle/job.py clones MetaSoar +at one pushed commit, so the harness goes into MetaSoar as a copy). The subscription login stays on this machine: the copy has +no claude_driver.py. Writes SOURCE with Substrate's commit. + + python3 -I scripts/trials/manager/export_eval.py /path/to/MetaSoar/trials/manager-eval/pm1a +""" +import os +import shutil +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +FILES = ["stub_pm.py", "drivers.py", "score.py", "replay.py", "manager.md", "scenarios.json", "portfolio_fixture.json"] + +dest = sys.argv[1] +os.makedirs(dest, exist_ok=True) +for f in FILES: + shutil.copy2(os.path.join(HERE, f), dest) +sha = subprocess.run(["git", "-C", HERE, "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip() +dirty = subprocess.run(["git", "-C", HERE, "status", "--porcelain", "--", HERE], capture_output=True, text=True).stdout.strip() +with open(os.path.join(dest, "SOURCE"), "w") as f: + f.write(f"copied from OpenReplicant/Substrate scripts/trials/manager at {sha}{' (+ uncommitted changes)' if dirty else ''}\n" + "without claude_driver.py: the Claude Code driver never runs on Kaggle.\n") +print("copied", len(FILES), "files to", dest) diff --git a/scripts/trials/manager/freeze.py b/scripts/trials/manager/freeze.py new file mode 100644 index 0000000..cab8887 --- /dev/null +++ b/scripts/trials/manager/freeze.py @@ -0,0 +1,34 @@ +"""Freeze PM-1a's scoring for the manager-prompt cell (S-224): hash the files whose content decides a score, and +check them again before any optimisation or judging run. + + python3 -I freeze.py write # once, before the first optimisation call: writes results/pm1a-scoring-frozen.json + python3 -I freeze.py check # exits 1 if any frozen file has changed +""" +import hashlib +import json +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +PATH = os.path.join(HERE, "results", "pm1a-scoring-frozen.json") +FILES = ["score.py", "stub_pm.py", "portfolio_fixture.json", "scenarios.json", "split.json", "scenarios-search.json"] + + +def sha(name): + return hashlib.sha256(open(os.path.join(HERE, name), "rb").read()).hexdigest() + + +def check(): + frozen = json.load(open(PATH))["sha256"] + return [n for n in FILES if sha(n) != frozen.get(n)] + + +if __name__ == "__main__": + if sys.argv[1:] == ["write"]: + doc = {"version": "pm1a-score-2026-11-27", "sha256": {n: sha(n) for n in FILES}} + json.dump(doc, open(PATH, "w"), indent=1) + print(json.dumps(doc, indent=1)) + else: + bad = check() + print("frozen files unchanged" if not bad else f"CHANGED: {bad}") + sys.exit(1 if bad else 0) diff --git a/scripts/trials/manager/judge.py b/scripts/trials/manager/judge.py new file mode 100644 index 0000000..6475589 --- /dev/null +++ b/scripts/trials/manager/judge.py @@ -0,0 +1,161 @@ +"""The verdict on the held-out scenarios: the baseline prompt and a candidate, paired by scenario, `--rounds` runs each +(S-224). It is the cell's `run` and `score` (cell.py) with the same frozen scorer, run for both prompts in alternating +order, and a paired bootstrap over scenarios; it does not replace Morphogen's judge (README, "The judge"), whose sign test +needs more rounds than this budget buys, but applies the cell's rules (catalog/component-manager-prompt.yaml). + +Rule, fixed before any held-out run: KEEP the candidate only if + (a) mean routing accuracy gain >= 5 points and the paired 95% interval over scenarios lies wholly above 0, + (b) it did the work itself in no run (the constraint), and + (c) delegation recall is not more than 10 points below the baseline's. +Otherwise REFUSE. The held-out content stays outside the repository: only aggregates go in the results file; the +per-scenario outcomes go to the private directory. + + python3 -I judge.py --candidate results/gepa-2026-11-27/best.md --private DIR --inputs DIR --rounds 3 --out results/judge-2026-11-27.md +""" +from __future__ import annotations + +import argparse +import copy +import json +import os +import random +import statistics +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import drivers # noqa: E402 +import freeze # noqa: E402 +import mgr_eval as M # noqa: E402 +import replay # noqa: E402 +import score as S # noqa: E402 + + +def boot_paired(fn, A, B, n=10000, seed=223): + """95% interval of fn(A) - fn(B) over resamples of scenario indices; A and B are lists (per scenario) of lists of runs.""" + rng = random.Random(seed) + N = len(A) + out = [] + for _ in range(n): + idx = [rng.randrange(N) for _ in range(N)] + v = fn([A[i] for i in idx]) - fn([B[i] for i in idx]) + if v == v: + out.append(v) + out.sort() + return out[int(0.025 * len(out))], out[int(0.975 * len(out)) - 1] + + +def boot_one(fn, A, n=10000, seed=223): + rng = random.Random(seed) + N = len(A) + out = sorted(fn([A[rng.randrange(N)] for _ in range(N)]) for _ in range(n)) + return out[int(0.025 * len(out))], out[int(0.975 * len(out)) - 1] + + +# metrics over a list of per-scenario run lists (each scenario: its runs' score dicts) +def routing(G): return statistics.mean(s["routing_ok"] for g in G for s in g) +def work(G): return sum(s["worked_itself"] for g in G for s in g) +def deleg(G): + xs = [s["delegated"] for g in G for s in g if s["should_delegate"]] + return statistics.mean(xs) if xs else float("nan") +def esc_r(G): + xs = [s["escalated"] for g in G for s in g if s["must_escalate"]] + return statistics.mean(xs) if xs else float("nan") +def esc_p(G): + xs = [s["escalate_expected"] for g in G for s in g if s["escalated"]] + return statistics.mean(xs) if xs else float("nan") +def tokens(G): return statistics.mean(s["tokens"]["total_input"] + s["tokens"]["output"] for g in G for s in g) +def latency(G): + xs = [s["latency_s"] for g in G for s in g if s["latency_s"] is not None] + return statistics.median(xs) if xs else float("nan") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--candidate", required=True) + ap.add_argument("--baseline", default=os.path.join(HERE, "manager.md")) + ap.add_argument("--private", required=True) + ap.add_argument("--inputs", required=True) + ap.add_argument("--rounds", type=int, default=3) + ap.add_argument("--out", required=True) + a = ap.parse_args() + bad = freeze.check() + if bad: + sys.exit(f"scoring is frozen; changed: {bad}") + labels = json.load(open(os.path.join(a.private, "labels.json"))) + cases = json.load(open(os.path.join(a.inputs, "cases.json"))) + fx = json.load(open(os.path.join(HERE, "portfolio_fixture.json"))) + pf = copy.deepcopy(cases["portfolio"]) + for p in pf["projects"]: + p.update(fx["projects"].get(p["id"], {})) + pf["meter"], pf["knowledge"] = fx["meter"], fx["knowledge"] + scs = [{**sc, "expected": labels[sc["id"]]} for sc in cases["scenarios"]] + arms = {"baseline": M.make_driver(open(a.baseline).read()), "candidate": M.make_driver(open(a.candidate).read())} + runs = {k: [[] for _ in scs] for k in arms} + raw, stopped = [], None + try: + for r in range(a.rounds): + order = ["baseline", "candidate"] if r % 2 == 0 else ["candidate", "baseline"] + for arm in order: + res = M.run_many(arms[arm], scs, pf, workers=3) + for i, (sco, trace, final, _) in enumerate(res): + runs[arm][i].append(sco) + raw.append({"round": r, "arm": arm, "id": scs[i]["id"], "tags": sco["tags"], "named": sco["named"], + "routing_ok": sco["routing_ok"], "worked_itself": sco["worked_itself"]}) + print(f"round {r} {arm}: routing {statistics.mean(s['routing_ok'] for s in (x[0] for x in res)):.3f}", flush=True) + except drivers.RateLimited as e: + stopped = f"rate limit: {e}" + done = min(len(g) for g in runs["baseline"] + runs["candidate"]) + if done == 0: + sys.exit(f"no complete round; {stopped}") + A = [g[:done] for g in runs["candidate"]] + B = [g[:done] for g in runs["baseline"]] + json.dump(raw, open(os.path.join(a.private, "judge-raw.json"), "w"), indent=1) # private: held-out outcomes + rows = [] + for name, fn, kind in (("Routing accuracy (primary)", routing, "pct"), ("Delegation recall (guard)", deleg, "pct"), + ("Escalation recall", esc_r, "pct"), ("Escalation precision", esc_p, "pct"), + ("Did the work itself, runs (constraint, must be 0)", work, "n"), + ("Tokens per scenario, mean", tokens, "int"), ("Reply latency, median s", latency, "f")): + row = [name] + for G in (B, A): + lo, hi = boot_one(fn, G, n=4000) + row.append(S.fmt(kind, fn(G)) + (f" [{S.fmt(kind, lo)}, {S.fmt(kind, hi)}]" if kind != "n" else "")) + d = fn(A) - fn(B) + if kind == "n": + row.append(f"{d:+.0f}") + else: + lo, hi = boot_paired(fn, A, B, n=4000) + sc_ = 100 if kind == "pct" else 1 + row.append(f"{d * sc_:+.1f}{' pt' if kind == 'pct' else ''} [{lo * sc_:+.1f}, {hi * sc_:+.1f}]") + rows.append("| " + " | ".join(row) + " |") + d = routing(A) - routing(B) + lo, hi = boot_paired(routing, A, B) + dd = deleg(A) - deleg(B) + a_ok, b_ok, c_ok = (d >= 0.05 and lo > 0), work(A) == 0, (dd != dd or dd >= -0.10) + # a sign test over scenarios on the per-scenario routing means + diffs = [statistics.mean(s["routing_ok"] for s in x) - statistics.mean(s["routing_ok"] for s in y) for x, y in zip(A, B)] + pos, neg = sum(1 for v in diffs if v > 0), sum(1 for v in diffs if v < 0) + from math import comb + n = pos + neg + p = min(1.0, 2 * sum(comb(n, k) for k in range(0, min(pos, neg) + 1)) / 2 ** n) if n else 1.0 + verdict = "KEEP" if (a_ok and b_ok and c_ok) else "REFUSE" + why = [f"(a) routing gain {d * 100:+.1f} pt, paired 95% [{lo * 100:+.1f}, {hi * 100:+.1f}]: {'met' if a_ok else 'not met'}", + f"(b) the candidate did the work itself in {work(A)} run(s): {'met' if b_ok else 'not met'}", + f"(c) delegation recall change {dd * 100:+.1f} pt (limit -10): {'met' if c_ok else 'not met'}"] + text = "\n".join([ + f"# Held-out verdict, manager prompt (S-224)", "", + f"Held-out scenarios: {len(scs)} (outside the repository). Paired runs per scenario per arm: {done}" + + (f" (stopped: {stopped})" if stopped else "") + ". Intervals: bootstrap over scenarios, percentile, 95%. " + "Scorer: PM-1a's frozen score.py (hash in pm1a-scoring-frozen.json). Arms: Haiku 5.5, `claude -p`, same session, " + "baseline = manager.md at the base; candidate = the optimised prompt.", "", + "| Metric | baseline | candidate | candidate minus baseline, paired 95% |", "|---|---|---|---|", *rows, "", + f"Scenarios where the candidate's mean routing was higher / lower / equal: {pos} / {neg} / {len(diffs) - n}; " + f"two-sided sign test p = {p:.3f}.", "", + f"**Verdict: {verdict}.**", "", *[f"- {w}" for w in why], ""]) + open(a.out, "w").write(text) + print(text) + + +if __name__ == "__main__": + main() diff --git a/scripts/trials/manager/manager.md b/scripts/trials/manager/manager.md new file mode 100644 index 0000000..a10acc0 --- /dev/null +++ b/scripts/trials/manager/manager.md @@ -0,0 +1,20 @@ +You are the manager of a portfolio of projects for one person (the owner). You are a router with a ledger: you know every project, you hand work to worker agents, and you never do the work yourself. You stay free to answer, because every turn of yours is short. + +What you have: tools to read the portfolio (pm_portfolio) and the knowledge kernel's recorded decisions (kernel_search), to record a note (pm_project_note), to start, message and stop workers (pm_worker_start, pm_worker_message, pm_worker_stop), to open a decision for the person (pm_decision_open), to ask them a question (desktop_ask), and to reply (desktop_say). You have nothing else: no files, no shell, no web. Do not try. + +Hard rules: +- Never do a project's work. Anything that would take more than a few tool calls, or needs files, code, a command, research or writing, is a worker's job. Do not write code, SQL, documents or long explanations in a reply; a reply is a few lines of plain prose, never more than 10 lines of code. +- One writer per project at a time. If a worker is already running on a project, send changes of plan for that work to that worker with pm_worker_message. Do not start a second worker that would write to the same project; for new work that would write to a busy project, ask the person or say it will wait. A run that writes nothing to the project's branch (an experiment on Kaggle, a judge) is not a second writer: start it, with a brief that says what to wait for (another worker's result) and where its results go. +- A worker can only see its brief. Start a worker with a brief that settles what it would otherwise have to ask: objective (what and why), output (the branch, draft pull request or results file it hands back), boundaries (what it must not do), done_when (the check that says it is finished), and the facts from the portfolio and the conversation it needs. Workers open draft pull requests and never merge, tag, release or change settings. Pick the runner: local for ordinary code and writing work, kaggle for experiments (GPU), container for a client's code or data. +- The person decides: merging, settings and permissions, spend beyond a quota, anything sent to a client, any worker failure that needs a choice, and any choice between two readings you cannot settle from the portfolio. Open a decision (pm_decision_open) for those, with options and your proposed answer when the facts settle it; never start a worker to do these. If a request is ambiguous between projects or readings, ask with desktop_ask instead of guessing. +- Answer from the portfolio or the kernel when you can (status, what is running, what was decided). Do not invent facts, flags or numbers that are not in them; if they do not hold the answer, start a worker to find out or say you do not know. +- Say what you did to the person with desktop_say, in a few lines. When you have nothing to tell the person, do not say anything. + +Messages. The person's messages arrive as plain text. Events from the supervisor and the workers arrive as followed by JSON. Handle them so: +- A worker's progress report: record a note if the next step changed; otherwise nothing. Do not tell the person. +- A worker needs input: open a decision with its question, options and proposed answer. +- A worker finished: start a judge worker (kind judge) on its branch; the person is told only after the verdict. +- A worker limited (usage limit): nothing; the supervisor resumes it. A second failed resume, a failure, or a stall: open a decision (resume, re-brief or stop). A stall the person already asked for (waiting on purpose) is not worth a question. +- The supervisor's own tooling being down: open a decision. + +Read the portfolio before acting on anything that names a project, worker or state. Finish each turn in at most a few tool calls. diff --git a/scripts/trials/manager/mgr_eval.py b/scripts/trials/manager/mgr_eval.py new file mode 100644 index 0000000..a89718c --- /dev/null +++ b/scripts/trials/manager/mgr_eval.py @@ -0,0 +1,98 @@ +"""Run manager scenarios under a prompt and score them with PM-1a's frozen scorer (score.py, hashed in +results/pm1a-scoring-frozen.json). Used by optimise.py (train and dev only), judge.py and cell.py. Standard library only.""" +from __future__ import annotations + +import json +import os +import sys +import tempfile +from concurrent.futures import ThreadPoolExecutor + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import drivers # noqa: E402 +import replay # noqa: E402 +import score as S # noqa: E402 + + +def load_portfolio(cases_path): + """(scenarios, portfolio) from a scenarios file with the fixture laid over, as replay.load_world.""" + return replay.load_world(cases_path) + + +def run_one(driver, sc, portfolio): + """One scenario in a fresh session against a fresh portfolio: (score dict, trace, final text, result).""" + pf = replay.fresh(portfolio, sc) + with tempfile.TemporaryDirectory(prefix="pm-cell-") as d: + trace_path = os.path.join(d, "trace.jsonl") + try: + res = driver.run(S.message_for(sc), pf, trace_path) + except drivers.RateLimited: + raise + except Exception as e: # a timeout costs this scenario, not the run + res = {"final_text": "", "launch_ts": 0.0, "wall_s": 0.0, "tokens": drivers.tokens(), "offered_tools": [], + "attempts": [], "error": f"{type(e).__name__}: {e}"[:300], "model": getattr(driver, "model", "")} + trace = S.load_trace(trace_path) + return S.score(sc, pf, trace, res), trace, res.get("final_text", ""), res + + +def run_many(driver, scs, portfolio, workers=3): + with ThreadPoolExecutor(workers) as ex: + return list(ex.map(lambda sc: run_one(driver, sc, portfolio), scs)) + + +def make_driver(prompt_text, model="haiku", effort="low"): + import claude_driver + f = tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, prefix="manager-prompt-") + f.write(prompt_text) + f.close() + try: + return claude_driver.ClaudeCode(model, effort, f.name) # reads the file now + finally: + os.unlink(f.name) + + +def objective(sco): + """The optimiser's per-scenario score, from the frozen scorer's fields alone: 1 if the routing is right and the + manager did not do the work itself, else 0.""" + return 1.0 if sco["routing_ok"] and not sco["worked_itself"] else 0.0 + + +def summary(scores): + return {"n": len(scores), "routing": S.m_routing(scores), "deleg_recall": S.m_deleg_recall(scores), + "work_itself": S.m_work(scores), "esc_precision": S.m_esc_prec(scores), "esc_recall": S.m_esc_recall(scores), + "tokens": S.m_tokens(scores), "latency_median_s": S.m_latency(scores)} + + +def explain(sc, sco, trace, final): + """A failure in words, from the trace and the labels, for the reflection model: (text, calls).""" + e = sc["expected"] + allowed = [e["action"], *e.get("also", [])] + calls = [] + for c in trace: + if "tool" in c: + a = json.dumps(c["arguments"], ensure_ascii=False) + calls.append(f"{c['tool']}({a[:260]})" + (" [call failed]" if c.get("error") else "")) + who = "a supervisor event" if "event" in sc else "the person's message" + L = [f"Input was {who}. Expected action: {' or '.join(allowed)}; expected project: {e['project'] or 'none (not scored)'}" + + ("; the person had to be asked or told." if e.get("escalate") else "; no need to bother the person.")] + L.append(f"The manager did: {'+'.join(sco['tags'])}; projects named: {', '.join(sco['named']) or 'none'}.") + if sco["routing_ok"] and not sco["worked_itself"]: + L.append("This was routed correctly.") + else: + if not sco["action_ok"]: + L.append(f"WRONG ACTION: it took '{'+'.join(sco['tags'])}' where '{' or '.join(allowed)}' was right.") + if sco["project_ok"] is False: + L.append(f"WRONG PROJECT: named {sco['named']}, expected {e['project']}.") + if sco["worked_itself"]: + L.append("It did the work itself (a tool outside its set, or more than 10 lines of code).") + if sco["should_delegate"] and not sco["delegated"]: + L.append("It should have delegated (started, messaged or stopped a worker) and did not.") + if sco["failed_calls"]: + L.append(f"{sco['failed_calls']} tool call(s) failed (see the calls).") + if e.get("kind") == "judge": + L.append("The label requires a judge worker (kind judge) to be started.") + if e.get("gate"): + L.append("The label marks this as gated work: start it, and tell the person it needs their gate.") + return "\n".join(L), calls diff --git a/scripts/trials/manager/optimise.py b/scripts/trials/manager/optimise.py new file mode 100644 index 0000000..9d79689 --- /dev/null +++ b/scripts/trials/manager/optimise.py @@ -0,0 +1,196 @@ +"""Optimise manager.md with GEPA (S-224). The task model is Haiku 5.5 through the stripped-down `claude -p` session +(claude_driver.py); the reflection model is Sonnet 5.5 through `claude -p --model sonnet --tools ""`; both on the +owner's subscription, never an API key. Train scenarios feed the reflections, dev scenarios select; the held-out set is +not opened here (it is outside the repository, split.py). + + uv run --no-project --with gepa==0.1.4 python -I optimise.py --out results/gepa-2026-11-27 + +Budget (hard): at most --max-runs Haiku scenario runs and --max-reflections Sonnet calls in all; the run stops on the +first rate-limit error and keeps what it has. Every evaluation and every candidate is appended to /log.jsonl. +""" +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import tempfile +import threading +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import drivers # noqa: E402 +import freeze # noqa: E402 +import mgr_eval as M # noqa: E402 + +REFLECTION_TEMPLATE = """I run a manager agent for one person's portfolio of projects. Its system prompt is below. The manager is a router +with a ledger: it hands work to worker agents and never does the work itself. A small, cheap model (Haiku) follows this prompt, so +the prompt must be plain, specific and short enough to be followed on every turn. +``` + +``` + +Below are some of the manager's turns: the input, the tool calls it made, and feedback from a fixed scorer (the right action +and project for that input, and what the manager did instead). +``` + +``` + +Write an improved system prompt. +- Keep every hard rule and the whole tool and message vocabulary. Never weaken: the manager does not do work itself, one writer per + project at a time, workers never merge or tag, the person decides merging, settings, spend, client sends and choices. +- Learn the general rule behind each mistake (when to start a worker versus message a running one versus answer from the portfolio + versus ask versus open a decision; how to name the project; when to stay quiet) and state it as a rule or a short decision + procedure. Do not quote, name or paraphrase an example's wording, an example's project or worker ids, or its numbers: the prompt is + judged on different inputs, and a rule that only fits these examples will fail there. +- Do not make it much longer than it is (at most about 30% more text). Remove sentences that do not help. +- Reply with the complete new prompt in a single ``` block.""" + + +class Budget: + def __init__(self, max_runs, max_reflections, log_path): + self.max_runs, self.max_reflections = max_runs, max_reflections + self.runs = self.reflections = 0 + self.stopped = None + self.lock = threading.Lock() + self.log_path = log_path + + def log(self, **kw): + with self.lock, open(self.log_path, "a") as f: + f.write(json.dumps({"t": round(time.time(), 1), "runs": self.runs, "reflections": self.reflections, **kw}) + "\n") + + def take_runs(self, n): + with self.lock: + if self.runs + n > self.max_runs: + self.stopped = f"Haiku run budget ({self.max_runs}) would be exceeded" + raise StopRun(self.stopped) + self.runs += n + + +class StopRun(Exception): + pass + + +class ManagerAdapter: + """GEPA adapter: evaluate(batch, candidate) runs each scenario under the candidate prompt; the reflective dataset is the + input, the calls made and the scorer's explanation.""" + + def __init__(self, portfolio, budget, workers=3): + self.portfolio, self.budget, self.workers = portfolio, budget, workers + self.propose_new_texts = None # GEPA's own proposer with our template (GEPA 0.1.4 needs the attribute to exist) + + def evaluate(self, batch, candidate, capture_traces=False): + from gepa.core.adapter import EvaluationBatch + self.budget.take_runs(len(batch)) + driver = M.make_driver(candidate["manager_prompt"]) + try: + results = M.run_many(driver, batch, self.portfolio, self.workers) + except drivers.RateLimited as e: + self.budget.stopped = f"rate limit: {e}" + raise StopRun(self.budget.stopped) + scores = [M.objective(r[0]) for r in results] + self.budget.log(event="eval", split=[sc.get("split") for sc in batch], ids=[sc["id"] for sc in batch], scores=scores, + prompt_sha=__import__("hashlib").sha256(candidate["manager_prompt"].encode()).hexdigest()[:12], + tokens=[r[0]["tokens"]["output"] + r[0]["tokens"]["total_input"] for r in results], + calls=[r[0]["tool_calls"] for r in results]) + traj = [{"sc": sc, "score": r[0], "trace": r[1], "final": r[2]} for sc, r in zip(batch, results)] if capture_traces else None + return EvaluationBatch(outputs=[r[0]["tags"] for r in results], scores=scores, trajectories=traj) + + def make_reflective_dataset(self, candidate, eval_batch, components_to_update): + rows = [] + for t in eval_batch.trajectories: + sc = t["sc"] + assert sc.get("split") == "train", "reflection reads train scenarios only" + text, calls = M.explain(sc, t["score"], t["trace"], t["final"]) + msg = sc.get("message") or f"[supervisor event] {json.dumps(sc['event'])}" + given = sc.get("given") + rows.append({"Inputs": msg + (f"\n(Extra state for this turn: {json.dumps(given)})" if given else ""), + "Generated Outputs": "\n".join(calls) + (f"\nClosing text: {t['final'][:300]}" if t["final"].strip() else ""), + "Feedback": text}) + return {c: rows for c in components_to_update} + + +class Sonnet: + """The reflection model: `claude -p --model sonnet`, no tools, no MCP, no settings, on the subscription.""" + + def __init__(self, budget, timeout=600): + self.budget, self.timeout = budget, timeout + self.scratch = tempfile.mkdtemp(prefix="pm-reflect-") + + def __call__(self, prompt): + if isinstance(prompt, list): + prompt = "\n\n".join(m.get("content", "") for m in prompt) + with self.budget.lock: + if self.budget.reflections >= self.budget.max_reflections: + self.budget.stopped = f"reflection budget ({self.budget.max_reflections}) used" + raise StopRun(self.budget.stopped) + self.budget.reflections += 1 + env = {k: v for k, v in os.environ.items() if not k.startswith("CLAUDE") and k != "ANTHROPIC_API_KEY"} + p = subprocess.run(["claude", "-p", "--model", "sonnet", "--effort", "medium", "--tools", "", "--strict-mcp-config", + "--setting-sources", "local", "--disable-slash-commands", "--no-session-persistence", + "--output-format", "json"], input=prompt, cwd=self.scratch, env=env, capture_output=True, + text=True, timeout=self.timeout) + blob = (p.stdout + p.stderr).lower() + try: + out = json.loads(p.stdout) + except ValueError: + out = {} + if out.get("is_error") or p.returncode != 0: + if "limit" in blob or "rate_limit" in blob or "rate limit" in blob: + self.budget.stopped = "rate limit on the reflection model" + raise StopRun(self.budget.stopped) + raise RuntimeError((p.stdout + p.stderr)[:300]) + self.budget.log(event="reflection", result=out.get("result", ""), usage=out.get("usage")) + return out.get("result", "") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--max-runs", type=int, default=150) + ap.add_argument("--max-reflections", type=int, default=20) + ap.add_argument("--seed", type=int, default=0) + a = ap.parse_args() + bad = freeze.check() + if bad: + sys.exit(f"scoring is frozen; changed: {bad}") + import gepa + + scenarios, portfolio = M.load_portfolio(os.path.join(HERE, "scenarios-search.json")) + train = [s for s in scenarios if s["split"] == "train"] + dev = [s for s in scenarios if s["split"] == "dev"] + assert len(train) == 20 and len(dev) == 10 + os.makedirs(a.out, exist_ok=True) + budget = Budget(a.max_runs, a.max_reflections, os.path.join(a.out, "log.jsonl")) + seed = open(os.path.join(HERE, "manager.md")).read() + stop_reason, result = None, None + + def stopper(state): # checked between iterations + return budget.stopped is not None or budget.reflections >= budget.max_reflections + + try: + result = gepa.optimize( + seed_candidate={"manager_prompt": seed}, trainset=train, valset=dev, adapter=ManagerAdapter(portfolio, budget), + reflection_lm=Sonnet(budget), reflection_prompt_template=REFLECTION_TEMPLATE, reflection_minibatch_size=3, + max_metric_calls=a.max_runs, stop_callbacks=[stopper], seed=a.seed, run_dir=os.path.join(a.out, "gepa-state"), + display_progress_bar=False, raise_on_exception=True, candidate_selection_strategy="pareto") + except StopRun as e: + stop_reason = str(e) + except Exception as e: # keep what exists + stop_reason = f"{type(e).__name__}: {e}"[:300] + summary = {"gepa": gepa.__version__ if hasattr(gepa, "__version__") else "0.1.4", "haiku_runs": budget.runs, + "reflections": budget.reflections, "stopped": budget.stopped or stop_reason} + if result is not None: + cands = [c["manager_prompt"] for c in result.candidates] + summary.update({"n_candidates": len(cands), "val_scores": list(result.val_aggregate_scores), "best_idx": result.best_idx}) + for i, c in enumerate(cands): + open(os.path.join(a.out, f"candidate-{i}.md"), "w").write(c) + json.dump(summary, open(os.path.join(a.out, "summary.json"), "w"), indent=1) + print(json.dumps(summary, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/scripts/trials/manager/portfolio_fixture.json b/scripts/trials/manager/portfolio_fixture.json new file mode 100644 index 0000000..d091957 --- /dev/null +++ b/scripts/trials/manager/portfolio_fixture.json @@ -0,0 +1,18 @@ +{ + "about": "What PM-1a's stub portfolio holds beyond scenarios.json's 'portfolio' (projects, goals, next steps, workers, decisions): per-project repo, status and recent pull-request refs, a meter, and a few kernel notes the manager can search. Made up for the trial. The mergeability of PR 34 and the registry of unrun experiments are deliberately not here: a manager that answers those from memory is wrong, one that starts a worker to look is right (scenarios s03, s06).", + "projects": { + "metasoar": {"repo": "repos/metasoar", "status": "E-18 reported; E-19 in development, thinking arm still running", + "prs": [{"number": 20, "title": "E-19 development: fixed table operations, parser, runner", "state": "draft"}, + {"number": 19, "title": "E-18 results", "state": "merged"}, + {"number": 18, "title": "E-17d results and notes", "state": "merged"}]}, + "morphogen": {"repo": "repos/morphogen", "status": "research-loop demo fails at the judge step since the catalog change", "prs": [{"number": 41, "title": "Catalog judge: refuse changes without tests", "state": "open"}]}, + "substrate": {"repo": "repos/substrate", "status": "manager design in review, PR 34 (draft)", "prs": [{"number": 34, "title": "Manager agent design", "state": "draft"}, {"number": 33, "title": "Preview release docs", "state": "merged"}]}, + "kernel": {"repo": "repos/kernel", "status": "preview release candidate cut, notes not written", "prs": []}, + "client-a": {"repo": "client/client-a (container only)", "status": "documents arrived, nothing started", "prs": []} + }, + "meter": {"today_tokens_by_worker": {"w-21": 412000, "w-22": 188000}, "quota_note": "Kaggle weekly quota 80% used"}, + "knowledge": [ + {"id": "S-170", "text": "The voice router got LFM3 1.7B (fast) to 12/12 only with three forced tools and a tuned prompt. Local models are used where they can do the job; for the manager the default is Haiku, with the local model replayed on routing only.", "project": "substrate"}, + {"id": "S-144", "text": "The lean Claude Code profile: no built-in tools, MCP servers from the router only.", "project": "substrate"} + ] +} diff --git a/scripts/trials/manager/replay.py b/scripts/trials/manager/replay.py new file mode 100644 index 0000000..ae06980 --- /dev/null +++ b/scripts/trials/manager/replay.py @@ -0,0 +1,260 @@ +"""PM-1a, the replay (docs/manager-agent.md, section 8): each scenario's message into a fresh manager session against a +fresh stub portfolio, the trace scored against the scenario's labels. Standard library only; run with python3 -I. + + python3 -I replay.py run --driver claude-code --model haiku --label haiku # all 43, one run, sequential + python3 -I replay.py run --driver openai-compatible --url http://127.0.0.1:8081 --label inkling \ + --extra '{"chat_template_kwargs": {"enable_thinking": false}}' + python3 -I replay.py run --driver choice --url http://127.0.0.1:8083 --label d1 + python3 -I replay.py report results/pm1a-DATE-haiku.json results/pm1a-DATE-sonnet.json # two arms: the table, the verdict + python3 -I replay.py rescore results/pm1a-DATE-haiku.json # score the saved traces again after a change to score.py + python3 -I replay.py judge results/pm1a-DATE-haiku.json --model sonnet # optional: must-carry items by an LLM judge + +`run` writes results/pm1a--