From a7d8fce53a2e497565cbacabea6900d6cd3473b3 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 18 Sep 2026 01:08:33 +0100 Subject: [PATCH] perf: reduce Codex workflow token overhead --- bin/codex_usage.py | 250 ++++++++++++ bin/install.sh | 99 +++++ docs/codex_usage.md | 55 +++ docs/index.md | 1 + policy/workspace_model_delegation.md | 10 + policy/workspace_model_delegation_pointer.md | 5 + skills/MODEL_DELEGATION.md | 78 ++++ skills/WORKFLOW.md | 403 ++++--------------- skills/ship_library/SKILL.md | 2 +- skills/ship_library/reference.md | 5 +- skills/ship_library/ship_library.md | 3 +- skills/ship_workspace/SKILL.md | 2 +- skills/ship_workspace/reference.md | 3 +- skills/ship_workspace/ship_workspace.md | 5 +- skills/start_bundle/start_bundle.md | 16 +- skills/start_dev/SKILL.md | 2 +- skills/start_dev/start_dev.md | 7 +- skills/start_library/SKILL.md | 2 +- tests/test_codex_usage.py | 261 ++++++++++++ tests/test_skill_install.py | 95 ++++- 20 files changed, 950 insertions(+), 354 deletions(-) create mode 100755 bin/codex_usage.py create mode 100644 docs/codex_usage.md create mode 100644 policy/workspace_model_delegation.md create mode 100644 policy/workspace_model_delegation_pointer.md create mode 100644 skills/MODEL_DELEGATION.md create mode 100644 tests/test_codex_usage.py diff --git a/bin/codex_usage.py b/bin/codex_usage.py new file mode 100755 index 00000000..370dccd8 --- /dev/null +++ b/bin/codex_usage.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +"""Report metadata-only usage from explicitly selected Codex JSONL rollouts.""" + +from __future__ import annotations + +import argparse +import json +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + + +COUNTERS = ( + "input_tokens", + "cached_input_tokens", + "output_tokens", + "reasoning_output_tokens", +) +COORDINATION = { + "spawn_agent": "spawn", + "send_message": "message", + "followup_task": "followup", + "wait_agent": "wait", + "list_agents": "list", + "interrupt_agent": "interrupt", + "collaboration.spawn_agent": "spawn", + "collaboration.send_message": "message", + "collaboration.followup_task": "followup", + "collaboration.wait_agent": "wait", + "collaboration.list_agents": "list", + "collaboration.interrupt_agent": "interrupt", +} + + +def _timestamp(value: Any) -> datetime | None: + if not isinstance(value, str): + return None + try: + result = datetime.fromisoformat(value.replace("Z", "+00:00")) + return result.replace(tzinfo=result.tzinfo or timezone.utc) + except ValueError: + return None + + +def parse_rollout(path: Path) -> dict[str, Any]: + session_id = None + snapshots: list[dict[str, int]] = [] + models: set[str] = set() + efforts: set[str] = set() + times: list[datetime] = [] + coordination: dict[str, int] = {} + limitations: list[str] = [] + + try: + handle = path.open(encoding="utf-8") + except OSError as exc: + return { + "path": str(path), + "session_id": None, + "complete": False, + "usage": None, + "models": [], + "reasoning_efforts": [], + "duration_seconds": None, + "coordination": {}, + "limitations": [f"unreadable: {exc}"], + } + + latest_snapshot_invalid = False + try: + for number, line in enumerate(handle, 1): + try: + event = json.loads(line) + except json.JSONDecodeError: + limitations.append(f"line {number}: malformed JSON ignored") + continue + if not isinstance(event, dict): + continue + payload = ( + event.get("payload") + if isinstance(event.get("payload"), dict) + else event + ) + event_type = event.get("type") + if event_type == "session_meta": + candidate_id = payload.get("id") or payload.get("session_id") + if isinstance(candidate_id, str): + session_id = candidate_id + elif candidate_id is not None: + limitations.append(f"line {number}: non-string session id ignored") + for candidate in (event.get("timestamp"), payload.get("timestamp")): + parsed = _timestamp(candidate) + if parsed: + times.append(parsed) + model = payload.get("model") + effort = payload.get("reasoning_effort") or payload.get("effort") + if isinstance(model, str): + models.add(model) + if isinstance(effort, str): + efforts.add(effort) + usage = payload.get("total_token_usage") + if not isinstance(usage, dict): + info = payload.get("info") + usage = ( + info.get("total_token_usage") if isinstance(info, dict) else None + ) + if isinstance(usage, dict): + values = {key: usage.get(key) for key in COUNTERS} + if not all( + isinstance(value, int) + and not isinstance(value, bool) + and value >= 0 + for value in values.values() + ): + limitations.append( + f"line {number}: incomplete or invalid cumulative counters ignored" + ) + latest_snapshot_invalid = True + elif ( + values["cached_input_tokens"] > values["input_tokens"] + or values["reasoning_output_tokens"] > values["output_tokens"] + ): + limitations.append( + f"line {number}: subset counter exceeds inclusive total; snapshot ignored" + ) + latest_snapshot_invalid = True + else: + snapshots.append(values) + latest_snapshot_invalid = False + if event_type == "response_item" and payload.get("type") in { + "function_call", + "custom_tool_call", + }: + name = str(payload.get("name", "")) + operation = COORDINATION.get(name) + if operation: + coordination[operation] = coordination.get(operation, 0) + 1 + except (OSError, UnicodeError) as exc: + limitations.append(f"read error: {exc}") + latest_snapshot_invalid = True + finally: + handle.close() + usage = snapshots[-1] if snapshots and not latest_snapshot_invalid else None + if usage: + usage = usage | { + "uncached_input_tokens": usage["input_tokens"] + - usage["cached_input_tokens"], + "total_tokens": usage["input_tokens"] + usage["output_tokens"], + } + if usage is None: + limitations.append("no cumulative usage snapshot; token totals are unknown") + duration = (max(times) - min(times)).total_seconds() if len(times) > 1 else None + return { + "path": str(path), + "session_id": session_id, + "complete": usage is not None, + "usage": usage, + "models": sorted(models), + "reasoning_efforts": sorted(efforts), + "duration_seconds": duration, + "coordination": coordination, + "limitations": limitations, + } + + +def aggregate(paths: list[Path], child_paths: set[Path]) -> dict[str, Any]: + sessions: list[dict[str, Any]] = [] + seen_files: set[Path] = set() + seen_ids: set[str] = set() + limitations: list[str] = [] + for path in paths: + resolved = path.resolve() + if resolved in seen_files: + limitations.append(f"duplicate file ignored: {path}") + continue + seen_files.add(resolved) + result = parse_rollout(path) + identity = result.get("session_id") + if identity and identity in seen_ids: + prior = next( + item for item in sessions if item.get("session_id") == identity + ) + if prior.get("usage") != result.get("usage"): + prior["complete"] = False + prior["usage"] = None + prior["limitations"].append( + "conflicting duplicate session counters; total is unknown" + ) + limitations.append(f"conflicting duplicate session id: {identity}") + else: + limitations.append(f"duplicate session id ignored: {identity}") + continue + if identity: + seen_ids.add(identity) + result["role"] = "child" if resolved in child_paths else "parent" + sessions.append(result) + + complete = all(item.get("complete") for item in sessions) and bool(sessions) + totals = {key: 0 for key in COUNTERS} if complete else None + if totals is not None: + for item in sessions: + for key in (*COUNTERS, "uncached_input_tokens", "total_tokens"): + totals.setdefault(key, 0) + totals[key] += item["usage"][key] + if child_paths: + limitations.append( + "child rollouts may inherit parent events after full-history forks; " + "aggregation cannot prove exclusivity and may over-count" + ) + return { + "complete": complete, + "totals": totals, + "sessions": sessions, + "limitations": limitations, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "rollouts", nargs="+", type=Path, help="explicit JSONL rollout files" + ) + parser.add_argument( + "--child", action="append", default=[], type=Path, help="explicit child rollout" + ) + parser.add_argument("--json", action="store_true") + args = parser.parse_args() + paths = args.rollouts + args.child + report = aggregate(paths, {path.resolve() for path in args.child}) + if args.json: + print(json.dumps(report, indent=2, sort_keys=True)) + else: + print("Codex usage report (metadata extracted; conversations are never output)") + for item in report["sessions"]: + usage = item.get("usage") or "unknown" + print( + f"- {item['role']} {item['path']}: usage={usage}; models={item['models']}; efforts={item['reasoning_efforts']}; duration_s={item['duration_seconds']}; coordination={item['coordination']}" + ) + for limitation in item["limitations"]: + print(f" limitation: {limitation}") + print( + f"totals: {report['totals'] if report['complete'] else 'unknown/incomplete'}" + ) + for limitation in report["limitations"]: + print(f"limitation: {limitation}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/bin/install.sh b/bin/install.sh index 74ca5d65..34b7efcd 100755 --- a/bin/install.sh +++ b/bin/install.sh @@ -36,6 +36,8 @@ # # .claude/ + .codex/ discovery per repo # bash PyAutoBrain/bin/install.sh --check-project-discovery # drift-check that discovery (exit 1) # # trailing repo names narrow the check +# bash PyAutoBrain/bin/install.sh --write-workspace-policy # refresh root AGENTS.md delegation block +# bash PyAutoBrain/bin/install.sh --check-workspace-policy # drift-check that block # # The command-surface modes are the agent-agnostic half of command discovery: # per-tool symlinks (above) are absent in cloud/web sessions, which load only @@ -69,6 +71,12 @@ CODEX_HOME="${CODEX_HOME:-$HOME/.codex}" COMMANDS_BEGIN="" COMMANDS_END="" ORGAN_REPOS=(PyAutoBrain PyAutoMind PyAutoMemory PyAutoHeart PyAutoHands) +WORKSPACE_POLICY="$SCRIPT_DIR/../policy/workspace_model_delegation.md" +WORKSPACE_POLICY_BEGIN="" +WORKSPACE_POLICY_END="" +WORKSPACE_POINTER="$SCRIPT_DIR/../policy/workspace_model_delegation_pointer.md" +WORKSPACE_POINTER_BEGIN="" +WORKSPACE_POINTER_END="" # Emit the canonical command-surface block (identical in every organ) to stdout, # sourced from the agent registry in bin/pyauto-brain — the single source of @@ -174,6 +182,95 @@ check_agents_surface() { return "$drift" } +workspace_policy() { + local mode="$1" agents="$PYAUTO_ROOT/AGENTS.md" target tmp tmp2 begin_count end_count legacy=0 pointer_legacy=0 + [ -f "$agents" ] || { echo "skipped (absent): $agents"; return 0; } + target="$(readlink -f "$agents")" + begin_count="$(grep -cFx "$WORKSPACE_POLICY_BEGIN" "$agents" || true)" + end_count="$(grep -cFx "$WORKSPACE_POLICY_END" "$agents" || true)" + if [ "$begin_count" = 0 ] && [ "$end_count" = 0 ]; then + [ "$(grep -cF -- '- **Delegate execution to a subagent' "$target" || true)" = 1 ] && + [ "$(grep -cF -- '- **Never rewrite pushed history.' "$target" || true)" = 1 ] || { + echo "cannot locate unique legacy delegation block: $agents"; return 1; + } + legacy=1 + elif [ "$begin_count" != 1 ] || [ "$end_count" != 1 ]; then + echo "malformed workspace-policy markers: $agents"; return 1 + fi + [ "$(grep -cFx "$WORKSPACE_POLICY_BEGIN" "$WORKSPACE_POLICY" || true)" = 1 ] && + [ "$(grep -cFx "$WORKSPACE_POLICY_END" "$WORKSPACE_POLICY" || true)" = 1 ] || { + echo "malformed policy source: $WORKSPACE_POLICY"; return 1; + } + awk -v begin="$WORKSPACE_POLICY_BEGIN" -v end="$WORKSPACE_POLICY_END" ' + $0 == begin { if (seen_end) exit 2; seen_begin=1 } + $0 == end { if (!seen_begin) exit 2; seen_end=1 } + END { if (!seen_begin || !seen_end) exit 2 } + ' "$WORKSPACE_POLICY" || { echo "unordered policy source: $WORKSPACE_POLICY"; return 1; } + [ "$(grep -cFx "$WORKSPACE_POINTER_BEGIN" "$WORKSPACE_POINTER" || true)" = 1 ] && + [ "$(grep -cFx "$WORKSPACE_POINTER_END" "$WORKSPACE_POINTER" || true)" = 1 ] || { + echo "malformed pointer source: $WORKSPACE_POINTER"; return 1; + } + awk -v begin="$WORKSPACE_POINTER_BEGIN" -v end="$WORKSPACE_POINTER_END" ' + $0 == begin { if (seen_end) exit 2; seen_begin=1 } + $0 == end { if (!seen_begin) exit 2; seen_end=1 } + END { if (!seen_begin || !seen_end) exit 2 } + ' "$WORKSPACE_POINTER" || { echo "unordered pointer source: $WORKSPACE_POINTER"; return 1; } + if [ "$(grep -cFx "$WORKSPACE_POINTER_BEGIN" "$target" || true)" = 0 ] && + [ "$(grep -cFx "$WORKSPACE_POINTER_END" "$target" || true)" = 0 ]; then + [ "$(grep -cF -- '- **Model delegation** (provider-aware defaults:' "$target" || true)" = 1 ] || { + echo "cannot locate unique legacy delegation pointer: $agents"; return 1; + } + awk ' + /- \*\*Model delegation\*\* \(provider-aware defaults:/ { if (seen_end) exit 2; seen_begin=1 } + /PyAutoBrain\/skills\/WORKFLOW\.md/ { if (seen_begin) seen_end=1 } + END { if (!seen_begin || !seen_end) exit 2 } + ' "$target" || { echo "unordered legacy delegation pointer: $agents"; return 1; } + pointer_legacy=1 + elif [ "$(grep -cFx "$WORKSPACE_POINTER_BEGIN" "$target" || true)" != 1 ] || + [ "$(grep -cFx "$WORKSPACE_POINTER_END" "$target" || true)" != 1 ]; then + echo "malformed workspace-pointer markers: $agents"; return 1 + else + awk -v begin="$WORKSPACE_POINTER_BEGIN" -v end="$WORKSPACE_POINTER_END" ' + $0 == begin { if (seen_end) exit 2; seen_begin=1 } + $0 == end { if (!seen_begin) exit 2; seen_end=1 } + END { if (!seen_begin || !seen_end) exit 2 } + ' "$target" || { echo "unordered workspace-pointer markers: $agents"; return 1; } + fi + if [ "$legacy" = 1 ]; then awk ' + /- \*\*Delegate execution to a subagent/ { if (seen_end) exit 2; seen_begin=1 } + /- \*\*Never rewrite pushed history\./ { if (!seen_begin) exit 2; seen_end=1 } + END { if (!seen_begin || !seen_end) exit 2 } + ' "$target" || { echo "unordered legacy delegation block: $agents"; return 1; }; fi + if [ "$legacy" = 0 ]; then awk -v begin="$WORKSPACE_POLICY_BEGIN" -v end="$WORKSPACE_POLICY_END" ' + $0 == begin { if (seen_end) exit 2; seen_begin=1 } + $0 == end { if (!seen_begin) exit 2; seen_end=1 } + END { if (!seen_begin || !seen_end) exit 2 } + ' "$target" || { echo "unordered workspace-policy markers: $agents"; return 1; }; fi + tmp="$(mktemp "$(dirname "$target")/.agents-policy.XXXXXX")" + awk -v begin="$WORKSPACE_POLICY_BEGIN" -v end="$WORKSPACE_POLICY_END" -v policy="$WORKSPACE_POLICY" -v legacy="$legacy" ' + legacy && /^- \*\*Delegate execution to a subagent/ { while ((getline line < policy) > 0) print line; close(policy); skip=1; next } + legacy && skip && /^- \*\*Never rewrite pushed history\./ { skip=0; print; next } + $0 == begin { while ((getline line < policy) > 0) print line; close(policy); skip=1; next } + $0 == end { skip=0; next } + !skip { print } + ' "$target" > "$tmp" + tmp2="$(mktemp "$(dirname "$target")/.agents-pointer.XXXXXX")" + awk -v begin="$WORKSPACE_POINTER_BEGIN" -v end="$WORKSPACE_POINTER_END" -v policy="$WORKSPACE_POINTER" -v legacy="$pointer_legacy" ' + legacy && /^- \*\*Model delegation\*\* \(provider-aware defaults:/ { while ((getline line < policy) > 0) print line; close(policy); skip=1; next } + legacy && skip && /PyAutoBrain\/skills\/WORKFLOW\.md/ { skip=0; next } + $0 == begin { while ((getline line < policy) > 0) print line; close(policy); skip=1; next } + $0 == end { skip=0; next } + !skip { print } + ' "$tmp" > "$tmp2" + rm -f "$tmp"; tmp="$tmp2" + chmod --reference="$target" "$tmp" + if cmp -s "$target" "$tmp"; then + echo "OK: $agents"; rm -f "$tmp"; return 0 + fi + if [ "$mode" = write ]; then mv "$tmp" "$target"; echo "updated: $agents"; return 0; fi + rm -f "$tmp"; echo "DRIFT: $agents — run: bash PyAutoBrain/bin/install.sh --write-workspace-policy"; return 1 +} + # ---------- Committed per-tool discovery (web/cloud) ---------- # # The user-level ~/.claude / ~/.codex symlinks (below) are NOT loaded in cloud/ @@ -271,6 +368,8 @@ case "${1:-}" in --check-agents-surface) check_agents_surface; exit $? ;; --write-project-discovery) write_project_discovery; exit 0 ;; --check-project-discovery) shift; check_project_discovery "$@"; exit $? ;; + --write-workspace-policy) workspace_policy write; exit $? ;; + --check-workspace-policy) workspace_policy check; exit $? ;; --help|-h) sed -n '2,24p' "$0"; exit 0 ;; esac diff --git a/docs/codex_usage.md b/docs/codex_usage.md new file mode 100644 index 00000000..bdc7fe53 --- /dev/null +++ b/docs/codex_usage.md @@ -0,0 +1,55 @@ +# Measuring Codex workflow usage + +`bin/codex_usage.py` is a read-only, standard-library report over rollout JSONL +files the user names explicitly. It parses each selected line but extracts and +outputs metadata only; prompts, responses, tool arguments, and secrets are never +reported. + +```bash +python bin/codex_usage.py parent.jsonl --child child-a.jsonl --child child-b.jsonl +python bin/codex_usage.py --json parent.jsonl +``` + +The report uses the last cumulative usage snapshot per session, never sums +snapshots, and de-duplicates repeated files and session IDs. Cached input is +included in input; reasoning is included in output, so those subset counters +are reported separately rather than added again. All observed model and effort +values are listed. Missing counters make the total `unknown/incomplete`, not +zero. Coordination-call counts describe tool calls, not their cause or value. + +Explicit children are summed only when every selected session has counters. +Full-history forks may repeat inherited parent events; the current schema does +not always expose a reliable baseline, so child aggregation carries an +over-count warning rather than claiming an exact task total. The report never +converts tokens to billing or subscription cost. + +## Activate the workspace policy + +After this Brain change merges, update the workspace-root `AGENTS.md` through +the tracked installer: + +```bash +bash PyAutoBrain/bin/install.sh --write-workspace-policy +bash PyAutoBrain/bin/install.sh --check-workspace-policy +``` + +The writer migrates the known legacy delegation text, preserves the root file +and any symlink to it, and fails closed on malformed markers. Do not run it +before `MODEL_DELEGATION.md` exists on the installed branch because the +generated root policy links to that reference. + +## Comparison protocol + +After 3–5 comparable completed tasks, record for each task: + +- selected parent and child rollout paths and whether aggregation is reliable; +- observed models and reasoning-effort values; +- input, cached-input, output, and reasoning-output counters; +- duration and coordination-call count; +- outcome quality and independent-review verdict; +- number of correction loops or user interventions. + +Compare medians only across similar task types and report unknown sessions. +Treat the current Astra Medium configuration as the baseline; do not change +local model configuration merely to manufacture a comparison. Do not claim +savings until both usage and outcome/correction evidence support it. diff --git a/docs/index.md b/docs/index.md index 143bfaa8..354b1b57 100644 --- a/docs/index.md +++ b/docs/index.md @@ -76,4 +76,5 @@ example :hidden: agent_failure_modes +codex_usage ``` diff --git a/policy/workspace_model_delegation.md b/policy/workspace_model_delegation.md new file mode 100644 index 00000000..4674aaf9 --- /dev/null +++ b/policy/workspace_model_delegation.md @@ -0,0 +1,10 @@ + +- **Choose delegation by provider.** Anthropic preserves its execution-tier + policy: Fable → Opus, Opus → Opus, with Sonnet only for the documented + mechanical floor. OpenAI executes routine sequential work directly and uses + Sol workers selectively for independent parallel work, substantial noisy work + needing separate context, or independent review. Duration alone is not a + reason to spawn. Brain roles are not automatic LLM spawns. State the + session model before the first delegation decision. Full policy: + `PyAutoBrain/skills/MODEL_DELEGATION.md`. + diff --git a/policy/workspace_model_delegation_pointer.md b/policy/workspace_model_delegation_pointer.md new file mode 100644 index 00000000..14edfe59 --- /dev/null +++ b/policy/workspace_model_delegation_pointer.md @@ -0,0 +1,5 @@ + +- **Model delegation** (Anthropic execution tier; OpenAI direct-by-default; + bounded workers; tutorial and Cortex behavior) + → `PyAutoBrain/skills/MODEL_DELEGATION.md`. + diff --git a/skills/MODEL_DELEGATION.md b/skills/MODEL_DELEGATION.md new file mode 100644 index 00000000..d2adfd03 --- /dev/null +++ b/skills/MODEL_DELEGATION.md @@ -0,0 +1,78 @@ +# Model delegation policy + +Brain roles and faculties are architectural roles; invoking one does not itself +require an LLM subagent. + +## Anthropic: preserve the execution-tier split + +| Session model | Judgment tier | Execution tier | +|---|---|---| +| Fable | Fable plans, decomposes, judges, and talks to the user | Opus performs all remaining implementation, edits, tests, diagnostics, and prose | +| Opus | Opus | Opus, except the mechanical floor below may use Sonnet | +| Sonnet | Sonnet | Run inline; there is no lower tier | + +Fable and Opus delegate execution even when the target worker is also Opus. +Answering from already-loaded context, reading a handful of files, editing a +few lines in files already read, and conversations with the user (plans, +decisions, reviews, and judgment calls) remain in-session. +Sonnet is used from Opus only for fixed shell/git recipes whose errors surface +immediately: test/commit/push/open-PR in `ship_library`; commit/push/smoke/ +open-PR/cross-reference in `ship_workspace`; and format/generate/version-bump/ +commit/push/dispatch in `pre_build`. If it is unclear whether work is +mechanical enough, it goes to Opus. +Narrative science tutorials always go to Opus; code-heavy notes may use Sonnet +only for a mechanical adaptation of an existing sibling. + +For Anthropic, planning, worktree/environment setup, release triage, commit and +PR wording, downstream-impact and merge decisions, registry/completion updates, +final issue comments, and all user-facing judgment remain in the main session. + +## OpenAI: direct by default + +Astra and Sol normally execute routine sequential work in the current session, +including edits, targeted tests, and git steps. Use a Sol worker selectively +when independent work can run usefully in parallel, a separate context is +justified by substantial noisy execution or independent progress, or a +genuinely independent review is required. Wall-clock duration alone is not a +reason to spawn, and delegation is not presumed to save tokens. + +Keep planning, user decisions, approval gates, registry updates, and final +judgment in the main session. Do not spawn a worker merely because a Brain +conductor consults a faculty or a workflow reaches a shell/git phase. The +review faculty remains independent for both provider families. + +No default is defined for other model families. If a requested worker is not +available, execute in-session without changing safety or approval gates. + +## Bounded worker contract + +- Pass only the worktree, affected files, accepted plan, required commands, + and the smallest relevant evidence. +- Give one coherent phase to a worker and reuse it for related fixes. +- Request concise results: changed files, pass/fail counts, and only the + decision-relevant tail of a failure. +- Keep full logs in a file or harness transcript, not chat. +- Do not rerun an unchanged successful check unless inputs or its gate changed. +- Prefer native completion events. Do not repeatedly poll unchanged pending + state or agent lists; use bounded waits only when needed, and never arm a + timer or monitor that outlives the turn. + +Long Anthropic delegations retain the existing milestone heartbeat: one short +line per phase/test/commit milestone in a progress file, roughly every 10–20 +minutes of healthy work, monitored by the main session and stopped on return. +Long OpenAI delegations may use the same bounded heartbeat; inline work does not. + +## Bundles, Cortex, and teaching prose + +Bundles parallelize only independent members. Anthropic members use their +execution tier; OpenAI members use workers only for the selective reasons above. +Within one repo, members remain sequential. + +Cortex work still enters through the declared assistant and returns scientific +results plus assistant drift. The provider policy decides whether that work +uses a subagent; the assistant boundary does not force a spawn. + +Narrative science scripts use Opus in the Anthropic family. OpenAI authors them +inline by default, or with Sol when a selective delegation reason applies. The +content heuristic is unchanged: science instruction gets teaching prose; code +exercise scripts get concise usage notes. diff --git a/skills/WORKFLOW.md b/skills/WORKFLOW.md index 0665383e..0d8b9927 100644 --- a/skills/WORKFLOW.md +++ b/skills/WORKFLOW.md @@ -1,361 +1,104 @@ # PyAuto workflow skills — shared reference -The `start_*` / `ship_*` skills are the -**development-workflow entry points** of the PyAuto organism. They are *not* -independent reasoning systems: each one is a thin entry point that delegates to -the organs. This file is the shared context every workflow skill points at, so -the individual skill files can stay short. +The `start_*` and `ship_*` skills are entry points, not independent reasoning +systems. Mind owns task state, Brain plans and coordinates, Memory supplies +read-only context, Heart gates shipping, and Hands handles releases only. -## Organ boundary (who owns what) - -The organs and boundaries are defined once in -[`../ORGANISM.md`](../ORGANISM.md). What the workflow skills need to know on -top of that: Mind owns the workflow **state** (`active.md` / `planned.md` / -the `complete/` records, the prompt taxonomy), and Build owns **no dev-workflow skills** -— it is the release/packaging executor only. - -A workflow skill reasons through **Brain**, gates ship through **Heart**, records -state in **Mind**, and pulls context from **Memory**. The **dev-workflow's own -git mechanics** (worktrees, branches, commits, feature PRs) are part of feature -development — they are **not** Build's job. **Build is release work only** -(PyPI/tags/notebooks); `ship_*` *calls* Build only at actual release time. A -skill never re-implements another organ's job. - -## The call chains +## Call chains +```text +start_dev → Brain feature decision → Mind task + plan → start_library/workspace +ship_* → Brain review/vitals → Heart gate → commit/push/feature PR +release → Brain release decision → Heart gate → Hands ``` -start_dev → Brain Feature Agent → Mind task + Memory context → plan → start_library/start_workspace -ship_library → Brain dev-workflow → Brain vitals faculty → Heart (GREEN/YELLOW/RED) → commit / push / feature-PR -ship_workspace → Brain dev-workflow → Brain vitals faculty → Heart → commit / push / feature-PR -release (later)→ Brain Build/Release Agent → Brain vitals faculty → Heart → PyAutoHands (tag / notebooks / PyPI) -``` - -`ship_*` is **feature-development** work: the commit/push/feature-PR is the dev -workflow's own execution, gated by Heart. It is **not** a Build task. Build is -release/packaging only; `ship_*` reaches Build solely to trigger the release step -once changes are ready to publish. - -Brain agents consult one another — e.g. the Build Agent never queries Heart -directly; it asks the vitals faculty, and only the vitals faculty talks to the Heart -organ. The same applies when the dev workflow consults the vitals faculty for its -ship gate. - -## Autonomy (how much human checkpointing) - -The human checkpoints across these skills — plan approval, ship PR sign-off, -Heart YELLOW acknowledgement, merge/close, the `pre_build` version ask, -post-merge cleanup — are governed by **the autonomy contract**, -[`../AUTONOMY.md`](../AUTONOMY.md): what each Mind-prompt `Autonomy:` level -(`safe`/`supervised`/`human-required`) does at each checkpoint, the -per-work-type caps, and the hard invariants (merge is always human; autonomous -runs end at PR-open). Levels bind **only** under an explicit `--auto` launch; -default runs present-and-wait at every checkpoint, exactly as the steps below -describe. Do not restate checkpoint rules in a skill body — link the contract. -The gate's automatic-review leg is the **review faculty** -(`bin/pyauto-brain review --task `; `agents/faculties/review/AGENTS.md`). - -## Brain agent entry points - -Reasoning is delegated to PyAutoBrain agents (`PyAutoBrain/AGENTS.md` is authoritative): - -```bash -bin/pyauto-brain feature [//.md] # classify + plan a task (Feature/Bug/Refactor/… routing) -bin/pyauto-brain build [--dry-run] # consult vitals, then delegate execution to Build -bin/pyauto-brain release # release door → Build Agent release mode (gate + pre_build) -bin/pyauto-brain vitals # one health tick + the unified dashboard card -``` - -If a dedicated agent for a work type does not exist yet (e.g. Docs/Research), -the Feature Agent's routing applies the closest available reasoning and the -missing agent is recorded as a follow-up — the skill still runs end-to-end. - -When `pyauto-brain` is not on `PATH` and no PyAutoBrain checkout is present -(e.g. a GitHub-only session), perform the same reasoning inline following this -file and `PyAutoBrain/AGENTS.md`, and note that the agent was emulated. - -## Model delegation (judgment tier plans, execution tier ships) - -The workflow skills split work across **capability tiers**, then resolve those -tiers within the provider family and subagent mechanism exposed by the current -harness. Do not carry model names or invocation syntax from one provider or -harness into another: - -- **Judgment tier** — the session model itself. Planning, orchestration, risk - judgment, and anything user-facing. Never delegated, never handed *up*. -- **Execution tier** — the model assigned below for the session's provider - family, delegated through the harness's subagent mechanism when available. - -The tiers are resolved from the model the session is actually running on. Do -not assume the provider, session model, or subagent-call syntax: - -| Provider family | Session model | Judgment tier (in-session) | Execution tier (subagents) | -|-----------------|---------------|----------------------------|----------------------------| -| Anthropic | **Fable** | Fable — the architect: all planning and decomposition | **Opus** — *all* remaining work | -| Anthropic | **Opus** | Opus | **Opus** — Sonnet only for the simple-and-mechanical floor below | -| Anthropic | **Sonnet** | Sonnet | Sonnet (nothing below; run inline) | -| OpenAI | **Astra** | Astra — the architect: all planning and decomposition | **Sol** — *all* remaining work | -| OpenAI | **Sol** | Sol | **Sol** | - -No default mapping is defined here for other models, including Terra or Luna. -When the harness cannot target the named execution model or has no subagent -mechanism, follow the cross-harness fallback below and execute directly. - -A **Fable or Astra session is the architect**. It plans, decomposes, judges and -talks to the user, then hands *every* execution phase to its family's execution -tier: Fable → Opus; Astra → Sol. This includes implementation, edits, tests and -tutorial prose, not only the mechanical shell/git steps listed below. - -An **Opus or Sol session delegates to the same model** for execution: Opus → -Opus; Sol → Sol. Use the current harness's native subagent call and exact model -identifier. In particular, do not use Anthropic-specific -`Agent(model="opus", …)` syntax or an Opus target from an OpenAI session. - -Within the Anthropic family, **Sonnet is the exception, not the default:** it -gets a phase only when that phase is *really simple and mechanical* — a fixed -recipe of shell/git steps with no design decisions in it, where a wrong answer -surfaces immediately as a failed command. If you are weighing whether a phase -is mechanical enough for Sonnet, it isn't: send it to Opus. The OpenAI policy -has no corresponding lower mechanical tier; those phases stay on Sol. - -The main session stays on the judgment tier; bulk execution moves to the -execution tier — no manual model toggling, and no waiting to be told which -model to use. - -**Scope: every task, not only the workflow skills.** The ladder is a property -of the *session*, not of `start_dev`. Direct work on the organs (Brain, Mind, -Heart, Hands, Memory, Gut, Nerves), hygiene and cleanup sweeps, skill/doc -edits, one-off fixes, profiling runs and diagnostics that execute code all -delegate the same way. A Fable, Opus, Astra or Sol session should say which -model it is running on in its opening line and treat "should this be a -subagent?" as the first question for any task. **Stays in-session (no -delegation):** answering from context already loaded; reading a handful of -files; edits of a few lines in files already read; and anything that is itself -a conversation with the user — plans, decisions, reviews, judgment calls. -Everything else is a delegation candidate; when in doubt, delegate one -coherent phase and keep the judgment. - -**The simple-and-mechanical floor — always delegated when the harness supports -subagents, and the only phases an Anthropic Opus session may hand to Sonnet:** - -- `ship_library` — step 3 (test, commit, push, open PR). -- `ship_workspace` — step 3 (commit, push, smoke test, open PR, cross-reference). -- `pre_build` — step 2 (format, generate, version bump, stage, commit, push, - dispatch workflow). - -That list is a floor, not a ceiling. Everything above it that is still -*execution* — `start_library` / `start_workspace` source edits, script -authoring, test writing, fix loops, doc and skill edits, hygiene sweeps, -diagnostics — goes to the **Opus** execution tier from a Fable *or* an Opus -session, or to the **Sol** execution tier from an Astra *or* a Sol session, one -subagent per coherent phase, using the same prompt contract below. - -**Several tasks in one session — `start_bundle`.** The ladder above scales a -single task across tiers; a **bundle** scales one session across several -*independent* tasks. The PyAutoMind dashboard's Bundles section proposes them -(and `PyAutoMind/bundles.md` pins them); [`start_bundle/start_bundle.md`](start_bundle/start_bundle.md) -is the contract: the architect session reads every member, runs `/start_dev` -per member (one issue each — the no-bulk-issue rule is unchanged), creates -**one shared worktree per repo** for the whole bundle, delegates each member's -implementation to its own execution-tier subagent under the prompt contract -below, and ships **one PR per member** so `/prm` closes each out unchanged. -Within one repo the members are sequenced (a worktree holds one branch at a -time); across repos they may run in parallel. A bundle is never an epic — if -the members need an order, it belongs in `epics.md` instead. - -**Stays in the judgment tier:** planning (`start_dev`), environment setup -(`start_library`/`start_workspace`), release triage (`review_release`); -identifying affected repos, drafting the commit message and full PR body -(`## API Changes` / `## Scripts Changed`), workspace-impact analysis, the -library-first merge gate, the merge decision, `active.md` / completion-record -updates, and final issue comments. In `pre_build`: validating clean `main`, -asking for the minor version, printing the summary. - -**Subagent prompt contract (all delegated calls):** - -- **Inputs the judgment tier passes:** worktree path / `$WT_ROOT`, repo list, - pre-drafted commit message, pre-drafted PR body (paste verbatim via HEREDOC — - never rewrite), relevant URLs (library PR, issue), target branch, labels. -- **Subagent's job:** run the named shell steps exactly. `source activate.sh` - before `pytest` / `smoke_test`. Verify the branch is `feature/` - before committing — never auto-switch branches. **Never modify code to make - tests or smoke tests pass.** On failure, stop and return the failure verbatim - (failing test names + traceback tail, or the shell error). -- **Subagent returns:** one line per repo — test/smoke pass-fail counts, commit - SHA, PR URL, cross-reference/dispatch confirmations. -- **Judgment tier after return:** interpret failures, decide routing, update - registries, talk to the user. - -**Cortex project work.** Science projects delegate the same way. The Cortex -holds one ledger per project (`PyAutoCortex/projects/.md` — Now, Runs, -Log), and `/cortex`'s board carries a **resume** chip per active project: read -the ledger, then the project's own `ledger` file from its `projects.yaml` row, -then — when the row declares an `assistant:` — that assistant's `AGENTS.md`. -Paste that prompt verbatim into the execution-tier subagent; it enters the -project through the assistant it names. The subagent **finishes** by telling -the judgment tier what it saw and **returns two parts**: what it found in the -results (the human decides what to log — a `result` or `lesson` entry is -written only in the human's words, with `scripts/cortex.py log`), and -assistant drift — any skill or wiki page that was wrong, missing or stale. The -judgment tier files each drift item through `/intake` against the assistant -repo; nobody edits the assistant from the Cortex chat. A row that says -`assistant: none` routes through no assistant and the work is plain workspace -work. The heartbeat below applies whenever the run is a long one. - -**Progress heartbeat (delegations expected to run > ~15 min).** Subagents have -no clock, so a wall-clock cadence cannot be promised; milestones can. The -judgment tier passes a progress-file path (under the session scratchpad, e.g. -`$SCRATCHPAD/progress-