diff --git a/plugins/gitea/.claude-plugin/plugin.json b/plugins/gitea/.claude-plugin/plugin.json index e101812..e924395 100644 --- a/plugins/gitea/.claude-plugin/plugin.json +++ b/plugins/gitea/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "gitea", - "version": "0.1.0", - "description": "Gitea issue integration: fetch/create/list/close tickets, post comments, scaffold labels. Workpad-aware.", + "version": "0.1.1", + "description": "Gitea issue integration: fetch/create/list/close tickets, post comments, scaffold labels. Quire-aware (formerly workpad).", "author": { "name": "Gabor Körber", "email": "gab@g4b.org" diff --git a/plugins/gitea/.codex-plugin/plugin.json b/plugins/gitea/.codex-plugin/plugin.json index af10b0e..7ded4f1 100644 --- a/plugins/gitea/.codex-plugin/plugin.json +++ b/plugins/gitea/.codex-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "gitea", - "version": "0.1.0", - "description": "Gitea issue integration: fetch/create/list/close tickets, post comments, scaffold labels. Workpad-aware.", + "version": "0.1.1", + "description": "Gitea issue integration: fetch/create/list/close tickets, post comments, scaffold labels. Quire-aware (formerly workpad).", "author": { "name": "Gabor Korber", "email": "gab@g4b.org" @@ -10,7 +10,7 @@ "interface": { "displayName": "Gitea", "shortDescription": "Work with Gitea tickets from Codex.", - "longDescription": "Fetch, create, list, close, and comment on Gitea issues using self-contained uv scripts, with workpad-aware workflows.", + "longDescription": "Fetch, create, list, close, and comment on Gitea issues using self-contained uv scripts, with quire-aware workflows.", "developerName": "Gabor Korber", "category": "Productivity", "capabilities": ["Skills", "Scripts"], diff --git a/plugins/gitea/README.md b/plugins/gitea/README.md index 42b53a4..de98a3b 100644 --- a/plugins/gitea/README.md +++ b/plugins/gitea/README.md @@ -53,7 +53,7 @@ Creates a default emoji-prefixed label set. Override per-project by placing `.gi ## Architecture notes -- All scripts use **CWD-relative paths** for git, `.env`, and workpad lookups. The plugin directory is only consulted for shipped resources (like `labels.default.json`). +- All scripts use **CWD-relative paths** for git, `.env`, and quire lookups. The plugin directory is only consulted for shipped resources (like `labels.default.json`). - Imports are **flat sibling imports** (`from client import …`) — scripts are run as files, not as a package. - Each CLI entrypoint carries a PEP 723 `# /// script` header listing its own dependencies, so no shared environment, lockfile, or `pyproject.toml` is needed. diff --git a/plugins/gitea/skills/gitea/SKILL.md b/plugins/gitea/skills/gitea/SKILL.md index 87bf0eb..9ce5064 100644 --- a/plugins/gitea/skills/gitea/SKILL.md +++ b/plugins/gitea/skills/gitea/SKILL.md @@ -1,11 +1,11 @@ --- name: gitea -description: Use when working with Gitea tickets — fetching ticket context, creating issues from workpad goals, posting plans or reports as comments, listing/searching issues, closing issues, or scaffolding standard labels for a new repo. +description: Use when working with Gitea tickets — fetching ticket context, creating issues from quire goals, posting plans or reports as comments, listing/searching issues, closing issues, or scaffolding standard labels for a new repo. --- # Gitea Ticket Integration -Bidirectional integration between the workpad and a Gitea instance. All operations are CLI scripts shipped with this plugin; nothing needs to be installed in the user's project. +Bidirectional integration between the quire and a Gitea instance. All operations are CLI scripts shipped with this plugin; nothing needs to be installed in the user's project. ## Configuration @@ -36,24 +36,25 @@ Prints the resolved URL/repo and `Connection: OK` on success. Do not retry or work around auth failures. -## Workpad path +## Quire path -Most ticket-related scripts need a workpad path. Resolve it once at the start of the session: +Most ticket-related scripts need a quire path. Resolve it once at the start of the session: -1. **`WORKPAD_FOLDER`** env var (read via `printenv WORKPAD_FOLDER`, or a `just workpad-folder` recipe if defined). -2. If unset, **ask the user** where the workpad is. Don't guess. +1. **`QUIRE_FOLDER`** env var (try `just quire-folder` if defined, then `printenv QUIRE_FOLDER`). +2. If unset, **`WORKPAD_FOLDER`** (old name, fallback; same way: `just workpad-folder`, then `printenv WORKPAD_FOLDER`). +3. If neither is set, **ask the user** where the quire is. Don't guess. -Then pass `--workpad ` to every script that takes it. If the user keeps tickets *outside* the workpad, use `--tickets-dir ` instead (overrides the `/tickets/` default). +Then pass `--quire ` to every script that takes it (`--workpad` is accepted as the old alias). If the user keeps tickets *outside* the quire, use `--tickets-dir ` instead (overrides the `/tickets/` default). ## Available scripts All invocations use `uv run ${CLAUDE_PLUGIN_ROOT}/skills/gitea/scripts/.py`. Each script carries inline PEP 723 dependencies — uv builds an isolated env on first run and caches it. -### `fetch_ticket.py --workpad [--tickets-dir ] [--no-comments]` +### `fetch_ticket.py --quire [--tickets-dir ] [--no-comments]` -Pulls a ticket as structured markdown to `//context.md` (default tickets dir = `/tickets`). Includes labels, assignees, milestone, description, and all comments unless `--no-comments`. +Pulls a ticket as structured markdown to `//context.md` (default tickets dir = `/tickets`). Includes labels, assignees, milestone, description, and all comments unless `--no-comments`. -### `start_ticket.py --workpad [--tickets-dir ] [--slug SLUG] [--no-checkout]` +### `start_ticket.py --quire [--tickets-dir ] [--slug SLUG] [--no-checkout]` Recommended entry point when starting work on a ticket. Fetches the ticket, creates a branch `ticket/-` from current HEAD, writes `context.md` to the tickets dir. Slug is derived from the title if not given. Warns if the current branch isn't main/master. Fails if the branch already exists locally or on the remote. @@ -82,16 +83,16 @@ Creates the standard label set in the repo (or a project-defined set if `.gitea- ### Start work on an existing ticket ```bash -uv run ${CLAUDE_PLUGIN_ROOT}/skills/gitea/scripts/start_ticket.py 42 --workpad +uv run ${CLAUDE_PLUGIN_ROOT}/skills/gitea/scripts/start_ticket.py 42 --quire ``` -Then read `/tickets/42/context.md` to understand the ticket. +Then read `/tickets/42/context.md` to understand the ticket. -### Turn a workpad goal into a ticket +### Turn a quire goal into a ticket ```bash uv run ${CLAUDE_PLUGIN_ROOT}/skills/gitea/scripts/create_ticket.py \ - --from-goal /goals/my-feature.md \ + --from-goal /goals/my-feature.md \ --labels "✨ feature,📋 workpad" ``` @@ -99,7 +100,7 @@ uv run ${CLAUDE_PLUGIN_ROOT}/skills/gitea/scripts/create_ticket.py \ ```bash uv run ${CLAUDE_PLUGIN_ROOT}/skills/gitea/scripts/post_comment.py 42 \ - /plans/2026-05-19-10-my-plan.md \ + /plans/2026-05-19-10-my-plan.md \ --header "## Implementation Plan" ``` @@ -130,4 +131,4 @@ That's it — URL/owner/repo come from `git remote get-url origin`. - Don't attempt to work around auth failures. - Don't modify the plugin's scripts from within a user session — that's a separate plugin-development task. - Don't skip the connectivity check. -- Don't guess the workpad path — read `WORKPAD_FOLDER` or ask. +- Don't guess the quire path — read `QUIRE_FOLDER` (or `WORKPAD_FOLDER`) or ask. diff --git a/plugins/gitea/skills/gitea/scripts/fetch_ticket.py b/plugins/gitea/skills/gitea/scripts/fetch_ticket.py index 8763c45..5567da3 100644 --- a/plugins/gitea/skills/gitea/scripts/fetch_ticket.py +++ b/plugins/gitea/skills/gitea/scripts/fetch_ticket.py @@ -6,10 +6,10 @@ """Fetch a Gitea ticket and write structured markdown. Usage: - uv run fetch_ticket.py --workpad [--tickets-dir ] [--no-comments] + uv run fetch_ticket.py --quire [--tickets-dir ] [--no-comments] Output: //context.md - (default tickets-dir = /tickets) + (default tickets-dir = /tickets) """ from __future__ import annotations @@ -64,13 +64,13 @@ def render_issue_markdown(issue: GiteaIssue, comments: List[GiteaComment] | None return "\n".join(lines) -def resolve_tickets_dir(workpad: Path | None, tickets_dir: Path | None) -> Path: +def resolve_tickets_dir(quire: Path | None, tickets_dir: Path | None) -> Path: if tickets_dir is not None: return tickets_dir - if workpad is None: - print("Error: either --workpad or --tickets-dir must be provided.", file=sys.stderr) + if quire is None: + print("Error: either --quire or --tickets-dir must be provided.", file=sys.stderr) sys.exit(1) - return workpad / "tickets" + return quire / "tickets" def fetch_and_write(ticket_number: int, target_dir: Path, include_comments: bool = True) -> Path: @@ -91,12 +91,12 @@ def fetch_and_write(ticket_number: int, target_dir: Path, include_comments: bool def main() -> None: parser = argparse.ArgumentParser(description="Fetch a Gitea ticket as markdown.") parser.add_argument("ticket", type=int, help="Ticket number to fetch") - parser.add_argument("--workpad", type=Path, default=None, help="Workpad root (tickets go to /tickets//)") - parser.add_argument("--tickets-dir", type=Path, default=None, help="Direct tickets directory (overrides workpad)") + parser.add_argument("--quire", "--workpad", dest="quire", type=Path, default=None, help="Quire root (tickets go to /tickets//); --workpad is the old name") + parser.add_argument("--tickets-dir", type=Path, default=None, help="Direct tickets directory (overrides quire)") parser.add_argument("--no-comments", action="store_true", help="Skip fetching comments") args = parser.parse_args() - target = resolve_tickets_dir(args.workpad, args.tickets_dir) + target = resolve_tickets_dir(args.quire, args.tickets_dir) try: out = fetch_and_write(args.ticket, target, include_comments=not args.no_comments) print(f"Wrote ticket #{args.ticket} to {out}") diff --git a/plugins/gitea/skills/gitea/scripts/start_ticket.py b/plugins/gitea/skills/gitea/scripts/start_ticket.py index 1ff460c..a241158 100644 --- a/plugins/gitea/skills/gitea/scripts/start_ticket.py +++ b/plugins/gitea/skills/gitea/scripts/start_ticket.py @@ -6,7 +6,7 @@ """Start working on a Gitea ticket: create a branch and fetch ticket context. Usage: - uv run start_ticket.py --workpad [--tickets-dir ] [--slug SLUG] [--no-checkout] + uv run start_ticket.py --quire [--tickets-dir ] [--slug SLUG] [--no-checkout] """ from __future__ import annotations @@ -61,13 +61,13 @@ def current_branch() -> str: def main() -> None: parser = argparse.ArgumentParser(description="Start working on a Gitea ticket.") parser.add_argument("ticket", type=int, help="Ticket number") - parser.add_argument("--workpad", type=Path, default=None, help="Workpad root") - parser.add_argument("--tickets-dir", type=Path, default=None, help="Direct tickets directory (overrides workpad)") + parser.add_argument("--quire", "--workpad", dest="quire", type=Path, default=None, help="Quire root; --workpad is the old name") + parser.add_argument("--tickets-dir", type=Path, default=None, help="Direct tickets directory (overrides quire)") parser.add_argument("--slug", type=str, default=None, help="Custom branch slug") parser.add_argument("--no-checkout", action="store_true", help="Create branch without switching to it") args = parser.parse_args() - target = resolve_tickets_dir(args.workpad, args.tickets_dir) + target = resolve_tickets_dir(args.quire, args.tickets_dir) config = load_config() try: diff --git a/plugins/spire/UPGRADES.md b/plugins/spire/UPGRADES.md new file mode 100644 index 0000000..0d0349a --- /dev/null +++ b/plugins/spire/UPGRADES.md @@ -0,0 +1,62 @@ +# Spire upgrade notes + +Actions a user must take after upgrading Spire. A release gets an entry here only if it requires user action. Each item restates the release note with its check and fix; the duplication is intended. + +Igor reads this file automatically at startup and shows the entries newer than this checkout's marker. `.spire/upgrades.lock` records what this checkout has handled. To see the notes again, delete the marker or write a lower version into it. + +### Format contract (for authors) + +The startup script depends on this. Never put a `## ` heading in the preamble or inside an entry, code fences included. + +- The preamble sits before the first entry heading and is never printed. +- Entry heading: a line starting `## ` whose next word is `X.Y.Z`, for example `## 0.4.0` or `## 0.4.0 (2026-12-01)`. The body runs until the next line starting `## ` or EOF. Entries are newest first. +- A `## ` line whose second word is not a version also ends the current entry and starts no new one. +- Each item in an entry: + +``` +### +- Change: +- Affects: +- Check: +- Fix: +``` + +`Check:` is run by Igor's scout, never by the startup script. Keep it read-only (grep, ls, test). + +## 0.4.0 + +### workpad is now quire +- Change: the skill `spire:workpad` is gone; use `spire:quire`. The helper is `quire.py`, the folder default is `docs/quire` (`QUIRE_FOLDER`, `--quire` in gitea). `docs/workpad` still works as a fallback; if both exist, quire wins. +- Affects: agent files that preload `spire:workpad` (the preload is lost silently), and a `docs/workpad/` folder. +- Check: `grep -rn 'spire:workpad' .claude/agents/ 2>/dev/null` (hits = applies; no output = already done or not applicable). +- Fix: replace `spire:workpad` with `spire:quire` in agent `skills:` lists. Optionally `git mv docs/workpad docs/quire` and repoint the `.gitignore` logs line and project.md `**Quire**:`. + +### attacker is now advocate +- Change: the agent `spire:attacker` is now `spire:advocate`; the step verb "attack" is now "castigate". Saying "attack the plan" still triggers it. +- Affects: `spire:attacker` or `attacker` in dispatch lists, project.md, or permissions. +- Check: `grep -rn 'spire:attacker\|"attacker"' .claude/ CLAUDE.md AGENTS.md 2>/dev/null` (hits = applies; no output = already done or not applicable). +- Fix: replace `spire:attacker` with `spire:advocate` in those places. + +### Harness references moved +- Change: harness references moved from `skills/implementation/references/providers/` to the plugin root `providers/` (`runtimes/`, `hosts/`). `subagent-writes.md` folded into `providers/runtimes/claude-code/spawning.md`. +- Affects: project overrides or notes that cite the old path. +- Check: `grep -rn 'implementation/references/providers' .claude/ CLAUDE.md AGENTS.md docs/ 2>/dev/null` (hits = applies; no output = not applicable). +- Fix: repoint the citations to the new `providers/` paths. + +### Gremlins need --harness outside a harness +- Change: `G init` needs `--harness claude` (or `codex`) when run from a shell with no harness marker (plain terminal, CI); inside a harness the caller's harness is detected. Only `init` takes `--harness`; other gremlins commands read the harness stored in the run. +- Affects: scripts or CI that call `gremlins.py init` (or `G init`, `G` being `uv run --script …/gremlins.py`). +- Check: `grep -rnE "(gremlins\.py['\"]?|(^|[^a-z])G)[[:space:]]+init" --include='*.sh' --include='*.yml' --include='*.yaml' --include='Justfile' --include='Makefile' . 2>/dev/null | grep -v -- '--harness'` (hits = init calls without the flag, applies; a call continued over several lines may be a false hit, read it; no output = not applicable). +- Fix: add `--harness claude` (or `codex`) to those `init` calls. + +### Secret-shaped env names are scrubbed from gremlins +- Change: secret-shaped environment names are scrubbed from gremlin environments (this strips e.g. `CLAUDE_CODE_CLIENT_KEY`; unlisted `CLAUDE_CODE_*` stay). Only inherited env is scrubbed; secrets exported by shell startup files reach tool shells again. +- Affects: a gremlin run that needs a variable whose name looks like a secret (KEY, TOKEN, SECRET, PASSWORD). +- Check: `grep -rn 'pass-env' .claude/ CLAUDE.md AGENTS.md docs/ 2>/dev/null` (hits = pass-through already configured, likely done; no output and gremlins in use = review by hand). +- Fix: pass what a gremlin really needs with `--pass-env NAME` at `init`. + +### Finish or re-init in-flight 0.3.x gremlin runs +- Change: templates are not frozen per run, so a run started under 0.3.x would get the new spawn text without the old preamble's companion rules, plus the new scrub. New runs use the new preamble and templates; handoff notes live in `notes/.md` and the Athanor copies them into the run log. +- Affects: gremlin run state from before the upgrade that is still in progress. This is an action for after the upgrade. +- Check: `ls -d .spire/gremlins/* .spire/scratch/*/gremlins 2>/dev/null` (any listing = run state exists; compare its dates with the upgrade; no output = not applicable). +- Fix: finish those runs, or re-init them. Do not resume them. diff --git a/plugins/spire/agents/designer.md b/plugins/spire/agents/designer.md new file mode 100644 index 0000000..ddb437a --- /dev/null +++ b/plugins/spire/agents/designer.md @@ -0,0 +1,34 @@ +--- +name: designer +description: > + Writes one buildable design from a goal and its research, pinned to Opus + 5.5. Reads the code and docs the approach touches. Never plans, castigates, + builds or reviews from its own design. Dispatched by Igor at stage 3, or by + an Athanor on a design job. +model: claude-opus-5-5[1m] +tools: Bash, Glob, Grep, Read, Edit, Write +skills: + - spire:project +--- + +You write the design. Someone else plans from it, the advocate castigates the plan, the Athanor builds it. You never do those jobs. + +## Input + +The brief names the goal, the research or reports to read, the `Scope:` level and the output path. Read the code and docs the approach touches; design against the code as it is. + +## What the design holds + +- **Reuse first**: what libraries, the harness and the existing architecture already give. Design only what they do not, and say in a line where one falls short. +- **One approach**, buildable, with a line on why it beats the obvious alternative. At `Scope: high` you may sketch a second. +- **Capability per goal box** at the `Scope:` level (`spire:project`), with what comes with each box listed. +- **Parts and seams**: components, data shapes and interfaces where parts meet; no code bodies. +- **Phases** only where a dependency or risk splits the work, never to make a first slice smaller. A deferred capability item names its reason, and size is not one. +- **Out of scope**, said explicitly. +- **Open questions**: the likeliest answer, flagged `**Assumed:**`. A blocker only when a wrong pick wastes the build. + +## Rules + +- Stamp the model id you ran on and the `Scope:` level in the design's header. +- Write only the design file. Do not touch code. +- Your final message: the design's path, the approach in three lines, the `**Assumed:**` points and any blocker. diff --git a/plugins/spire/agents/planner.md b/plugins/spire/agents/planner.md index b976c47..6ed564b 100644 --- a/plugins/spire/agents/planner.md +++ b/plugins/spire/agents/planner.md @@ -2,7 +2,7 @@ name: planner description: > Writes an implementation plan from a goal and (optionally) a design, pinned - to Opus 5.5. Reads the code the plan touches. Does not build, attack or + to Opus 5.5. Reads the code the plan touches. Does not build, castigate or review the plan it wrote. Dispatched by Igor at stage 4 of the cycle. model: claude-opus-5-5[1m] tools: Bash, Glob, Grep, Read, Edit, Write @@ -10,7 +10,7 @@ skills: - spire:project --- -You write the plan. Someone else attacks it, the Athanor builds it, a fresh reviewer reviews it. You never do those jobs. +You write the plan. Someone else castigates it, the Athanor builds it, a fresh reviewer reviews it. You never do those jobs. ## Input @@ -18,8 +18,8 @@ The brief names the goal, the design if there is one, and the output path. Read ## What the plan holds -- **Ecosystem inventory**, written before anything is designed to be built: what the harness, CLI output, the stdlib and the project's existing tools already provide for this goal. Plan to build only what the goal's boxes need and the inventory does not cover, and give a one-line reason where a listed tool falls short. -- **Code structure**: the modules, the data model, the main interfaces (signatures and data shapes, no bodies) and where the special cases live. Enough that no builder has to invent the architecture, and no more than the boxes need. +- **Ecosystem inventory**, written before anything is designed to be built: what the harness, CLI output, the stdlib and the project's existing tools already provide for this goal. Plan to build what the goal's boxes need at the `Scope:` level (`spire:project`) and the inventory does not cover, and give a one-line reason where a listed tool falls short. +- **Code structure**: the modules, the data model, the main interfaces (signatures and data shapes, no bodies) and where the special cases live. Enough that no builder has to invent the architecture. - **Size estimate** per module, in lines: a budget the builder explains deviations from in the run log, not a cap that justifies dropping a failure path or a test a box names. - **Decisions** the builder cannot make alone, each with a one-line why. - **Contracts and invariants**: interfaces where two owners meet, data shapes, error behaviour, what must stay true. @@ -31,6 +31,6 @@ Code goes in only where its exact form is the decision (a schema, a wire format, ## Rules -- Stamp the model id you ran on in the plan's header. +- Stamp the model id you ran on and the `Scope:` level in the plan's header. - Write only the plan file. Do not touch code. - Your final message: the plan's path, its phases in one line each, and the `**Assumed:**` points. diff --git a/plugins/spire/providers/README.md b/plugins/spire/providers/README.md new file mode 100644 index 0000000..6b25b72 --- /dev/null +++ b/plugins/spire/providers/README.md @@ -0,0 +1,46 @@ +# Providers + +A **runtime** is the agent engine that runs Spire's text (Claude Code, Codex). A **host** is the app around it that may add session tools (Claude Desktop, T3 Code). Paths below are relative to this file. + +Under Codex, `${CLAUDE_PLUGIN_ROOT}` is not substituted: the plugin root is the parent of the `skills/` root Codex shows for a skill (a skill's SKILL.md is `/skills//SKILL.md`). Do not search elsewhere. + +- [`runtimes/claude-code/spawning.md`](runtimes/claude-code/spawning.md): dispatch, resume, models, Rules of thumb (owner) +- [`runtimes/codex/spawning.md`](runtimes/codex/spawning.md): dispatching into Codex +- [`hosts/claude-desktop/spawning.md`](hosts/claude-desktop/spawning.md): Desktop session layer +- [`hosts/t3-code/spawning.md`](hosts/t3-code/spawning.md): T3 threads and delegates +- `hosts/codex-desktop/`: planned, nothing known + +## Detection (reading, not calling) + +Igor reads its tool names, deferred ones included. Spire's agents load only in Claude Code, so the runtime is claude-code. Spire also ships a Codex manifest exposing `skills/`; whether Codex loads them and expands the plugin-root path variable is unknown, and Igor under Codex is unsupported in 0.4.0. + +| Tool names present | Host | Read | +|---|---|---| +| any `mcp__ccd_session__*` or `mcp__ccd_session_mgmt__*` | claude-desktop | runtime + `hosts/claude-desktop/` | +| any `mcp__t3-code__*`, or a tool ending in `orchestrator_capabilities` or `delegate_task` | t3-code | runtime + `hosts/t3-code/` | +| neither, no other session-layer server | none | runtime only | +| both, or an unlisted session-layer server | unclear | runtime only | + +- A session-layer server has tools that create, start, launch, send to or hand off sessions, threads, tasks or agents (e.g. `mcp__claude-code-remote__*`). Other MCP servers do not affect detection. +- **Unclear: do not guess.** Use runtime primitives only, tell the user once which signals you saw, ask which host this is. Never call a host spawn tool on a guess. +- Journal once: `Harness: runtime claude-code, host (signal: )`. +- Re-detect after a resume on another machine, when a host tool fails as absent, and when a session-layer tool first appears in the tool or deferred-tool list. While the pair is `none`, re-read the tool list once before the first background `Agent` dispatch (hosts load tools late). +- Env vars are not a signal. + +## Who reads what + +Igor reads the runtime file and the detected host file, plus the Codex runtime file when delegating to Codex. Zathras follows Igor's rule by reference. The Athanor reads the runtime file only and never calls host spawn tools (Desktop `mcp__ccd_session*__*`, T3 `delegate_task`, threads, any `mcp__t3-code__*`); Igor owns them. Leaf agents read nothing here; their briefs carry what they need. + +## Status legend + +Each claim carries a status and a date. +- **verified**: read from tool schema text, host system-prompt text or vendor docs that date; not runtime-tested unless the row says so. +- **observed**: seen in real runs, source given; mechanism may be assumed. +- **assumed**: inferred, unchecked. +- **unknown**: open; check before relying on it. + +Host files open with "Versions seen"; a row that depends on a version names it. A claim fails: fix the row with a new date. + +## Path rule + +Skill and agent bodies point here as `${CLAUDE_PLUGIN_ROOT}/providers///.md`. Files read with `Read` use relative links; other reference files write `providers/...` plus "(plugin root)". diff --git a/plugins/spire/providers/hosts/claude-desktop/spawning.md b/plugins/spire/providers/hosts/claude-desktop/spawning.md new file mode 100644 index 0000000..9af6e46 --- /dev/null +++ b/plugins/spire/providers/hosts/claude-desktop/spawning.md @@ -0,0 +1,72 @@ +# Spawning on Claude Desktop (Code tab) + +Host layer over [the runtime file](../../runtimes/claude-code/spawning.md). Detection, legend, who reads what: [`../../README.md`](../../README.md). + +## Versions seen + +Desktop app build: unknown (not recorded). All claims read 2026-11-12 unless dated otherwise. + +## Primitives + +§n = section of the dirigent Desktop report. + +| Primitive | What it is | Reaches the parent | Status | +|---|---|---|---| +| `Agent` | As the runtime file; in the tasks pane, not the sidebar | final report | verified 2026-11-12 (code.claude.com docs, §2) | +| `mcp__ccd_session__start_session`, `initiation: "user_asked"` | Full session, own transcript, sidebar row under the parent; user can open, steer, stop, archive it | after each child turn, a note quoting the first 400 chars of its latest report | verified 2026-11-12 (Desktop tool text, §3) | +| same, `initiation: "offer"` | "New session / Do it here" card; nothing runs until picked | as above once started | verified 2026-11-12 (Desktop tool text, §4). Docs call the button **Start** (minor diff) | +| same, `initiation: "own_initiative"` | Proposal card; expires after a week unstarted; `dismiss_task` withdraws it | as above once started | verified 2026-11-12 (Desktop tool text, §3-4). Expiry not in docs | +| `context: "fresh"` / `"fork"` | brief plus required `background` / copy of the parent conversation | n/a | verified 2026-11-12 (Desktop tool text, §3) | +| `use_worktree`, `target` (local, ssh, cloud), `cwd`, `preset`, `model`, `effort`, `permission_mode` (at most the parent's) | start options | n/a | verified 2026-11-12 (Desktop tool text, §3) | +| `SendMessage` to `local_…`; `mcp__ccd_session_mgmt__get_session`, `list_events`, `list_sessions {"linked": true}` | steer and inspect a linked child | n/a | verified 2026-11-12 (Desktop tool text, §3) | +| `mcp__ccd_session__hand_off_to_session` | moves the parent's task into its own session | n/a | verified 2026-11-12 (Desktop tool text, §3) | + +## Visible vs in-process + +`Agent` children are in-process, in the tasks pane, tied to the parent. Linked sessions are sidebar rows, independent, outlive the parent's turn, share no context after start (verified 2026-11-12, Desktop tool text). A child's note is its own claim, not proof. + +## Worktree defaults + +- `Agent isolation: "worktree"`: branches from the default branch, not the parent's HEAD (verified 2026-11-12, subagents docs). +- `use_worktree: true`: the linked session gets its own worktree; its base: unknown. `false`: shares the parent folder (verified 2026-11-12, Desktop tool text). +- With `false`, the PR badge follows the folder's branch, not the child's task (observed 2026-11-12: two sessions on one checkout both showed one PR, §3). +- Default of the new-session Worktree toggle: unknown (docs say off; a search snippet says on, §7.1). + +## Wake and notification + +- A `` wakes the parent only when it is idle and no linked child is still working (verified 2026-11-12, Desktop tool text). +- The child can message the parent when it is blocked (verified 2026-11-12, Desktop tool text, §3). +- Cloud children never report back (verified 2026-11-12, Desktop tool text; docs agree). +- A message to a busy session waits; archived sessions receive nothing (verified 2026-11-12, desktop docs). + +## Host rules that override Spire defaults + +None known. Desktop adds tools; `Agent` is unrestricted. + +## Spire use + +Rules; Igor only. The Athanor never calls `mcp__ccd_session__*` or `mcp__ccd_session_mgmt__*`; Igor owns them (rests on: unknown "subagents see the session tools"; a child's notes would land in a session the Athanor does not own). + +- **Default unchanged.** Igor dispatches as in the CLI: `Agent` for leaves, adepts, planner, advocate, reviewer and the single Athanor. +- **A linked side session beats a background `Agent` when:** (1) the user asks for a separate session or wants to watch or steer; (2) a parallel, independent workstream on disjoint code (a second ticket): `use_worktree: true`, one session per stream; (3) the work should outlive Igor's session or the user continues it by hand. Otherwise `Agent` (Igor synthesizes, needs a `subagent_type` pin, or resumes adepts). +- **Start options.** `initiation: "user_asked"`, `context: "fresh"` with a self-contained brief and `background`, `permission_mode` equal to Igor's, `model` named explicitly. Never `target: "cloud"` unasked (no report-back). +- **Brief shape.** The child is a session root: its agents' notifications reach it, not Igor. For case 2 the brief says "Dispatch `spire:athanor` foreground with ``; when it returns, write the hand-back to ``", and asks the child to open its final message with `; output: ` inside 400 characters. Rests on: assumed "a linked child loads the same plugins and agent types". +- **Journal** each start: `local_…` id, purpose, worktree. On a note or wake, read the output file first. +- **Cards.** `offer` when the user asks for a session but not how to run it. `own_initiative` only after the user said yes to proposal cards this session. Dismiss stale cards Igor made (`dismiss_task`). +- **Never** `hand_off_to_session` unasked. + +## Unknowns + +| Item | Status | +|---|---| +| Worktree base of a linked session with `use_worktree: true` | unknown (§3) | +| A linked child loads the same plugins and agent types | assumed 2026-11-24 (same project folder and settings; not tested) | +| A linked child can spawn its own linked sessions | unknown (§7.4) | +| Subagents see `mcp__ccd_session__*` | unknown (not probed) | +| 400-char note, wake rule and one-week expiry stay stable | unknown (undocumented, §7.3) | +| `Agent` nesting depth: docs say 3 layers, setup observed "generally not" | unknown (docs differ, §2; runtime docs row: [`../../runtimes/claude-code/spawning.md`](../../runtimes/claude-code/spawning.md) Limits) | +| Desktop app build | unknown | + +## Sources + +dirigent workpad (separate repo): `reports/2026-11-12-10-claude-desktop-sessions-and-subagents.md` ("dirigent Desktop report"); docs: code.claude.com `desktop`, `subagents`. diff --git a/plugins/spire/providers/hosts/t3-code/spawning.md b/plugins/spire/providers/hosts/t3-code/spawning.md new file mode 100644 index 0000000..37700e4 --- /dev/null +++ b/plugins/spire/providers/hosts/t3-code/spawning.md @@ -0,0 +1,78 @@ +# Spawning on T3 Code + +Host layer over [the runtime file](../../runtimes/claude-code/spawning.md). Detection and legend: [`../../README.md`](../../README.md). + +## Versions seen + +T3 Code (Beta) 0.1.11 with Claude 2.1.330 and Codex 0.171.0 (dirigent T3 tools report §2). + +## Primitives + +§n = dirigent T3 tools report; "lineage" = dirigent T3 lineage report; "bundle" = tool text and system-prompt rules of the 0.1.11 app. + +| Primitive | What it is | Reaches the parent | Status | +|---|---|---|---| +| native `Agent` (Claude runtime) | provider's own subagent, in-process, same provider, no extra settings | final report | verified 2026-11-23 (bundle, §1) | +| `delegate_task` | child thread run by T3, "no parent history"; any provider and model from `orchestrator_capabilities` | completion wakes the parent; `task_status` returns `summary`, marks it delivered | verified 2026-11-23 (bundle, §1-2); wake observed (lineage §3) | +| `orchestrator_capabilities` | lists providers, models, options, runtime modes | n/a | verified 2026-11-23 (bundle, §2); returned live, observed (lineage §2) | +| `t3_thread_launch` | new top-level thread; `workspaceStrategy`, `modelSelection`, first `message` | nothing; pull with `t3_thread_wait` / `t3_thread_read` | verified 2026-11-23 (bundle, §3); flat, steerable: observed (lineage §3) | +| `create_threads` | several top-level threads here; "Not delegation" | as above | verified 2026-11-23 (bundle, §3) | +| `t3_thread_send` (`auto`/`queue`/`steer`/`restart`), `_interrupt`, `_read`, `_wait` | drive a thread | n/a | verified 2026-11-23 (bundle, §3) | +| `task_cancel` | stops a delegate, its delegates, PR watches; never `t3_thread_interrupt` its `childThreadId` | n/a | verified 2026-11-23 (bundle, §2) | +| `t3_background_wait` | keeps the thread Working during background Bash; Claude and OpenCode only; not for `Agent` or delegate ids | n/a | verified 2026-11-23 (bundle, §2) | + +## Visible vs in-process + +- Native `Agent` is in-process. A `delegate_task` child shows only in the parent's right-hand panel (no tree in the left list), is one-shot, and records `parentThreadId` plus `relationshipToParent: "subagent"` (observed 2026-11-23, lineage §3-4). +- A launched thread is a flat top-level peer, steerable, with no parent recorded even with `delegatedFrom` (observed, lineage §3). No reparenting either way; the title is the only free-text handle (observed, lineage §5-6). +- A native general-purpose subagent saw `mcp__t3-code__*` (observed 2026-11-23, §1). + +## Worktree defaults + +- `delegate_task isolation: "worktree"`: new checkout from the parent commit; uncommitted edits stay out. `"shared"` (default): the parent checkout. Unsupported for remote delegation (verified 2026-11-23, bundle, §1, §8). +- `t3_thread_launch workspaceStrategy: "worktree"`: from `baseRef`, default `origin/` with `startFromOrigin: true`. Omitted `workspaceStrategy` = project root, not the caller's worktree (verified 2026-11-23, bundle, §3, §10). + +## Wake and notification + +- Delegate completion is injected into the parent thread; its `next` says "Completion wakes this thread. Do not wait on it or poll it." (observed 2026-11-23, lineage §3). +- `mode: "wait"` caps at 45 s; a timeout does not cancel. Threads: pull only (verified 2026-11-23, bundle, §2-3). + +## Host rules that override Spire defaults + +T3 puts these in the system prompt; they win over Spire defaults. All verified 2026-11-23 (bundle, §1-3, §10). +- Never a background native `Agent`; background work goes through `delegate_task`. Collides with a background Athanor (see Spire use). +- New threads only when the user asks; "subagent", "delegate", "parallel" never mean one. +- Call `orchestrator_capabilities` once per thread before the first `delegate_task`. Unavailable provider or model: say so, never fall back silently. +- Do not poll delegates (`task_status`, `sleep`, Monitor). +- Each delegate review or re-check is a new `delegate_task`, never a send to the old one. +- Mention a thread by its `link`, verbatim. +- Children and launched threads cannot exceed the caller's permission modes. +- As a subagent or child, do the work yourself; start no subagents unless the task says to. + +## Spire use + +Rules; Igor only. The Athanor never calls any `mcp__t3-code__*` tool (`delegate_task`, threads); Igor owns them (rests on: unknown "whose thread wakes for a delegate a native subagent started"). + +- **Native `Agent`, foreground**: anything needing a Spire agent type (pin, skills, `SendMessage` resume): planner, advocate, reviewer, adepts, researcher, search, scout, the Athanor. +- **`delegate_task`, `mode: "async"`**: another provider or model (Codex review), user-asked settings (effort max), a separate checkout from the parent commit, or a leaf run in the background. Self-contained brief: agent body pasted (e.g. `agents/reviewer.md`), input files, output path, hand-back headings; no secrets; at most 120k chars. A Codex child has no Spire (read [the Codex file](../../runtimes/codex/spawning.md) first); a Claude child gets the body pasted too, since `delegate_task` takes no agent type (rests on: assumed Claude-delegate row). +- Before `isolation: "worktree"`, commit what the child must see; `"shared"`: the child writes only its output path. After a wake, read the output file. +- **The Athanor in T3.** Igor dispatches it as a foreground native `Agent` (no background `Agent` here). Igor tells the user it blocks until hand-back. Assumed default; Athanor-as-delegate awaits a probe. Igor's brief says the Athanor runs its own subagents (the child rule may reach it). +- **Threads.** `t3_thread_launch` only when the user asks for a thread or peer. Always set `workspaceStrategy`. Title `[igor] `; journal id and `link`. +- **Background Bash.** Before ending a turn on background Bash, Igor calls `t3_background_wait` (task id). +- **Supervision.** Children inherit full-access (observed, lineage §3). `runtimeMode: "approval-required"` only on user request (rests on: assumed row below). +- **Not used by Spire in 0.4.0**: PR and issue tools, `request_secret`, `html_render`, previews, devices, `schedule_task`, linked environments, `t3_worktree_handoff`, `t3_thread_transfer`. + +## Unknowns + +| Item | Status | +|---|---| +| Whose thread wakes for a delegate started by a native subagent | unknown (untested) | +| A Claude delegate child loads Spire | assumed 2026-11-24 (not tested) | +| `SendMessage` resume of an adept is not a background `Agent` under T3's rule | assumed 2026-11-24 (Igor waits; adepts reply in one turn) | +| A send to a finished delegate keeps its context | unknown (untested; lineage §3) | +| `approval-required` children behave as supervised | assumed 2026-11-23 (lineage §3, untested) | +| `t3-thread://` handled by the OS | unknown (untested; lineage §7) | + +## Sources + +dirigent workpad (separate repo): `reports/2026-11-23-11-t3-code-mcp-tools.md` ("dirigent T3 tools report"); `reports/2026-11-23-16-t3-code-threads-lineage-and-links.md` ("dirigent T3 lineage report"). diff --git a/plugins/spire/skills/implementation/references/spawning-claude-code.md b/plugins/spire/providers/runtimes/claude-code/spawning.md similarity index 68% rename from plugins/spire/skills/implementation/references/spawning-claude-code.md rename to plugins/spire/providers/runtimes/claude-code/spawning.md index 00788be..f6c9930 100644 --- a/plugins/spire/skills/implementation/references/spawning-claude-code.md +++ b/plugins/spire/providers/runtimes/claude-code/spawning.md @@ -1,15 +1,8 @@ # Spawning agents in Claude Code -Harness mechanics: dispatch, resume, fork. Other harnesses: own `spawning-.md` when needed. +Harness mechanics: dispatch, resume, fork. Other hosts: see the convention in [`../../README.md`](../../README.md). -Status per claim, with date: - -- **verified**: read from the tool schema text that date; not runtime-tested unless the row says so. -- **observed**: seen in real runs, source given; mechanism may be assumed. -- **assumed**: inferred, unchecked; a hypothesis. -- **unknown**: open; check before relying on it. - -A claim fails: fix it here with a new date. +Status legend: [../../README.md](../../README.md) ## Rules of thumb @@ -21,8 +14,10 @@ Owner of the harness rules; Igor, Zathras and the Athanor point here. - **Pinned agents: omit `model`.** The per-call alias overrides the frontmatter pin. Override only on purpose, noted in the journal or run log. - **Unpinned agents: pass `model`.** Omitted, they inherit the caller's model, possibly Fable. - **Stamp the model id.** Every agent reads its exact id from its system prompt and writes it into its output. -- **Leaf briefs say "do this yourself; do not dispatch further agents."** Only orchestrators (the Athanor) fan out. +- **Leaf briefs say "do this yourself; do not dispatch further agents."** Only orchestrators (the Athanor) fan out. Gremlin briefs are exempt: the gremlins preamble says it and the launch removes the tools. - **Notifications report a turn ending, not a job finishing.** Read the result text before concluding. Check `ListAgents` before resuming. +- **Output filenames.** Claude Code blocks subagent writes to `.md` files whose basename starts with `report`, `summary`, `findings` or `analysis`. Whoever names the path (the brief, or the agent when none is given) uses a role-prefixed name: `qa-report.md`, `research-findings.md`, `review-.md`. Spire's dated document names and `logs/` names (`run.md`, `review-`, `recheck-`, `brief-`) comply. +- **Host layer.** Visible sessions, threads and delegates belong to the host file the README detection picks; the Athanor never uses them. ## Dispatch and notification @@ -38,6 +33,17 @@ Owner of the harness rules; Igor, Zathras and the Athanor point here. | `TaskList` is the todo list, unrelated to agents. `TaskOutput` on an agent dumps its whole transcript into your context; never use it for agents. | observed 2026-09-22 | | A `general-purpose` agent has the Agent tool and delegates if its brief reads like an orchestration brief. | observed 2026-09-22 | | Once auto mode ends, a child's hand-back may wait on permission (`SubagentHandback` refused): idle, not hung. Before a long or overnight step: keep auto mode on, defer it with a journal note, or warn the user. | observed once 2026-10-21 (ai-developer bundle D); what the refusal blocks is unverified | +| Desktop: `Agent` subagents show in the session's tasks pane, not the sidebar; output viewable and stoppable there. | verified 2026-11-12 (code.claude.com desktop docs, via dirigent Desktop report §2) | +| `isolation: "worktree"` branches from the **default branch**, not the caller's HEAD; cleaned up when the child makes no changes. | verified 2026-11-12 (subagents docs, via dirigent Desktop report §2) | + +## Limits + +| Claim | Status | +|---|---| +| At most 20 subagents running per session (default). The 21st Agent-tool spawn fails with `Concurrent subagent limit reached`, and the error tells Claude not to retry; spawning works again once the running count drops. `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS` (positive integer) changes the cap but cannot disable it. Not enforced under ultracode. Requires v2.1.217+. | verified 2026-11-24 (code.claude.com/docs/en/sub-agents#concurrent-subagent-limit, /docs/en/env-vars); observed twice (spacecraft Athanor fan-outs, 2026-11-16, version not recorded; error text then: "You can run 20 subagents at once... increase `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS`") | +| The cap counts the whole session, not one parent: Igor's other running children count too. A `/subtask` fork takes a slot. Resuming a finished subagent takes a slot without checking the cap, so resumes can push the count past it. Workflow agents and agent-team teammates have their own limits. No limit on total spawns per session (`CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION` is a no-op since v2.1.224). | verified 2026-11-24 (same pages) | +| Gremlins are separate `claude -p` sessions, so they take no slot in the caller's session. | assumed from the docs' scope ("subagents running in a session"); not probed | +| Nesting depth: 3 subagent layers below the main conversation by default (`CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH`; v2.1.217-218 defaulted to 1). Igor's session root → Athanor → child → grandchild is the deepest that works; the grandchild cannot spawn. | documented 2026-11-24 (env-vars page); a Desktop setup observed otherwise, see [`../../hosts/claude-desktop/spawning.md`](../../hosts/claude-desktop/spawning.md) | ## Resume @@ -55,9 +61,9 @@ Owner of the harness rules; Igor, Zathras and the Athanor point here. | A full model id (e.g. `claude-opus-5-5`) is settable only in agent frontmatter; pinning by full id = a pinned agent dispatched without `model`. | verified 2026-10-05 (follows from the alias-only parameter) | | The `opus` alias overrode 4.6 pins in 184 of 184 spawns (they ran on 5.5). | observed 2026-09-27 (spacecraft MVP retrospective) | | A 4.6 Igor passing `model: "opus"` to the then 4.6-pinned Athanor got a 4.6 run (the dirigent end review that passed with zero findings). | observed 2026-10-05 (user's attribution; the dirigent report recorded the model as unknown). | -| What the `opus` alias resolves to (caller's model, a session default, or newest Opus). | unknown. Check the stamped id of every plan, attack and review instead. | +| What the `opus` alias resolves to (caller's model, a session default, or newest Opus). | unknown. Check the stamped id of every plan, castigation and review instead. | | Every agent sees its exact model id in its system prompt. | observed 2026-10-05 for general-purpose agents (prompt shows `claude-opus-5-5`); not checked for plugin agents with their own bodies | -| Context window of bare `claude-opus-5-5` pin vs `[1m]` suffix (other Spire pins carry `[1m]`). | resolved 2026-10-05: all Opus-pinned Spire agents (igor, adept, athanor, zathras) pinned to `claude-opus-5-5[1m]` (user decision); the ~600k guesstimate in `models.md` assumes the larger window | +| Context window of bare `claude-opus-5-5` pin vs `[1m]` suffix (other Spire pins carry `[1m]`). | resolved 2026-10-05: all Opus-pinned Spire agents (igor, adept, athanor, zathras, designer, planner, advocate, reviewer) pinned to `claude-opus-5-5[1m]` (user decision); the ~600k guesstimate in `models.md` assumes the larger window | ## Fork diff --git a/plugins/spire/providers/runtimes/codex/spawning.md b/plugins/spire/providers/runtimes/codex/spawning.md new file mode 100644 index 0000000..d48d68e --- /dev/null +++ b/plugins/spire/providers/runtimes/codex/spawning.md @@ -0,0 +1,38 @@ +# Codex runtime: spawning (partly verified) + +Read only when dispatching into Codex (T3 `delegate_task` to Codex, Codex gremlins). Spire's own agents run on claude-code. Legend: [README](../../README.md). codex-cli 0.172.0. + +| Claim | Status | +|---|---| +| `codex exec --json` runs non-interactively; first event is `thread.started{thread_id}`. No preassigned session id | verified 2026-11-24 (help, source, live runs) | +| `codex exec fork [PROMPT]` and `exec resume [id] [PROMPT]`; `exec`, `--ephemeral fork`, `resume` read the prompt from stdin `-`; concurrent forks ran. `--ignore-user-config` keeps auth | verified 2026-11-24 (help, source, P3 live, `gpt-6-luna`) | +| `-s`, `-C`, `--add-dir`, `-p` are not global: for fork/resume they precede the subcommand (`codex exec -s read-only -C --json fork ""`) | verified 2026-11-24 (source) | +| A fork takes model, effort, sandbox and cwd from the current call, not the base: repeat `-m`, `-c model_reasoning_effort=…`, `-s`, `-C` | verified 2026-11-24 (source) | +| `exec` forces `approval_policy = never`, never prompts | verified 2026-11-24 (source, live runs) | +| No trust entry: default sandbox read-only, project config, hooks, rules off. Outside a git repo `exec` exits without `--skip-git-repo-check` | observed 2026-11-24 (live runs) | +| Tool shells inherit the full env; the `*KEY*/*SECRET*/*TOKEN*` filter is off (leak itself not seen) | verified 2026-11-24 (source) | +| Multi-agent tools exist; `-c agents.enabled=false` disables them (accepted live) | verified 2026-11-24 (source, P3 live) | +| `--ephemeral` forks wrote no rollout and read the base prefix from cache (2/2); persisted forks missed (0/3) | observed 2026-11-24 (research, P3; turn-delta estimate) | +| A resumed base keeps its thread id and cache key | observed 2026-11-24 (research, P3) | +| `turn.completed.usage` is the thread's running total, base included | observed 2026-11-24 (research) | +| Nested `codex exec` works with `--add-dir ` plus network on (n1 failed, n3 worked); escalation per helper call is untried (P4) | observed 2026-11-24 (n1/n3); escalation assumed | +| Under `workspace-write` `.git` is read-only: a fork's `git commit` fails (`index.lock: Read-only file system`); forks never commit | verified 2026-11-24 (source); observed 2026-11-24 (P3) | +| Native subagent tool is `spawn_agent`, then wait | assumed 2026-11-23 (T3 0.1.11 host rules, dirigent `reports/2026-11-23-11-t3-code-mcp-tools.md` §1, `reports/2026-11-23-11-harnesses.md`; not checked against Codex) | +| `AGENTS.md` is the instruction file; skills via `.agents/skills`; Claude plugins do nothing | observed 2026-09-28 (dirigent `reports/2026-11-23-11-harnesses.md`, citing ai-developer reports) | +| Spire ships a Codex manifest exposing `skills/`; whether Codex loads them and expands the plugin-root path variable | unknown | +| Codex desktop, its sessions and worktrees | unknown | + +## Consequence for Spire + +A Codex child gets a self-contained brief: no `subagent_type`, no Spire skills relied on, no plugin-root path variable; paste what it needs. Keep secrets out of the brief: Codex does not scrub its tool shells, but the gremlins helper scrubs secret-shaped inherited env (`--pass-env` lets one through). Repeat model, effort, sandbox and cwd on every fork. Igor under Codex is unsupported in 0.4.0. + +## Unknowns + +- Manifest and skill loading; Codex desktop, worktrees. +- `spawn_agent` arguments and wait semantics. +- Which of `--add-dir ` and network is needed for a nested `codex exec` is not isolated. +- Rule syntax to deny `git push` or `codex` in a child; explicitly untrusted dirs. + +## Sources + +reliquary quire (unshipped): `research/2026-11-24-09-codex-gremlins-verification.md`. dirigent workpad (separate repo): `reports/2026-11-23-11-harnesses.md`, `reports/2026-11-23-11-t3-code-mcp-tools.md`. diff --git a/plugins/spire/skills/gremlins/grm/call.py b/plugins/spire/skills/gremlins/grm/call.py index d09c40d..28df47f 100644 --- a/plugins/spire/skills/gremlins/grm/call.py +++ b/plugins/spire/skills/gremlins/grm/call.py @@ -41,9 +41,10 @@ def _read(stdout, raw, ss) -> None: pass # the raw file or pipe was closed after READER_JOIN_S -def run_claude(argv, prompt: str, env, cwd, raw_path, on_start): - """Run one call to its end. Returns (ss, exit_code, stopped).""" - ss = StreamState() +def run_claude(argv, prompt: str, env, cwd, raw_path, on_start, stream_state=None): + """Run one call to its end. Returns (ss, exit_code, stopped). `stream_state` is the harness's + stream reader (default: a Claude `StreamState`).""" + ss = StreamState() if stream_state is None else stream_state raw_path = Path(raw_path) with open(raw_path, "wb") as raw, open(raw_path.with_suffix(".err"), "wb") as err: child = subprocess.Popen(argv, cwd=cwd, env=env, stdin=subprocess.PIPE, diff --git a/plugins/spire/skills/gremlins/grm/cli.py b/plugins/spire/skills/gremlins/grm/cli.py index b7b382f..6ea7fa7 100644 --- a/plugins/spire/skills/gremlins/grm/cli.py +++ b/plugins/spire/skills/gremlins/grm/cli.py @@ -1,4 +1,5 @@ -"""argparse and the commands; each launch is record -> one `claude -p` call -> record.""" +"""argparse and the commands; each launch is record -> one harness call (through the run's +adapter, `grm/harness.py`) -> record.""" import argparse import json import os @@ -10,7 +11,8 @@ import time import uuid from pathlib import Path -from grm import call, launch, store, stream +from grm import call, harness, scrub, store, stream, title +from grm.errors import Refusal SKILL_DIR = Path(__file__).resolve().parent.parent NAME_RE = re.compile(r"^[A-Za-z0-9._-]+$") @@ -18,16 +20,11 @@ EXCERPT_CHARS = 500 LAUNCHES = ("train", "spawn", "rebase") -class Refusal(Exception): - """Refused before or instead of a launch: exit 2, payload printed as the JSON object.""" - - def __init__(self, error: str, **fields): - super().__init__(error) - self.payload = {"error": error, **fields} - - class _Parser(argparse.ArgumentParser): def error(self, message): + # never echo stray argument values (a `--pass-env NAME VALUE` slip would print the value) + if message.startswith("unrecognized arguments"): + message = "unrecognized arguments" raise Refusal("usage", detail=message) @@ -97,15 +94,18 @@ def _read_brief(path: str) -> str: raise Refusal("cannot read brief", brief=path, detail=str(e)) -def _load_run(run: str) -> tuple[Path, dict]: - """State dir and run.json of a launch; the stored binary must still exist (no job file yet).""" +def _load_run(run: str): + """State dir, run.json and adapter of a launch. Before any job file: the caller's harness + must be the run's (or unclear), and the stored binary must still exist.""" state = store.state_dir(run) r = store.read_json(state / "run.json") if r is None: raise Refusal("no run.json for this run; call init first", state=str(state)) + h = harness.of(r) + harness.check_caller(r, os.environ) if not os.path.isfile(r["argv"][0]): - raise Refusal("claude binary missing", binary=r["argv"][0]) - return state, r + raise Refusal("%s binary missing" % h.binary_name, binary=r["argv"][0]) + return state, r, h def _load_base(state: Path, b: str) -> dict: @@ -125,10 +125,10 @@ def _warmth(lines: list, base: dict, now: float) -> dict: return {**stream.warmth(stream.parse_iso(last["hit_at"]), ttl, now), "ttl_s": ttl} -def _execute(run: str, state: Path, r: dict, *, job, kind, base, sid, argv, prompt, +def _execute(run: str, state: Path, r: dict, h, *, job, kind, base, sid, t, argv, prompt, before=(None, 0.0), base_ctx=None): """One call: job file `running` -> run_claude -> job file final + one ledger line. - Returns (job record, StreamState|None, usage|None, ledger line|None).""" + `t` is the call's title. Returns (job record, stream state|None, usage|None, ledger line|None).""" fp = r["fingerprint"] jpath = state / "jobs" / (job + ".json") raw = state / "raw" / (job + ".jsonl") @@ -136,15 +136,15 @@ def _execute(run: str, state: Path, r: dict, *, job, kind, base, sid, argv, prom t0 = time.time() rec = {"job": job, "kind": kind, "base": base, "session_id": sid, "status": "running", "reason": None, "started": stream.iso(t0), "ended": None, "child_pid": None, - "raw": str(raw), "note": None, "cache": None, "result_excerpt": None} + "raw": str(raw), "note": None, "cache": None, "result_excerpt": None, "title": t} store.write_json(jpath, rec) def on_start(pid): rec["child_pid"] = pid store.write_json(jpath, rec) try: - ss, code, stopped = call.run_claude(argv, prompt, launch.scrubbed_env(fp["binary"]), - fp["cwd"], raw, on_start) + ss, code, stopped = call.run_claude(argv, prompt, h.env(fp), fp["cwd"], raw, on_start, + stream_state=h.new_stream(fp)) except OSError as e: rec.update(status="error", reason="launch_error", ended=stream.iso(), result_excerpt=str(e)[:EXCERPT_CHARS]) @@ -152,8 +152,8 @@ def _execute(run: str, state: Path, r: dict, *, job, kind, base, sid, argv, prom return rec, None, None, None wall = time.time() - t0 status, reason = stream.classify(ss, code, stopped) - u = stream.usage_from_result(ss.result, *before) if ss.result else None - cache = stream.cache_verdict(ss.first_usage, base_ctx) if kind != "train" else None + u = h.usage(ss, *before) if ss.result else None + cache = h.cache_verdict(ss, u, base_ctx) if kind != "train" else None hit_t = None if kind in ("train", "rebase") and status == "ok": hit_t = ss.last_assistant_at @@ -200,68 +200,80 @@ def cmd_init(args) -> dict: state = store.state_dir(args.run) if (state / "run.json").exists(): raise Refusal("run.json exists; init never overwrites a run", state=str(state)) - binary = launch.resolve_binary(args.binary) + target, caller = harness.select(args.harness, os.environ) + h = harness.named(target) + binary = h.resolve_binary(args.binary) if not binary or not os.path.isfile(binary): - raise Refusal("no claude binary (no --binary, no $CLAUDE_CODE_EXECPATH, none on PATH)", - binary=binary) + raise Refusal("%s binary missing" % h.binary_name, binary=binary, + detail="pass --binary, or put `%s` on PATH" % h.binary_name) cwd = os.path.abspath(args.cwd) if args.cwd else _git_out(["rev-parse", "--show-toplevel"], os.getcwd()) if not cwd or not os.path.isdir(cwd): raise Refusal("no usable cwd (pass --cwd, or run inside a git repository)", cwd=cwd) - if not launch.MODEL_RE.match(args.model): # before anything is written - raise Refusal("model must be a full id (aliases are refused)", model=args.model) + cwd, network = os.path.abspath(cwd), bool(args.network) + # everything is validated before anything is written + h.check_init(cwd=cwd, agent=args.agent, network=network) + h.check_model(args.model, args.effort) + env_pass = scrub.check_pass_env(args.pass_env or [], os.environ) + # preflight sees the init inputs only: the fingerprint needs the state's preamble copy + h.preflight({"harness": target, "binary": binary, "cwd": cwd, "env_pass": env_pass}) state = store.init_state(args.run) pre = state / "preamble.md" store.atomic_write_bytes(pre, (SKILL_DIR / "preamble.md").read_bytes()) mcp = state / "mcp-empty.json" store.write_json(mcp, {"mcpServers": {}}) - fpd = launch.build_fingerprint(binary=binary, model=args.model, effort=args.effort, - cwd=os.path.abspath(cwd), agent=args.agent, - preamble_path=str(pre), mcp_config=str(mcp)) - run = {"run": os.path.abspath(args.run), "created": stream.iso(), **fpd} + fpd = h.build_fingerprint(binary=binary, model=args.model, effort=args.effort, cwd=cwd, + agent=args.agent, network=network, state=str(state), + preamble_path=str(pre), mcp_config=str(mcp), env_pass=env_pass) + run = {"run": os.path.abspath(args.run), "created": stream.iso(), "caller_harness": caller, **fpd} store.write_json(state / "run.json", run) - return {"state": str(state), **run} + return {"state": str(state), **run, "harness": target, + "env_dropped": scrub.env_dropped(target, os.environ, env_pass)} def cmd_train(args) -> dict: - """B1: one blocking call with `--session-id`; the base file only on `ok`.""" + """B1: one blocking call (Claude: with `--session-id`); the base file only on `ok`.""" b = _name("base", args.base) - state, r = _load_run(args.run) + state, r, h = _load_run(args.run) bpath = state / "bases" / (b + ".json") if bpath.exists(): raise Refusal("base exists", base=b) brief = _read_brief(args.brief) - sid, job = str(uuid.uuid4()), b + "-train" - prompt = render_template("train.md", { + sid = str(uuid.uuid4()) if h.preassigns_session_id else None + job, t = b + "-train", title.make("train", b, None, r["run"]) + rendered = render_template("train.md", { "base": b, "run": r["run"], "state_dir": str(state), "notes_dir": str(state / "notes"), "out_dir": str(state / "out"), "brief": brief}) - rec, ss, u, line = _execute(args.run, state, r, job=job, kind="train", base=b, sid=sid, - argv=launch.train_argv(r, sid), prompt=prompt) + rec, ss, u, line = _execute(args.run, state, r, h, job=job, kind="train", base=b, sid=sid, t=t, + argv=h.train_argv(r, sid, t), prompt=h.train_prompt(state, t, rendered)) + warnings = [] if rec["status"] == "ok": + ctx, warnings = h.context_tokens(r["fingerprint"], ss) store.write_json(bpath, { "base": b, "session_id": rec["session_id"], "train_job": job, "commit": git_head(r["fingerprint"]["cwd"]), "trained_at": rec["ended"], - "context_tokens": stream.context_tokens(ss.last_usage), "model_usage": u["model_usage"], - "cost_cumulative_usd": _cost_basis(ss), "ttl_s": stream.infer_ttl(u["tokens"], None), + "context_tokens": ctx, "model_usage": u["model_usage"], + "cost_cumulative_usd": _cost_basis(ss), "ttl_s": h.infer_ttl(u["tokens"], None), "rebases": []}) - return _out(rec, line) + return {**_out(rec, line), "warnings": list(warnings)} def cmd_spawn(args) -> dict: """B2, B3, B5: one blocking fork of the base; never writes the base file.""" b, j = _name("base", args.base), _name("job", args.job) - state, r = _load_run(args.run) + state, r, h = _load_run(args.run) base = _load_base(state, b) if (state / "jobs" / (j + ".json")).exists(): raise Refusal("job exists; pick a new --job", job=j) brief = _read_brief(args.brief) - sid = str(uuid.uuid4()) + sid = str(uuid.uuid4()) if h.preassigns_session_id else None + t = title.make("spawn", b, j, r["run"]) prompt = render_template("spawn.md", { "block": j, "base": b, "run": r["run"], "delta": delta_header(r["fingerprint"]["cwd"], base.get("commit")), "note_path": str(state / "notes" / (j + ".md")), "out_dir": str(state / "out"), - "brief": brief}) - rec, _, _, line = _execute(args.run, state, r, job=j, kind="spawn", base=b, sid=sid, - argv=launch.fork_argv(r, base["session_id"], sid), prompt=prompt, + "commit_line": h.commit_line, "brief": brief}) + rec, _, _, line = _execute(args.run, state, r, h, job=j, kind="spawn", base=b, sid=sid, t=t, + argv=h.fork_argv(r, base["session_id"], sid, t), prompt=prompt, before=(base.get("model_usage"), base.get("cost_cumulative_usd")), base_ctx=base.get("context_tokens")) return _out(rec, line) @@ -270,28 +282,31 @@ def cmd_spawn(args) -> dict: def cmd_rebase(args) -> dict: """B7: resume the base without a fork; on `ok` the base takes the result's session id.""" b = _name("base", args.base) - state, r = _load_run(args.run) + state, r, h = _load_run(args.run) base = _load_base(state, b) brief = _read_brief(args.brief) running = sorted(rec["job"] for rec in map(store.read_json, (state / "jobs").glob("*.json")) if rec and rec.get("base") == b and rec.get("status") == "running") warnings = ["jobs of %s still marked running: %s" % (b, ", ".join(running))] if running else [] - job = "%s-rebase%d" % (b, len(base.get("rebases") or []) + 1) + n = len(base.get("rebases") or []) + 1 + job, t = "%s-rebase%d" % (b, n), title.make("rebase", b, str(n), r["run"]) cwd = r["fingerprint"]["cwd"] prompt = render_template("rebase.md", { "base": b, "run": r["run"], "notes_dir": str(state / "notes"), "delta": delta_header(cwd, base.get("commit")), "brief": brief}) - rec, ss, u, line = _execute(args.run, state, r, job=job, kind="rebase", base=b, sid=None, - argv=launch.resume_argv(r, base["session_id"]), prompt=prompt, + rec, ss, u, line = _execute(args.run, state, r, h, job=job, kind="rebase", base=b, sid=None, t=t, + argv=h.resume_argv(r, base["session_id"], t), prompt=prompt, before=(base.get("model_usage"), base.get("cost_cumulative_usd")), base_ctx=base.get("context_tokens")) if rec["status"] == "ok": base["rebases"] = list(base.get("rebases") or []) + [{ "job": job, "at": rec["ended"], "from_commit": base.get("commit"), "from_session": base["session_id"]}] + ctx, ctx_warnings = h.context_tokens(r["fingerprint"], ss) + warnings += ctx_warnings base.update(session_id=rec["session_id"] or base["session_id"], commit=git_head(cwd), - context_tokens=stream.context_tokens(ss.last_usage), model_usage=u["model_usage"], - cost_cumulative_usd=_cost_basis(ss), ttl_s=stream.infer_ttl(u["tokens"], base.get("ttl_s"))) + context_tokens=ctx, model_usage=u["model_usage"], + cost_cumulative_usd=_cost_basis(ss), ttl_s=h.infer_ttl(u["tokens"], base.get("ttl_s"))) store.write_json(state / "bases" / (b + ".json"), base) return {**_out(rec, line), "warnings": warnings} @@ -325,7 +340,10 @@ def _parser() -> argparse.ArgumentParser: sub = p.add_subparsers(dest="cmd", required=True) s = sub.add_parser("init") s.add_argument("--model", required=True) - s.add_argument("--effort", default="high", choices=launch.EFFORTS) + s.add_argument("--effort", default="high") # each adapter validates it + s.add_argument("--harness", choices=harness.HARNESSES) + s.add_argument("--pass-env", action="append", metavar="NAME", dest="pass_env") + s.add_argument("--network", action="store_true") # Codex sandbox network; refused on Claude s.add_argument("--cwd") s.add_argument("--agent") s.add_argument("--binary") diff --git a/plugins/spire/skills/gremlins/grm/codex.py b/plugins/spire/skills/gremlins/grm/codex.py new file mode 100644 index 0000000..5a359a4 --- /dev/null +++ b/plugins/spire/skills/gremlins/grm/codex.py @@ -0,0 +1,275 @@ +"""The Codex adapter (design §3.1, §4): `codex exec` argv and fingerprint, init checks, the model +and effort check against `/models_cache.json`, the rollout reader (base context) and +the `CODEX_HOME` write preflight. Imports neither `harness` nor `cli`.""" +import glob +import json +import os +import re +import shutil +import subprocess +import tempfile +from pathlib import Path + +from grm import launch, scrub, stream +from grm.errors import Refusal + +MODEL_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$") +EFFORTS = ("none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra", "persistent") +SANDBOX = "workspace-write" +NETWORK_CONFIG = "sandbox_workspace_write.network_access=true" +CODEX_NOMINAL_TTL_S = 600 +COMMIT_LINE = (" You cannot commit here (`.git` is read-only in your sandbox); list the paths you " + "changed on the note's Commits line.") +STALE_CACHE_REMEDY = ("pick a slug listed in models_cache.json; if the cache is stale, run `codex` " + "once to refresh it") +MISSING_HOME_REMEDY = ("check CODEX_HOME (a typo, or a home never used); run `codex` once to create it " + "and log in") +PREFLIGHT_REMEDY = ("run G escalated, or start the caller with --add-dir %s " + "-c sandbox_workspace_write.network_access=true") + + +def codex_home(environ=None) -> str: + """`CODEX_HOME`, else `~/.codex`, made absolute. Used at `init` only; later calls use the + fingerprint's `codex_home`.""" + if environ is None: + environ = os.environ + return os.path.abspath(os.path.expanduser(environ.get("CODEX_HOME") or "~/.codex")) + + +def _cached_models(home: str) -> dict | None: + """{slug: [efforts]} from `/models_cache.json`; None when it is missing, unparsable or + has no `models[].slug` list. Only `slug` and `supported_reasoning_levels[].effort` are read.""" + try: + with open(os.path.join(home, "models_cache.json"), "rb") as f: + data = json.loads(f.read().decode("utf-8")) + except (OSError, ValueError): + return None + models = data.get("models") if isinstance(data, dict) else None + if not isinstance(models, list): + return None + out = {} + for m in models: + if isinstance(m, dict) and isinstance(m.get("slug"), str): + levels = m.get("supported_reasoning_levels") or [] + out[m["slug"]] = [lv["effort"] for lv in levels + if isinstance(lv, dict) and isinstance(lv.get("effort"), str)] + return out or None + + +def rollout_path(home: str, thread_id: str) -> str | None: + """`/sessions/*/*/*/rollout-*-.jsonl`; with more than one match the newest + mtime wins; None when there is none.""" + pattern = os.path.join(glob.escape(home), "sessions", "*", "*", "*", + "rollout-*-%s.jsonl" % glob.escape(thread_id)) + best = None + for p in glob.glob(pattern): + try: + m = os.path.getmtime(p) + except OSError: + continue + if best is None or m > best[0]: + best = (m, p) + return best[1] if best else None + + +def _rollout_context(path: str) -> int | None: + """The last `event_msg`/`token_count` `info.last_token_usage.input_tokens`, or None. Lines + without `token_count` are not decoded; of the others only `type` and that record are read.""" + try: + with open(path, "rb") as f: + data = f.read() + except OSError: + return None + last = None + for ln in data.splitlines(): + if b"token_count" not in ln: + continue + try: + ev = json.loads(ln.decode("utf-8", "replace")) + except ValueError: + continue + if not isinstance(ev, dict) or ev.get("type") != "event_msg": + continue + payload = ev.get("payload") + if not isinstance(payload, dict) or payload.get("type") != "token_count": + continue + info = payload.get("info") # null before the first usage + ltu = info.get("last_token_usage") if isinstance(info, dict) else None + n = ltu.get("input_tokens") if isinstance(ltu, dict) else None + if isinstance(n, int) and not isinstance(n, bool): + last = n + return last + + +def _inside(path: str, root: str) -> bool: + p, r = os.path.realpath(path), os.path.realpath(root) + return p == r or p.startswith(r.rstrip("\\/") + os.sep) + + +def _argv(fp: dict) -> list[str]: + """The fingerprinted command line (design §4.1); its order must never change (cache hit). + Non-global flags (`-s`, `-C`, `--add-dir`) sit before any subcommand.""" + a = [fp["binary"], "exec", "--json"] + if fp["ignore_user_config"]: + a.append("--ignore-user-config") + a += ["-s", fp["sandbox"], "-C", fp["cwd"]] + for d in fp["add_dirs"]: + a += ["--add-dir", d] + a += ["-m", fp["model"]] + for c in fp["config"]: + a += ["-c", c] + if fp["network"]: + a += ["-c", NETWORK_CONFIG] + return a + + +class CodexAdapter: + name = binary_name = "codex" + preassigns_session_id = False # the id comes from `thread.started` + commit_line = COMMIT_LINE + + def resolve_binary(self, explicit): + path = explicit or shutil.which("codex") + return os.path.abspath(path) if path else None + + def binary_version(self, path): + """Last token of ` --version` (`codex-cli 0.172.0` -> `0.172.0`), or None.""" + try: + r = subprocess.run([path, "--version"], stdin=subprocess.DEVNULL, capture_output=True, + timeout=60) + except (OSError, subprocess.SubprocessError): + return None + toks = r.stdout.decode("utf-8", "replace").split() + return toks[-1] if r.returncode == 0 and toks else None + + def check_init(self, *, cwd, agent, network): + if agent: + raise Refusal("Codex has no main-thread agent", agent=agent) + try: + r = subprocess.run(["git", "--no-optional-locks", "rev-parse", "--show-toplevel"], cwd=cwd, + stdin=subprocess.DEVNULL, capture_output=True, timeout=60) + ok = r.returncode == 0 and r.stdout.strip() + except (OSError, subprocess.SubprocessError): + ok = False + if not ok: + raise Refusal("Codex runs need a git repository", cwd=cwd, + detail="codex exec refuses a cwd outside a git repository") + + def check_model(self, model, effort): + """Design §4.2: a slug, not a Claude id; with a readable cache the slug must be listed and + the effort must be one of its levels; without one, only the effort enum is checked.""" + if (model or "").startswith("claude-") or not MODEL_RE.match(model or ""): + raise Refusal("model must be a Codex model slug", model=model) + cached = _cached_models(codex_home()) + if cached is not None: + if model not in cached: + raise Refusal("unknown model", model=model, models=sorted(cached), + remedy=STALE_CACHE_REMEDY) + if cached[model]: + if effort not in cached[model]: + raise Refusal("unknown effort", effort=effort, efforts=list(cached[model]), model=model) + return + if effort not in EFFORTS: + raise Refusal("unknown effort", effort=effort, efforts=list(EFFORTS)) + + def build_fingerprint(self, *, binary, model, effort, cwd, agent, network, state, preamble_path, + mcp_config, env_pass): + """Design §4.1 plus `env_pass` and `network`; `fp_hash` over the final dict. `mcp_config` + and `agent` are not used on Codex (`check_init` refuses an agent).""" + if not os.path.isdir(cwd): + raise ValueError("cwd is not a directory: %s" % cwd) + if not os.path.isfile(preamble_path): + raise ValueError("preamble not found: %s" % preamble_path) + if not binary or not os.path.isfile(binary): + raise ValueError("codex binary not found: %s" % binary) + cwd, state, preamble_path = os.path.abspath(cwd), os.path.abspath(state), os.path.abspath(preamble_path) + fp = { + "harness": self.name, + "binary": os.path.abspath(binary), + "binary_version": self.binary_version(binary), + "model": model, + "effort": effort, + "sandbox": SANDBOX, + "network": bool(network), + "add_dirs": [] if _inside(state, cwd) else [state], + "cwd": cwd, + "ignore_user_config": True, + "config": ['model_reasoning_effort="%s"' % effort, 'web_search="disabled"', + "agents.enabled=false"], + "ephemeral_forks": True, + "codex_home": codex_home(), + "preamble": {"path": preamble_path, "sha256": launch._sha256_file(preamble_path), + "placement": "train_prompt"}, + "env_pass": sorted(env_pass or []), + } + return {"fingerprint": fp, "argv": _argv(fp), + "fp_hash": launch._sha256_bytes(launch.canonical_json(fp).encode("utf-8"))} + + def preflight(self, fp): + """Design §6.3: a nested `codex exec` must write `CODEX_HOME`. Create and remove one file + under `/tmp/` (`tmp/` made if missing; a missing home is refused, never + created). `init` passes its inputs, not the final fingerprint, so `codex_home` falls back + to the env, as `build_fingerprint` does.""" + home = fp.get("codex_home") or codex_home() + if not os.path.isdir(home): + raise Refusal("codex_home_missing", codex_home=home, remedy=MISSING_HOME_REMEDY) + tmp = os.path.join(home, "tmp") + try: + if not os.path.isdir(tmp): + os.mkdir(tmp) + fd, probe = tempfile.mkstemp(prefix=".spire-preflight-", dir=tmp) + os.close(fd) + os.remove(probe) + except OSError as e: + raise Refusal("codex_home_not_writable", codex_home=home, + detail="%s: %s" % (type(e).__name__, e.strerror or "write failed"), + remedy=PREFLIGHT_REMEDY % home) + + # per-call tails: the title is not in any Codex argv (it is line 1 of the train prompt) + def train_argv(self, run, sid, title): + return list(run["argv"]) + ["-"] + + def fork_argv(self, run, base_sid, sid, title): + return list(run["argv"]) + ["--ephemeral", "fork", base_sid, "-"] + + def resume_argv(self, run, base_sid, title): + return list(run["argv"]) + ["resume", base_sid, "-"] + + def train_prompt(self, state, title, rendered): + """No system-prompt file on Codex: the frozen preamble heads the train turn (design §4.3).""" + preamble = (Path(state) / "preamble.md").read_text(encoding="utf-8") + return title + "\n\n" + preamble + "\n\n---\n\n" + rendered + + def env(self, fp, environ=None): + return scrub.env_for("codex", fp, environ) + + def infer_ttl(self, tokens, prev): + return prev or CODEX_NOMINAL_TTL_S + + def new_stream(self, fp): + return stream.CodexStreamState(fp["model"]) + + def usage(self, ss, before_mu, cost_before): + return stream.codex_usage(ss.result, before_mu, cost_before) + + def cache_verdict(self, ss, u, base_ctx): + """None when the call produced no usage (a failed turn), as on Claude; else the turn-delta + estimate.""" + if not u or not isinstance((ss.result or {}).get("usage"), dict): + return None + return stream.codex_cache_verdict(u["tokens"], base_ctx) + + def context_tokens(self, fp, ss): + """(base context tokens, warnings) after a persisted call (train, rebase): the last + `token_count` `last_token_usage.input_tokens` of the thread's rollout (cached tokens are + part of it). 0 with a warning when none is found; `hit` is then never reported.""" + tid = ss.session_id + if not tid: + return 0, ["no thread id: base context unknown (0); spawns cannot report cache: hit"] + path = rollout_path(fp.get("codex_home") or codex_home(), tid) + n = _rollout_context(path) if path else None + if n is None: + what = "no rollout found" if path is None else "no token_count record in the rollout" + return 0, ["%s for thread %s: base context unknown (0); spawns cannot report cache: hit" + % (what, tid)] + return n, [] diff --git a/plugins/spire/skills/gremlins/grm/errors.py b/plugins/spire/skills/gremlins/grm/errors.py new file mode 100644 index 0000000..da7a579 --- /dev/null +++ b/plugins/spire/skills/gremlins/grm/errors.py @@ -0,0 +1,9 @@ +"""Exceptions shared across grm modules.""" + + +class Refusal(Exception): + """Refused before or instead of a launch: exit 2, payload printed as the JSON object.""" + + def __init__(self, error: str, **fields): + super().__init__(error) + self.payload = {"error": error, **fields} diff --git a/plugins/spire/skills/gremlins/grm/harness.py b/plugins/spire/skills/gremlins/grm/harness.py new file mode 100644 index 0000000..17551f7 --- /dev/null +++ b/plugins/spire/skills/gremlins/grm/harness.py @@ -0,0 +1,131 @@ +"""Harness selection and the adapter seam (design §2, §3): which CLI a run launches, and one +adapter per harness that the cli calls instead of `launch`/`stream` directly.""" +from pathlib import Path + +from grm import launch, scrub, stream +from grm.errors import Refusal + +HARNESSES = ("claude", "codex") +MARKERS = {"claude": lambda e: e.get("CLAUDECODE") == "1", + "codex": lambda e: bool(e.get("CODEX_THREAD_ID"))} +MARKER_NAMES = {"claude": "CLAUDECODE", "codex": "CODEX_THREAD_ID"} +CROSS_DETAIL = "running the other harness's gremlins is a later, explicit opt-in" + + +def _seen(environ) -> list[str]: + return [h for h in HARNESSES if MARKERS[h](environ)] + + +def detect(environ) -> str | None: + """'claude' or 'codex' when exactly one marker is set, else None (unclear).""" + seen = _seen(environ) + return seen[0] if len(seen) == 1 else None + + +def select(asked: str | None, environ) -> tuple[str, str | None]: + """(target harness, caller_harness or None) for `init` (plan §3.1).""" + if asked is not None and asked not in HARNESSES: + raise Refusal("unknown harness", asked=asked, harnesses=list(HARNESSES)) + d = detect(environ) + if d is not None: + if asked not in (None, d): + raise Refusal("cross_harness", detected=d, asked=asked, detail=CROSS_DETAIL) + return d, d + if asked is None: + raise Refusal("harness_unclear", markers=sorted(MARKER_NAMES[h] for h in _seen(environ)), + remedy="pass --harness claude|codex") + return asked, None + + +def run_harness(run: dict) -> str: + """The run's target harness; a run.json from before 0.4 (no `fingerprint.harness`) is claude.""" + return (run.get("fingerprint") or {}).get("harness") or "claude" + + +def check_caller(run: dict, environ) -> None: + """Launch-time check: a clear caller harness must be the run's; an unclear one passes.""" + d, target = detect(environ), run_harness(run) + if d is not None and d != target: + raise Refusal("cross_harness", detected=d, asked=target, detail=CROSS_DETAIL) + + +def named(name: str): + if name == "claude": + return ClaudeAdapter() + if name == "codex": + from grm import codex # lazy: codex.py never imports harness + return codex.CodexAdapter() + raise Refusal("unknown harness", asked=name, harnesses=list(HARNESSES)) + + +def of(run: dict): + return named(run_harness(run)) + + +def _rehash(fpd: dict, **extra) -> dict: + """fp_hash over the final fingerprint, after the adapter has added its fields.""" + fp = {**fpd["fingerprint"], **extra} + return {**fpd, "fingerprint": fp, + "fp_hash": launch._sha256_bytes(launch.canonical_json(fp).encode("utf-8"))} + + +class ClaudeAdapter: + """Wraps today's `launch` and `stream` functions unchanged.""" + name = binary_name = "claude" + preassigns_session_id = True + commit_line = "" + + def resolve_binary(self, explicit): + return launch.resolve_binary(explicit) + + def binary_version(self, path): + return launch.binary_version(path) + + def check_init(self, *, cwd, agent, network): + if network: + raise Refusal("Claude gremlins have no sandbox network switch", network=True) + + def check_model(self, model, effort): + if not launch.MODEL_RE.match(model or ""): + raise Refusal("model must be a full id (aliases are refused)", model=model) + if effort not in launch.EFFORTS: + raise Refusal("unknown effort", effort=effort, efforts=list(launch.EFFORTS)) + + def build_fingerprint(self, *, binary, model, effort, cwd, agent, network, state, preamble_path, + mcp_config, env_pass): + fpd = launch.build_fingerprint(binary=binary, model=model, effort=effort, cwd=cwd, agent=agent, + preamble_path=preamble_path, mcp_config=mcp_config) + return _rehash(fpd, harness=self.name, env_pass=sorted(env_pass or [])) + + def preflight(self, fp): + return None + + def train_argv(self, run, sid, title): + return launch.train_argv(run, sid, title) + + def fork_argv(self, run, base_sid, sid, title): + return launch.fork_argv(run, base_sid, sid, title) + + def resume_argv(self, run, base_sid, title): + return launch.resume_argv(run, base_sid, title) + + def train_prompt(self, state: Path, title, rendered): + return rendered # the preamble is the system prompt; the title is `--name` + + def env(self, fp, environ=None): + return scrub.env_for("claude", fp, environ) + + def new_stream(self, fp): + return stream.StreamState() + + def usage(self, ss, before_mu, cost_before): + return stream.usage_from_result(ss.result, before_mu, cost_before) + + def cache_verdict(self, ss, u, base_ctx): + return stream.cache_verdict(ss.first_usage, base_ctx) + + def context_tokens(self, fp, ss): + return stream.context_tokens(ss.last_usage), [] + + def infer_ttl(self, tokens, prev): + return stream.infer_ttl(tokens, prev) diff --git a/plugins/spire/skills/gremlins/grm/launch.py b/plugins/spire/skills/gremlins/grm/launch.py index c8f46c2..b8e4de7 100644 --- a/plugins/spire/skills/gremlins/grm/launch.py +++ b/plugins/spire/skills/gremlins/grm/launch.py @@ -1,11 +1,15 @@ -"""Launch fingerprint, env scrub, binary lookup and the `claude -p` argv (B1, B2, B7, B8).""" +"""Launch fingerprint, binary lookup and the `claude -p` argv (B1, B2, B7). The env scrub lives in +`scrub.py`; its names are re-exported here.""" import hashlib import json import os import re import shutil import subprocess -import sys + +from grm.scrub import ( # noqa: F401 re-exported + ENV_PINNED_LAUNCH, SCRUB_DROP, SCRUB_DROP_PATTERNS, SCRUB_KEEP, SCRUB_PINNED, SCRUB_PINNED_BINARY, + scrub_class, scrubbed_env) MODEL_RE = re.compile(r"^claude-[a-z0-9-]+(\[1m\])?$") EFFORTS = ("low", "medium", "high", "xhigh", "max") @@ -14,36 +18,6 @@ DEFAULT_TOOLS = ["Bash", "Read", "Edit", "Write", "Glob", "Grep", "Skill"] DEFAULT_DISALLOWED = ["Bash(git push:*)", "Bash(git rebase:*)", "Bash(git reset --hard:*)", "Bash(claude:*)"] -# Env pinned into every launch; part of the fingerprint. -ENV_PINNED_LAUNCH = {"CLAUDE_CODE_PROMPT_CACHE_TTL": "1h", "DISABLE_AUTOUPDATER": "1"} - -# Host env that must not reach a child `claude -p`. -SCRUB_DROP = frozenset({ - # Desktop host vars - "CLAUDE_CODE_MESSAGING_SOCKET", "CLAUDE_CODE_MESSAGING_TOKEN", "CLAUDE_CODE_HOST_SESSION_ID", - "CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_DESKTOP_APP_VERSION", - "CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH", "CLAUDE_CODE_TERMINAL_MCP_TOOLS", - "CLAUDE_CODE_REPORT_FINDINGS", "CLAUDE_CODE_SESSION_ID", "CLAUDE_AGENT_SDK_VERSION", - "CLAUDE_CODE_ENABLE_ASK_USER_QUESTION_TOOL", "CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING", - # Remote Control (`claude rc`) host vars; the BRIDGE_ and REMOTE_CONTROL_ prefixes are patterns - "CLAUDE_CODE_WORKER_EPOCH", "CLAUDE_CODE_SESSION_ATTENDED", "CLAUDE_CODE_ENVIRONMENT_KIND", - # fingerprint and auth path - "CLAUDE_EFFORT", "ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", - "ENABLE_PROMPT_CACHING_1H", "FORCE_PROMPT_CACHING_5M", "CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL", - "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", - # uv - "VIRTUAL_ENV", -}) -SCRUB_DROP_PATTERNS = (re.compile(r"^ANTHROPIC_DEFAULT_.+_MODEL$"), re.compile(r"^UV_"), - re.compile(r"^CLAUDE_CODE_BRIDGE_"), re.compile(r"^CLAUDE_REMOTE_CONTROL_")) -SCRUB_KEEP = frozenset({ - "CLAUDECODE", "CLAUDE_CODE_CHILD_SESSION", "AI_AGENT", "CLAUDE_PID", "CLAUDE_CODE_GIT_BASH_PATH", - "PATH", "HOME", "USERPROFILE", - "ANTHROPIC_BASE_URL", # kept: gateways need it -}) -SCRUB_PINNED = ENV_PINNED_LAUNCH -SCRUB_PINNED_BINARY = "CLAUDE_CODE_EXECPATH" # set to the stored absolute binary path - def canonical_json(obj) -> str: return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True) @@ -58,54 +32,6 @@ def _sha256_file(path: str) -> str: return _sha256_bytes(f.read()) -def scrub_class(name: str) -> str | None: - """'drop', 'pinned', 'keep' or None (on no list; kept).""" - n = name.upper() - if n in SCRUB_DROP or any(p.match(n) for p in SCRUB_DROP_PATTERNS): - return "drop" - if n in SCRUB_PINNED or n == SCRUB_PINNED_BINARY: - return "pinned" - if n in SCRUB_KEEP: - return "keep" - return None - - -def _venv_prefixes(environ) -> list[str]: - out = [] - venv = environ.get("VIRTUAL_ENV") - if venv: - out.append(venv) - if os.path.normcase(os.path.abspath(sys.prefix)) != os.path.normcase(os.path.abspath(sys.base_prefix)): - out.append(sys.prefix) - return [os.path.normcase(os.path.normpath(os.path.abspath(x))) for x in out] - - -def _under(path: str, prefixes) -> bool: - try: - p = os.path.normcase(os.path.normpath(os.path.abspath(path))) - except ValueError: - return False - return any(p == px or p.startswith(px.rstrip("\\/") + os.sep) for px in prefixes) - - -def scrubbed_env(binary: str, environ=None) -> dict: - """The child env: host env minus the drop list, venv PATH entries removed, pinned vars on - top, `CLAUDE_CODE_EXECPATH` = the stored binary path.""" - if environ is None: - environ = os.environ - prefixes = _venv_prefixes(environ) - env = {} - for k, v in environ.items(): - if scrub_class(k) in ("drop", "pinned"): - continue - if k.upper() == "PATH": - v = os.pathsep.join(e for e in v.split(os.pathsep) if e and not _under(e, prefixes)) - env[k] = v - env.update(SCRUB_PINNED) - env[SCRUB_PINNED_BINARY] = binary - return env - - def resolve_binary(explicit: str | None = None) -> str | None: """Absolute path of `claude`: `explicit`, else $CLAUDE_CODE_EXECPATH, else PATH.""" path = explicit or os.environ.get("CLAUDE_CODE_EXECPATH") or shutil.which("claude") @@ -172,14 +98,20 @@ def build_fingerprint(*, binary, model, effort, cwd, agent, preamble_path, mcp_c "fp_hash": _sha256_bytes(canonical_json(fp).encode("utf-8"))} -def train_argv(run: dict, sid: str) -> list[str]: - return list(run["argv"]) + ["--session-id", sid] +def _name(title) -> list[str]: + """`--name `: a per-call flag, never in the stored argv (design §5.2).""" + return ["--name", title] if title else [] -def fork_argv(run: dict, base_sid: str, sid: str) -> list[str]: - return list(run["argv"]) + ["--resume", base_sid, "--fork-session", "--session-id", sid] +def train_argv(run: dict, sid: str, title=None) -> list[str]: + return list(run["argv"]) + ["--session-id", sid] + _name(title) -def resume_argv(run: dict, base_sid: str) -> list[str]: - """No `--session-id`: claude refuses it on a resume without a fork.""" - return list(run["argv"]) + ["--resume", base_sid] +def fork_argv(run: dict, base_sid: str, sid: str, title=None) -> list[str]: + return list(run["argv"]) + ["--resume", base_sid, "--fork-session", "--session-id", sid] + _name(title) + + +def resume_argv(run: dict, base_sid: str, title=None) -> list[str]: + """No `--session-id`: claude refuses it on a resume without a fork. `--name` goes before + `--resume`, so the argv still ends in `--resume <base>`.""" + return list(run["argv"]) + _name(title) + ["--resume", base_sid] diff --git a/plugins/spire/skills/gremlins/grm/scrub.py b/plugins/spire/skills/gremlins/grm/scrub.py new file mode 100644 index 0000000..67d6eb3 --- /dev/null +++ b/plugins/spire/skills/gremlins/grm/scrub.py @@ -0,0 +1,200 @@ +"""Child env per target harness (design §6.1, build plan §3.1): pure table logic. + +For each name (compared upper-case) the first rule that matches decides: +1 pinned (host value dropped, pinned value set at the end); 2 harness rows; 2b Claude target +only: any other `CLAUDE_CODE_*` is kept; 3 never secret-shaped; 4 `env_pass`; 5 secret-shaped +names are dropped; 6 everything else is kept. Then venv entries leave `PATH` (both targets). +Names only ever leave this module: no env value is printed, logged or stored.""" +import os +import re +import sys + +from grm.errors import Refusal + +TARGETS = ("claude", "codex") + +# Env pinned into every Claude launch; part of the Claude fingerprint. +ENV_PINNED_LAUNCH = {"CLAUDE_CODE_PROMPT_CACHE_TTL": "1h", "DISABLE_AUTOUPDATER": "1"} +SCRUB_PINNED = ENV_PINNED_LAUNCH +SCRUB_PINNED_BINARY = "CLAUDE_CODE_EXECPATH" # set to the stored absolute binary path +CODEX_PINNED_HOME = "CODEX_HOME" # set to fp["codex_home"] on the Codex target + +# Claude host and session vars (both targets drop them) +CLAUDE_HOST = frozenset({ + # Desktop host vars + "CLAUDE_CODE_MESSAGING_SOCKET", "CLAUDE_CODE_MESSAGING_TOKEN", "CLAUDE_CODE_HOST_SESSION_ID", + "CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_DESKTOP_APP_VERSION", + "CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH", "CLAUDE_CODE_TERMINAL_MCP_TOOLS", + "CLAUDE_CODE_REPORT_FINDINGS", "CLAUDE_CODE_SESSION_ID", "CLAUDE_AGENT_SDK_VERSION", + "CLAUDE_CODE_ENABLE_ASK_USER_QUESTION_TOOL", "CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING", + # Remote Control (`claude rc`) host vars; the BRIDGE_ and REMOTE_CONTROL_ prefixes are patterns + "CLAUDE_CODE_WORKER_EPOCH", "CLAUDE_CODE_SESSION_ATTENDED", "CLAUDE_CODE_ENVIRONMENT_KIND", + # fingerprint + "CLAUDE_EFFORT", "ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", + "ENABLE_PROMPT_CACHING_1H", "FORCE_PROMPT_CACHING_5M", "CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL", +}) +CLAUDE_HOST_PATTERNS = (re.compile(r"^ANTHROPIC_DEFAULT_.+_MODEL$"), re.compile(r"^CLAUDE_CODE_BRIDGE_"), + re.compile(r"^CLAUDE_REMOTE_CONTROL_")) +CLAUDE_MARKERS = frozenset({"CLAUDECODE", "CLAUDE_CODE_CHILD_SESSION", "CLAUDE_PID", "AI_AGENT", + "CLAUDE_CODE_GIT_BASH_PATH"}) +ANTHROPIC_AUTH = frozenset({"ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", + "CLAUDE_CODE_USE_VERTEX"}) +ANTHROPIC_GATEWAY = frozenset({"ANTHROPIC_BASE_URL", "CLAUDE_CODE_OAUTH_TOKEN"}) +CODEX_TARGET_KEEP = frozenset({"CODEX_HOME", "CODEX_SQLITE_HOME", "CODEX_CA_CERTIFICATE"}) +OPENAI_AUTH = frozenset({"OPENAI_API_KEY", "CODEX_API_KEY", "OPENAI_ORGANIZATION", "OPENAI_PROJECT", + "OPENAI_IDENTITY_TOKEN_FILE", "OPENAI_FEDERATION_RULE_ID", + "OPENAI_WORKLOAD_IDENTITY_CONTEXT"}) +OPENAI_GATEWAY = frozenset({"OPENAI_BASE_URL", "CODEX_ACCESS_TOKEN"}) +UV_NAMES = frozenset({"VIRTUAL_ENV"}) + +# 0.3.x names, kept importable (also from `launch`): what the Claude target drops and keeps. +SCRUB_DROP = CLAUDE_HOST | ANTHROPIC_AUTH | UV_NAMES +SCRUB_DROP_PATTERNS = CLAUDE_HOST_PATTERNS + (re.compile(r"^UV_"),) +SCRUB_KEEP = CLAUDE_MARKERS | ANTHROPIC_GATEWAY | frozenset({"PATH", "HOME", "USERPROFILE"}) + +NEVER_SECRET = frozenset({"SSH_AUTH_SOCK", "GPG_AGENT_INFO", "PATH", "HOME", "USERPROFILE"}) +SECRET_PARTS = frozenset({"TOKEN", "TOKENS", "SECRET", "SECRETS", "PASSWORD", "PASSWD", "APIKEY", + "CREDENTIAL", "CREDENTIALS"}) +SECRET_PAIRS = frozenset({("API", "KEY"), ("ACCESS", "KEY"), ("PRIVATE", "KEY")}) +ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") + + +def _in(names, *patterns): + return lambda n: n in names or any(p.match(n) for p in patterns) + + +# Rule 2, in order; the first row that matches decides: (matches, claude action, codex action). +_ROWS = ( + (_in(OPENAI_GATEWAY), "drop", "keep"), # before the ^CODEX_ row + (_in(OPENAI_AUTH, re.compile(r"^OPENAI_SPIFFE_")), "drop", "drop"), + (_in(CODEX_TARGET_KEEP), "drop", "keep"), + (_in(frozenset(), re.compile(r"^CODEX_")), "drop", "drop"), + (_in(CLAUDE_HOST, *CLAUDE_HOST_PATTERNS), "drop", "drop"), + (_in(ANTHROPIC_AUTH), "drop", "drop"), + (_in(ANTHROPIC_GATEWAY), "keep", "drop"), + (_in(CLAUDE_MARKERS), "keep", "drop"), + (_in(UV_NAMES, re.compile(r"^UV_")), "drop", "drop"), + (_in(frozenset(), re.compile(r"^CLAUDE"), re.compile(r"^ANTHROPIC_")), None, "drop"), +) + + +def _target(target: str) -> str: + if target not in TARGETS: + raise ValueError("unknown harness %r (one of %s)" % (target, ", ".join(TARGETS))) + return target + + +def _pinned(target: str) -> frozenset: + if target == "claude": + return frozenset(SCRUB_PINNED) | {SCRUB_PINNED_BINARY} + return frozenset({CODEX_PINNED_HOME}) + + +def secret_shaped(name: str) -> bool: + """Whole `_` parts: a secret word, a `<API|ACCESS|PRIVATE> KEY` pair, or a last part `KEY`. + `TOKENIZERS_PARALLELISM` is not secret-shaped.""" + parts = name.upper().split("_") + if any(p in SECRET_PARTS for p in parts) or parts[-1] == "KEY": + return True + return any(pair in SECRET_PAIRS for pair in zip(parts, parts[1:])) + + +def decide(target: str, name: str, env_pass=()) -> tuple[str, str]: + """(action, rule) for one name: action 'pinned', 'drop' or 'keep'; rule '1', '2', '2b', '3', + '4', '5' or '6'.""" + n = name.upper() + if n in _pinned(_target(target)): + return "pinned", "1" + col = 1 if target == "claude" else 2 + for row in _ROWS: + if row[0](n) and row[col] is not None: + return row[col], "2" + if target == "claude" and n.startswith("CLAUDE_CODE_"): + return "keep", "2b" + if n in NEVER_SECRET: + return "keep", "3" + if n in {p.upper() for p in env_pass}: + return "keep", "4" + if secret_shaped(n): + return "drop", "5" + return "keep", "6" + + +def scrub_class(name: str, target: str = "claude") -> str | None: + """'drop', 'pinned', 'keep' (a listed keep) or None (on no list; kept), without env_pass.""" + action, rule = decide(target, name) + return None if rule == "6" else action + + +def _venv_prefixes(environ) -> list[str]: + out = [] + venv = environ.get("VIRTUAL_ENV") + if venv: + out.append(venv) + if os.path.normcase(os.path.abspath(sys.prefix)) != os.path.normcase(os.path.abspath(sys.base_prefix)): + out.append(sys.prefix) + return [os.path.normcase(os.path.normpath(os.path.abspath(x))) for x in out] + + +def _under(path: str, prefixes) -> bool: + try: + p = os.path.normcase(os.path.normpath(os.path.abspath(path))) + except ValueError: + return False + return any(p == px or p.startswith(px.rstrip("\\/") + os.sep) for px in prefixes) + + +def env_for(target: str, fp: dict, environ=None) -> dict: + """The child env for `target`. `fp`: "binary" (Claude), "codex_home" (Codex), "env_pass" + (default []).""" + _target(target) + if environ is None: + environ = os.environ + env_pass = fp.get("env_pass") or [] + prefixes = _venv_prefixes(environ) + env = {} + for k, v in environ.items(): + if decide(target, k, env_pass)[0] != "keep": + continue + if k.upper() == "PATH": + v = os.pathsep.join(e for e in v.split(os.pathsep) if e and not _under(e, prefixes)) + env[k] = v + if target == "claude": + env.update(SCRUB_PINNED) + env[SCRUB_PINNED_BINARY] = fp["binary"] + else: + env[CODEX_PINNED_HOME] = fp["codex_home"] + return env + + +def env_dropped(target: str, environ, env_pass) -> list[str]: + """Sorted names that rules 2 and 5 drop from `environ` (pinned names are replaced, not + dropped). Names only, never values.""" + return sorted(k for k in environ if decide(target, k, env_pass or [])[0] == "drop") + + +def check_pass_env(names, environ=None) -> list[str]: + """Sorted, deduplicated `--pass-env` names. Refuses, in this order: + - an argument equal to the value of a variable in `environ` (when given) that is not itself + a set name: `--pass-env "$TOKEN"` passed the value; no `name` field, nothing echoed; + - `NAME=VALUE`, naming only the part before the first `=`; + - an invalid env name, by its position (`index`) only: the argument may be a value; + - a name that rule 1, 2 or 2b decides on either target (it belongs to a harness).""" + values = {v for v in (environ or {}).values() if v} + for i, name in enumerate(names): + if name in values and name not in (environ or {}): + raise Refusal("pass_env_refused", index=i, + detail="that looks like a value, not a variable name") + if "=" in (name or ""): + raise Refusal("pass_env_refused", name=name.split("=", 1)[0], + detail="pass names only, not NAME=VALUE") + if not ENV_NAME_RE.match(name or ""): + raise Refusal("pass_env_refused", index=i, detail="not a valid environment variable name") + if any(decide(t, name)[1] in ("1", "2", "2b") for t in TARGETS): + raise Refusal("pass_env_refused", name=name, detail="that variable belongs to a harness") + return sorted(set(names)) + + +def scrubbed_env(binary: str, environ=None) -> dict: + """0.3.x entry point: the Claude target with no env_pass.""" + return env_for("claude", {"binary": binary}, environ) diff --git a/plugins/spire/skills/gremlins/grm/stream.py b/plugins/spire/skills/gremlins/grm/stream.py index 27c3aea..a4df108 100644 --- a/plugins/spire/skills/gremlins/grm/stream.py +++ b/plugins/spire/skills/gremlins/grm/stream.py @@ -1,4 +1,5 @@ -"""Stream-json reader and accounting for one `claude -p` call: pure functions, no IO.""" +"""Stream readers and accounting for one `claude -p` or `codex exec --json` call: pure +functions, no IO (the Codex rollout reader lives in `codex.py`).""" import datetime as _dt import json import re @@ -173,6 +174,96 @@ def infer_ttl(tokens: dict | None, prev): return prev +class CodexStreamState: + """What one `codex exec --json` stream told us so far; the same attributes as StreamState, so + `classify` and the cli read it unchanged (design §3.3). `first_usage`/`last_usage` are not + used on Codex (the verdict comes from the turn delta).""" + + def __init__(self, model: str): + self.model = model + self.session_id = None + self.first_usage = None + self.first_at = None # first item.* event: the base prefix was read + self.last_usage = None # the last turn.completed usage (running totals) + self.last_assistant_at = None + self.last_text = None # the last agent_message + self.result = None + + def feed(self, ev: dict, t: float | None) -> None: + if not isinstance(ev, dict): + return + ty = ev.get("type") + if not isinstance(ty, str): + return + if ty == "thread.started": + if self.session_id is None: + self.session_id = ev.get("thread_id") + elif ty.startswith("item."): + if self.first_at is None: + self.first_at = t + item = ev.get("item") or {} + if ty == "item.completed" and isinstance(item, dict) and item.get("type") == "agent_message": + self.last_text = item.get("text") + elif ty == "turn.completed": + usage = ev.get("usage") if isinstance(ev.get("usage"), dict) else {} + self.last_usage, self.last_assistant_at = usage, t + self.result = {"type": "result", "is_error": False, "session_id": self.session_id, + "result": self.last_text, "usage": usage, + "modelUsage": {self.model: codex_model_usage(usage)}, "total_cost_usd": None} + if self.session_id is None: # a base without an id would make every fork `fork None` + self.result.update(is_error=True, result="no thread.started event") + elif ty in ("turn.failed", "error"): + err = ev.get("error") if ty == "turn.failed" else ev + msg = err.get("message") if isinstance(err, dict) else None + self.result = {"type": "result", "is_error": True, "session_id": self.session_id, + "result": msg if isinstance(msg, str) and msg else ty, "usage": None, + "modelUsage": {}, "total_cost_usd": None} + + +def codex_model_usage(usage: dict | None) -> dict: + """Codex running totals in Claude's `modelUsage` keys; cached input is a subset of input.""" + usage = usage or {} + inp, cached = int(usage.get("input_tokens") or 0), int(usage.get("cached_input_tokens") or 0) + return {"inputTokens": inp - cached, "outputTokens": int(usage.get("output_tokens") or 0), + "cacheReadInputTokens": cached, + "cacheCreationInputTokens": int(usage.get("cache_write_input_tokens") or 0)} + + +def codex_usage(result: dict, before_mu: dict | None, cost_before) -> dict: + """`usage_from_result`'s shape from a Codex result. `turn.completed.usage` is the thread's + running total, base included, so `tokens` = mapped totals minus `before_mu` (None for train: + the whole total counts). No 1h/5m split and no cost on Codex. A result without usage (a + failed turn) gives zero tokens and no model usage.""" + result = result or {} + after = result.get("modelUsage") if isinstance(result.get("usage"), dict) else None + after = after or {} + before_mu = before_mu or {} + delta = {} + for m, v in after.items(): + b = before_mu.get(m) or {} + delta[m] = {f: int((v or {}).get(f) or 0) - int(b.get(f) or 0) for f in MU_FIELDS} + tot = {f: sum(d[f] for d in delta.values()) for f in MU_FIELDS} + tokens = {"input": tot["inputTokens"], "output": tot["outputTokens"], + "cache_creation": tot["cacheCreationInputTokens"], "cache_read": tot["cacheReadInputTokens"], + "cache_creation_1h": 0, "cache_creation_5m": 0} + grew = [m for m, d in delta.items() if any(x > 0 for x in d.values())] + models_used = sorted(grew, key=lambda m: (-sum(delta[m].values()), m)) + return {"tokens": tokens, "models_used": models_used, "cost_delta": None, "total": None, + "model_usage": after} + + +def codex_cache_verdict(tokens: dict | None, base_ctx) -> str | None: + """An estimate from the turn delta (ephemeral forks write no rollout): `hit` when the call + read at least 0.9 of the base context from cache and its uncached input stayed under half of + it; `partial` on any cache read; else `miss`. A large fork reads `partial`.""" + if tokens is None: + return None + cr, inp = int(tokens.get("cache_read") or 0), int(tokens.get("input") or 0) + if base_ctx and cr >= CACHE_HIT_RATIO * float(base_ctx) and inp < 0.5 * float(base_ctx): + return "hit" + return "partial" if cr > 0 else "miss" + + def warmth(last_hit_ts: float | None, ttl_s, now: float) -> dict: """warm until `margin` before last_hit + ttl, expiring until last_hit + ttl, then cold; margin = max(120, ttl/10). No hit at all is cold.""" diff --git a/plugins/spire/skills/gremlins/grm/title.py b/plugins/spire/skills/gremlins/grm/title.py new file mode 100644 index 0000000..c7f9919 --- /dev/null +++ b/plugins/spire/skills/gremlins/grm/title.py @@ -0,0 +1,24 @@ +"""Session titles for the calls grm launches: `<emoji> B1 › <job> · <build> · MM-DD HH:MM`.""" +import re +import time + +from grm import store + +TITLE_EMOJI = "🐾" # placeholder; the only emoji literal in grm/ +_DATE_PREFIX = re.compile(r"^\d{4}-\d{2}-\d{2}-(\d{2}-)?") +_BUILD_CHARS = 40 + + +def make(kind: str, base: str, job: str, run_md, t: float | None = None) -> str: + """Title of one call. `kind` is train, spawn or rebase (for rebase `job` is the rebase number).""" + if kind == "train": + head = "%s %s" % (TITLE_EMOJI, base) + elif kind == "spawn": + head = "%s %s \u203a %s" % (TITLE_EMOJI, base, job) + elif kind == "rebase": + head = "%s %s \u203a rebase %s" % (TITLE_EMOJI, base, job) + else: + raise ValueError("unknown title kind: %r" % (kind,)) + build = _DATE_PREFIX.sub("", store.run_slug(run_md))[:_BUILD_CHARS] + when = time.strftime("%m-%d %H:%M", time.localtime(time.time() if t is None else t)) + return "%s \u00b7 %s \u00b7 %s" % (head, build, when) diff --git a/plugins/spire/skills/gremlins/tests/_pin.py b/plugins/spire/skills/gremlins/tests/_pin.py new file mode 100644 index 0000000..8634e97 --- /dev/null +++ b/plugins/spire/skills/gremlins/tests/_pin.py @@ -0,0 +1,30 @@ +"""Pin the caller's harness markers and `CODEX_HOME` for a test, so no test depends on the host's +env (this suite usually runs inside a Claude Code Bash, with a real `~/.codex`).""" +import os +import shutil +import tempfile +from unittest import mock + +MARKERS = {"claude": {"CLAUDECODE": "1"}, "codex": {"CODEX_THREAD_ID": "pinned-thread"}, + "both": {"CLAUDECODE": "1", "CODEX_THREAD_ID": "pinned-thread"}, None: {}} + + +def pinned(environ, harness, codex_home) -> dict: + """A copy of `environ` with only `harness`'s markers (None: no marker; "both": both) and + `CODEX_HOME` = `codex_home`.""" + env = {k: v for k, v in environ.items() if k not in ("CLAUDECODE", "CODEX_THREAD_ID")} + env.update(MARKERS[harness]) + env["CODEX_HOME"] = str(codex_home) + return env + + +def pin_caller(test, harness, codex_home=None) -> str: + """Patch os.environ for `test` (undone at cleanup); returns the pinned `CODEX_HOME`, a fresh + temp dir unless given.""" + if codex_home is None: + codex_home = tempfile.mkdtemp(prefix="codex-home-") + test.addCleanup(shutil.rmtree, codex_home, True) + patch = mock.patch.dict(os.environ, pinned(os.environ, harness, codex_home), clear=True) + patch.start() + test.addCleanup(patch.stop) + return str(codex_home) diff --git a/plugins/spire/skills/gremlins/tests/fake_claude.py b/plugins/spire/skills/gremlins/tests/fake_claude.py index 401a9f8..406b429 100644 --- a/plugins/spire/skills/gremlins/tests/fake_claude.py +++ b/plugins/spire/skills/gremlins/tests/fake_claude.py @@ -1,5 +1,6 @@ """Fake `claude -p` for the CLI tests. $FAKE_CLAUDE_SCENARIO: ok (default), miss, api_error, -noresult, two_models, no_cost, sleep. $FAKE_CLAUDE_LOG: one JSON line per call (argv, pid).""" +noresult, two_models, no_cost, sleep. $FAKE_CLAUDE_LOG: one JSON line per call (argv, pid, +prompt_chars, sorted env names; never values).""" import json import os import sys @@ -24,7 +25,8 @@ def main(): scen = os.environ.get("FAKE_CLAUDE_SCENARIO", "ok") if os.environ.get("FAKE_CLAUDE_LOG"): with open(os.environ["FAKE_CLAUDE_LOG"], "a", encoding="utf-8") as f: - f.write(json.dumps({"argv": sys.argv, "pid": os.getpid(), "prompt_chars": len(prompt)}) + "\n") + f.write(json.dumps({"argv": sys.argv, "pid": os.getpid(), "prompt_chars": len(prompt), + "env_names": sorted(os.environ)}) + "\n") # names, never values resume, model = opt("--resume"), opt("--model") # a plain resume (no fork, no --session-id) gets a new id, as `-p` may give one sid = opt("--session-id") or ("resumed-" + uuid.uuid4().hex if resume else str(uuid.uuid4())) diff --git a/plugins/spire/skills/gremlins/tests/fake_codex.py b/plugins/spire/skills/gremlins/tests/fake_codex.py new file mode 100644 index 0000000..323c521 --- /dev/null +++ b/plugins/spire/skills/gremlins/tests/fake_codex.py @@ -0,0 +1,203 @@ +"""Fake `codex exec --json` for the CLI tests (design §9.1), modelled on fake_claude.py. + +Argv: `--version` prints `codex-cli 0.172.0`. Otherwise `exec`, options, then an optional +`fork <id>` or `resume <id>`, then the prompt (`-` reads stdin). `fork` without a prompt exits 2. + +State lives in the fake home `$CODEX_HOME`: `fake_threads.json` (running totals and context per +thread id) and rollouts `sessions/2026/11/24/rollout-<ts>-<id>.jsonl` for train, resume and +persisted forks. An `--ephemeral` fork writes nothing. + +Cache model: every first request reads the generic GENERIC tokens from cache. An ephemeral fork, +or a resume of a known thread, also reads the thread's last request input (the base context). A +persisted fork reads only the generic prefix (as measured, research §4). + +$FAKE_CODEX_SCENARIO: ok (default), miss (an ephemeral fork or resume reads only the generic +prefix), turn_failed, usage_limit (`error` + `turn.failed`, exit 1), noresult (exit 1 after +`thread.started`), sleep, ro_home (stderr "Read-only file system (os error 30)", exit 1, no +events), no_thread (`turn.completed` without `thread.started`), no_rollout (as ok, but no +rollout file is written; the thread state is kept). +$FAKE_CODEX_LOG: one JSON line per call: argv, pid, prompt_chars, prompt_head (200 chars) and +the sorted env names (never values).""" +import json +import os +import sys +import time +import uuid + +VERSION = "codex-cli 0.172.0" +GENERIC = 100 # the generic Codex prefix every fresh request reads from cache +TRAIN_TOKENS = 1000 # the train prompt's own tokens +CALL_TOKENS = 50 # a fork's or resume's new prompt tokens +OUTPUT_TOKENS = 20 +VALUE_OPTS = {"-m", "--model", "-C", "--cd", "-s", "--sandbox", "--add-dir", "-c", "--config", + "-p", "--profile", "-o", "--output-last-message", "--color"} +USAGE_KEYS = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens") + + +def emit(ev): + print(json.dumps(ev), flush=True) + + +def fail(msg, code): + sys.stderr.write(msg + "\n") + sys.stderr.flush() + sys.exit(code) + + +def parse(args): + """(options, flags, positionals) of the args after `exec`.""" + opts, flags, pos = {}, set(), [] + i = 0 + while i < len(args): + a = args[i] + if a in VALUE_OPTS: + if i + 1 >= len(args): + fail("error: %s needs a value" % a, 2) + opts.setdefault(a, []).append(args[i + 1]) + i += 2 + continue + if a.startswith("-") and a != "-": + flags.add(a) + else: + pos.append(a) + i += 1 + return opts, flags, pos + + +def home() -> str: + h = os.environ.get("CODEX_HOME") + if not h: + fail("fake_codex: CODEX_HOME must be set by the test", 3) + return h + + +def load_threads() -> dict: + try: + with open(os.path.join(home(), "fake_threads.json"), "r", encoding="utf-8") as f: + return json.load(f) + except FileNotFoundError: + return {} + + +def save_threads(threads: dict) -> None: + path = os.path.join(home(), "fake_threads.json") + tmp = "%s.%d.tmp" % (path, os.getpid()) + with open(tmp, "w", encoding="utf-8") as f: + json.dump(threads, f) + os.replace(tmp, path) + + +def new_thread_id() -> str: + """UUIDv7-like: a time-ordered head, a random tail.""" + h = "%012x" % (int(time.time() * 1000) & 0xFFFFFFFFFFFF) + uuid.uuid4().hex[12:] + h = h[:12] + "7" + h[13:] + return "%s-%s-%s-%s-%s" % (h[:8], h[8:12], h[12:16], h[16:20], h[20:32]) + + +def rollout_dir() -> str: + d = os.path.join(home(), "sessions", "2026", "11", "24") + os.makedirs(d, exist_ok=True) + return d + + +def rollout_for(tid: str) -> str: + """The thread's rollout path (an existing one for a resume).""" + d = rollout_dir() + for name in sorted(os.listdir(d)): + if name.endswith("-%s.jsonl" % tid): + return os.path.join(d, name) + ts = time.strftime("%Y-%m-%dT%H-%M-%S") + return os.path.join(d, "rollout-%s-%s.jsonl" % (ts, tid)) + + +def write_rollout(tid: str, request: dict, totals: dict, meta: dict | None) -> None: + lines = [] + if meta is not None: + lines.append({"type": "session_meta", "payload": meta}) + lines.append({"type": "event_msg", "payload": {"type": "token_count", "info": None}}) + lines.append({"type": "response_item", "payload": {"type": "message", "role": "assistant"}}) + lines.append({"type": "event_msg", "payload": {"type": "token_count", "info": { + "last_token_usage": dict(request, reasoning_output_tokens=0, + total_tokens=request["input_tokens"] + request["output_tokens"]), + "total_token_usage": dict(totals), "model_context_window": 200000}}}) + with open(rollout_for(tid), "a", encoding="utf-8") as f: + for ln in lines: + f.write(json.dumps(ln) + "\n") + + +def main(): + argv = sys.argv[1:] + if argv[:1] == ["--version"]: + print(VERSION) + return + if not argv or argv[0] != "exec": + fail("fake_codex: only `exec` is faked", 2) + opts, flags, pos = parse(argv[1:]) + sub = pos[0] if pos and pos[0] in ("fork", "resume") else None + ref = pos[1] if sub and len(pos) > 1 else None + rest = pos[2:] if sub else pos + if sub and ref is None: + fail("error: %s needs a session id" % sub, 2) + if not rest: + fail("error: a prompt is required here (ForkOnly is not faked)", 2) + prompt = sys.stdin.buffer.read().decode("utf-8") if rest[0] == "-" else rest[0] + scen = os.environ.get("FAKE_CODEX_SCENARIO", "ok") + if os.environ.get("FAKE_CODEX_LOG"): + with open(os.environ["FAKE_CODEX_LOG"], "a", encoding="utf-8") as f: + f.write(json.dumps({"argv": sys.argv, "pid": os.getpid(), "prompt_chars": len(prompt), + "prompt_head": prompt[:200], + "env_names": sorted(os.environ)}) + "\n") # names, never values + if scen == "ro_home": + fail("WARNING: proceeding, even though we could not create PATH aliases: Read-only file " + "system (os error 30)\nError: failed to initialize in-process app-server client: " + "Read-only file system (os error 30)", 1) + if "-m" not in opts and "--model" not in opts: + fail("fake_codex: the stored argv always passes -m", 2) + ephemeral = "--ephemeral" in flags + threads = load_threads() + base = None + if sub: + base = threads.get(ref) + if base is None: + fail("Error: thread/session not found: %s" % ref, 1) + # this call's single request and the thread's running totals after it + if base is None: # train: a fresh thread + cached, inp = GENERIC, GENERIC + TRAIN_TOKENS + before = {k: 0 for k in USAGE_KEYS} + else: + reads_base = (ephemeral or sub == "resume") and scen != "miss" + cached = base["last_input"] if reads_base else GENERIC + inp = base["ctx"] + CALL_TOKENS + before = base["totals"] + request = {"input_tokens": inp, "cached_input_tokens": cached, "cache_write_input_tokens": 0, + "output_tokens": OUTPUT_TOKENS} + totals = {k: int(before.get(k) or 0) + request[k] for k in USAGE_KEYS} + tid = ref if sub == "resume" else new_thread_id() + + if scen != "no_thread": + emit({"type": "thread.started", "thread_id": tid}) + emit({"type": "turn.started"}) + if scen == "noresult": + sys.exit(1) + if scen in ("turn_failed", "usage_limit"): + msg = ("You've hit your usage limit. Try again later." if scen == "usage_limit" + else "stream disconnected before completion") + if scen == "usage_limit": + emit({"type": "error", "message": msg}) + emit({"type": "turn.failed", "error": {"message": msg}}) + sys.exit(1) + emit({"type": "item.completed", "item": {"id": "item_0", "type": "agent_message", "text": "reading"}}) + if scen == "sleep": + time.sleep(60) + emit({"type": "item.completed", "item": {"id": "item_1", "type": "agent_message", "text": "done"}}) + if scen != "no_thread" and not ephemeral: # persisted: train, resume, persisted fork + meta = None if sub == "resume" else {"id": tid, "forked_from_id": ref} + if scen != "no_rollout": + write_rollout(tid, request, totals, meta) + threads[tid] = {"totals": totals, "last_input": inp, "ctx": inp + OUTPUT_TOKENS} + save_threads(threads) + emit({"type": "turn.completed", "usage": totals}) + + +if __name__ == "__main__": + main() diff --git a/plugins/spire/skills/gremlins/tests/test_cli.py b/plugins/spire/skills/gremlins/tests/test_cli.py index 9fead13..5b1969c 100644 --- a/plugins/spire/skills/gremlins/tests/test_cli.py +++ b/plugins/spire/skills/gremlins/tests/test_cli.py @@ -15,8 +15,10 @@ from unittest import mock SKILL = Path(__file__).resolve().parent.parent sys.path.insert(0, str(SKILL)) +sys.path.insert(0, str(SKILL / "tests")) from grm import cli # noqa: E402 +from _pin import pin_caller, pinned # noqa: E402 FAKE = str(SKILL / "tests" / "fake_claude.py") MODEL = "claude-opus-5-5" @@ -40,6 +42,7 @@ class CliTest(unittest.TestCase): "SPIRE_SCRATCH": str(self.tmp / "scratch")}) env.start() self.addCleanup(env.stop) + pin_caller(self, "claude") # D4: a Claude caller, whatever the host shell is code, out = self.g("init", "--run", self.run_md, "--model", MODEL, "--cwd", str(repo), "--binary", sys.executable) self.assertEqual(code, 0, out) run = json.loads((self.state / "run.json").read_text(encoding="utf-8")) @@ -80,9 +83,10 @@ class CliTest(unittest.TestCase): """B1, B2, B5: base keeps the --session-id; fork argv = stored argv + resume/fork; ledger.""" code, out = self.train() self.assertEqual((code, out["status"]), (0, "ok")) - sid = self.calls()[0]["argv"][-1] + sid = self.calls()[0]["argv"][-3] + t = json.loads((self.state / "jobs" / "B1-train.json").read_text(encoding="utf-8"))["title"] # the fake logs its sys.argv: the stored argv without the interpreter - self.assertEqual(self.calls()[0]["argv"], self.stored[1:] + ["--session-id", sid]) + self.assertEqual(self.calls()[0]["argv"], self.stored[1:] + ["--session-id", sid, "--name", t]) self.assertEqual(self.base_rec()["session_id"], sid) code, out = self.spawn("1.1") self.assertEqual((code, out["status"], out["cache"]), (0, "ok", "hit")) @@ -257,13 +261,14 @@ class RunDirLaterTest(unittest.TestCase): repo.mkdir() subprocess.run(["git", "init", "-q"], cwd=repo, check=True, capture_output=True) env = {k: v for k, v in os.environ.items() if k != "SPIRE_SCRATCH"} + env = pinned(env, "claude", tmp / "codex-home") # D4 patch = mock.patch.dict(os.environ, env, clear=True) patch.start() self.addCleanup(patch.stop) old = os.getcwd() os.chdir(repo) self.addCleanup(os.chdir, old) - run_dir = repo / "docs" / "workpad" / "logs" / "2026-10-22-10-x" + run_dir = repo / "docs" / "quire" / "logs" / "2026-10-22-10-x" run_md = str(run_dir / "run.md") def g(*args): diff --git a/plugins/spire/skills/gremlins/tests/test_cli_codex.py b/plugins/spire/skills/gremlins/tests/test_cli_codex.py new file mode 100644 index 0000000..8ff1d8d --- /dev/null +++ b/plugins/spire/skills/gremlins/tests/test_cli_codex.py @@ -0,0 +1,350 @@ +"""The CLI end to end on fake_codex (design §9.2 `test_cli_codex` row, build plan 3.4). The caller +is pinned as Codex with a temp `CODEX_HOME` (tests/_pin.py); `--binary` is a wrapper that runs +tests/fake_codex.py, so no real `codex` and no real `~/.codex` is touched. + +The read-only `CODEX_HOME` refusal at `init` (`codex_home_not_writable`, nothing written) is the +init preflight path and is covered through the cli in test_codex.PreflightTest; the `ro_home` +scenario here is the other path: a launch that fails at Codex startup.""" +import contextlib +import io +import json +import os +import shutil +import signal +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from pathlib import Path +from unittest import mock + +SKILL = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(SKILL)) +sys.path.insert(0, str(SKILL / "tests")) + +from grm import cli, codex, title # noqa: E402 +from _pin import pin_caller # noqa: E402 + +FAKE = str(SKILL / "tests" / "fake_codex.py") +MODEL = "gpt-6-luna" +CACHE = {"models": [{"slug": MODEL, "supported_reasoning_levels": [{"effort": "low"}, {"effort": "high"}]}]} +# fake_codex's cache model (train 1100 in / 100 cached; each later call adds 50 + the 20 output) +BASE_CTX = 1100 + + +def wrapper_bin(d: Path) -> str: + """An executable `codex` that runs fake_codex.py with this interpreter.""" + p = d / "codex" + p.write_text("#!%s\nimport os, sys\nos.execv(sys.executable, [sys.executable, %r] + sys.argv[1:])\n" + % (sys.executable, FAKE), encoding="utf-8") + p.chmod(0o755) + return str(p) + + +@unittest.skipIf(os.name == "nt", "the fake binary is a shebang script") +class CodexCliTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.repo = self.tmp / "repo" + self.repo.mkdir() + for a in (["init", "-q"], ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", + "--allow-empty", "-m", "x"]): + subprocess.run(["git", *a], cwd=self.repo, check=True, capture_output=True) + self.run_md = str(self.tmp / "run" / "run.md") + self.state = self.tmp / "scratch" / "run" / "gremlins" + self.log = self.tmp / "fake.jsonl" + self.brief = self.tmp / "brief.md" + self.brief.write_text("do the thing\n", encoding="utf-8") + self.home = Path(pin_caller(self, "codex", self.tmp / "codex-home")) + self.home.mkdir() + (self.home / "models_cache.json").write_text(json.dumps(CACHE), encoding="utf-8") + env = mock.patch.dict(os.environ, {"FAKE_CODEX_LOG": str(self.log), "FAKE_CODEX_SCENARIO": "ok", + "SPIRE_SCRATCH": str(self.tmp / "scratch")}) + env.start() + self.addCleanup(env.stop) + self.bin = wrapper_bin(self.tmp) + + # ---- helpers ---- + def g(self, *args, scenario=None): + if scenario: + os.environ["FAKE_CODEX_SCENARIO"] = scenario + buf = io.StringIO() + try: + with contextlib.redirect_stdout(buf): + code = cli.main(list(args)) + finally: + os.environ["FAKE_CODEX_SCENARIO"] = "ok" + return code, json.loads(buf.getvalue().splitlines()[-1]) + + def init(self, *extra): + code, out = self.g("init", "--run", self.run_md, "--model", MODEL, "--effort", "low", + "--cwd", str(self.repo), "--binary", self.bin, *extra) + self.assertEqual(code, 0, out) + return out + + def train(self, scenario=None): + return self.g("train", "--run", self.run_md, "--base", "B1", "--brief", str(self.brief), + scenario=scenario) + + def spawn(self, job, scenario=None): + return self.g("spawn", "--run", self.run_md, "--base", "B1", "--job", job, + "--brief", str(self.brief), scenario=scenario) + + def rebase(self, scenario=None): + return self.g("rebase", "--run", self.run_md, "--base", "B1", "--brief", str(self.brief), + scenario=scenario) + + def calls(self): + if not self.log.exists(): + return [] + return [json.loads(ln) for ln in self.log.read_text(encoding="utf-8").splitlines()] + + def ledger(self): + return [json.loads(ln) for ln in (self.state / "ledger.jsonl").read_text(encoding="utf-8").splitlines()] + + def run_json(self): + return json.loads((self.state / "run.json").read_text(encoding="utf-8")) + + def base_rec(self): + p = self.state / "bases" / "B1.json" + return json.loads(p.read_text(encoding="utf-8")) if p.exists() else None + + def job(self, j): + return json.loads((self.state / "jobs" / (j + ".json")).read_text(encoding="utf-8")) + + def tail(self, call): + """The logged argv after the stored prefix (the fake logs its own path as argv[0]).""" + stored = self.run_json()["argv"] + self.assertEqual(call["argv"][1:len(stored)], stored[1:]) + return call["argv"][len(stored):] + + # ---- happy path ---- + def test_train_spawn_rebase_happy(self): + out = self.init() + self.assertEqual((out["harness"], out["fingerprint"]["binary_version"]), ("codex", "0.172.0")) + preamble = (self.state / "preamble.md").read_text(encoding="utf-8") + + code, out = self.train() + self.assertEqual((code, out["status"], out["warnings"]), (0, "ok", []), out) + tid = out["session_id"] + self.assertTrue(tid) + self.assertEqual(self.base_rec()["session_id"], tid) + self.assertEqual(self.tail(self.calls()[0]), ["-"]) + t = self.job("B1-train")["title"] + self.assertTrue(t.startswith("%s B1 · run · " % title.TITLE_EMOJI), t) + brief = (self.state / "briefs" / "B1-train.md").read_text(encoding="utf-8") + self.assertTrue(brief.startswith(t + "\n\n" + preamble), brief[:300]) + self.assertTrue(self.calls()[0]["prompt_head"].startswith(t + "\n\n# Headless implementer")) + base = self.base_rec() + self.assertEqual((base["context_tokens"], base["ttl_s"], base["cost_cumulative_usd"]), + (BASE_CTX, 600, None)) + self.assertEqual(base["model_usage"], {MODEL: {"inputTokens": 1000, "outputTokens": 20, + "cacheReadInputTokens": 100, + "cacheCreationInputTokens": 0}}) + code, st = self.g("status", "--run", self.run_md) + self.assertEqual((st["bases"]["B1"]["base_state"], st["bases"]["B1"]["ttl_s"]), ("warm", 600)) + + code, out = self.spawn("1.1") + self.assertEqual((code, out["status"], out["cache"]), (0, "ok", "hit"), out) + self.assertEqual(self.tail(self.calls()[1]), ["--ephemeral", "fork", tid, "-"]) + sp = (self.state / "briefs" / "1.1.md").read_text(encoding="utf-8") + for phrase in ("Trained once, as the base", "Forked once per task", "Headless implementer", + "newest delta header wins"): + self.assertNotIn(phrase, sp) + self.assertIn(codex.COMMIT_LINE, sp) + line = self.ledger()[-1] + self.assertEqual((line["job"], line["model"], line["models_used"], line["cache"]), + ("1.1", MODEL, [MODEL], "hit")) + self.assertIsNone(line["cost_delta_usd"]) + self.assertIsNone(line["cost_cumulative_usd"]) + # per-call deltas, not the thread's running totals (which include the base) + self.assertEqual(line["tokens"], {"input": 70, "output": 20, "cache_creation": 0, "cache_read": 1100, + "cache_creation_1h": 0, "cache_creation_5m": 0}) + self.assertEqual(self.base_rec(), base) # spawn never writes the base + + code, out = self.rebase() + self.assertEqual((code, out["status"], out["session_id"], out["warnings"]), (0, "ok", tid, []), out) + self.assertEqual(self.tail(self.calls()[2]), ["resume", tid, "-"]) + rb = self.base_rec() + self.assertEqual((rb["session_id"], rb["context_tokens"], len(rb["rebases"])), (tid, 1170, 1)) + self.assertNotEqual(rb["model_usage"], base["model_usage"]) + self.assertEqual(rb["model_usage"][MODEL]["cacheReadInputTokens"], 1200) + self.assertEqual(self.job("B1-rebase1")["title"].split(" · ")[0], + "%s B1 › rebase 1" % title.TITLE_EMOJI) + + code, out = self.spawn("1.2") # a fork of the resumed base still hits + self.assertEqual((code, out["cache"], self.ledger()[-1]["tokens"]["cache_read"]), (0, "hit", 1170)) + + def test_prefix_unchanged(self): + """§3.2: run.json argv, fp_hash and the preamble copy are constant; tails are per call.""" + self.init() + r0 = self.run_json() + pre0 = (self.state / "preamble.md").read_bytes() + self.train() + self.spawn("1.1") + self.rebase() + r1 = self.run_json() + self.assertEqual((r1["argv"], r1["fp_hash"], r1["fingerprint"]), (r0["argv"], r0["fp_hash"], r0["fingerprint"])) + self.assertEqual((self.state / "preamble.md").read_bytes(), pre0) + self.assertEqual(len(self.calls()), 3) + for c in self.calls(): + self.tail(c) + self.assertNotIn("-", r0["argv"]) + self.assertFalse(any(x in r0["argv"] for x in ("fork", "resume", "--ephemeral"))) + + def test_codex_home_pinned_from_fingerprint(self): + """D-B4: a caller CODEX_HOME that moved after init does not move the rollouts.""" + self.init() + other = self.tmp / "other-home" + other.mkdir() + os.environ["CODEX_HOME"] = str(other) # pin_caller's patch restores it + code, out = self.train() + self.assertEqual((code, out["warnings"]), (0, []), out) + self.assertTrue(list((self.home / "sessions").glob("*/*/*/rollout-*-%s.jsonl" % out["session_id"]))) + self.assertFalse((other / "sessions").exists()) + + def test_rendered_templates_have_no_unresolved_keys(self): + self.init() + self.train() + self.spawn("1.1") + self.rebase() + names = sorted(p.name for p in (self.state / "briefs").glob("*.md")) + self.assertEqual(names, ["1.1.md", "B1-rebase1.md", "B1-train.md"]) + for n in names: + self.assertNotIn("${", (self.state / "briefs" / n).read_text(encoding="utf-8"), n) + + # ---- failure paths ---- + def test_miss_scenario_reads_partial(self): + """D-B7: an ephemeral fork that reads only the generic prefix still has cache_read > 0.""" + self.init() + self.train() + code, out = self.spawn("1.1", scenario="miss") + self.assertEqual((code, out["status"], out["cache"]), (0, "ok", "partial")) + + def test_spawn_failures(self): + """turn_failed -> error/is_error; usage_limit -> usage_limit; the base is untouched.""" + self.init() + self.train() + base = self.base_rec() + for j, scenario, reason in (("f1", "turn_failed", "is_error"), ("f2", "usage_limit", "usage_limit"), + ("f3", "noresult", "exit_code")): + code, out = self.spawn(j, scenario=scenario) + self.assertEqual((code, out["status"], out["reason"]), (1, "error", reason), scenario) + self.assertEqual(self.job(j)["status"], "error") + # review 2 M1: no usage means no verdict (as on Claude), not a recorded miss + self.assertIsNone(self.job(j)["cache"], scenario) + self.assertIsNone(self.ledger()[-1]["cache"], scenario) + self.assertEqual(len(self.ledger()), 4) + self.assertEqual(self.base_rec(), base) + + def test_train_failures_write_no_base(self): + """noresult and ro_home (a launch failing at Codex startup) end error/exit_code; a train + whose stream has no thread.started ends error and writes no base file.""" + self.init() + for scenario, reason in (("noresult", "exit_code"), ("ro_home", "exit_code"), ("no_thread", "is_error")): + code, out = self.train(scenario) + self.assertEqual((code, out["status"], out["reason"]), (1, "error", reason), scenario) + self.assertIsNone(self.base_rec(), scenario) + self.assertEqual(out["result_excerpt"], "no thread.started event") + self.assertEqual(len(self.ledger()), 3) + self.assertEqual(list((self.state / "bases").iterdir()), []) + + def test_no_rollout_warns(self): + """review 2 M4, design §4.4: a train or rebase whose rollout is missing reports one warning + through the cli, and the base context is 0 (a later spawn cannot read `hit`).""" + self.init() + code, out = self.train("no_rollout") + self.assertEqual((code, out["status"]), (0, "ok"), out) + self.assertEqual(len(out["warnings"]), 1, out) + self.assertIn("no rollout found", out["warnings"][0]) + self.assertEqual(self.base_rec()["context_tokens"], 0) + code, out = self.rebase("no_rollout") + self.assertEqual((code, out["status"]), (0, "ok"), out) + self.assertEqual([w for w in out["warnings"] if "no rollout found" in w], out["warnings"]) + self.assertEqual(len(out["warnings"]), 1, out) + self.assertEqual(self.base_rec()["context_tokens"], 0) + code, out = self.spawn("1.1") + self.assertEqual((code, out["status"]), (0, "ok")) + self.assertNotEqual(out["cache"], "hit") + + def test_ro_home_stderr_kept(self): + self.init() + code, out = self.train("ro_home") + self.assertEqual((code, out["reason"]), (1, "exit_code")) + self.assertIn(b"Read-only file system (os error 30)", (self.state / "raw" / "B1-train.err").read_bytes()) + self.assertEqual((self.state / "raw" / "B1-train.jsonl").read_bytes(), b"") + + def test_parallel_spawns(self): + self.init() + self.train() + ts = [threading.Thread(target=cli.main, args=(["spawn", "--run", self.run_md, "--base", "B1", + "--job", j, "--brief", str(self.brief)],)) + for j in ("p1", "p2")] + with contextlib.redirect_stdout(io.StringIO()): + for t in ts: + t.start() + for t in ts: + t.join(60) + for j in ("p1", "p2"): + self.assertEqual((self.job(j)["status"], self.job(j)["cache"]), ("ok", "hit")) + lines = self.ledger() + self.assertEqual(sorted(ln["job"] for ln in lines[1:]), ["p1", "p2"]) + + def test_stop_signal(self): + """B4 on Codex: the helper subprocess inherits the pinned env (a Codex caller).""" + self.init() + self.train() + env = dict(os.environ, FAKE_CODEX_SCENARIO="sleep") + h = subprocess.Popen([sys.executable, str(SKILL / "gremlins.py"), "spawn", "--run", self.run_md, + "--base", "B1", "--job", "s1", "--brief", str(self.brief)], + env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + jpath, raw = self.state / "jobs" / "s1.json", self.state / "raw" / "s1.jsonl" + deadline = time.time() + 30 + while time.time() < deadline and not ( + jpath.exists() and json.loads(jpath.read_text(encoding="utf-8")).get("child_pid") + and raw.exists() and b'"item.completed"' in raw.read_bytes()): + time.sleep(0.2) + pid = json.loads(jpath.read_text(encoding="utf-8"))["child_pid"] + os.kill(h.pid, signal.SIGTERM) + out, _ = h.communicate(timeout=30) + self.assertEqual(h.returncode, 1) + self.assertEqual(json.loads(out.decode("utf-8").splitlines()[-1])["status"], "stopped") + self.assertEqual(self.job("s1")["status"], "stopped") + self.assertIn(b'"thread.started"', raw.read_bytes()) + with self.assertRaises(ProcessLookupError): + os.kill(pid, 0) + + # ---- env scrub as the gremlin sees it ---- + def test_scrub_names_in_child_env(self): + values = {"CLAUDE_CODE_OAUTH_TOKEN": "val-claude-oauth-1", "ANTHROPIC_BASE_URL": "val-anthropic-2", + "CLAUDE_PID": "val-claude-pid-3", "OPENAI_API_KEY": "val-openai-4", + "CODEX_SESSION_ID": "val-codex-session-5", "OTHER_SECRET": "val-other-6", + "GITEA_TOKEN": "val-gitea-7", "CODEX_ACCESS_TOKEN": "val-codex-access-8", + "PLAIN_SETTING": "val-plain-9"} + os.environ.update(values) # pin_caller's patch restores the env + out = self.init("--pass-env", "GITEA_TOKEN") + self.assertEqual(self.run_json()["fingerprint"]["env_pass"], ["GITEA_TOKEN"]) + for n in ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "CLAUDE_PID", "OPENAI_API_KEY", + "CODEX_SESSION_ID", "CODEX_THREAD_ID", "OTHER_SECRET"): + self.assertIn(n, out["env_dropped"]) + self.train() + self.spawn("1.1") + calls = self.calls() + self.assertEqual(len(calls), 2) + for c in calls: + names = set(c["env_names"]) + for n in ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "CLAUDE_PID", "OPENAI_API_KEY", + "CODEX_SESSION_ID", "CODEX_THREAD_ID", "OTHER_SECRET", "CLAUDECODE"): + self.assertNotIn(n, names) + for n in ("CODEX_HOME", "GITEA_TOKEN", "CODEX_ACCESS_TOKEN", "PLAIN_SETTING", "PATH"): + self.assertIn(n, names) + text = self.log.read_text(encoding="utf-8") + json.dumps(out) + for v in values.values(): + self.assertNotIn(v, text) + + +if __name__ == "__main__": + unittest.main() diff --git a/plugins/spire/skills/gremlins/tests/test_codex.py b/plugins/spire/skills/gremlins/tests/test_codex.py new file mode 100644 index 0000000..8c8bcb2 --- /dev/null +++ b/plugins/spire/skills/gremlins/tests/test_codex.py @@ -0,0 +1,532 @@ +"""Codex adapter, block 3.1 rows: argv and fingerprint, init checks, model and effort check +(design §4.1-4.2, build plan §2). No real `codex`, no real `~/.codex`: every test pins +`CODEX_HOME` to a temp dir and uses a fake binary.""" +import contextlib +import io +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +SKILL = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(SKILL)) +sys.path.insert(0, str(SKILL / "tests")) + +from grm import cli, codex, harness, launch, stream # noqa: E402 +from grm.errors import Refusal # noqa: E402 +from _pin import pin_caller # noqa: E402 + +MODEL = "gpt-6-luna" +CACHE = {"models": [{"slug": MODEL, "supported_reasoning_levels": [ + {"effort": "low", "description": "d"}, {"effort": "medium"}, {"effort": "high"}]}, + {"slug": "gpt-6-sol", "supported_reasoning_levels": []}]} +FP_KEYS = {"harness", "binary", "binary_version", "model", "effort", "sandbox", "network", "add_dirs", + "cwd", "ignore_user_config", "config", "ephemeral_forks", "codex_home", "preamble", "env_pass"} + + +def fake_codex_bin(d: Path) -> str: + """An executable that prints `codex-cli 0.172.0` for `--version`.""" + p = d / "codex" + p.write_text("#!%s\nprint('codex-cli 0.172.0')\n" % sys.executable, encoding="utf-8") + p.chmod(0o755) + return str(p) + + +def git_repo(d: Path) -> Path: + d.mkdir(parents=True) + subprocess.run(["git", "init", "-q"], cwd=d, check=True, capture_output=True) + return d + + +class _Tmp(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.home = self.tmp / "codex-home" + self.home.mkdir() + pin_caller(self, "codex", self.home) + self.h = harness.named("codex") + + def write_cache(self, data): + p = self.home / "models_cache.json" + p.write_bytes(data if isinstance(data, bytes) else json.dumps(data).encode("utf-8")) + + def refused(self, fn, *a, **kw): + with self.assertRaises(Refusal) as e: + fn(*a, **kw) + return e.exception.payload + + +class AdapterBasicsTest(_Tmp): + def test_members(self): + self.assertIsInstance(self.h, codex.CodexAdapter) + self.assertEqual((self.h.name, self.h.binary_name, self.h.preassigns_session_id), ("codex", "codex", False)) + self.assertTrue(self.h.commit_line.startswith(" You cannot commit here (`.git` is read-only")) + self.assertEqual(self.h.infer_ttl({"cache_creation_1h": 5}, None), 600) + self.assertEqual(self.h.infer_ttl(None, 900), 900) + + @unittest.skipIf(os.name == "nt", "shebang script") + def test_version_parse(self): + self.assertEqual(self.h.binary_version(fake_codex_bin(self.tmp)), "0.172.0") + self.assertIsNone(self.h.binary_version(str(self.tmp / "nope"))) + + def test_resolve_binary(self): + self.assertEqual(self.h.resolve_binary("rel/codex"), os.path.abspath("rel/codex")) + with mock.patch.object(codex.shutil, "which", return_value=None): + self.assertIsNone(self.h.resolve_binary(None)) + + def test_codex_home(self): + self.assertEqual(codex.codex_home(), str(self.home)) + self.assertEqual(codex.codex_home({}), os.path.abspath(os.path.expanduser("~/.codex"))) + self.assertEqual(codex.codex_home({"CODEX_HOME": "rel"}), os.path.abspath("rel")) + + +class CheckInitTest(_Tmp): + def test_agent_refused(self): + repo = git_repo(self.tmp / "repo") + p = self.refused(self.h.check_init, cwd=str(repo), agent="reviewer", network=False) + self.assertEqual(p["error"], "Codex has no main-thread agent") + self.h.check_init(cwd=str(repo), agent=None, network=True) + + def test_non_git_cwd_refused(self): + d = self.tmp / "plain" + d.mkdir() + with mock.patch.dict(os.environ, {"GIT_CEILING_DIRECTORIES": str(self.tmp)}): + p = self.refused(self.h.check_init, cwd=str(d), agent=None, network=False) + self.assertEqual(p["error"], "Codex runs need a git repository") + + +class CheckModelTest(_Tmp): + def test_against_cache(self): + self.write_cache(CACHE) + self.h.check_model(MODEL, "low") + p = self.refused(self.h.check_model, "gpt-6-nova", "low") + self.assertEqual((p["error"], p["models"]), ("unknown model", ["gpt-6-luna", "gpt-6-sol"])) + self.assertIn("run `codex` once to refresh", p["remedy"]) + p = self.refused(self.h.check_model, MODEL, "max") + self.assertEqual((p["error"], p["efforts"]), ("unknown effort", ["low", "medium", "high"])) + # a listed model without levels: the effort enum + self.h.check_model("gpt-6-sol", "ultra") + self.assertEqual(self.refused(self.h.check_model, "gpt-6-sol", "bogus")["error"], "unknown effort") + + def test_slug_shape(self): + self.write_cache(CACHE) + for m in ("claude-opus-5-5", "Gpt-6", "gpt 6", "", "-gpt"): + self.assertEqual(self.refused(self.h.check_model, m, "low")["error"], + "model must be a Codex model slug", m) + + def test_no_cache_or_unparsable(self): + for data in (None, b"{not json", {"models": "x"}, {"other": 1}, []): + if data is None: + (self.home / "models_cache.json").unlink(missing_ok=True) + else: + self.write_cache(data) + self.h.check_model("gpt-anything", "persistent") + self.assertEqual(self.refused(self.h.check_model, "gpt-anything", "bogus")["error"], + "unknown effort") + + +class FingerprintTest(_Tmp): + def setUp(self): + super().setUp() + self.cwd = git_repo(self.tmp / "repo") + self.bin = fake_codex_bin(self.tmp) + + def fp(self, state, network=False, env_pass=()): + state = Path(state) + state.mkdir(parents=True, exist_ok=True) + pre = state / "preamble.md" + pre.write_text("# preamble\n", encoding="utf-8") + return self.h.build_fingerprint(binary=self.bin, model=MODEL, effort="low", cwd=str(self.cwd), + agent=None, network=network, state=str(state), + preamble_path=str(pre), mcp_config=str(state / "mcp-empty.json"), + env_pass=list(env_pass)) + + def test_stored_argv_and_tails(self): + fpd = self.fp(self.cwd / ".spire" / "scratch" / "r" / "gremlins") + argv = fpd["argv"] + self.assertEqual(argv, [os.path.abspath(self.bin), "exec", "--json", "--ignore-user-config", + "-s", "workspace-write", "-C", str(self.cwd), "-m", MODEL, + "-c", 'model_reasoning_effort="low"', "-c", 'web_search="disabled"', + "-c", "agents.enabled=false"]) + run = {"argv": argv} + n = len(argv) + for a, tail in ((self.h.train_argv(run, None, "t"), ["-"]), + (self.h.fork_argv(run, "th-1", None, "t"), ["--ephemeral", "fork", "th-1", "-"]), + (self.h.resume_argv(run, "th-1", "t"), ["resume", "th-1", "-"])): + self.assertEqual((a[:n], a[n:]), (argv, tail)) + self.assertNotIn("t", a) + self.assertEqual(len(run["argv"]), n) # the stored list is not mutated + + def test_add_dir_only_outside_cwd(self): + self.assertEqual(self.fp(self.cwd / "s")["fingerprint"]["add_dirs"], []) + out = self.tmp / "scratch" / "r" / "gremlins" + fpd = self.fp(out) + self.assertEqual(fpd["fingerprint"]["add_dirs"], [str(out)]) + i = fpd["argv"].index("--add-dir") + self.assertEqual(fpd["argv"][i + 1], str(out)) + self.assertLess(i, fpd["argv"].index("-m")) + + def test_network(self): + off, on = self.fp(self.cwd / "a"), self.fp(self.cwd / "a", network=True) + self.assertFalse(off["fingerprint"]["network"]) + self.assertNotIn(codex.NETWORK_CONFIG, off["argv"]) + self.assertTrue(on["fingerprint"]["network"]) + self.assertEqual(on["argv"][-2:], ["-c", "sandbox_workspace_write.network_access=true"]) + self.assertNotEqual(off["fp_hash"], on["fp_hash"]) + + @unittest.skipIf(os.name == "nt", "shebang script") + def test_fingerprint_keys_and_hash(self): + fpd = self.fp(self.cwd / "a", env_pass=["GH_TOKEN", "GITEA_TOKEN"]) + fp = fpd["fingerprint"] + self.assertEqual(set(fp), FP_KEYS) + self.assertEqual((fp["harness"], fp["binary_version"], fp["sandbox"], fp["ignore_user_config"], + fp["ephemeral_forks"], fp["codex_home"], fp["env_pass"]), + ("codex", "0.172.0", "workspace-write", True, True, str(self.home), + ["GH_TOKEN", "GITEA_TOKEN"])) + self.assertEqual(fp["config"], ['model_reasoning_effort="low"', 'web_search="disabled"', + "agents.enabled=false"]) + self.assertEqual(set(fp["preamble"]), {"path", "sha256", "placement"}) + self.assertEqual(fp["preamble"]["placement"], "train_prompt") + self.assertEqual(fpd["fp_hash"], launch._sha256_bytes(launch.canonical_json(fp).encode("utf-8"))) + + def test_env_pins_codex_home(self): + fp = self.fp(self.cwd / "a")["fingerprint"] + env = self.h.env(fp, {"CODEX_HOME": "/host/codex", "CODEX_THREAD_ID": "x", "CLAUDECODE": "1", + "PATH": os.defpath}) + self.assertEqual(env["CODEX_HOME"], str(self.home)) + self.assertNotIn("CODEX_THREAD_ID", env) + self.assertNotIn("CLAUDECODE", env) + + def test_train_prompt(self): + state = self.cwd / "a" + self.fp(state) + p = self.h.train_prompt(state, "TITLE", "RENDERED") + self.assertEqual(p, "TITLE\n\n# preamble\n\n\n---\n\nRENDERED") + + +class InitCliTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.repo = git_repo(self.tmp / "repo") + self.run_md = str(self.tmp / "run" / "run.md") + self.state = self.tmp / "scratch" / "run" / "gremlins" + env = mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(self.tmp / "scratch")}) + env.start() + self.addCleanup(env.stop) + self.bin = fake_codex_bin(self.tmp) + + def g(self, *args): + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = cli.main(list(args)) + return code, json.loads(buf.getvalue().splitlines()[-1]) + + def init(self, *extra, model=MODEL): + return self.g("init", "--run", self.run_md, "--model", model, "--effort", "low", + "--cwd", str(self.repo), "--binary", self.bin, *extra) + + def run_json(self): + p = self.state / "run.json" + return json.loads(p.read_text(encoding="utf-8")) if p.exists() else None + + def test_init_codex_writes_run(self): + home = pin_caller(self, "codex") + code, out = self.init("--harness", "codex", "--network") + self.assertEqual(code, 0, out) + r = self.run_json() + fp = r["fingerprint"] + self.assertEqual((fp["harness"], r["caller_harness"], out["harness"], fp["codex_home"], fp["network"]), + ("codex", "codex", "codex", home, True)) + self.assertEqual(r["argv"][1:3], ["exec", "--json"]) + self.assertEqual(fp["add_dirs"], [str(self.state)]) # SPIRE_SCRATCH is outside the repo + self.assertIn(codex.NETWORK_CONFIG, r["argv"]) + self.assertNotIn("-", r["argv"]) + self.assertTrue((self.state / "preamble.md").is_file()) + + def test_init_codex_refusals_write_nothing(self): + pin_caller(self, "codex") + for extra, model, error in ((["--agent", "a"], MODEL, "Codex has no main-thread agent"), + ([], "claude-opus-5-5", "model must be a Codex model slug"), + (["--effort", "bogus"], MODEL, "unknown effort")): + code, out = self.init(*extra, model=model) + self.assertEqual((code, out["error"]), (2, error), out) + self.assertFalse(self.state.exists()) + + def test_network_refused_on_claude(self): + """D5: `--network` reaches the Claude adapter's check and is refused.""" + pin_caller(self, "claude") + code, out = self.g("init", "--run", self.run_md, "--model", "claude-opus-5-5", "--cwd", str(self.repo), + "--binary", sys.executable, "--network") + self.assertEqual((code, out["error"]), (2, "Claude gremlins have no sandbox network switch")) + self.assertFalse(self.state.exists()) + + +# ---- block 3.3: stream, accounting, verdict, rollout, preflight ---- + +def usage(inp, cached, out=10, write=0): + return {"input_tokens": inp, "cached_input_tokens": cached, "cache_write_input_tokens": write, + "output_tokens": out, "reasoning_output_tokens": 0} + + +def events(tid, u, text="done", tool=False): + """A `codex exec --json` stream in the P3 shapes (event types and usage keys only).""" + evs = [{"type": "thread.started", "thread_id": tid}, {"type": "turn.started"}, + {"type": "item.completed", "item": {"id": "i0", "type": "agent_message", "text": "reading"}}] + if tool: + cmd = {"id": "i1", "type": "command_execution", "command": "ls", "aggregated_output": "", + "exit_code": None, "status": "in_progress"} + evs += [{"type": "item.started", "item": cmd}, + {"type": "item.completed", "item": dict(cmd, exit_code=0, status="completed")}] + evs += [{"type": "item.completed", "item": {"id": "i2", "type": "agent_message", "text": text}}, + {"type": "turn.completed", "usage": u}] + return evs + + +def feed(evs, model=MODEL): + ss = stream.CodexStreamState(model) + for i, ev in enumerate(evs): + ss.feed(ev, 100.0 + i) + return ss + + +def mapped(inp, cached, out=10): + return {MODEL: {"inputTokens": inp - cached, "outputTokens": out, "cacheReadInputTokens": cached, + "cacheCreationInputTokens": 0}} + + +class CodexStreamTest(unittest.TestCase): + def test_p3_train_stream(self): + """P3 base B2 train (one tool call): id, first item time, last text, mapped totals.""" + ss = feed(events("th-b2", usage(38778, 11648, 151), text="trained", tool=True)) + self.assertEqual((ss.session_id, ss.first_at, ss.last_assistant_at), ("th-b2", 102.0, 106.0)) + r = ss.result + self.assertEqual((r["is_error"], r["session_id"], r["result"], r["total_cost_usd"]), + (False, "th-b2", "trained", None)) + self.assertEqual(r["modelUsage"], mapped(38778, 11648, 151)) + self.assertEqual(stream.classify(ss, 0, False), ("ok", None)) + + def test_first_thread_id_wins(self): + evs = events("th-1", usage(1, 0)) + ss = feed(evs[:1] + [{"type": "thread.started", "thread_id": "th-2"}] + evs[1:]) + self.assertEqual((ss.session_id, ss.result["session_id"]), ("th-1", "th-1")) + + def test_no_thread_started_is_error(self): + """Build plan §2: an `ok` turn without `thread.started` must not write a base.""" + ss = feed(events("x", usage(23827, 11648))[1:]) + self.assertIsNone(ss.session_id) + self.assertEqual((ss.result["is_error"], ss.result["result"]), (True, "no thread.started event")) + self.assertEqual(stream.classify(ss, 0, False), ("error", "is_error")) + + def test_failures_classify(self): + """usage limit -> usage_limit; unmatched text -> is_error; no turn end -> exit_code.""" + limit = "You've hit your usage limit. Try again later." + ss = feed(events("th", usage(1, 0))[:2] + [{"type": "error", "message": limit}, + {"type": "turn.failed", "error": {"message": limit}}]) + self.assertEqual(stream.classify(ss, 1, False), ("error", "usage_limit")) + self.assertEqual(ss.session_id, "th") + ss = feed(events("th", usage(1, 0))[:2] + [{"type": "turn.failed", "error": {"message": "sandbox denied"}}]) + self.assertEqual(stream.classify(ss, 1, False), ("error", "is_error")) + ss = feed(events("th", usage(1, 0))[:2] + [{"type": "error"}]) + self.assertEqual((ss.result["result"], stream.classify(ss, 1, False)), ("error", ("error", "is_error"))) + ss = feed(events("th", usage(1, 0))[:3]) + self.assertIsNone(ss.result) + self.assertEqual(stream.classify(ss, 1, False), ("error", "exit_code")) + + def test_later_turn_completed_replaces_an_error(self): + evs = events("th", usage(5, 0)) + ss = feed(evs[:2] + [{"type": "error", "message": "Reconnecting... 1/5"}] + evs[2:]) + self.assertEqual(stream.classify(ss, 0, False), ("ok", None)) + + def test_ignores_junk(self): + ss = stream.CodexStreamState(MODEL) + for ev in (None, [], {"type": 3}, {"no": "type"}, {"type": "item.updated", "item": None}): + ss.feed(ev, 1.0) + self.assertEqual((ss.session_id, ss.result, ss.first_at), (None, None, 1.0)) + + +class CodexUsageTest(unittest.TestCase): + def test_train_counts_whole_total(self): + u = stream.codex_usage({"usage": usage(23827, 11648, 34), "modelUsage": mapped(23827, 11648, 34)}, + None, None) + self.assertEqual(u["tokens"], {"input": 12179, "output": 34, "cache_creation": 0, "cache_read": 11648, + "cache_creation_1h": 0, "cache_creation_5m": 0}) + self.assertEqual((u["models_used"], u["cost_delta"], u["total"]), ([MODEL], None, None)) + self.assertEqual(u["model_usage"], mapped(23827, 11648, 34)) + + def test_r5_fork_delta(self): + """r5 (persisted fork): 47,688 - 23,827 input, 23,296 - 11,648 cached.""" + base = mapped(23827, 11648) + u = stream.codex_usage({"usage": usage(47688, 23296, 20), "modelUsage": mapped(47688, 23296, 20)}, + base, None) + self.assertEqual((u["tokens"]["input"] + u["tokens"]["cache_read"], u["tokens"]["cache_read"]), + (47688 - 23827, 23296 - 11648)) + self.assertEqual((u["tokens"]["input"], u["tokens"]["output"]), (12213, 10)) + + def test_n4_after_resume(self): + """n4: the resumed base's totals are the new basis (71,565 - 47,678; 59,008 - 35,328).""" + u = stream.codex_usage({"usage": usage(71565, 59008), "modelUsage": mapped(71565, 59008)}, + mapped(47678, 35328), None) + self.assertEqual((u["tokens"]["input"] + u["tokens"]["cache_read"], u["tokens"]["cache_read"]), + (23887, 23680)) + + def test_error_result_without_usage(self): + for res in ({"is_error": True, "result": "x", "usage": None, "modelUsage": {}}, {}, None): + u = stream.codex_usage(res, mapped(100, 50), None) + self.assertEqual(set(u["tokens"].values()), {0}) + self.assertEqual((u["models_used"], u["model_usage"], u["cost_delta"]), ([], {}, None)) + + def test_through_the_adapter(self): + h = codex.CodexAdapter() + ss = h.new_stream({"model": MODEL}) + self.assertIsInstance(ss, stream.CodexStreamState) + for i, ev in enumerate(events("g1", usage(65748, 38400, 188))): + ss.feed(ev, float(i)) + u = h.usage(ss, mapped(38778, 11648, 151), None) + self.assertEqual((u["tokens"]["cache_read"], u["tokens"]["input"]), (26752, 218)) + self.assertEqual(h.cache_verdict(ss, u, 26904), "hit") + self.assertIsNone(h.cache_verdict(ss, None, 26904)) + + +class CodexVerdictTest(unittest.TestCase): + def tok(self, inp, cr): + return {"input": inp, "cache_read": cr} + + def test_verdicts(self): + v = stream.codex_cache_verdict + self.assertEqual(v(self.tok(218, 26752), 26904), "hit") # P3 g1/g2 + self.assertEqual(v(self.tok(181, 23680), 23827), "hit") # r7 ephemeral + self.assertEqual(v(self.tok(12213, 11648), 23827), "partial") # r5 persisted + self.assertEqual(v(self.tok(23861, 0), 23827), "miss") + self.assertEqual(v(self.tok(20000, 26752), 26904), "partial") # big fork + self.assertEqual(v(self.tok(218, 26752), 0), "partial") # no rollout: never hit + self.assertEqual(v(self.tok(218, 26752), None), "partial") + self.assertIsNone(v(None, 26904)) + + +def rollout_lines(*input_tokens): + out = [{"timestamp": "t", "type": "session_meta", "payload": {"id": "x"}}, + {"type": "event_msg", "payload": {"type": "token_count", "info": None}}, + {"type": "response_item", "payload": {"type": "message", "content": "token_count mention"}}] + for n in input_tokens: + out.append({"type": "event_msg", "payload": {"type": "token_count", "info": { + "last_token_usage": usage(n, n // 2), "total_token_usage": usage(n * 2, n)}}}) + return "\n".join(json.dumps(x) for x in out) + "\nnot json token_count\n" + + +class RolloutTest(_Tmp): + def write(self, day, tid, text, mtime=None): + d = self.home / "sessions" / "2026" / "11" / day + d.mkdir(parents=True, exist_ok=True) + p = d / ("rollout-2026-11-%sT10-00-00-%s.jsonl" % (day, tid)) + p.write_text(text, encoding="utf-8") + if mtime is not None: + os.utime(p, (mtime, mtime)) + return p + + def ss(self, tid): + s = stream.CodexStreamState(MODEL) + s.session_id = tid + return s + + def test_last_token_count_and_newest_wins(self): + tid = "019a-th-b2" + self.write("23", tid, rollout_lines(999), mtime=1_000_000) + self.write("24", tid, rollout_lines(11648, 26904), mtime=2_000_000) + self.write("24", "019a-other", rollout_lines(5)) + fp = {"codex_home": str(self.home)} + self.assertEqual(self.h.context_tokens(fp, self.ss(tid)), (26904, [])) + self.assertEqual(codex.rollout_path(str(self.home), tid).split(os.sep)[-2], "24") + # no fp codex_home: the env (init-time) home + self.assertEqual(self.h.context_tokens({}, self.ss(tid)), (26904, [])) + + def test_none_found(self): + fp = {"codex_home": str(self.home)} + for tid in ("missing", None): + n, warnings = self.h.context_tokens(fp, self.ss(tid)) + self.assertEqual((n, len(warnings)), (0, 1)) + self.write("24", "th-empty", rollout_lines()) + n, warnings = self.h.context_tokens(fp, self.ss("th-empty")) + self.assertEqual(n, 0) + self.assertIn("no token_count record", warnings[0]) + + def test_glob_chars_in_id_are_literal(self): + self.write("24", "abc", rollout_lines(7)) + self.assertIsNone(codex.rollout_path(str(self.home), "a*")) + + +class PreflightTest(_Tmp): + def test_ok_creates_tmp_and_leaves_no_file(self): + self.h.preflight({"codex_home": str(self.home)}) + self.assertEqual(list((self.home / "tmp").iterdir()), []) + + def test_init_inputs_fall_back_to_env_home(self): + """review 2 M3: with init inputs (no `codex_home`) preflight probes the env's CODEX_HOME, + a fresh pinned home; HOME is pinned too, so a wrong fallback can never reach ~/.codex.""" + other, fake_home = self.tmp / "other-home", self.tmp / "user-home" + other.mkdir() + fake_home.mkdir() + with mock.patch.dict(os.environ, {"CODEX_HOME": str(other), "HOME": str(fake_home)}): + self.h.preflight({"harness": "codex", "binary": "b", "cwd": "c", "env_pass": []}) + self.assertEqual(list((other / "tmp").iterdir()), []) + self.assertFalse((self.home / "tmp").exists()) + self.assertEqual(list(fake_home.iterdir()), []) + + def test_missing_home_refused_not_created(self): + """review 2 M2: a CODEX_HOME that does not exist is refused, never created.""" + missing = self.tmp / "no-such-home" + p = self.refused(self.h.preflight, {"codex_home": str(missing)}) + self.assertEqual((p["error"], p["codex_home"]), ("codex_home_missing", str(missing))) + self.assertIn("run `codex` once", p["remedy"]) + self.assertFalse(missing.exists()) + state = self.tmp / "scratch" / "run" / "gremlins" + repo = git_repo(self.tmp / "repo") + buf = io.StringIO() + with mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(self.tmp / "scratch"), + "CODEX_HOME": str(missing)}), contextlib.redirect_stdout(buf): + code = cli.main(["init", "--run", str(self.tmp / "run" / "run.md"), "--model", MODEL, + "--effort", "low", "--cwd", str(repo), "--binary", sys.executable]) + out = json.loads(buf.getvalue().splitlines()[-1]) + self.assertEqual((code, out["error"]), (2, "codex_home_missing")) + self.assertFalse(state.exists()) + self.assertFalse(missing.exists()) + + @unittest.skipIf(os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), + "POSIX permissions; root writes anywhere") + def test_read_only_home_refused(self): + for make_tmp in (False, True): + home = self.tmp / ("ro-%s" % make_tmp) + (home / "tmp").mkdir(parents=True) if make_tmp else home.mkdir() + ro = home / "tmp" if make_tmp else home + ro.chmod(0o555) + self.addCleanup(ro.chmod, 0o755) + p = self.refused(self.h.preflight, {"codex_home": str(home)}) + self.assertEqual(p["error"], "codex_home_not_writable") + self.assertIn("run G escalated", p["remedy"]) + self.assertIn("--add-dir %s -c sandbox_workspace_write.network_access=true" % home, p["remedy"]) + + @unittest.skipIf(os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), + "POSIX permissions; root writes anywhere") + def test_init_refuses_before_writing(self): + state = self.tmp / "scratch" / "run" / "gremlins" + repo = git_repo(self.tmp / "repo") + self.home.chmod(0o555) + self.addCleanup(self.home.chmod, 0o755) + buf = io.StringIO() + with mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(self.tmp / "scratch")}), \ + contextlib.redirect_stdout(buf): + code = cli.main(["init", "--run", str(self.tmp / "run" / "run.md"), "--model", MODEL, + "--effort", "low", "--cwd", str(repo), "--binary", sys.executable]) + out = json.loads(buf.getvalue().splitlines()[-1]) + self.assertEqual((code, out["error"]), (2, "codex_home_not_writable")) + self.assertFalse(state.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/plugins/spire/skills/gremlins/tests/test_harness.py b/plugins/spire/skills/gremlins/tests/test_harness.py new file mode 100644 index 0000000..923521f --- /dev/null +++ b/plugins/spire/skills/gremlins/tests/test_harness.py @@ -0,0 +1,288 @@ +import contextlib +import io +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +SKILL = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(SKILL)) +sys.path.insert(0, str(SKILL / "tests")) + +from grm import cli, harness, launch, stream # noqa: E402 +from grm.errors import Refusal # noqa: E402 +from _pin import pin_caller # noqa: E402 + +FAKE = str(SKILL / "tests" / "fake_claude.py") +MODEL = "claude-opus-5-5" +CLAUDE = {"CLAUDECODE": "1"} +CODEX = {"CODEX_THREAD_ID": "t-1"} + + +class DetectTest(unittest.TestCase): + def test_markers(self): + """Design §2.1: exactly one marker gives the harness; none or both is unclear.""" + self.assertEqual(harness.detect(CLAUDE), "claude") + self.assertEqual(harness.detect(CODEX), "codex") + self.assertIsNone(harness.detect({**CLAUDE, **CODEX})) + self.assertIsNone(harness.detect({})) + self.assertIsNone(harness.detect({"CLAUDECODE": "0", "CODEX_THREAD_ID": ""})) + + def test_select_table(self): + """Plan §3.1: the four rows, with their payloads.""" + self.assertEqual(harness.select(None, CLAUDE), ("claude", "claude")) + self.assertEqual(harness.select("codex", CODEX), ("codex", "codex")) + self.assertEqual(harness.select("codex", {}), ("codex", None)) + self.assertEqual(harness.select("claude", {**CLAUDE, **CODEX}), ("claude", None)) + with self.assertRaises(Refusal) as e: + harness.select("codex", CLAUDE) + self.assertEqual(e.exception.payload["error"], "cross_harness") + self.assertEqual((e.exception.payload["detected"], e.exception.payload["asked"]), ("claude", "codex")) + with self.assertRaises(Refusal) as e: + harness.select(None, {**CLAUDE, **CODEX}) + self.assertEqual(e.exception.payload, {"error": "harness_unclear", + "markers": ["CLAUDECODE", "CODEX_THREAD_ID"], + "remedy": "pass --harness claude|codex"}) + + def test_check_caller_and_of(self): + """Design §2.2: a clear other caller is refused, unclear passes; old runs are claude.""" + old = {"fingerprint": {"binary": "/x/claude"}} + self.assertEqual(harness.of(old).name, "claude") + harness.check_caller(old, CLAUDE) + harness.check_caller(old, {}) + with self.assertRaises(Refusal) as e: + harness.check_caller(old, CODEX) + self.assertEqual((e.exception.payload["error"], e.exception.payload["asked"]), + ("cross_harness", "claude")) + self.assertEqual(harness.named("codex").name, "codex") # 3.1: the adapter exists + + def test_claude_adapter_env_and_rehash(self): + """The adapter's env is the Claude scrub with env_pass; fp_hash covers harness/env_pass.""" + h = harness.named("claude") + env = h.env({"binary": "/b/claude", "env_pass": ["GITEA_TOKEN"]}, + {"GITEA_TOKEN": "v1", "GH_TOKEN": "v2", "PATH": "/usr/bin"}) + self.assertEqual(sorted(env), sorted(["GITEA_TOKEN", "PATH", "CLAUDE_CODE_EXECPATH", + *launch.SCRUB_PINNED])) + self.assertEqual(h.commit_line, "") + self.assertTrue(h.preassigns_session_id) + self.assertEqual(h.context_tokens({}, stream.StreamState()), (0, [])) + + +class _Cli(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.repo = self.tmp / "repo" + self.repo.mkdir() + for a in (["init", "-q"], ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", + "--allow-empty", "-m", "x"]): + subprocess.run(["git", *a], cwd=self.repo, check=True, capture_output=True) + self.run_md = str(self.tmp / "run" / "run.md") + self.state = self.tmp / "scratch" / "run" / "gremlins" + self.log = self.tmp / "fake.jsonl" + self.brief = self.tmp / "brief.md" + self.brief.write_text("do the thing\n", encoding="utf-8") + env = mock.patch.dict(os.environ, {"FAKE_CLAUDE_LOG": str(self.log), "FAKE_CLAUDE_SCENARIO": "ok", + "SPIRE_SCRATCH": str(self.tmp / "scratch")}) + env.start() + self.addCleanup(env.stop) + + def pin(self, h): + pin_caller(self, h) + + def g(self, *args): + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = cli.main(list(args)) + return code, json.loads(buf.getvalue().splitlines()[-1]), buf.getvalue() + + def init(self, *extra): + return self.g("init", "--run", self.run_md, "--model", MODEL, "--cwd", str(self.repo), + "--binary", sys.executable, *extra) + + def run_json(self): + p = self.state / "run.json" + return json.loads(p.read_text(encoding="utf-8")) if p.exists() else None + + def fake_argv(self, drop_harness=False): + r = self.run_json() + r["argv"] = [sys.executable, FAKE] + r["argv"][1:] + if drop_harness: + del r["fingerprint"]["harness"] + (self.state / "run.json").write_text(json.dumps(r), encoding="utf-8") + + def assert_refused(self, res, error): + code, out, _ = res + self.assertEqual((code, out["error"]), (2, error), out) + self.assertIsNone(self.run_json()) + + +class InitRulesTest(_Cli): + def test_rule_table_through_init(self): + """Plan §3.1 through `cli.main init`: refusals exit 2 and write no run.json.""" + self.pin("claude") + self.assert_refused(self.init("--harness", "codex"), "cross_harness") + self.pin(None) + code, out, _ = self.init() + self.assertEqual(out, {"error": "harness_unclear", "markers": [], "remedy": "pass --harness claude|codex"}) + self.assert_refused((code, out, ""), "harness_unclear") + self.pin("both") + code, out, _ = self.init() + self.assertEqual(out["markers"], ["CLAUDECODE", "CODEX_THREAD_ID"]) + self.assert_refused((code, out, ""), "harness_unclear") + # 3.1: the Codex adapter exists; a Claude model id is refused by its model check + self.assert_refused(self.init("--harness", "codex"), "model must be a Codex model slug") + self.assert_refused(self.init("--harness", "nope"), "usage") + self.assertFalse(self.state.exists()) + + def test_unclear_settled_by_flag(self): + """An unclear caller + --harness claude: caller_harness null, fingerprint harness claude.""" + self.pin(None) + code, out, _ = self.init("--harness", "claude") + self.assertEqual(code, 0, out) + r = self.run_json() + self.assertEqual((r["caller_harness"], r["fingerprint"]["harness"], out["harness"]), + (None, "claude", "claude")) + + def test_detected_claude(self): + """A Claude caller: caller_harness claude; fp_hash is over the final fingerprint.""" + self.pin("claude") + code, out, _ = self.init() + self.assertEqual(code, 0, out) + r = self.run_json() + self.assertEqual((r["caller_harness"], r["fingerprint"]["harness"], r["fingerprint"]["env_pass"]), + ("claude", "claude", [])) + self.assertEqual(r["fp_hash"], launch._sha256_bytes(launch.canonical_json(r["fingerprint"]).encode())) + self.assertNotIn("--name", r["argv"]) + + def test_model_and_effort_refused_before_writing(self): + """`--effort` has no choices; the adapter refuses it before anything is written.""" + self.pin("claude") + self.assert_refused(self.init("--effort", "ultra"), "unknown effort") + self.assertFalse(self.state.exists()) + code, out, _ = self.g("init", "--run", self.run_md, "--model", "opus", "--cwd", str(self.repo), + "--binary", sys.executable) + self.assert_refused((code, out, ""), "model must be a full id (aliases are refused)") + self.assertFalse(self.state.exists()) + + def test_pass_env(self): + """--pass-env: a harness name is refused; a secret-shaped name is recorded and passes; + env_dropped lists names only (no value in the output).""" + self.pin("claude") + os.environ.update(GITEA_TOKEN="val-gitea-1", MY_SECRET="val-secret-2", ANTHROPIC_API_KEY="val-key-3") + code, out, _ = self.init("--pass-env", "ANTHROPIC_API_KEY") + self.assertEqual((code, out["error"], out["name"]), (2, "pass_env_refused", "ANTHROPIC_API_KEY")) + self.assertIsNone(self.run_json()) + self.assert_refused(self.init("--pass-env", "BAD-NAME"), "pass_env_refused") + code, out, raw = self.init("--pass-env", "GITEA_TOKEN=val-gitea-1") + self.assertEqual((code, out["error"], out["name"]), (2, "pass_env_refused", "GITEA_TOKEN")) + self.assertNotIn("val-gitea-1", raw) + self.assertIsNone(self.run_json()) + code, out, raw = self.init("--pass-env", "GITEA_TOKEN", "--pass-env", "GITEA_TOKEN") + self.assertEqual(code, 0, out) + self.assertEqual(self.run_json()["fingerprint"]["env_pass"], ["GITEA_TOKEN"]) + self.assertIn("MY_SECRET", out["env_dropped"]) + self.assertIn("ANTHROPIC_API_KEY", out["env_dropped"]) + self.assertNotIn("GITEA_TOKEN", out["env_dropped"]) + self.assertNotIn("CLAUDE_CODE_EXECPATH", out["env_dropped"]) + for v in ("val-gitea-1", "val-secret-2", "val-key-3"): + self.assertNotIn(v, raw) + self.assertNotIn(v, (self.state / "run.json").read_text(encoding="utf-8")) + + def test_pass_env_value_never_echoed_or_stored(self): + """review 2 I1: `--pass-env "$TOKEN"` passes the value. A digit-led hex token and a token + shaped like a valid name are both refused; neither value reaches stdout or any file, and + nothing is written.""" + hexv, ghp = "3f9a0c1d5e7b2a4c6d8e0f1a3b5c7d9e1f2a4b6c", "ghp_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789" + self.pin("claude") + os.environ.update(GITEA_TOKEN=hexv, GH_TOKEN=ghp) + for value in (hexv, ghp): + code, out, raw = self.init("--pass-env", value) + self.assertEqual((code, out["error"]), (2, "pass_env_refused"), out) + self.assertNotIn("name", out) + for v in (hexv, ghp): + self.assertNotIn(v, raw) + self.assertIsNone(self.run_json()) + self.assertFalse(self.state.exists()) + scratch = self.tmp / "scratch" + files = [p for p in scratch.rglob("*") if p.is_file()] if scratch.exists() else [] + for p in files: + data = p.read_bytes() + for v in (hexv, ghp): + self.assertNotIn(v.encode(), data, p) + + def test_usage_error_never_echoes_values(self): + """`--pass-env NAME VALUE` (a slip for NAME=VALUE): the stray value is not printed.""" + self.pin("claude") + code, out, raw = self.init("--pass-env", "GITEA_TOKEN", "val-xyz") + self.assertEqual((code, out["error"], out["detail"]), (2, "usage", "unrecognized arguments")) + self.assertNotIn("val-xyz", raw) + self.assertIsNone(self.run_json()) + + +class PassEnvLaunchTest(_Cli): + def test_child_env_names(self): + """M1: through train and spawn, the child gets the passed GITEA_TOKEN and not an unpassed + secret-shaped name (fake_claude logs env names only).""" + self.pin("claude") + os.environ.update(GITEA_TOKEN="val-gitea-1", OTHER_SECRET="val-secret-2") + code, out, _ = self.init("--pass-env", "GITEA_TOKEN") + self.assertEqual(code, 0, out) + self.fake_argv() + code, out, _ = self.g("train", "--run", self.run_md, "--base", "B1", "--brief", str(self.brief)) + self.assertEqual((code, out["status"]), (0, "ok")) + code, out, _ = self.g("spawn", "--run", self.run_md, "--base", "B1", "--job", "1.1", + "--brief", str(self.brief)) + self.assertEqual((code, out["status"]), (0, "ok")) + log = self.log.read_text(encoding="utf-8") + calls = [json.loads(ln) for ln in log.splitlines()] + self.assertEqual(len(calls), 2) + for c in calls: + self.assertIn("GITEA_TOKEN", c["env_names"]) + self.assertNotIn("OTHER_SECRET", c["env_names"]) + self.assertEqual(c["env_names"], sorted(c["env_names"])) + for v in ("val-gitea-1", "val-secret-2"): + self.assertNotIn(v, log) + + +class LaunchCallerTest(_Cli): + def setUp(self): + super().setUp() + self.pin("claude") + code, out, _ = self.init() + self.assertEqual(code, 0, out) + self.fake_argv() + + def calls(self): + return self.log.read_text(encoding="utf-8").splitlines() if self.log.exists() else [] + + def test_cross_harness_at_spawn(self): + """A clear Codex caller on a Claude run: refused before any job file; unclear passes.""" + code, out, _ = self.g("train", "--run", self.run_md, "--base", "B1", "--brief", str(self.brief)) + self.assertEqual(code, 0, out) + self.pin("codex") + code, out, _ = self.g("spawn", "--run", self.run_md, "--base", "B1", "--job", "1.1", + "--brief", str(self.brief)) + self.assertEqual((code, out["error"], out["detected"], out["asked"]), (2, "cross_harness", "codex", "claude")) + self.assertFalse((self.state / "jobs" / "1.1.json").exists()) + self.assertEqual(len(self.calls()), 1) + self.pin(None) + code, out, _ = self.g("spawn", "--run", self.run_md, "--base", "B1", "--job", "1.1", + "--brief", str(self.brief)) + self.assertEqual((code, out["status"]), (0, "ok")) + + def test_old_run_is_claude(self): + """A run.json without fingerprint.harness (0.3.x) launches through the Claude adapter.""" + self.fake_argv(drop_harness=True) + code, out, _ = self.g("train", "--run", self.run_md, "--base", "B1", "--brief", str(self.brief)) + self.assertEqual((code, out["status"], out["warnings"]), (0, "ok", [])) + self.assertIn("--session-id", json.loads(self.calls()[0])["argv"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/plugins/spire/skills/gremlins/tests/test_scrub.py b/plugins/spire/skills/gremlins/tests/test_scrub.py new file mode 100644 index 0000000..8b671f0 --- /dev/null +++ b/plugins/spire/skills/gremlins/tests/test_scrub.py @@ -0,0 +1,274 @@ +"""Env scrub per target (design §6.1, build plan §3.1). Every test passes an explicit environ.""" +import json +import os +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from grm import launch, scrub # noqa: E402 +from grm.errors import Refusal # noqa: E402 + +BIN = "/bin/claude" +CODEX_HOME = os.path.abspath(os.path.join(os.sep, "pinned", "codex-home")) +FP = {"binary": BIN, "codex_home": CODEX_HOME} +# synthetic token shapes (review 2 I1): a 40-hex Gitea token led by a digit, a GitHub-style one +TOKEN_HEX = "3f9a0c1d5e7b2a4c6d8e0f1a3b5c7d9e1f2a4b6c" +TOKEN_GHP = "ghp_AbCdEfGhIjKlMnOpQrStUvWxYz0123456789" + +# (name, kept on the claude target, kept on the codex target): one row per class x target +ROWS = [ + # Claude host and session vars + ("CLAUDE_CODE_MESSAGING_TOKEN", False, False), + ("CLAUDE_CODE_SESSION_ID", False, False), + ("CLAUDE_CODE_BRIDGE_SESSION_ID", False, False), + ("CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX", False, False), + ("ANTHROPIC_DEFAULT_OPUS_MODEL", False, False), + ("ENABLE_PROMPT_CACHING_1H", False, False), + # Claude markers + ("CLAUDECODE", True, False), + ("CLAUDE_CODE_CHILD_SESSION", True, False), + ("CLAUDE_PID", True, False), + ("AI_AGENT", True, False), + ("CLAUDE_CODE_GIT_BASH_PATH", True, False), + # Anthropic auth path + ("ANTHROPIC_API_KEY", False, False), + ("ANTHROPIC_AUTH_TOKEN", False, False), + ("CLAUDE_CODE_USE_BEDROCK", False, False), + ("CLAUDE_CODE_USE_VERTEX", False, False), + # Anthropic gateway and token + ("ANTHROPIC_BASE_URL", True, False), + ("CLAUDE_CODE_OAUTH_TOKEN", True, False), + # unlisted ANTHROPIC_* name: rule 6 on Claude, the ^ANTHROPIC_ catch-all on Codex + ("ANTHROPIC_CUSTOM_HEADERS", True, False), + # Codex host and session vars, with the three Codex-target keeps + ("CODEX_THREAD_ID", False, False), + ("CODEX_SESSION_ID", False, False), + ("CODEX_TOOL_CALL_ID", False, False), + ("CODEX_VERSION", False, False), + ("CODEX_CI", False, False), + ("CODEX_SANDBOX_NETWORK_DISABLED", False, False), + ("CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS", False, False), + ("CODEX_SQLITE_HOME", False, True), + ("CODEX_CA_CERTIFICATE", False, True), + # OpenAI auth path + ("OPENAI_API_KEY", False, False), + ("CODEX_API_KEY", False, False), + ("OPENAI_ORGANIZATION", False, False), + ("OPENAI_PROJECT", False, False), + ("OPENAI_IDENTITY_TOKEN_FILE", False, False), + ("OPENAI_SPIFFE_SOCKET", False, False), + ("OPENAI_FEDERATION_RULE_ID", False, False), + ("OPENAI_WORKLOAD_IDENTITY_CONTEXT", False, False), + # OpenAI gateway and token + ("OPENAI_BASE_URL", False, True), + ("CODEX_ACCESS_TOKEN", False, True), + # uv / venv + ("VIRTUAL_ENV", False, False), + ("UV_CACHE_DIR", False, False), + # rule 2b: other CLAUDE_CODE_* names, Claude target only + ("CLAUDE_CODE_CLIENT_KEY", True, False), + ("CLAUDE_CODE_API_KEY_HELPER_TTL_MS", True, False), + # secret-shaped + ("GITEA_TOKEN", False, False), + ("GH_TOKEN", False, False), + ("AWS_SECRET_ACCESS_KEY", False, False), + ("MY_API_KEY", False, False), + ("SERVICE_APIKEY", False, False), + ("DB_PASSWORD", False, False), + ("NET_PASSWD", False, False), + ("GOOGLE_APPLICATION_CREDENTIALS", False, False), + ("SIGNING_KEY", False, False), + ("SSH_PRIVATE_KEY_PATH", False, False), + ("gitea_token", False, False), # compared upper-case + # never secret-shaped, and not secret-shaped at all + ("SSH_AUTH_SOCK", True, True), + ("GPG_AGENT_INFO", True, True), + ("HOME", True, True), + ("USERPROFILE", True, True), + ("TOKENIZERS_PARALLELISM", True, True), + ("KEYBOARD_LAYOUT", True, True), + ("MONKEY_BUSINESS", True, True), + ("OTHER", True, True), +] + + +def value(name): + return "val-%s-9f3c" % name.lower() + + +class TableTest(unittest.TestCase): + def test_rows_per_class_and_target(self): + """Design §6.1: every class row on both targets (explicit environ, values never asserted).""" + environ = {n: value(n) for n, _, _ in ROWS} + for target, col in (("claude", 1), ("codex", 2)): + env = scrub.env_for(target, FP, environ) + for row in ROWS: + self.assertEqual(row[0] in env, row[col], "%s on %s" % (row[0], target)) + + def test_pinned_claude(self): + """Rule 1 on Claude: host values replaced by the pins; CODEX_HOME dropped.""" + environ = {"DISABLE_AUTOUPDATER": "0", "CLAUDE_CODE_PROMPT_CACHE_TTL": "5m", + "CLAUDE_CODE_EXECPATH": "/host/claude", "CODEX_HOME": "/host/codex"} + env = scrub.env_for("claude", FP, environ) + self.assertEqual({k: env[k] for k in scrub.SCRUB_PINNED}, scrub.SCRUB_PINNED) + self.assertEqual(env[scrub.SCRUB_PINNED_BINARY], BIN) + self.assertNotIn("CODEX_HOME", env) + + def test_pinned_codex_home(self): + """D-B4: on Codex the host CODEX_HOME is replaced by fp["codex_home"]; no Claude pins.""" + environ = {"CODEX_HOME": "/host/codex", "CLAUDE_CODE_PROMPT_CACHE_TTL": "1h", + "CLAUDE_CODE_EXECPATH": "/host/claude"} + env = scrub.env_for("codex", FP, environ) + self.assertEqual(env["CODEX_HOME"], CODEX_HOME) + self.assertEqual(scrub.env_for("codex", FP, {})["CODEX_HOME"], CODEX_HOME) + for k in ("CLAUDE_CODE_PROMPT_CACHE_TTL", "CLAUDE_CODE_EXECPATH"): + self.assertNotIn(k, env) + + def test_env_pass(self): + """Rule 4: a passed name survives the secret-shaped rule; it cannot rescue a harness row.""" + environ = {"GITEA_TOKEN": value("g"), "ANTHROPIC_API_KEY": value("a")} + for target in ("claude", "codex"): + env = scrub.env_for(target, dict(FP, env_pass=["GITEA_TOKEN", "ANTHROPIC_API_KEY"]), environ) + self.assertIn("GITEA_TOKEN", env) + self.assertNotIn("ANTHROPIC_API_KEY", env) + self.assertNotIn("GITEA_TOKEN", scrub.env_for(target, FP, environ)) + + def test_venv_path_stripped_on_both_targets(self): + """As today: venv PATH entries are removed, on both targets.""" + venv = os.path.abspath(os.path.join(os.sep, "tmp", "venv")) + keep = os.path.abspath(os.path.join(os.sep, "usr", "bin")) + environ = {"PATH": os.pathsep.join([os.path.join(venv, "bin"), keep]), "VIRTUAL_ENV": venv} + for target in ("claude", "codex"): + self.assertEqual(scrub.env_for(target, FP, environ)["PATH"], keep, target) + + def test_scrubbed_env_is_claude_target(self): + """`scrubbed_env(binary, environ)` = `env_for("claude", {"binary": binary}, environ)`; + `launch` re-exports it.""" + environ = {n: value(n) for n, _, _ in ROWS} + self.assertEqual(scrub.scrubbed_env(BIN, environ), + scrub.env_for("claude", {"binary": BIN}, environ)) + self.assertIs(launch.scrubbed_env, scrub.scrubbed_env) + self.assertIs(launch.SCRUB_DROP, scrub.SCRUB_DROP) + + def test_unknown_target(self): + with self.assertRaises(ValueError): + scrub.env_for("gemini", FP, {}) + + +class DirectionTest(unittest.TestCase): + """The three directions of the bundle, as whole envs.""" + + CLAUDE_HOST_ENV = {"CLAUDECODE": "1", "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_MESSAGING_TOKEN": "m", + "CLAUDE_CODE_OAUTH_TOKEN": "o", "CLAUDE_PID": "1", "AI_AGENT": "claude", + "ANTHROPIC_BASE_URL": "u", "CLAUDE_CODE_CLIENT_KEY": "k", "HOME": "/h", "PATH": "/usr/bin"} + CODEX_HOST_ENV = {"CODEX_THREAD_ID": "t", "CODEX_SESSION_ID": "s", "CODEX_TOOL_CALL_ID": "c", + "CODEX_VERSION": "v", "CODEX_CI": "1", "CODEX_SANDBOX_NETWORK_DISABLED": "1", + "CODEX_HOME": "/host/codex", "CODEX_ACCESS_TOKEN": "a", "OPENAI_API_KEY": "k", + "CODEX_API_KEY": "k", "OPENAI_BASE_URL": "u", "HOME": "/h", "PATH": "/usr/bin"} + + def test_claude_caller_to_codex_gremlin(self): + """Every CLAUDE* and ANTHROPIC* name is dropped, the messaging token included.""" + env = scrub.env_for("codex", FP, self.CLAUDE_HOST_ENV) + self.assertEqual(sorted(env), ["CODEX_HOME", "HOME", "PATH"]) + + def test_codex_caller_to_claude_gremlin(self): + """Every CODEX_* name and the OpenAI auth path are dropped.""" + env = scrub.env_for("claude", FP, self.CODEX_HOST_ENV) + self.assertEqual(sorted(env), sorted(["HOME", "PATH", scrub.SCRUB_PINNED_BINARY, *scrub.SCRUB_PINNED])) + + def test_codex_caller_to_codex_gremlin(self): + """The caller's session vars are dropped; CODEX_HOME (pinned), the access token and the + gateway are kept.""" + env = scrub.env_for("codex", FP, self.CODEX_HOST_ENV) + self.assertEqual(sorted(env), ["CODEX_ACCESS_TOKEN", "CODEX_HOME", "HOME", "OPENAI_BASE_URL", "PATH"]) + self.assertEqual(env["CODEX_HOME"], CODEX_HOME) + + +class DroppedTest(unittest.TestCase): + def test_env_dropped_names_only(self): + """Rules 2 and 5 only (pinned names are replaced, not dropped); sorted; no value in the JSON.""" + environ = {"GITEA_TOKEN": value("g"), "ANTHROPIC_API_KEY": value("a"), "CODEX_THREAD_ID": value("t"), + "DISABLE_AUTOUPDATER": value("d"), "CODEX_HOME": value("h"), "OTHER": value("o"), + "SSH_AUTH_SOCK": value("s"), "GH_TOKEN": value("gh")} + got = scrub.env_dropped("claude", environ, ["GH_TOKEN"]) + self.assertEqual(got, ["ANTHROPIC_API_KEY", "CODEX_HOME", "CODEX_THREAD_ID", "GITEA_TOKEN"]) + got_codex = scrub.env_dropped("codex", environ, []) + self.assertEqual(got_codex, ["ANTHROPIC_API_KEY", "CODEX_THREAD_ID", "GH_TOKEN", "GITEA_TOKEN"]) + for out in (got, got_codex): + blob = json.dumps(out) + for v in environ.values(): + self.assertNotIn(v, blob) + + +class PassEnvTest(unittest.TestCase): + def refused(self, name): + with self.assertRaises(Refusal) as cm: + scrub.check_pass_env(["GITEA_TOKEN", name]) + self.assertEqual((cm.exception.payload["error"], cm.exception.payload["name"]), + ("pass_env_refused", name)) + return cm.exception.payload["detail"] + + def test_accepts_and_dedupes(self): + """Secret-shaped and harmless names are accepted, sorted and deduplicated.""" + self.assertEqual(scrub.check_pass_env(["GITEA_TOKEN", "GH_TOKEN", "GITEA_TOKEN", "PATH", "OTHER"]), + ["GH_TOKEN", "GITEA_TOKEN", "OTHER", "PATH"]) + self.assertEqual(scrub.check_pass_env([]), []) + + def test_refuses_harness_names(self): + """Rules 1, 2 and 2b on either target: 'that variable belongs to a harness'.""" + for name in ("ANTHROPIC_API_KEY", "CODEX_HOME", "DISABLE_AUTOUPDATER", "CLAUDE_CODE_EXECPATH", + "CODEX_ACCESS_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_CLIENT_KEY", + "OPENAI_API_KEY", "UV_INDEX_TOKEN", "anthropic_api_key"): + self.assertEqual(self.refused(name), "that variable belongs to a harness", name) + + def test_refuses_invalid_names(self): + """review 2 I1: an invalid name is refused by its position only; the argument (it may be a + value) is never echoed.""" + for name in ("", "1BAD", "A-B", "A B"): + with self.assertRaises(Refusal) as cm: + scrub.check_pass_env(["GITEA_TOKEN", name]) + payload = cm.exception.payload + self.assertEqual((payload["error"], payload["index"], payload["detail"]), + ("pass_env_refused", 1, "not a valid environment variable name"), name) + self.assertNotIn("name", payload, name) + if name: + self.assertNotIn(name, json.dumps(payload), name) + + def test_value_instead_of_name_never_echoes(self): + """review 2 I1: `--pass-env "$GITEA_TOKEN"` (the value, not the name), for a digit-led hex + token and for one shaped like a valid env name: refused with no `name`, no echo.""" + environ = {"GITEA_TOKEN": TOKEN_HEX, "GH_TOKEN": TOKEN_GHP, "PATH": "/usr/bin"} + for value in (TOKEN_HEX, TOKEN_GHP): + with self.assertRaises(Refusal) as cm: + scrub.check_pass_env(["GITEA_TOKEN", value], environ) + payload = cm.exception.payload + self.assertEqual((payload["error"], payload["detail"]), + ("pass_env_refused", "that looks like a value, not a variable name")) + self.assertNotIn("name", payload) + for v in (TOKEN_HEX, TOKEN_GHP): + self.assertNotIn(v, json.dumps(payload)) + self.assertNotIn(v, str(cm.exception)) + # without an environ the digit-led token is still refused unechoed (invalid name) + with self.assertRaises(Refusal) as cm: + scrub.check_pass_env([TOKEN_HEX]) + self.assertNotIn(TOKEN_HEX, json.dumps(cm.exception.payload)) + # a name that is also some variable's value, but itself set, is a name + self.assertEqual(scrub.check_pass_env(["GITEA_TOKEN"], {"GITEA_TOKEN": "x", "REF": "GITEA_TOKEN"}), + ["GITEA_TOKEN"]) + + def test_name_value_pair_never_echoes_the_value(self): + """I1: `--pass-env NAME=VALUE` names only the part before the first `=`; no value leaves.""" + for arg, name in (("GITEA_TOKEN=val-tok-9f3c=x", "GITEA_TOKEN"), ("=val-tok-9f3c", "")): + with self.assertRaises(Refusal) as cm: + scrub.check_pass_env([arg]) + payload = cm.exception.payload + self.assertEqual((payload["error"], payload["name"], payload["detail"]), + ("pass_env_refused", name, "pass names only, not NAME=VALUE")) + self.assertNotIn("val-tok-9f3c", json.dumps(payload)) + self.assertNotIn("val-tok-9f3c", str(cm.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/plugins/spire/skills/gremlins/tests/test_title.py b/plugins/spire/skills/gremlins/tests/test_title.py new file mode 100644 index 0000000..f9bb46c --- /dev/null +++ b/plugins/spire/skills/gremlins/tests/test_title.py @@ -0,0 +1,128 @@ +import contextlib +import io +import json +import os +import shutil +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path +from unittest import mock + +SKILL = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(SKILL)) +sys.path.insert(0, str(SKILL / "tests")) + +from grm import cli, title # noqa: E402 +from _pin import pin_caller # noqa: E402 + +GRM = SKILL / "grm" +FAKE = str(SKILL / "tests" / "fake_claude.py") +T = 1795000000 +WHEN = time.strftime("%m-%d %H:%M", time.localtime(T)) +RUN = "/x/logs/2026-11-24-11-acp-client-name/run.md" + + +class TitleTest(unittest.TestCase): + def test_formats(self): + e = title.TITLE_EMOJI + self.assertEqual(title.make("train", "B1", "", RUN, T), + "%s B1 \u00b7 acp-client-name \u00b7 %s" % (e, WHEN)) + self.assertEqual(title.make("spawn", "B1", "1.1", RUN, T), + "%s B1 \u203a 1.1 \u00b7 acp-client-name \u00b7 %s" % (e, WHEN)) + self.assertEqual(title.make("rebase", "B1", "2", RUN, T), + "%s B1 \u203a rebase 2 \u00b7 acp-client-name \u00b7 %s" % (e, WHEN)) + + def test_date_prefixes(self): + self.assertIn(" \u00b7 name \u00b7 ", title.make("train", "B1", "", "/x/logs/2026-11-24-name/run.md", T)) + self.assertIn(" \u00b7 name \u00b7 ", title.make("train", "B1", "", "/x/logs/2026-11-24-11-name/run.md", T)) + + def test_no_date_prefix_kept(self): + self.assertIn(" \u00b7 plain-name \u00b7 ", title.make("train", "B1", "", "/x/logs/plain-name/run.md", T)) + + def test_truncation(self): + slug = "2026-11-24-11-" + "a" * 60 + out = title.make("train", "B1", "", "/x/logs/%s/run.md" % slug, T) + self.assertIn(" \u00b7 " + "a" * 40 + " \u00b7 ", out) + self.assertNotIn("a" * 41, out) + + def test_unknown_kind(self): + with self.assertRaises(ValueError): + title.make("bogus", "B1", "", RUN, T) + + def test_default_time(self): + out = title.make("train", "B1", "", RUN) + self.assertRegex(out, r" \u00b7 \d\d-\d\d \d\d:\d\d$") + + +class EmojiTest(unittest.TestCase): + def test_only_title_emoji(self): + hits = [] + for p in sorted(GRM.glob("*.py")): + for ch in p.read_text(encoding="utf-8"): + if ord(ch) >= 0x1F000 or 0x2600 <= ord(ch) <= 0x27BF: + hits.append((p.name, ch)) + self.assertEqual(hits, [("title.py", title.TITLE_EMOJI)]) + + +class TitleCliTest(unittest.TestCase): + """Design §5.2 through the cli on fake_claude: `--name` per call only, the prefix unchanged.""" + + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + repo = self.tmp / "repo" + repo.mkdir() + for a in (["init", "-q"], ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", + "--allow-empty", "-m", "x"]): + subprocess.run(["git", *a], cwd=repo, check=True, capture_output=True) + self.run_md = str(self.tmp / "logs" / "2026-11-24-11-title-probe" / "run.md") + self.state = self.tmp / "scratch" / "2026-11-24-11-title-probe" / "gremlins" + self.log = self.tmp / "fake.jsonl" + self.brief = self.tmp / "brief.md" + self.brief.write_text("do the thing\n", encoding="utf-8") + env = mock.patch.dict(os.environ, {"FAKE_CLAUDE_LOG": str(self.log), "FAKE_CLAUDE_SCENARIO": "ok", + "SPIRE_SCRATCH": str(self.tmp / "scratch")}) + env.start() + self.addCleanup(env.stop) + pin_caller(self, "claude") + code, out = self.g("init", "--run", self.run_md, "--model", "claude-opus-5-5", "--cwd", str(repo), + "--binary", sys.executable) + self.assertEqual(code, 0, out) + run = json.loads((self.state / "run.json").read_text(encoding="utf-8")) + run["argv"] = [sys.executable, FAKE] + run["argv"][1:] + (self.state / "run.json").write_text(json.dumps(run), encoding="utf-8") + + def g(self, *args): + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = cli.main(list(args)) + return code, json.loads(buf.getvalue().splitlines()[-1]) + + def test_name_per_call_and_prefix_unchanged(self): + before = (self.state / "run.json").read_bytes(), (self.state / "preamble.md").read_bytes() + common = ["--run", self.run_md, "--base", "B1", "--brief", str(self.brief)] + for cmd in (["train"], ["spawn", "--job", "1.1"], ["rebase"]): + code, out = self.g(*cmd, *common) + self.assertEqual((code, out["status"]), (0, "ok"), out) + self.assertEqual(((self.state / "run.json").read_bytes(), (self.state / "preamble.md").read_bytes()), + before) + stored = json.loads(before[0])["argv"] + self.assertNotIn("--name", stored) + calls = [json.loads(ln) for ln in self.log.read_text(encoding="utf-8").splitlines()] + heads = {"B1-train": "B1 \u00b7 ", "1.1": "B1 \u203a 1.1 \u00b7 ", "B1-rebase1": "B1 \u203a rebase 1 \u00b7 "} + self.assertEqual(len(calls), 3) + for job, call in zip(heads, calls): + rec = json.loads((self.state / "jobs" / (job + ".json")).read_text(encoding="utf-8")) + argv = call["argv"] + self.assertEqual(argv[:len(stored) - 1], stored[1:]) + self.assertEqual(argv.count("--name"), 1) + self.assertEqual(argv[argv.index("--name") + 1], rec["title"]) + self.assertTrue(rec["title"].startswith(title.TITLE_EMOJI + " " + heads[job]), rec["title"]) + self.assertIn(" \u00b7 title-probe \u00b7 ", rec["title"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/plugins/spire/skills/igor/references/upgrades.md b/plugins/spire/skills/igor/references/upgrades.md new file mode 100644 index 0000000..5a98fed --- /dev/null +++ b/plugins/spire/skills/igor/references/upgrades.md @@ -0,0 +1,10 @@ +# Spire upgrade notes: Igor's handling + +Read when startup printed `## Spire upgrade notes pending`. The header names the installed version, the marker and the `Ack command`. Follow these steps in order. + +1. **Check.** Dispatch one `scout`. Brief it with every printed item: title, `Affects:` and `Check:` lines verbatim. It runs each `Check:` in this checkout (from the project root, read-only) and returns per item: applies, already done, or not applicable, with the evidence line. +2. **Tell the user, once, concisely.** Spire was upgraded; only the items that apply, each with its change and fix; offer to do them. Items already done or not applicable get one summary line at most. +3. **Act only when the user asks.** Dispatch fixes by the normal delegation table. Destructive or outward-facing fixes follow Rules. Commits follow the project's conventions. +4. **Ack.** Once every pending item is done, dismissed by the user, or not applicable, run the header's `Ack command` yourself in one Bash call (the skill's `allowed-tools` covers your own call, not a child's; this is the one exception to delegating commands). Journal it. Never write the marker by hand. If ack exits 1, journal its stderr line and leave it; do not retry or debug. +5. **Later.** If the user says "later" or some item stays open: no ack. Journal it, say once that the notes return next session, and do not raise them again this session. +6. **Silence on failure.** Never report a missing or broken upgrade-notes mechanism. Silence is the designed error state. diff --git a/plugins/spire/skills/igor/tests/test_upgrade_notes.py b/plugins/spire/skills/igor/tests/test_upgrade_notes.py new file mode 100644 index 0000000..075efea --- /dev/null +++ b/plugins/spire/skills/igor/tests/test_upgrade_notes.py @@ -0,0 +1,514 @@ +import os +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path + +IGOR = Path(__file__).resolve().parent.parent +PLUGIN = IGOR.parent.parent +SCRIPT = IGOR / "upgrade-notes.sh" +TIMEOUT = 10 + +ENTRIES = ( + "## 0.5.0\n\n### Future thing\n- Change: later.\n- Affects: nothing yet.\n" + "- Check: grep -q future .\n- Fix: wait.\n\n" + "## 0.4.0 (2026-12-01)\n\n### Four thing\n- Change: four.\n- Affects: x.\n" + "- Check: grep -q four .\n- Fix: do four.\n\n" + "## 0.3.1\n\n### Three thing\n- Change: three.\n- Affects: y.\n" + "- Check: grep -q three .\n- Fix: do three.\n" +) +PREAMBLE = "# Spire upgrade notes\n\nPreamble text, never printed.\n\n" +UPGRADES = PREAMBLE + ENTRIES + +WIRING_LINE = ( + '!`sh "${CLAUDE_SKILL_DIR}/upgrade-notes.sh" "${CLAUDE_PLUGIN_ROOT}" ' + '"${CLAUDE_PROJECT_DIR}" 2>/dev/null || true`' +) + + +class Base(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()).resolve() + self.addCleanup(shutil.rmtree, self.tmp, True) + self.root = self.tmp / "plugin" + self.proj = self.tmp / "proj" + (self.root / ".claude-plugin").mkdir(parents=True) + self.proj.mkdir() + self.manifest("0.4.0") + self.upgrades(UPGRADES) + + def manifest(self, version): + body = '{\n "name": "spire",\n "version": "%s",\n "x": 1\n}\n' % version + (self.root / ".claude-plugin" / "plugin.json").write_text(body) + + def upgrades(self, text, newline=None): + with open(self.root / "UPGRADES.md", "w", newline=newline) as f: + f.write(text) + + def marker(self, content): + d = self.proj / ".spire" + d.mkdir(exist_ok=True) + (d / "upgrades.lock").write_bytes( + content if isinstance(content, bytes) else content.encode() + ) + + @property + def marker_path(self): + return self.proj / ".spire" / "upgrades.lock" + + def run_sh(self, *args, shell=("sh",), env=None): + return subprocess.run( + [*shell, str(SCRIPT), *args], + capture_output=True, + text=True, + timeout=TIMEOUT, + env=env, + ) + + def check(self, root=None, proj=None, **kw): + r = self.run_sh( + str(self.root) if root is None else root, + str(self.proj) if proj is None else proj, + **kw, + ) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(r.stderr, "") + return r.stdout + + def assertSilent(self, **kw): + self.assertEqual(self.check(**kw), "") + + +class CheckTest(Base): + def test_missing_marker(self): + out = self.check() + self.assertTrue(out.startswith("## Spire upgrade notes pending\n\n")) + self.assertIn("## 0.4.0 (2026-12-01)", out) + self.assertIn("## 0.3.1", out) + self.assertNotIn("## 0.5.0", out) + self.assertNotIn("Preamble text", out) + self.assertLess(out.index("## 0.4.0"), out.index("## 0.3.1")) + self.assertIn('marker: none (`%s/.spire/upgrades.lock`)' % self.proj, out) + + def test_header_exact(self): + out = self.check() + head = out.split("\n\n")[1] + r, p = self.root, self.proj + self.assertEqual( + head, + "Installed Spire 0.4.0; this checkout's marker: none " + "(`%s/.spire/upgrades.lock`). Follow `%s/skills/igor/references/upgrades.md`. " + 'Ack command: `sh "%s" ack "%s" "%s"`.' + % (p, r, SCRIPT, r, p), + ) + + def test_entries_verbatim(self): + out = self.check() + body = out.split("\n\n", 2)[2] + want = ENTRIES.split("## 0.3.1")[0].split("## 0.5.0")[1].split("## 0.4.0")[1] + self.assertEqual(body, "## 0.4.0" + want + "## 0.3.1" + ENTRIES.split("## 0.3.1")[1]) + + def test_partial(self): + self.marker("0.3.1\n") + out = self.check() + self.assertIn("marker: 0.3.1", out) + self.assertIn("## 0.4.0", out) + self.assertNotIn("## 0.3.1", out) + self.assertNotIn("## 0.5.0", out) + + def test_nothing_pending(self): + self.marker("0.4.0\n") + self.assertSilent() + + def test_newer_marker(self): + self.marker("0.9.0\n") + self.assertSilent() + + def test_marker_crlf_spaces(self): + self.marker(b" 0.3.1\r\n") + out = self.check() + self.assertIn("## 0.4.0", out) + self.assertNotIn("## 0.3.1", out) + + def test_marker_no_newline(self): + self.marker("0.3.1") + self.assertNotIn("## 0.3.1", self.check()) + + def test_broken_marker(self): + for content in ("garbage\n", "", "\n", "0.3\n", "0.3.1-rc1\n", "v0.3.1\n"): + with self.subTest(content=content): + self.marker(content) + self.assertSilent() + + def test_broken_manifest(self): + p = self.root / ".claude-plugin" / "plugin.json" + p.unlink() + self.assertSilent() + p.write_text("{}\n") + self.assertSilent() + self.manifest("0.4.0-rc1") + self.assertSilent() + self.manifest("garbage") + self.assertSilent() + + def test_missing_or_headless_upgrades(self): + (self.root / "UPGRADES.md").unlink() + self.assertSilent() + self.upgrades("Just prose.\n\n- no headings here\n") + self.assertSilent() + self.upgrades("") + self.assertSilent() + + def test_no_entry_in_range(self): + self.marker("0.3.1\n") + self.upgrades(PREAMBLE + ENTRIES.split("## 0.4.0")[0] + "## 0.3.1\n\nold\n") + self.assertSilent() + + def test_empty_args(self): + self.assertSilent(root="") + self.assertSilent(proj="") + r = self.run_sh() + self.assertEqual((r.returncode, r.stdout, r.stderr), (0, "", "")) + + def test_crlf_upgrades(self): + self.upgrades(UPGRADES, newline="\r\n") + raw = (self.root / "UPGRADES.md").read_bytes() + self.assertIn(b"\r\n", raw) + out = self.check() + self.assertIn("## 0.4.0 (2026-12-01)", out) + self.assertIn("## 0.3.1", out) + self.assertNotIn("\r", out) + + def test_crlf_manifest(self): + p = self.root / ".claude-plugin" / "plugin.json" + p.write_bytes(b'{\r\n "version": "0.4.0"\r\n}\r\n') + self.assertIn("## 0.4.0", self.check()) + + def test_numeric_compare(self): + self.manifest("0.10.0") + self.upgrades(PREAMBLE + "## 0.10.0\n\nten\n\n## 0.9.0\n\nnine\n") + self.marker("0.9.0\n") + out = self.check() + self.assertIn("## 0.10.0", out) + self.assertNotIn("## 0.9.0", out) + self.marker("0.10.0\n") + self.assertSilent() + + def test_non_version_heading_ends_entry(self): + self.upgrades(PREAMBLE + "## 0.4.0\n\nfour\n\n## Notes\n\nstray\n\n## 0.3.1\n\nthree\n") + out = self.check() + self.assertIn("four", out) + self.assertNotIn("stray", out) + self.assertIn("three", out) + + def test_check_lines_never_run(self): + ran = self.tmp / "ran" + ran2 = self.tmp / "ran2" + ran3 = self.tmp / "ran3" + lines = [ + "- Check: touch %s/ran" % self.tmp, + "- Check: echo $(touch %s/ran2)" % self.tmp, + "- Check: echo `touch %s/ran3`" % self.tmp, + ] + self.upgrades(PREAMBLE + "## 0.4.0\n\n### T\n- Change: c.\n- Affects: a.\n%s\n- Fix: f.\n" + % "\n".join(lines)) + out = self.check() + for line in lines: + self.assertIn(line + "\n", out) + for f in (ran, ran2, ran3): + self.assertFalse(f.exists(), f) + + def test_gawk_posix_shim(self): + shim = self.tmp / "shim" + shim.mkdir() + gawk = shutil.which("gawk") + if not gawk: + self.skipTest("no gawk") + a = shim / "awk" + a.write_text('#!/bin/sh\nexec %s --posix "$@"\n' % gawk) + a.chmod(0o755) + env = dict(os.environ, PATH="%s:%s" % (shim, os.environ["PATH"])) + out = self.check(env=env) + self.assertIn("## 0.4.0", out) + self.assertIn("## 0.3.1", out) + self.marker("0.3.1\n") + out = self.check(env=env) + self.assertIn("## 0.4.0", out) + self.assertNotIn("## 0.3.1", out) + self.upgrades(UPGRADES, newline="\r\n") + self.assertIn("## 0.4.0", self.check(env=env)) + + def test_bash_posix(self): + bash = shutil.which("bash") + if not bash: + self.skipTest("no bash") + shell = (bash, "--posix") + out = self.check(shell=shell) + self.assertIn("## 0.4.0", out) + self.assertIn("## 0.3.1", out) + self.marker("0.3.1\n") + out = self.check(shell=shell) + self.assertIn("## 0.4.0", out) + self.assertNotIn("## 0.3.1", out) + + def test_one_line_manifest(self): + p = self.root / ".claude-plugin" / "plugin.json" + p.write_text('{"name":"spire","version":"0.4.0"}') + out = self.check() + self.assertIn("## 0.4.0", out) + self.assertIn("Installed Spire 0.4.0;", out) + p.write_text('{"name": "spire", "version" : "0.4.0", "x": {"version": "9.9.9"}}\n') + self.assertIn("Installed Spire 0.4.0;", self.check()) + p.write_text('{"version":"0.4.0-rc1","x":{"version":"0.4.0"}}\n') + self.assertSilent() + + def test_fast_path_reads_first_record_only(self): + """Marker = installed: awk opens UPGRADES.md and reads its first record, then exits. + A huge file must cost far less than the same scan when entries are in range.""" + big = self.root / "UPGRADES.md" + with open(big, "w") as f: + f.write(PREAMBLE) + f.write("## 0.4.0\n") + f.write("filler line of an entry that is long enough to cost something\n" * 400000) + f.write("## 0.1.0\nold\n") + + def best(n=3): + t = [] + for _ in range(n): + t0 = time.perf_counter() + r = self.run_sh(str(self.root), str(self.proj)) + t.append(time.perf_counter() - t0) + self.assertEqual(r.returncode, 0) + return min(t), r.stdout + + self.marker("0.3.1\n") + slow, out = best() + self.assertIn("## 0.4.0", out) + self.marker("0.4.0\n") + fast, out = best() + self.assertEqual(out, "") + self.assertLess(fast, slow / 4, "fast path %.4fs vs full scan %.4fs" % (fast, slow)) + + @unittest.skipIf(os.geteuid() == 0, "root reads chmod 000 files") + def test_fast_path_skips_upgrades(self): + """Unreadable UPGRADES.md stays silent (the early exit itself is test_fast_path_reads_first_record_only).""" + self.marker("0.4.0\n") + up = self.root / "UPGRADES.md" + up.chmod(0) + self.addCleanup(up.chmod, stat.S_IRUSR | stat.S_IWUSR) + self.assertSilent() + + def test_writes_nothing(self): + before = sorted(p.relative_to(self.tmp) for p in self.tmp.rglob("*")) + self.check() + self.assertEqual(before, sorted(p.relative_to(self.tmp) for p in self.tmp.rglob("*"))) + self.assertFalse((self.proj / ".spire").exists()) + + def test_script_shape(self): + text = SCRIPT.read_text() + self.assertIn("exec 2>/dev/null", text) + check_part = text.split("exec 2>/dev/null", 1)[1] + self.assertNotIn("$(", check_part) + self.assertEqual(check_part.count("awk "), 1) + + +class AckTest(Base): + def ack(self, *args, **kw): + a = args or (str(self.root), str(self.proj)) + return self.run_sh("ack", *a, **kw) + + def test_fresh(self): + r = self.ack() + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("0.4.0", r.stdout) + self.assertEqual(len(r.stdout.splitlines()), 1) + self.assertEqual(r.stderr, "") + self.assertEqual(self.marker_path.read_bytes(), b"0.4.0\n") + self.assertEqual((self.proj / ".spire" / ".gitignore").read_bytes(), b"*\n") + self.assertIn(str(self.marker_path), r.stdout) + self.assertSilent() + + def test_one_line_manifest(self): + (self.root / ".claude-plugin" / "plugin.json").write_text('{"name":"spire","version":"0.4.0"}') + r = self.ack() + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(self.marker_path.read_bytes(), b"0.4.0\n") + + def test_real_manifest(self): + import json + real = PLUGIN / ".claude-plugin" / "plugin.json" + want = json.loads(real.read_text())["version"] + shutil.copy(real, self.root / ".claude-plugin" / "plugin.json") + r = self.ack() + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(self.marker_path.read_bytes(), (want + "\n").encode()) + + def test_keeps_existing_gitignore(self): + d = self.proj / ".spire" + d.mkdir() + (d / ".gitignore").write_bytes(b"# mine\n*\n!keep\n") + r = self.ack() + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual((d / ".gitignore").read_bytes(), b"# mine\n*\n!keep\n") + + def test_overwrites_old_marker(self): + self.marker("0.1.0\nextra\n") + r = self.ack() + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(self.marker_path.read_bytes(), b"0.4.0\n") + + def test_broken_manifest(self): + p = self.root / ".claude-plugin" / "plugin.json" + for body in (None, "{}\n", '{"version": "0.4.0-rc1"}\n'): + with self.subTest(body=body): + if body is None: + p.unlink() + else: + p.write_text(body) + r = self.ack() + self.assertEqual(r.returncode, 1) + self.assertNotEqual(r.stderr.strip(), "") + self.assertEqual(r.stdout, "") + self.assertFalse((self.proj / ".spire").exists()) + + def test_broken_manifest_keeps_marker(self): + self.marker("0.1.0\n") + (self.root / ".claude-plugin" / "plugin.json").write_text("{}\n") + r = self.ack() + self.assertEqual(r.returncode, 1) + self.assertEqual(self.marker_path.read_bytes(), b"0.1.0\n") + + def test_empty_args(self): + for args in ((), ("",), ("", str(self.proj)), (str(self.root), ""), (str(self.root),)): + with self.subTest(args=args): + r = self.run_sh("ack", *args) + self.assertEqual(r.returncode, 1) + self.assertNotEqual(r.stderr.strip(), "") + self.assertFalse((self.proj / ".spire").exists()) + + @unittest.skipIf(os.geteuid() == 0, "root ignores permissions") + def test_write_failure(self): + d = self.proj / ".spire" + d.mkdir() + self.marker("0.1.0\n") + d.chmod(stat.S_IRUSR | stat.S_IXUSR) + self.addCleanup(d.chmod, stat.S_IRWXU) + r = self.ack() + self.assertEqual(r.returncode, 1) + self.assertNotEqual(r.stderr.strip(), "") + self.assertEqual(self.marker_path.read_bytes(), b"0.1.0\n") + + +class ShippedTest(unittest.TestCase): + """Red until the shipped UPGRADES.md and Igor wiring land.""" + + def test_shipped_upgrades_items(self): + text = (PLUGIN / "UPGRADES.md").read_text() + m = re.search(r"^## 0\.4\.0\b.*?(?=^## |\Z)", text, re.S | re.M) + self.assertIsNotNone(m, "no ## 0.4.0 entry") + items = re.split(r"^### ", m.group(0), flags=re.M)[1:] + self.assertTrue(items) + for item in items: + for field in ("Change:", "Affects:", "Check:", "Fix:"): + self.assertIn("- " + field, item, item.splitlines()[0]) + + def test_shipped_upgrades_prints(self): + tmp = Path(tempfile.mkdtemp()).resolve() + self.addCleanup(shutil.rmtree, tmp, True) + (tmp / "root" / ".claude-plugin").mkdir(parents=True) + (tmp / "proj").mkdir() + shutil.copy(PLUGIN / "UPGRADES.md", tmp / "root" / "UPGRADES.md") + (tmp / "root" / ".claude-plugin" / "plugin.json").write_text('{\n "version": "0.4.0"\n}\n') + r = subprocess.run( + ["sh", str(SCRIPT), str(tmp / "root"), str(tmp / "proj")], + capture_output=True, text=True, timeout=TIMEOUT, + ) + self.assertEqual((r.returncode, r.stderr), (0, "")) + self.assertIn("## 0.4.0", r.stdout) + + # item title -> (fixture that must hit, fixture that must not hit); path -> text + CHECK_FIXTURES = { + "workpad is now quire": ( + {".claude/agents/a.md": "skills:\n - spire:workpad\n"}, + {".claude/agents/a.md": "skills:\n - spire:quire\n"}, + ), + "attacker is now advocate": ( + {".claude/agents/a.md": "dispatch: spire:attacker\n"}, + {".claude/agents/a.md": "dispatch: spire:advocate\n"}, + ), + "Harness references moved": ( + {"docs/n.md": "see skills/implementation/references/providers/x.md\n"}, + {"docs/n.md": "see providers/runtimes/x.md\n"}, + ), + "Gremlins need --harness outside a harness": ( + {".github/workflows/x.yml": "run: uv run --script a/gremlins.py init --run r --model m\n"}, + {".github/workflows/x.yml": "run: uv run --script a/gremlins.py init --run r --model m --harness claude\n"}, + ), + "Secret-shaped env names are scrubbed from gremlins": ( + {"CLAUDE.md": "gremlins use --pass-env FOO_KEY\n"}, + {"CLAUDE.md": "nothing relevant\n"}, + ), + "Finish or re-init in-flight 0.3.x gremlin runs": ( + {".spire/gremlins/r1/run.json": "{}\n"}, + {".spire/other/x": "x\n"}, + ), + } + + def shipped_checks(self): + text = (PLUGIN / "UPGRADES.md").read_text() + m = re.search(r"^## 0\.4\.0\b.*?(?=^## |\Z)", text, re.S | re.M) + out = {} + for item in re.split(r"^### ", m.group(0), flags=re.M)[1:]: + c = re.search(r"^- Check: `(.+?)`", item, re.M) + self.assertIsNotNone(c, item.splitlines()[0]) + out[item.splitlines()[0].strip()] = c.group(1) + return out + + def run_check(self, cmd, files): + tmp = Path(tempfile.mkdtemp()).resolve() + self.addCleanup(shutil.rmtree, tmp, True) + for rel, body in files.items(): + f = tmp / rel + f.parent.mkdir(parents=True, exist_ok=True) + f.write_text(body) + r = subprocess.run(["sh", "-c", cmd], cwd=tmp, capture_output=True, text=True, timeout=TIMEOUT) + return r.stdout + + def test_shipped_checks_hit_and_miss(self): + checks = self.shipped_checks() + self.assertEqual(sorted(checks), sorted(self.CHECK_FIXTURES), "every Check needs a fixture pair") + for title, cmd in checks.items(): + hit, miss = self.CHECK_FIXTURES[title] + with self.subTest(title=title): + self.assertNotEqual(self.run_check(cmd, hit), "", "must hit") + self.assertEqual(self.run_check(cmd, miss), "", "must not hit") + + def test_gremlins_check_forms(self): + cmd = self.shipped_checks()["Gremlins need --harness outside a harness"] + self.assertNotEqual(self.run_check(cmd, {"ci.sh": 'G init --run r --model m\n'}), "") + self.assertNotEqual(self.run_check(cmd, {"Justfile": 'x:\n G init --run r --model m\n'}), "") + self.assertEqual(self.run_check(cmd, {"ci.sh": 'G init --run r --model m --harness codex\n'}), "") + self.assertEqual(self.run_check(cmd, {"ci.sh": 'G launch --run r\n'}), "") + for line in ('run: uv run --script "$P/gremlins.py" init --run r --model m\n', + 'python3 "/x/gremlins.py" init --run r --model m\n', + "uv run --script '/x/gremlins.py' init --run r --model m\n"): + self.assertNotEqual(self.run_check(cmd, {"ci.yml": line}), "", line) + self.assertEqual(self.run_check( + cmd, {"ci.yml": 'run: uv run --script "$P/gremlins.py" init --run r --model m --harness claude\n'}), "") + + def test_igor_wiring(self): + text = (IGOR / "SKILL.md").read_text() + self.assertIn(WIRING_LINE, text) + fm = text.split("---", 2)[1] + m = re.search(r"^allowed-tools:.*$", fm, re.M) + self.assertIsNotNone(m, "no allowed-tools in frontmatter") + self.assertTrue("upgrade-notes.sh" in m.group(0) or "Bash(sh:*)" in m.group(0), m.group(0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/plugins/spire/skills/igor/upgrade-notes.sh b/plugins/spire/skills/igor/upgrade-notes.sh new file mode 100644 index 0000000..d0f3db5 --- /dev/null +++ b/plugins/spire/skills/igor/upgrade-notes.sh @@ -0,0 +1,99 @@ +#!/bin/sh +# Spire upgrade notes. Invoked as `sh upgrade-notes.sh ...`; the exec bit does not matter. +# check: upgrade-notes.sh <plugin-root> <project-dir> silent unless notes are pending, always exit 0 +# ack: upgrade-notes.sh ack <plugin-root> <project-dir> write the marker, exit 1 on error +# Never executes anything from UPGRADES.md. POSIX sh and awk only. +if [ "$1" = ack ]; then + if [ -z "$2" ] || [ -z "$3" ]; then + echo "upgrade-notes ack: usage: ack <plugin-root> <project-dir>" >&2 + exit 1 + fi + v=$(awk ' +function ver(l, s) { + if (!match(l, /"version"[ \t]*:/)) return "" + s = substr(l, RSTART) + if (!match(s, /^"version"[ \t]*:[ \t]*"[0-9]+\.[0-9]+\.[0-9]+"/)) return "" + s = substr(s, 1, RLENGTH) + match(s, /"[0-9]+\.[0-9]+\.[0-9]+"$/) + return substr(s, RSTART + 1, RLENGTH - 2) +} + { gsub(/\r/, "") } + /"version"[ \t]*:/ { print ver($0); exit }' "$2/.claude-plugin/plugin.json" 2>/dev/null) + if [ -z "$v" ]; then + echo "upgrade-notes ack: no valid X.Y.Z version in $2/.claude-plugin/plugin.json" >&2 + exit 1 + fi + d="$3/.spire" + k="$d/upgrades.lock" + t="$d/upgrades.lock.tmp$$" + mkdir -p "$d" 2>/dev/null || { echo "upgrade-notes ack: cannot create $d" >&2; exit 1; } + if [ ! -e "$d/.gitignore" ]; then + printf '*\n' > "$d/.gitignore" 2>/dev/null || { echo "upgrade-notes ack: cannot write $d/.gitignore" >&2; exit 1; } + fi + if printf '%s\n' "$v" > "$t" 2>/dev/null && mv -f "$t" "$k" 2>/dev/null; then + echo "Spire upgrade notes acknowledged: $v ($k)" + exit 0 + fi + rm -f "$t" 2>/dev/null + echo "upgrade-notes ack: cannot write $k" >&2 + exit 1 +fi + +exec 2>/dev/null +[ -n "$1" ] && [ -n "$2" ] || exit 0 +[ -r "$1/.claude-plugin/plugin.json" ] && [ -f "$1/UPGRADES.md" ] || exit 0 +if [ -r "$2/.spire/upgrades.lock" ]; then + have=1 + k="$2/.spire/upgrades.lock" +else + have=0 + k=/dev/null +fi +SELF="$0" ROOT="$1" PROJ="$2" awk -v have="$have" ' +function ver(l, s) { + if (!match(l, /"version"[ \t]*:/)) return "" + s = substr(l, RSTART) + if (!match(s, /^"version"[ \t]*:[ \t]*"[0-9]+\.[0-9]+\.[0-9]+"/)) return "" + s = substr(s, 1, RLENGTH) + match(s, /"[0-9]+\.[0-9]+\.[0-9]+"$/) + return substr(s, RSTART + 1, RLENGTH - 2) +} +function ok(s) { return match(s, /^[0-9]+\.[0-9]+\.[0-9]+$/) } +function cmp(a, b, x, y, i) { + split(a, x, "."); split(b, y, ".") + for (i = 1; i <= 3; i++) { + if (x[i] + 0 < y[i] + 0) return -1 + if (x[i] + 0 > y[i] + 0) return 1 + } + return 0 +} +{ gsub(/\r/, "") } +FILENAME == ARGV[1] { + if (!seen && $0 ~ /"version"[ \t]*:/) { seen = 1; inst = ver($0) } + next +} +FILENAME == ARGV[2] { + if (FNR == 1) { gsub(/^[ \t]+|[ \t]+$/, ""); if (ok($0)) mk = $0 } + next +} +FILENAME == ARGV[3] { + if (!decided) { + decided = 1 + if (inst == "") exit + if (have) { if (mk == "") exit } else mk = "0.0.0" + if (cmp(mk, inst) >= 0) exit + } + if ($0 ~ /^## /) { + on = 0 + if (ok($2) && cmp($2, mk) > 0 && cmp($2, inst) <= 0) { + if (!shown) { + shown = 1 + print "## Spire upgrade notes pending\n" + print "Installed Spire " inst "; this checkout\047s marker: " (have ? mk : "none") " (`" ENVIRON["PROJ"] "/.spire/upgrades.lock`). Follow `" ENVIRON["ROOT"] "/skills/igor/references/upgrades.md`. Ack command: `sh \"" ENVIRON["SELF"] "\" ack \"" ENVIRON["ROOT"] "\" \"" ENVIRON["PROJ"] "\"`.\n" + } + on = 1 + } + } + if (on) print +}' "$1/.claude-plugin/plugin.json" "$k" "$1/UPGRADES.md" +exit 0 diff --git a/plugins/spire/skills/project/SKILL.md b/plugins/spire/skills/project/SKILL.md index ed3035f..7823ca1 100644 --- a/plugins/spire/skills/project/SKILL.md +++ b/plugins/spire/skills/project/SKILL.md @@ -1,11 +1,24 @@ --- name: project -description: Loads per-project Spire configuration (override or bundled template). +description: Loads per-project Spire configuration (`.claude/spire/project.md`). allowed-tools: Bash(cat:*) --- !`cat "${CLAUDE_PROJECT_DIR}/.claude/spire/project.md" 2>/dev/null || echo "No project config found. Run /spire:init to set up this project."` +(Codex: run `cat <project root>/.claude/spire/project.md` yourself; the line above is not executed there, and a missing file means no project config.) + +`## Build` keys (all optional): Scope, Gate, Tests, Checkout, Branches, Staging, Owner models, Fork owner model, Assertion pattern, Parallel tests, Brief constraints, Host rules, Build plan. Unset = the reader's default; `none` = deliberately absent. Fork owner model, Assertion pattern and Parallel tests have no reader yet. + +`Scope:` sets how much capability a go builds, never how many checks or reviews. Set in `## Build`, the `Go:` line, briefs and design, plan and build-plan headers; the user's go wins, then `## Build`, then the coordinator's read of the go (journaled `Taken:`), else medium. Other wording in a brief never lowers it. +- **minimal**: the boxes read literally; the rest goes on the scope fence. +- **medium** (default): each box with what comes with it (inverse operations, status, listing, identification) where a user would miss it in normal use or the counterpart calls it unprompted. A deferral needs a reason other than size, the plan's own phasing or a workaround the user must know. +- **high**: medium plus a **Proposed beyond the goal** list, each item tied to the goal's purpose; the advocate tests each for fit and reuse and strikes one only with a reason; a kept one counts as a box. + +Every level: reuse what libraries and the architecture give, never rebuild it; failure paths, tests, security and the lean process stay. Briefs ask what the work rebuilds or leaves missing, not where it can shrink. Size is reported as a number, with its cause where far over, never as an overrun headline. + Personal overrides (`.claude/spire/project.local.md`; these win over the above): !`cat "${CLAUDE_PROJECT_DIR}/.claude/spire/project.local.md" 2>/dev/null || echo "(none)"` + +(Codex: run `cat <project root>/.claude/spire/project.local.md` yourself; the line above is not executed there.)