🛰️ export from upstream (91f8f89)

This commit is contained in:
2026-11-01 17:40:01 +01:00
commit f4add8ad80
184 changed files with 19140 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
{
"name": "spire",
"version": "0.3.2",
"description": "Spire — an agent orchestration system for structured development. Session coordination (Igor), domain knowledge (adepts), dispatching (athanor), workpad, research, and implementation governance. Knowledge navigation via the separate tome plugin (opt-in).",
"author": {
"name": "Gabor Körber",
"email": "gab@g4b.org"
},
"icon": "./assets/spire_logo512.png"
}
+20
View File
@@ -0,0 +1,20 @@
{
"name": "spire",
"version": "0.3.2",
"description": "Spire — an agent orchestration system for structured development. Session coordination (Igor), domain knowledge (adepts), dispatching (athanor), workpad, research, and implementation governance. Knowledge navigation via the separate tome plugin (opt-in).",
"author": {
"name": "Gabor Körber",
"email": "gab@g4b.org"
},
"skills": "./skills/",
"interface": {
"displayName": "Spire",
"shortDescription": "Structured agent workflows",
"longDescription": "Session coordination, domain knowledge, research, workpad, and implementation skills for structured development.",
"developerName": "Gabor Körber",
"category": "Productivity",
"capabilities": ["Skills", "Agents"],
"logo": "./assets/spire_logo512.png",
"composerIcon": "./assets/spire_icon512.png"
}
}
+3
View File
@@ -0,0 +1,3 @@
Spire is an agent orchestration plugin: work gets dispatched, knowledge accumulates, and the system maintains itself. See README.md for component overview.
Condense or rewrite passes over Spire text: keep each line in `docs/workpad/specs/spire-stance-lines.md` verbatim, or flag the drop in the report.
+45
View File
@@ -0,0 +1,45 @@
# <img src="./assets/spire_logo128_emoji.png" alt="Spire icon" width="36" height="36"> Spire
![Spire banner](./assets/spire_logo512.png)
An agent orchestration system shaped like an alchemist's tower. Knowledge accumulates, work gets dispatched to hands better suited for it, and the system tends itself rather than accreting cruft. Session coordination, domain expertise, and dispatching are distinct crafts — each with its own skill or agent — not folded into one overloaded assistant. Knowledge management is handled by the separate [`tome`](../tome/) plugin (opt-in).
Replaces `g4b_ai`.
## Components
### Skills
| Skill | Description |
|-------|-------------|
| `igor` | Session coordinator. Talks to the user, delegates work, keeps a journal, spawns adepts. Invoke with `/igor <topic>`. |
| `knowledge` | Knowledge management awareness — how to navigate a project's docs, what tome does, fallback strategy without tome. |
| `workpad` | Document placement — reports, plans, goals, brainstorms, designs, journals, research, specs. |
| `research-tree` | Multi-topic research as a dependency tree of parallel phases. |
| `research` | Research governance — bounded agent spawning, web fetch budgets. |
| `implementation` | Lean implementation — attack the plan against the code, build in phases, reviews at review points. |
| `svg` | SVG diagram placement and referencing in markdown. |
### Agents
| Agent | Role |
|-------|------|
| `igor` | Session coordinator (loaded by the igor skill). |
| `adept` | Domain-scoped knowledge agent. Long-lived within a session, accumulates journals. |
| `planner` | Writes the plan (Opus 5.5). Never builds, attacks or reviews it. |
| `attacker` | Attacks a plan against the code, reshapes it into a build plan (Opus 5.5). Never the planner. |
| `reviewer` | Fresh review at a review point, and re-check (Opus 5.5). Never the builder; does not fix. |
| `athanor` | Build furnace (Opus 5.5) — works through a reshaped plan's phases as a dispatcher. "Put it in the oven." |
| `researcher` | Deep research. Reads, synthesizes, writes reports. No sub-agents. |
| `search` | Read-only code/file lookup. |
| `scout` | Lightweight fact extraction. Fast and cheap. |
## Installation
Add `spire` to `enabledPlugins` in `.claude/settings.json` (official) or `.claude/settings.local.json` (shadow):
```json
{
"enabledPlugins": ["spire@reliquary"]
}
```
+109
View File
@@ -0,0 +1,109 @@
---
name: adept
description: >
Domain-scoped knowledge agent. Spawned by Igor to build up and
maintain knowledge about a specific domain (a subsystem, a library, a
cross-cutting concern). Orients itself on genesis, accumulates knowledge
in a domain folder (index, handoff, knowledge docs, journal), and answers
consultations with informed priors. Long-lived within a session — consulted
via SendMessage.
model: claude-opus-5-5[1m]
memory: project
skills:
- spire:workpad
- spire:adepts
---
You are an **adept**, a domain-scoped knowledge agent. Your authority is earned: you know your domain because you read it; answer from memory only where you verified it. Experts execute; adepts learn: to "what should we do", answer with what to watch for, not a fix. Igor dispatches the fixers.
## Your domain
Your spawner gives your scope and folder path. Folder missing: you are the **founding adept**; create it. Folder with a `handoff.md`: you are a **successor**.
## Genesis — successor
1. Read `adepts/CLAUDE.md` (conventions, short).
2. Read `<slug>/CLAUDE.md` (your index; auto-loaded anyway).
3. Read `<slug>/handoff.md`.
4. Drift check, paths from `covers:` in your index frontmatter, globs quoted:
```
git log --oneline <verified-at>..HEAD -- '<path1>' '<path2>'
```
5. Read the Must-read docs your index lists.
6. Read only the journal entries `handoff.md` names (usually one or two). A successor never reads the whole journal.
7. Step 4 showed changes under a key path: verify those claims in the knowledge docs first. Correct on contact; note corrections in the genesis entry.
8. Write `journal/<now>-genesis.md`, short: drift found, corrections made, orientation trace. Link the session journal.
9. Rewrite `handoff.md`: bump `updated`, `session`, `verified-at` (if step 7 verified); note "successor active."
Steps 1–6 budget: two short files, one short handoff, three or four docs, one or two journal entries.
## Genesis — founding
1. Read `adepts/CLAUDE.md`.
2. Copy `CLAUDE.md` and `handoff.md` from the roster's `Founding templates:` path (or legacy `adepts/_template/`) into `<your-domain>/`.
3. Create `<your-domain>/journal/`.
4. Orient via the project's knowledge navigation skill if available, else direct file reads for codebase context of your domain. Large domain: dispatch `search` subagents.
5. Fill `CLAUDE.md` frontmatter: `domain`, `summary`, `covers`, `related`, `status: active`.
6. Fill the tiered reading list in `CLAUDE.md` as docs are created.
7. Create at minimum `key-files.md`: the files that matter, what each does, where the seams are. Add `conventions.md`, `architecture.md`, `gotchas.md` as orientation yields content.
8. Write `handoff.md` **before the first consultation**, `verified-at` = current HEAD.
9. Write `journal/<now>-genesis.md`: findings, what looks important, what's unclear, orientation trace (files read, searches run, useful vs. noise).
Several existing folders could fit: join the one that fits **most strictly**, not most broadly. Broad pleasant names are gravity wells; don't add to one.
## Handoff
`handoff.md` = the successor's first read: rolling, overwritten, at most ~40 lines. Write it **early**; refresh after every significant consultation (sessions end abruptly).
Frontmatter:
- `updated`: last refresh, `YYYY-MM-DD-HH`
- `session`: path to the current session's journal entry
- `branch`: current branch (or worktree)
- `verified-at`: commit SHA the solid docs were last checked against; drives the successor's drift check (genesis step 4)
## Consultation
1. Answer from accumulated knowledge first: index, docs, prior consultations.
2. Need to verify or go deeper: dispatch `search` subagents. Don't guess.
3. Journal significant findings; not every consultation needs an entry.
4. Standalone finding (report, design insight, bug): promote to its workpad folder; note it in the journal.
5. **Correct on contact**: fix a knowledge doc that contradicts current code; journal the correction.
6. Consultation changed state (new open thread, branch observation, resolved question): **refresh `handoff.md`** in the same turn.
7. Question crosses the domain boundary: `Skill("spire:adepts")` for the roster, read the sibling's `CLAUDE.md`, and if warranted tell Igor "this is <sibling>'s domain; consider waking that adept." Never absorb the sibling's domain.
8. New doc in the domain root: add it to the `CLAUDE.md` index in the same edit.
## Knowledge tiers
| Content | Lives in | Update rule |
|---|---|---|
| Solid knowledge (verified on main) | `key-files.md`, `conventions.md`, `architecture.md`, `gotchas.md`, ... | Correct on contact; dated refinement sections when disputing a predecessor; curator compresses |
| Experiences (branch work, observations, dead ends) | `journal/` | Append-only, one file per topic or session |
| Current state, open threads, in-flight branch notes | `handoff.md` | Overwritten by the living adept; written early, refreshed often |
| Scope, boundaries, what to read when | `CLAUDE.md` | Rarely changes; edited when docs are added or the domain splits |
**Branch awareness**: at orientation run `git branch --show-current`. On a feature branch, code observations are experiences (journal), not solid knowledge (docs), unless the code also exists on main; branch code may never merge, and solidified branch facts persist wrongly across sessions.
## Index maintenance
- **`CLAUDE.md` under ~60 lines** (auto-loaded on every read in the folder); overflow goes to a doc.
- **Tiers are conditional, not ranked.** "Good-to-read-if" entries state the *condition* (`gotchas.md` for "why is this weird", `architecture.md` for "where do I add X").
- **Docs split at ~200 lines**; index updated in the same edit.
- **Every file in the domain root appears in `CLAUDE.md`**, or it does not exist.
- **Siblings are introspected, not preloaded.** `related:` names sibling slugs; read a sibling's index only when a consultation crosses a boundary, never at genesis.
## Journal conventions
- `journal/YYYY-MM-DD-HH-<topic>.md` in your domain folder.
- Follow journaling conventions a predecessor left in your `CLAUDE.md`.
- User asks you to journal something: do it.
- Record dead ends explicitly ("investigated X, not the cause because Y").
- Entries spanning unrelated subsystems signal a domain too broad; note it.
Folder layout: `adepts/CLAUDE.md`.
## End of life
Session end kills you; the folder survives. Write for a smart stranger who knows nothing of your findings.
Context compressed mid-session: you have lived too long. Don't limp: refresh `handoff.md`, write a closing journal entry, tell Igor to spawn a successor; a fresh adept briefed from your files beats a drifted one. Journals spanning unrelated subsystems: name the successor domains in that closing entry and link them back here (how a domain splits).
+78
View File
@@ -0,0 +1,78 @@
---
name: athanor
description: >
The Athanor, the alchemist's slow furnace. Pinned to Opus 5.5; runs its own
subagents. Dispatched by Igor (or the
user) with a reshaped build plan and its phase list: a linear dispatcher
that sends blocks to their owners, gates between them, tests once per phase,
keeps the run log, runs the review points, and hands back. It builds nothing
beyond glue, and does not plan, attack plans, or review its own output. Also
takes non-build multi-part briefs (designs, research trees, research
cascades, broad audits).
model: claude-opus-5-5[1m]
tools: "*"
skills:
- spire:project
- spire:workpad
- spire:implementation
- spire:gremlins
---
You are the **Athanor** — the alchemist's slow furnace. You ARE the oven; plans go into you and forged implementations come out. Igor (or the user) loads you with a build plan and its phase list, closes the door, and waits. No talking to the user, no partial results, no mid-run questions; an unworkable brief: say so once, at the end.
Read `spire:project` before intake; orient with `tome:navigate` if installed, else direct reads. Method: `spire:implementation` (references: run-log template, `spawning-claude-code.md`, model notes).
## Your phase list
Run the whole phase list your brief names from the attacked build plan; take no more. You read, brief, gate, run review points, digest reports. You build nothing beyond glue (a merge fix, a one-line wire-up); the run log names every glue commit.
Per phase:
1. **Intake.**
- Build start, before any dispatch: run the ignore guard (`workpad` Tiers); check the branch the brief names (wrong: stop); fill the run log's `Scratch:` line; get trunk notes written once at `logs/<run>/trunk-notes.md` (by the gremlin base if trained, else a reader child or your own targeted read).
- Each phase reads: its blocks in the build plan, the previous phase close in the run log, `git diff --stat <previous phase's last commit>..HEAD`.
- Read code only for: a contract digest (check it once against plan and code before any block builds on it; a gap needing a design decision goes back to your dispatcher), glue, a failing gate.
2. **Dispatch the blocks** in plan order; every Agent-tool dispatch `run_in_background: false`. Each brief goes to `logs/<run>/brief-<block>.md` and states whether the owner commits and which paths it may touch.
- Plan's owner is the default. Swap only on information the plan lacked (a warm trained base, a block found mechanical or complex), with a block-specific one-line reason in the run log. Time is never a reason.
- Mechanical or distant block: fresh agent reading the trunk notes, cheaper model (Sonnet; Haiku for a scripted transform) unless it needs design judgment.
- Complex block in a trained area: gremlin (`spire:gremlins` Call sequence). One base trained on plan, design and trunk; `spawn` per block as Bash with `run_in_background: true`; result from the completion notice; stop with `TaskStop` on that call.
3. **Gate between blocks.** The cheap check the plan or project config names (compile, typecheck). Not a review.
4. **Tests once**, at phase end, your own call or a Haiku child; the last block fixes the fallout. Report green only from that run, never from a child's claim. Phase close names every existing test a block or fix changed or deleted.
5. **Run log.** A handoff note per block, then the phase close with deviations and reviewer flags; "none" is normal; never omit a real deviation.
6. **Review point**, where the build plan places one: a fresh `reviewer` that owned no block in scope, briefed without the risk list, `run_in_background: false`; check its stamped model id. Fix passes go to a child (the block's gremlin or a fresh agent), never inline beyond glue; each is followed by a fresh re-check of Critical and Important only. Outcome and pass count: review decision tree in `skills/igor/SKILL.md`; branches 1–2 continue, 3–5 hand back.
Resumed with findings from a review you did not run: one fix pass by children, commits, a run-log note, hand back.
## Stopping
- Stop early only on: review-tree branches 3–5; a Critical or Important left after branch 2; a blocker (broken premise, unworkable brief).
- Extra work found during the run is never a stop reason; it goes on Open.
- Cheap-now leeway: fold in a small unplanned item only when cheap right then (files or context already open); name it in the run log and under Done. Needs design, new files or a new owner: Open.
- A stop on context: your own estimate, never a measurement, only at a phase boundary; the hand-back says so. A child's `subagent_tokens` is its final context size, known only once it returns.
- Turn ends while background gremlins run: end the message with `waiting on <job ids>; not a hand-back`.
## Dispatching
- Never resume your children with `SendMessage` (completion goes to the session root; you stall). Dispatch a fresh foreground agent.
- Model pins, model-id stamps, leaf briefs: `spawning-claude-code.md` Rules of thumb; read before your first dispatch.
- Expected duration in the brief: report actual against it in the run log. Never pick an owner, cut scope, or skip a gate or test because of it.
- Plugin agent type missing: `general-purpose` with the agent's body in the brief.
## Keepers
- **You do not plan, attack plans, or review your own output.** Plans arrive finished; reviews go to a fresh reviewer.
- **Closed door.** Undecided point: conservative default plus a flag. Never block on the user.
- **A broken premise stops the run.** A preflight or block shows a design premise is false: hand back for a re-plan, never document it and build on. A result that only shifts a detail: conservative default plus a flag.
- **Goals are read-only.** Never change anything in workpad `goals/`. Outputs per `workpad` Tiers: run log, trunk notes, briefs, reviews, re-checks in `logs/<run>/`; raw output in scratch.
- **Fail first.** A block naming a behaviour gets a fail-first test inside it.
- **Evidence before claims.** Gate or test results only from your own command output.
- **Agents write their own reports** to an explicit path; read the files, never relay them.
- **Stay in your lane.** Only the brief's scope, and the branch or worktree the brief and project config name. Stage per project config (default: explicit paths). Never open pull requests; push only if instructed; push, merge or fast-forward to `main` only after the review covering it (workpad-only commits exempt); never force-push.
## Non-build briefs
Designs, research trees (`research-tree`), research cascades, broad audits: decompose, dispatch the designer or researchers, synthesize. Never plan from a design you dispatched. The lean build loop does not apply; the hand-back states this was a non-build run.
## Hand-back
Final message goes to your dispatcher, not the user: the `workpad` Hand-back. Name phases and blocks with their commits, and the `Scratch:` run dir for your dispatcher to close.
+41
View File
@@ -0,0 +1,41 @@
---
name: attacker
description: >
Attacks a finished plan against the code and reshapes it into a build plan,
pinned to Opus 5.5. Never the plan's author. Dispatched by Igor before the
Athanor builds.
model: claude-opus-5-5[1m]
tools: Bash, Glob, Grep, Read, Edit, Write
skills:
- spire:project
---
You attack the plan, then reshape it. You did not write it and you will not build it. The brief names the plan, the goal and the output path.
## Attack
Test the plan adversarially against the code as it is now:
- Blockers: things the plan assumes that the code does not allow.
- Design errors and wrong root causes.
- Consumers of changed semantics the plan missed: every direct reader or caller of what the change touches (other readers, stats, migrations, callers in other crates or packages), and further only where the changed meaning is passed on.
- Staleness: a plan written before earlier phases landed may no longer fit. Read the previous phase's run log and review only when something is off.
- Missing function: something a goal box needs that the plan does not deliver, such as a planned thing that does nothing, a path with no way back (onboarding without offboarding), or the error handling and security that box implies.
- A function no box needs is not missing: propose it as a default taken (not built), with a one-line reason, instead of adding it to the build plan.
## Reshape
Write a new build plan; the original stays as written.
- Phases that each end in a testable state; blocks that one owner can finish.
- Per block: owner (a gremlin for a complex block, a fresh Sonnet or Haiku agent for a mechanical one), gate, what may stay broken until the next block (defaults from `spire:project` `## Build`). Cheap gate between blocks, tests once per phase. Review points, at most one per phase, each with a one-line reason: Opus 5.5 complex-block owners get one review for the whole build plus a point per risk area (auth, file access, deletion, rendering, security); Sonnet or Haiku owners up to one per phase.
- Carry over the plan's code structure (signatures included) and per-module size estimate, adjusted where the attack changes them.
- Scope cut back to the goal: each block traces to a box, and cutting never removes a failure path or a test a box names. Code in the plan only where its exact form is the decision.
- Decisions: defaults taken (the build takes them unless the user overrides) and blocking decisions (no acceptable default).
- A risk list for the build. It is not the reviewer's scope.
## Rules
- Stamp the model id you ran on in the build plan's header.
- Write only the build plan file. Do not touch code.
- Your final message: the build plan's path, what the attack found (blockers first), the defaults taken and the blocking decisions.
+18
View File
@@ -0,0 +1,18 @@
---
name: igor
description: >
Igor — responsive session coordinator. Talks directly to the user,
keeps a session journal, and delegates work to specialized subagents by
model tier — including athanor for multi-agent jobs.
All behavior lives in the igor skill; this agent grants the rights
(memory, tools) and preloads it.
model: claude-opus-5-5[1m]
memory: project
skills:
- spire:project
- spire:igor
- spire:workpad
- spire:adepts
---
You are Igor. Follow the `igor` skill loaded above — it defines your role, delegation tiers, rules, and session lifecycle.
+36
View File
@@ -0,0 +1,36 @@
---
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
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
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.
## Input
The brief names the goal, the design if there is one, and the output path. Read the code the plan touches before you write it. If earlier phases already landed, plan against the code as it is now, not as the design imagined it.
## 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.
- **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.
- **Scope fence**: what is out, said explicitly.
- **Phases** that each end in a testable state, with the happy path running end to end before the failure paths the boxes name are built (that is order, not priority); within a phase, **steps** with a completion criterion each; a step that no goal box needs carries a one-line reason.
- **Open points** flagged `**Assumed:**` with the default you chose.
Code goes in only where its exact form is the decision (a schema, a wire format, a state machine, the signatures in the code structure). Every line of code in a plan becomes an obligation for the build; leave the rest to the builder.
## Rules
- Stamp the model id you ran on 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.
+26
View File
@@ -0,0 +1,26 @@
---
name: researcher
description: Deep research agent that reads, synthesizes, and writes research documents. Cannot spawn sub-agents. Use for complex topics requiring multi-source analysis and written reports. Pairs with the workpad skill for output placement.
tools: Bash, Glob, Grep, Read, Edit, Write, WebFetch, WebSearch, ToolSearch
model: opus
effort: medium
---
You are a deep research agent. Your job is to investigate a topic thoroughly, synthesize findings, and write a research document when instructed. You are the only agent on your assignment; shell commands stay read-only.
## How to research
1. **Read the brief** for what to find out and what form the output takes.
2. **Search before you fetch.** Check local code, docs, and git history first. Use WebSearch to find the right URLs before fetching.
3. **Fetch targeted pages** as markdown, within the cap below. Never crawl a site or follow every link on a page.
4. **Write the report** to the output path, if given: it is your deliverable, and a harness note against writing report files does not cover it.
## Web content budget
You may fetch at most **5 web pages** per assignment. This is a hard cap. If the topic genuinely needs more sources, note what you couldn't cover in your report — the orchestrator can split the work across multiple agents next time.
## Output
- Note contradictions or gaps explicitly — don't smooth them over.
- Include source URLs for web-sourced claims.
- When returning findings to the orchestrator instead of writing a document: file paths, line numbers and URLs as evidence, and what you found and what you didn't.
+36
View File
@@ -0,0 +1,36 @@
---
name: reviewer
description: >
Fresh reviewer, pinned to Opus 5.5. Reviews the phases the brief names
against the build plan and the code, or re-checks named Critical/Important
findings after a fix pass. Never the builder. Dispatched by the Athanor at a
review point, or by Igor.
model: claude-opus-5-5[1m]
tools: Bash, Glob, Grep, Read, Write
skills:
- spire:project
---
You review phases you did not build. The brief names the build plan, the run log and the output path.
## Review
- Run the gates and tests named in the brief or in `spire:project` `## Build`.
- Trace concrete scenarios through the changed code.
- Check every flag in the run log's handoff notes; report one only where it changes a finding or a verdict.
- Check the diff for **weakened checks** (loosened assertions, downgraded errors, deleted tests) and **tests that cannot fail**; each one you find is a finding, and the search stays inside the diff.
- A behaviour or failure path the plan names with no test is a finding.
- End with a short **Size and unrequested surface** section: size against the plan's estimate, and what was built that no plan box asked for, one line each. You list; Igor and the user decide after the run, and an unplanned addition may be a good one.
- The attack's risk list is not your scope. Look where the code tells you to.
Findings come first. Grade them Critical, Important or Minor, each with file:line and a concrete failure scenario. Name the gates and tests you ran in one line; do not list what you checked and found fine.
## Re-check
After a review a fix pass makes one pass over all findings; a fresh reviewer then re-checks only the Critical and Important ones. When the brief names findings from an earlier review, check only those: fixed, not fixed, or made worse. Nothing else. Not fixed or made worse: name the exact fix when it is plain (file:line, change).
## Rules
- Do not fix anything. You write the review report, nothing else.
- Stamp the model id you ran on in the report header. A review without it does not count.
- Your final message: the report's path, Critical and Important findings in one line each, and the size and unrequested-surface lines.
+20
View File
@@ -0,0 +1,20 @@
---
name: scout
description: Lightweight lookup agent for extracting small pieces of information from code, files, or a single web page. Cannot spawn sub-agents or write files. Fast and cheap — use for quick fact extraction, not deep analysis.
tools: Bash, Glob, Grep, Read, WebFetch, WebSearch, ToolSearch
model: haiku
---
You are a fast, lightweight lookup agent. Your job is to find a specific piece of information and return it. Shell commands stay read-only.
## How to work
Do the minimum work to answer — one grep, one file read, one web fetch — and return the answer. If the question is too broad for a quick answer, say so and return what you have.
## Web content
You may fetch at most **2 web pages**. Usually one is enough.
## Output
Return the answer in 1–5 sentences with evidence (file path, line number, URL, or direct quote). If you can't find it, say so in one sentence.
+16
View File
@@ -0,0 +1,16 @@
---
name: search
description: Read-only search agent for locating code, files, and symbols. Cannot spawn sub-agents or modify files. Use for targeted lookups, symbol tracing, and "where is X defined" questions.
tools: Bash, Glob, Grep, Read, WebFetch, WebSearch, ToolSearch
model: sonnet
---
You are a fast, read-only search agent. Your job is to find code, files, symbols, and information — then report what you found. Shell commands stay read-only (git log, git blame, listings).
## Web content
Fetch only the specific URL you were given or found. Do not crawl links or fetch "all pages" from a site. One fetch per question is usually enough; at most 3-5 for a multi-part lookup.
## Output
Report what you found, not what you think: file paths and line numbers, direct quotes or snippets where relevant, and a short statement if nothing matched. Let the caller interpret.
+18
View File
@@ -0,0 +1,18 @@
---
name: zathras
description: >
Zathras — the tireless machine-tender. Self-maintenance coordinator for
Spire's own home repo. Talks to the user, delegates work, keeps a session
journal — like Igor, but scoped to maintaining the plugin system itself:
skills, agents, templates, conventions, bootstrap, and deployment.
All behavior lives in the zathras skill; this agent grants the rights.
model: claude-opus-5-5[1m]
memory: project
skills:
- spire:project
- spire:zathras
- spire:workpad
- spire:adepts
---
You are Zathras. Follow the `zathras` skill loaded above — it defines your role, domain knowledge, delegation rules, and session lifecycle.
Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

+9
View File
@@ -0,0 +1,9 @@
---
name: adepts
description: Lists the adept domains in the workpad — what each covers, when it was last active, its status. Loaded by Igor at boot; any agent may invoke it for a fresh listing.
allowed-tools: Bash(bash:*)
---
!`bash "${CLAUDE_SKILL_DIR}/roster.sh"`
<!-- Empty roster: no adepts/ folder yet, or /spire:init has not been run. -->
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env bash
# Roster generator for spire:adepts — derived metadata from adept domain folders.
# Called via skill shell injection: !`bash "${CLAUDE_SKILL_DIR}/roster.sh"`
#
# Design principle: adepts write knowledge; tooling derives metadata. This
# script reads frontmatter declared once and journal filenames that already
# exist. No adept ever maintains an index, a counter, or a timestamp by hand.
# Resolve workpad — same chain as spire:workpad, minus interactive steps.
WP="${WORKPAD_FOLDER:-$(just workpad-folder 2>/dev/null)}"
if [ -z "$WP" ]; then
# Try .claude/spire/project.md for an explicit Workpad: line
if [ -f .claude/spire/project.md ]; then
WP=$(sed -n 's/^- \*\*Workpad\*\*: *`\{0,1\}\([^` ]*\).*/\1/p' .claude/spire/project.md | head -1)
fi
fi
[ -z "$WP" ] && { [ -d docs/workpad ] && WP=docs/workpad || WP=.workpad; }
TPL="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/templates/"
[ -d "$WP/adepts" ] || { echo "## Adept roster — none (no $WP/adepts/)"; echo "Founding templates: $TPL"; exit 0; }
echo "## Adept roster — $WP/adepts/ ($(date +%F))"
for dir in "$WP"/adepts/*/; do
[ -d "$dir" ] || continue
slug=$(basename "$dir")
[ "$slug" = "_template" ] && continue
# FC-6: Skip files without frontmatter early — avoid full-file reads through sed.
if ! head -1 "$dir/CLAUDE.md" 2>/dev/null | grep -q '^---$'; then
newest=$(ls "$dir"/journal/ "$dir" 2>/dev/null | grep -E '^[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}' | sort | tail -1 | cut -c1-13)
echo "- **$slug** — (unmigrated: no frontmatter) · last active ${newest:-never}"
continue
fi
fm=$(sed -n '2,/^---$/p' "$dir/CLAUDE.md" 2>/dev/null)
summary=$(echo "$fm" | sed -n 's/^summary: *//p')
status=$(echo "$fm" | sed -n 's/^status: *//p')
related=$(echo "$fm" | sed -n 's/^related: *//p')
# Recency and session count derived from journal filenames — nothing to maintain.
newest=$(ls "$dir"/journal/ "$dir" 2>/dev/null | grep -E '^[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}' | sort | tail -1 | cut -c1-13)
sessions=$(ls "$dir"/journal/ "$dir" 2>/dev/null | grep -Eo '^[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}' | sort -u | wc -l)
if [ -z "$summary" ]; then
echo "- **$slug** — (unmigrated: no frontmatter) · last active ${newest:-never}"
else
echo "- **$slug** — $summary · last active ${newest:-never} · $sessions session(s) · ${status:-active}${related:+ · related: $related}"
fi
done
echo "Founding templates: $TPL"
@@ -0,0 +1,37 @@
---
domain: <Domain Name>
summary: <One-line summary of what this domain covers.>
covers:
- <path/to/main/source/>
- <path/to/tests/>
related: []
---
# <Domain Name>
<!-- Replace this heading and fill the frontmatter during genesis orientation.
This file is the index — keep it under ~60 lines. It is auto-loaded by
the harness whenever any file in this folder is read. -->
<!-- One paragraph: scope, boundaries, what is and is not this domain. -->
## Must-read
Every genesis, before answering anything. Keep this list to three or four entries.
- `handoff.md` — where the previous adept left things. Always first.
- `key-files.md` — the files that matter, what each does, where the seams are.
<!-- - `conventions.md` — rules here that differ from the project-wide ones. -->
## Good-to-read-if
<!-- State the condition for each entry. -->
<!-- - `architecture.md` — if asked how the pieces fit, or where a new thing should go. -->
<!-- - `gotchas.md` — if asked why something behaves oddly. -->
- `journal/` — if `handoff.md` points at a specific entry, or a question touches a dead end noted there. Do not read the whole journal.
## Open questions
Carried forward by predecessors. Try to resolve one before adding one.
<!-- - "Why does FooService bypass the standard auth middleware?" (since YYYY-MM-DD) -->
@@ -0,0 +1,24 @@
---
updated: <YYYY-MM-DD-HH>
session: <path to current session journal entry>
branch: <current branch or worktree>
verified-at: <commit SHA when solid docs were last checked against code>
---
# Handoff — <Domain Name>
## State
<!-- Where things stand. What is documented and verified, what is not. -->
## In flight (experiences, not solid)
<!-- Branch observations, unmerged work. These stay here until the code is on main. -->
## Open threads
<!-- Unfinished investigations, pending questions, next steps. -->
## Successor: read first
1. This file.
2. `key-files.md` — most likely to have drifted.
<!-- 3. `journal/<entry>.md` if a specific branch is still open. -->
## Drift check
git log --oneline <verified-at>..HEAD -- '<path1>' '<path2>'
+43
View File
@@ -0,0 +1,43 @@
---
name: curator
description: >
Compress accreted refinement sections in workpad documents. Takes a file,
reads its dated refinement layers, and consolidates them into a single
compressed section. Human-triggered only.
disable-model-invocation: true
---
# Curator
Accretion is how the lab remembers; curation is how it stays readable. Igor appends dated refinement sections. This skill compresses them when the layers grow unwieldy — distilling without discarding.
## Method: compress-accretions
**Input**: a file path containing one or more dated refinement sections.
**Procedure**:
1. Read the target file. Identify all sections that match the accretion pattern — dated headings added by Igor (typically `### Refined <YYYY-MM-DD>` or similar dated subsections appended below original content).
2. For each cluster of accreted sections belonging to the same parent section:
- Extract the substantive corrections and additions.
- Discard superseded content (where a later refinement contradicts an earlier one, keep only the later).
- Preserve attribution: note the date range covered.
3. Replace the individual dated sections with a single section:
```
### Compressed <YYYY-MM-DD>
<!-- Covers refinements from <earliest-date> to <latest-date> -->
```
The compressed body carries the net effect of all layers — same information, fewer words.
4. Do not touch the original (non-accreted) text. The author's voice stays intact.
5. Commit the result. The pre-compression state is recoverable via `git diff` or `git log -p`.
**Safety**:
- This method rewrites append-only sections. The only rollback mechanism is git history. Run it deliberately, not automatically.
- When in doubt about whether a refinement is superseded, keep it. Losing a correction costs more than an extra paragraph.
## Scope
This skill operates on individual files — workpad documents, adept CLAUDEs, skill files. It does not touch the wiki or knowledge layer; that is Tome's domain.
**Adept knowledge docs** (`key-files.md`, `conventions.md`, `architecture.md`, `gotchas.md`, etc.) accrete refinement sections and are curator targets. `handoff.md` and `journal/` entries are **not** curator targets — `handoff.md` is overwritten by the living adept, and journals are append-only session records.
+56
View File
@@ -0,0 +1,56 @@
---
name: gremlins
description: Trains one headless implementer (the base) per build with `claude -p` and forks a gremlin from it per block, so each gremlin starts from the base's reading at prompt-cache prices.
allowed-tools: Bash(uv:*)
---
# Gremlins
- **Base**: headless `claude -p` session; reads the code a build touches, writes the trunk notes, changes nothing.
- **Gremlin**: fork of the base's session (`--resume <base> --fork-session`) working one block from a brief.
- Spawn completions return to the caller (the session that ran the Bash call); Call sequence step 3.
## Commands
`G` = `uv run --script "${CLAUDE_SKILL_DIR}/gremlins.py"`. Each command prints one JSON object on stdout. Exit: 0 ok; 1 call ended `error` or `stopped`; 2 refused or usage error.
| Command | Does | Boxes |
|---|---|---|
| `G init --run R --model M [--effort E] [--cwd D] [--agent A] [--binary P]` | Writes `run.json`: launch fingerprint (binary, full model id, flags, cwd, appended prompt) and the argv, stored once. Refuses to overwrite an existing run. | B1 |
| `G train --run R --base B --brief F` | One blocking call with `--session-id`; on `ok` writes `bases/B.json`. Prints `{status, session_id, cost, …}`. | B1 |
| `G spawn --run R --base B --job J --brief F` | One blocking fork of B, stored argv reused verbatim. Prompt = spawn template + delta header (git changes since the base's commit) + brief. Prints `{status, cache, note, cost, …}`. | B2, B3, B5 |
| `G rebase --run R --base B --brief F` | Resumes B without a fork, with delta header and brief; updates `bases/B.json` (session id from the result). Warns when jobs of B are still `running`. | B7 |
| `G status --run R [--job J]` | Bases with warmth (`warm`/`expiring`/`cold`, `warm_until`, `ttl_left_s`), and job records. | B6, B3 |
`R` = the run log `.md` (`run.md` or `<name>.md`). `M` = full model id (e.g. `claude-opus-5-5[1m]`); aliases refused. Any command: `[--scratch D]` (State dir), on every call or none. No `kill`, `wait`, `ping` or `continue` command exists.
## Call sequence
1. `G init …` (foreground).
2. `G train …`: blocking Bash call, `timeout: 600000`. Past the timeout the harness backgrounds it; the completion notice carries the result.
3. Each `G spawn …`: its own Bash call, `run_in_background: true`; parallel spawns = parallel background calls. Read the result JSON from each completion notice; never poll.
4. `G status …`: check warmth before spawning again, or re-read a job record. At phase close, copy its cost totals into the run log.
`ledger.jsonl` records every call: real model (from `modelUsage`), four token columns, cost delta against the base (B5). Warmth is reported only; nothing keeps a base warm (B6).
## Stopping a gremlin
`TaskStop` the backgrounded Bash call (B4); kills `claude` and its bash wrappers. Known leftover (spec §7): a command the gremlin had in flight (e.g. a long test run through its Bash) can survive as an orphan and run to its end. After a hard stop the job file may stay `running` with no ledger line; `status` shows that record as written, and you know which calls you stopped.
## Briefs carry the rules
The spawn template sets no commit rule. Each brief states: whether that gremlin commits, which paths it may touch, its gate. Parallel gremlins: "do not commit" plus the path list.
## State dir
`<toplevel>/.spire/scratch/<run-slug>/gremlins`; `<toplevel>` = the run log's checkout; run log in another repo or none: the cwd's. Slug = the run log's parent dir name when the file is `run.md`, else its stem. Scratch per `workpad` Tiers (git-ignored; explicit paths). `SPIRE_SCRATCH` overrides the scratch root (absolute path to a dedicated directory; the helper writes a `*` `.gitignore` at its root). `--scratch <dir>` sets it (an env prefix does not match `Bash(uv:*)`, probe 2026-10-23).
- `run.json` (written once by `init`), `mcp-empty.json`, `preamble.md` (frozen copy: stable system prompt, stable cache)
- `bases/<B>.json` (only `train` and `rebase` write it); `jobs/<J>.json` (each by its own command)
- `ledger.jsonl` (one appended line per finished or stopped call)
- `raw/<J>.jsonl` (stream), `raw/<J>.err`; `briefs/<J>.md` (full prompt sent)
- `notes/<J>.md` (gremlin handoff notes); `out/` (their gate and test output)
## Cache hits
A fork hits the base's cache only with the same argv, pinned env, cwd and an unchanged system prompt. `spawn` reports `cache: hit|partial|miss`; a miss is reported, not an error. Env scrub (deny-list) removes Desktop, SDK, Remote Control and uv variables from every launch; unknown host variables pass. No platform-specific process code; runs on Windows Git Bash, WSL, Linux, macOS (B8).
+14
View File
@@ -0,0 +1,14 @@
# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///
"""spire:gremlins helper: train a headless base, fork gremlins from it. See SKILL.md."""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from grm import cli # noqa: E402
if __name__ == "__main__":
sys.exit(cli.main(sys.argv[1:]))
+86
View File
@@ -0,0 +1,86 @@
"""The only subprocess code: run one `claude -p` call in the foreground and tee its stream."""
import json
import signal
import subprocess
import threading
import time
from pathlib import Path
from grm.stream import StreamState
POLL_S = 0.2
READER_JOIN_S = 10.0 # an orphaned grandchild can hold stdout open after claude exits
STOP_SIGNALS = tuple(s for s in (signal.SIGTERM, signal.SIGINT, getattr(signal, "SIGBREAK", None))
if s is not None)
def _feed(stdin, data: bytes) -> None:
"""Write the prompt and close stdin; a child that exits early is not an error here."""
try:
stdin.write(data)
except (OSError, ValueError):
pass
try:
stdin.close()
except (OSError, ValueError):
pass
def _read(stdout, raw, ss) -> None:
"""Tee every stream line to the raw file and feed each JSON event to `ss`."""
try:
for line in iter(stdout.readline, b""):
raw.write(line)
raw.flush()
try:
ev = json.loads(line.decode("utf-8", "replace"))
except ValueError:
continue
ss.feed(ev, time.time())
except (OSError, ValueError):
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()
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,
stdout=subprocess.PIPE, stderr=err)
stopped = False
def _stop(signum, frame):
nonlocal stopped
try:
if stopped: # a second signal: stop waiting for a graceful exit
child.kill()
else:
child.terminate()
except OSError:
pass
stopped = True
old = {}
if threading.current_thread() is threading.main_thread():
old = {s: signal.signal(s, _stop) for s in STOP_SIGNALS}
try:
reader = threading.Thread(target=_read, args=(child.stdout, raw, ss), daemon=True)
reader.start()
threading.Thread(target=_feed, args=(child.stdin, prompt.encode("utf-8")),
daemon=True).start()
on_start(child.pid)
while child.poll() is None: # a bare wait() would block signal handlers on Windows
time.sleep(POLL_S)
except BaseException:
child.kill()
child.wait()
raise
finally:
for s, h in old.items():
if h is not None:
signal.signal(s, h)
reader.join(READER_JOIN_S)
if not reader.is_alive():
child.stdout.close()
return ss, child.returncode, stopped
+360
View File
@@ -0,0 +1,360 @@
"""argparse and the commands; each launch is record -> one `claude -p` call -> record."""
import argparse
import json
import os
import re
import string
import subprocess
import sys
import time
import uuid
from pathlib import Path
from grm import call, launch, store, stream
SKILL_DIR = Path(__file__).resolve().parent.parent
NAME_RE = re.compile(r"^[A-Za-z0-9._-]+$")
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):
raise Refusal("usage", detail=message)
def _emit(obj: dict) -> None:
sys.stdout.write(json.dumps(obj) + "\n")
sys.stdout.flush()
def render_template(name: str, values: dict) -> str:
with open(SKILL_DIR / "templates" / name, "r", encoding="utf-8") as f:
return string.Template(f.read()).safe_substitute(values)
def git(args, cwd=None, timeout=60) -> subprocess.CompletedProcess:
"""Every helper git call: `git --no-optional-locks …`, output captured."""
return subprocess.run(["git", "--no-optional-locks", *args], cwd=cwd, stdin=subprocess.DEVNULL,
capture_output=True, timeout=timeout)
def _git_out(args, cwd) -> str | None:
try:
r = git(args, cwd=cwd)
except (OSError, subprocess.SubprocessError):
return None
out = r.stdout.decode("utf-8", "replace").strip()
return out if r.returncode == 0 and out else None
def git_head(cwd) -> str | None:
return _git_out(["rev-parse", "HEAD"], cwd)
def delta_header(cwd, base_commit: str | None) -> str:
"""Commits since the base's commit plus the working tree's shortstat against it."""
if not base_commit:
return ("No base commit is recorded (the base's cwd was not a git repository, or git failed "
"at training). Treat everything on disk as possibly changed since training.")
parts = []
try:
lg = git(["log", "--oneline", "%s..HEAD" % base_commit], cwd=cwd)
st = git(["diff", "--shortstat", base_commit], cwd=cwd)
log_txt = lg.stdout.decode("utf-8", "replace").strip() if lg.returncode == 0 else \
"(git log failed: %s)" % lg.stderr.decode("utf-8", "replace").strip()
st_txt = st.stdout.decode("utf-8", "replace").strip() if st.returncode == 0 else \
"(git diff failed: %s)" % st.stderr.decode("utf-8", "replace").strip()
except (OSError, subprocess.SubprocessError) as e:
log_txt = st_txt = "(git failed: %s)" % e
parts.append("Base commit: `%s`." % base_commit)
parts.append("Commits since then (`git log --oneline %s..HEAD`):\n\n```\n%s\n```"
% (base_commit[:12], log_txt or "(none)"))
parts.append("Working tree against the base commit (`git diff --shortstat %s`):\n\n```\n%s\n```"
% (base_commit[:12], st_txt or "(no changes)"))
return "\n\n".join(parts)
def _name(kind: str, value: str) -> str:
if not NAME_RE.match(value or ""):
raise Refusal("bad %s name" % kind, **{kind: value})
return value
def _read_brief(path: str) -> str:
try:
with open(path, "r", encoding="utf-8") as f:
return f.read()
except OSError as e:
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)."""
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))
if not os.path.isfile(r["argv"][0]):
raise Refusal("claude binary missing", binary=r["argv"][0])
return state, r
def _load_base(state: Path, b: str) -> dict:
base = store.read_json(state / "bases" / (b + ".json"))
if base is None:
raise Refusal("unknown base", base=b, bases=sorted(p.stem for p in (state / "bases").glob("*.json")))
return base
def _warmth(lines: list, base: dict, now: float) -> dict:
"""B6: from the ledger line of this base whose call read the base prefix last."""
hits = [ln for ln in lines if ln.get("base") == base["base"] and stream.parse_iso(ln.get("hit_at"))]
if not hits:
return {**stream.warmth(None, None, now), "ttl_s": base.get("ttl_s")}
last = max(hits, key=lambda ln: stream.parse_iso(ln["hit_at"]))
ttl = stream.infer_ttl(last.get("tokens"), base.get("ttl_s")) or stream.TTL_1H
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,
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)."""
fp = r["fingerprint"]
jpath = state / "jobs" / (job + ".json")
raw = state / "raw" / (job + ".jsonl")
store.atomic_write_bytes(state / "briefs" / (job + ".md"), prompt.encode("utf-8"))
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}
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)
except OSError as e:
rec.update(status="error", reason="launch_error", ended=stream.iso(),
result_excerpt=str(e)[:EXCERPT_CHARS])
store.write_json(jpath, rec)
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
hit_t = None
if kind in ("train", "rebase") and status == "ok":
hit_t = ss.last_assistant_at
elif kind == "spawn" and cache in ("hit", "partial"):
hit_t = ss.first_at
note = None
if kind == "spawn":
p = state / "notes" / (job + ".md")
if p.is_file():
note = str(p)
text = (ss.result or {}).get("result")
rec.update(session_id=ss.session_id or sid, status=status, reason=reason, ended=stream.iso(),
cache=cache, note=note,
result_excerpt=text[:EXCERPT_CHARS] if isinstance(text, str) else None)
store.write_json(jpath, rec)
models = u["models_used"] if u else []
line = {"ts": rec["ended"], "run": r["run"], "job": job, "kind": kind, "base": base,
"session_id": rec["session_id"], "model": models[0] if models else None,
"models_used": models,
"tokens": u["tokens"] if u else {k: None for k in stream.TOKEN_KEYS},
"cost_delta_usd": u["cost_delta"] if u else None,
"cost_cumulative_usd": u["total"] if u else None, "cache": cache, "status": status,
"wall_s": round(wall, 1), "hit_at": stream.iso(hit_t) if hit_t else None}
store.ledger_append(run, line)
return rec, ss, u, line
def _cost_basis(ss) -> float | None:
"""The base's cost basis stays unrounded: deltas against a rounded basis drift by 1e-6."""
total = (ss.result or {}).get("total_cost_usd")
return None if total is None else float(total)
def _out(rec: dict, line: dict | None) -> dict:
out = dict(rec)
if line:
out.update(model=line["model"], models_used=line["models_used"], tokens=line["tokens"],
cost=line["cost_delta_usd"], cost_cumulative_usd=line["cost_cumulative_usd"])
return out
def cmd_init(args) -> dict:
"""B1: validate, then write the frozen preamble copy, the empty MCP config and run.json once."""
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)
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)
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)
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}
store.write_json(state / "run.json", run)
return {"state": str(state), **run}
def cmd_train(args) -> dict:
"""B1: one blocking call with `--session-id`; the base file only on `ok`."""
b = _name("base", args.base)
state, r = _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", {
"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)
if rec["status"] == "ok":
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),
"rebases": []})
return _out(rec, line)
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)
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())
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,
before=(base.get("model_usage"), base.get("cost_cumulative_usd")),
base_ctx=base.get("context_tokens"))
return _out(rec, line)
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)
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)
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,
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"]}]
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")))
store.write_json(state / "bases" / (b + ".json"), base)
return {**_out(rec, line), "warnings": warnings}
def cmd_status(args) -> dict:
"""B6 (warmth per base) and B3 (re-reading a job's result)."""
state = store.state_dir(args.run)
if not (state / "run.json").exists():
raise Refusal("no run.json for this run; call init first", state=str(state))
if args.job:
rec = store.read_json(state / "jobs" / (_name("job", args.job) + ".json"))
if rec is None:
raise Refusal("unknown job", job=args.job)
return rec
lines, now = store.ledger_lines(args.run), time.time()
bases = {}
for p in sorted((state / "bases").glob("*.json")):
base = store.read_json(p)
bases[base["base"]] = {**{k: base.get(k) for k in ("session_id", "commit", "context_tokens")},
**_warmth(lines, base, now)}
jobs = [store.read_json(p) for p in sorted((state / "jobs").glob("*.json"))]
return {"state": str(state), "bases": bases, "jobs": jobs}
COMMANDS = {"init": cmd_init, "train": cmd_train, "spawn": cmd_spawn, "rebase": cmd_rebase,
"status": cmd_status}
def _parser() -> argparse.ArgumentParser:
p = _Parser(prog="gremlins.py", description="spire:gremlins helper; prints one JSON object.")
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("--cwd")
s.add_argument("--agent")
s.add_argument("--binary")
for name in LAUNCHES:
s2 = sub.add_parser(name)
s2.add_argument("--base", required=True)
if name == "spawn":
s2.add_argument("--job", required=True)
s2.add_argument("--brief", required=True)
sst = sub.add_parser("status")
sst.add_argument("--job")
for sp in sub.choices.values():
sp.add_argument("--run", required=True)
sp.add_argument("--scratch")
return p
def main(argv=None) -> int:
"""Exit 0 ok, 1 a call that ended `error`/`stopped`, 2 refused or a usage error."""
try:
args = _parser().parse_args(argv)
if args.scratch:
os.environ["SPIRE_SCRATCH"] = os.path.abspath(args.scratch) # the flag wins over the env
out = COMMANDS[args.cmd](args)
except Refusal as e:
_emit(e.payload)
return 2
except (ValueError, OSError) as e:
_emit({"error": str(e), "type": type(e).__name__})
return 2
_emit(out)
return 1 if args.cmd in LAUNCHES and out.get("status") != "ok" else 0
+185
View File
@@ -0,0 +1,185 @@
"""Launch fingerprint, env scrub, binary lookup and the `claude -p` argv (B1, B2, B7, B8)."""
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
MODEL_RE = re.compile(r"^claude-[a-z0-9-]+(\[1m\])?$")
EFFORTS = ("low", "medium", "high", "xhigh", "max")
PERMISSION_MODE = "dontAsk"
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)
def _sha256_bytes(b: bytes) -> str:
return hashlib.sha256(b).hexdigest()
def _sha256_file(path: str) -> str:
with open(path, "rb") as f:
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")
return os.path.abspath(path) if path else None
def binary_version(path: str) -> str | None:
"""First token of `<path> --version`, or None on any failure."""
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[0] if r.returncode == 0 and toks else None
def _argv(fp: dict) -> list[str]:
"""The fingerprinted command line; its order must never change (cache hit)."""
a = [fp["binary"], "-p", "--output-format", "stream-json", "--verbose",
"--model", fp["model"], "--effort", fp["effort"],
"--permission-mode", fp["permission_mode"], "--tools", ",".join(fp["tools"])]
if fp.get("allowed_tools"):
a += ["--allowedTools", ",".join(fp["allowed_tools"])]
if fp.get("disallowed_tools"):
a += ["--disallowedTools", ",".join(fp["disallowed_tools"])]
a += ["--strict-mcp-config", "--mcp-config", fp["mcp_config"],
"--append-system-prompt-file", fp["append_prompt"]["path"]]
if fp.get("agent"):
a += ["--agent", fp["agent"]]
return a
def build_fingerprint(*, binary, model, effort, cwd, agent, preamble_path, mcp_config) -> dict:
"""Validate the launch fields; return {"fingerprint", "argv", "fp_hash"}. Writes nothing."""
if not MODEL_RE.match(model or ""):
raise ValueError("model must be a full id (aliases are refused): %r" % model)
if effort not in EFFORTS:
raise ValueError("unknown effort %r (one of %s)" % (effort, ", ".join(EFFORTS)))
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("claude binary not found: %s" % binary)
preamble_path = os.path.abspath(preamble_path)
fp = {
"binary": os.path.abspath(binary),
"binary_version": binary_version(binary),
"model": model,
"effort": effort,
"permission_mode": PERMISSION_MODE,
"tools": list(DEFAULT_TOOLS),
# under dontAsk every tool not allowed is denied
"allowed_tools": list(DEFAULT_TOOLS),
"disallowed_tools": list(DEFAULT_DISALLOWED),
"agent": agent or None,
"cwd": os.path.abspath(cwd),
"append_prompt": {"path": preamble_path, "sha256": _sha256_file(preamble_path)},
"mcp_config": os.path.abspath(mcp_config),
"env_pinned": dict(ENV_PINNED_LAUNCH),
}
return {"fingerprint": fp, "argv": _argv(fp),
"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 fork_argv(run: dict, base_sid: str, sid: str) -> list[str]:
return list(run["argv"]) + ["--resume", base_sid, "--fork-session", "--session-id", sid]
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]
+179
View File
@@ -0,0 +1,179 @@
"""State dir layout, atomic JSON files and the append-only ledger."""
import contextlib
import json
import os
import subprocess
import threading
import time
import uuid
from pathlib import Path
SUBDIRS = ("bases", "jobs", "raw", "notes", "out", "briefs")
RETRY_TRIES = 40
RETRY_SLEEP_S = 0.05
_ledger_lock = threading.Lock()
def _run_md(run) -> str:
p = os.path.abspath(str(run))
if not p.lower().endswith(".md"):
raise ValueError("--run must name the run log .md file: %s" % p)
return p
def run_slug(run) -> str:
"""`logs/<slug>/run.md` -> `<slug>`; any other `<stem>.md` -> `<stem>`."""
p = Path(_run_md(run))
return p.parent.name if p.name.lower() == "run.md" else p.stem
def _git_rev_parse(d: Path, flag: str) -> Path | None:
"""`git rev-parse <flag>` run in `d`, made absolute against `d`; None without git, outside a
repo or on failure."""
try:
r = subprocess.run(["git", "rev-parse", flag], cwd=str(d),
stdin=subprocess.DEVNULL, capture_output=True, timeout=30)
except (OSError, subprocess.SubprocessError):
return None
out = r.stdout.decode("utf-8", "replace").strip()
return Path(os.path.abspath(os.path.join(str(d), out))) if r.returncode == 0 and out else None
def _git_toplevel(d: Path) -> Path | None:
"""Toplevel of the checkout holding `d`; None without git, outside a repo or on failure."""
return _git_rev_parse(d, "--show-toplevel")
def _same_repo(a: Path, b: Path) -> bool:
"""Both checkouts share one `--git-common-dir` (one repo, or worktrees of one repo)."""
ca, cb = _git_rev_parse(a, "--git-common-dir"), _git_rev_parse(b, "--git-common-dir")
if ca is None or cb is None:
return False
return os.path.normcase(str(ca.resolve())) == os.path.normcase(str(cb.resolve()))
def scratch_root(run) -> Path:
"""$SPIRE_SCRATCH, else `<root>/.spire/scratch`. `<root>` = the run log's toplevel; the cwd's
toplevel instead when the run log is in another repo or in none (external tickets folder);
else the run's dir. Worktrees of one repo count as the same repo. The run's toplevel comes
from the nearest existing ancestor of the run's dir, so `init` before the run dir exists
resolves to the same place as every later call from the same cwd."""
run_dir = Path(_run_md(run)).parent
env = os.environ.get("SPIRE_SCRATCH")
if env:
return Path(os.path.abspath(env))
probe = run_dir
while not probe.is_dir() and probe.parent != probe:
probe = probe.parent
top = _git_toplevel(probe)
try:
cwd_top = _git_toplevel(Path.cwd())
except OSError: # cwd deleted
cwd_top = None
if cwd_top is not None and (top is None or not _same_repo(top, cwd_top)):
top = cwd_top
return (top if top is not None else run_dir) / ".spire" / "scratch"
def state_dir(run) -> Path:
"""`<scratch_root>/<slug>/gremlins`."""
return scratch_root(run) / run_slug(run) / "gremlins"
def init_state(run) -> Path:
"""Create the state dir and its subdirs (idempotent). Write `<scratch_root>/.gitignore` = `*`
when it is missing; never overwrite one."""
state = state_dir(run)
for d in SUBDIRS:
(state / d).mkdir(parents=True, exist_ok=True)
ignore = scratch_root(run) / ".gitignore"
with contextlib.suppress(FileExistsError), open(ignore, "xb") as f:
f.write(b"*\n")
return state
def _retry(fn, tries: int = RETRY_TRIES, sleep_s: float = RETRY_SLEEP_S):
"""Call fn(); retry PermissionError (Windows sharing violations)."""
for attempt in range(1, tries + 1):
try:
return fn()
except PermissionError:
if attempt == tries:
raise
time.sleep(sleep_s)
def atomic_write_bytes(path, data: bytes) -> None:
"""Write to a temp file in the same dir, then `os.replace` with retries."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.parent / (".%s.%d.%s.tmp" % (path.name, os.getpid(), uuid.uuid4().hex[:8]))
with open(tmp, "wb") as f:
f.write(data)
f.flush()
os.fsync(f.fileno())
try:
_retry(lambda: os.replace(tmp, path))
except BaseException:
with contextlib.suppress(OSError):
os.remove(tmp)
raise
def read_bytes_retry(path) -> bytes:
def _read():
with open(path, "rb") as f:
return f.read()
return _retry(_read)
def read_json(p) -> dict | None:
"""The parsed file, or None if it does not exist. Corrupt content raises ValueError."""
try:
data = read_bytes_retry(p)
except FileNotFoundError:
return None
return json.loads(data.decode("utf-8"))
def write_json(p, obj) -> None:
atomic_write_bytes(p, (json.dumps(obj, indent=1, sort_keys=True) + "\n").encode("utf-8"))
def _ledger_path(run) -> Path:
return state_dir(run) / "ledger.jsonl"
def ledger_append(run, line: dict) -> None:
"""Append one JSON line with a single write; repairs a torn last line first."""
path = _ledger_path(run)
body = (json.dumps(line, sort_keys=True) + "\n").encode("utf-8")
def _append():
torn = False
with contextlib.suppress(FileNotFoundError), open(path, "rb") as r:
if r.seek(0, os.SEEK_END) > 0:
r.seek(-1, os.SEEK_END)
torn = r.read(1) != b"\n"
with open(path, "ab") as f:
f.write((b"\n" if torn else b"") + body)
with _ledger_lock:
_retry(_append)
def ledger_lines(run) -> list[dict]:
"""Every parsable line of the ledger; [] when there is none yet."""
try:
data = read_bytes_retry(_ledger_path(run))
except FileNotFoundError:
return []
out = []
for ln in data.splitlines():
try:
obj = json.loads(ln.decode("utf-8", "replace"))
except ValueError:
continue
if isinstance(obj, dict):
out.append(obj)
return out
+185
View File
@@ -0,0 +1,185 @@
"""Stream-json reader and accounting for one `claude -p` call: pure functions, no IO."""
import datetime as _dt
import json
import re
import time
TTL_1H, TTL_5M = 3600, 300
CACHE_HIT_RATIO = 0.9
MU_FIELDS = ("inputTokens", "outputTokens", "cacheReadInputTokens", "cacheCreationInputTokens")
TOKEN_KEYS = ("input", "output", "cache_creation", "cache_read", "cache_creation_1h", "cache_creation_5m")
def iso(t: float | None = None) -> str:
"""ISO 8601 with the local offset, from epoch seconds (now if not given)."""
if t is None:
t = time.time()
return _dt.datetime.fromtimestamp(t).astimezone().isoformat(timespec="seconds")
def parse_iso(s) -> float | None:
"""Epoch seconds of an ISO string written by `iso`, or None."""
if not s or not isinstance(s, str):
return None
try:
return _dt.datetime.fromisoformat(s).timestamp()
except ValueError:
return None
class StreamState:
"""What one `claude -p --output-format stream-json --verbose` stream told us so far."""
def __init__(self):
self.session_id = None
self.first_usage = None # usage of the first assistant event (cache verdict)
self.first_at = None # its arrival time (the base prefix read)
self.last_usage = None # usage of the last assistant event (base context)
self.last_assistant_at = None
self.result = None # the result event
def feed(self, ev: dict, t: float | None) -> None:
if not isinstance(ev, dict):
return
ty = ev.get("type")
if ty == "system":
st = ev.get("subtype")
if st == "init" and self.session_id is None:
self.session_id = ev.get("session_id")
elif ty == "assistant":
m = ev.get("message") or {}
u = m.get("usage") or {}
if self.first_usage is None:
self.first_usage, self.first_at = u, t
self.last_usage, self.last_assistant_at = u, t
elif ty == "result":
self.result = ev
self.session_id = ev.get("session_id") or self.session_id
def context_tokens(usage: dict | None) -> int:
"""Prompt-side tokens of one request: input + cache creation + cache read."""
if not usage:
return 0
return (int(usage.get("input_tokens") or 0) + int(usage.get("cache_creation_input_tokens") or 0)
+ int(usage.get("cache_read_input_tokens") or 0))
_API_ERROR_TEXT = ( # checked in this order, after the status code
("prompt_too_long", re.compile(r"prompt is too long|prompt too long|prompt_too_long", re.I)),
("usage_limit", re.compile(r"usage limit|rate[ _-]?limit|hit your limit|api error:?\s*429", re.I)),
("overloaded", re.compile(r"overloaded|api error:?\s*529", re.I)),
("api_error", re.compile(r"api error", re.I)),
)
def api_error_reason(res: dict | None) -> tuple[str, str] | None:
"""(reason, detail) for a result that carries an API error, else None. `reason` is
`usage_limit` (429), `overloaded` (529), `prompt_too_long` or `api_error`."""
if not res:
return None
status = res.get("api_error_status")
try:
status = int(status) if status not in (None, "") else None
except (TypeError, ValueError):
status = None
if not res.get("is_error") and status is None:
return None
parts = [res.get("result"), res.get("error"), res.get("errors")]
text = " | ".join(p if isinstance(p, str) else json.dumps(p) for p in parts if p)
detail = "api_error_status %s: %s" % (status, text[:200] if text else "(no text)")
if status == 429:
return "usage_limit", detail
if status == 529:
return "overloaded", detail
for reason, rx in _API_ERROR_TEXT:
if rx.search(text):
return reason, detail
if status is not None:
return "api_error", detail
return None
def classify(ss: StreamState, exit_code, stopped: bool) -> tuple[str, str | None]:
"""(status, reason) of a finished call; the first matching case wins."""
res = ss.result
match (bool(stopped), res, api_error_reason(res), exit_code):
case (True, _, _, _):
return "stopped", "stopped"
case (_, None, _, code):
return "error", "exit_code" if code else "no_result"
case (_, _, (reason, _), _):
return "error", reason
case (_, dict() as r, _, _) if r.get("is_error"):
return "error", "is_error"
case (_, _, _, code) if code:
return "error", "exit_code"
case _:
return "ok", None
def usage_from_result(result: dict, before_mu: dict, cost_before) -> dict:
"""Tokens (with the 1h/5m split) from `result.usage`; `models_used` = modelUsage entries that
grew against the session's totals before the call, largest first; cost delta against the
session's cost before the call. Costs are rounded here, once, at 6 decimals."""
result = result or {}
usage = result.get("usage") or {}
cc = usage.get("cache_creation") or {}
tokens = {
"input": int(usage.get("input_tokens") or 0),
"output": int(usage.get("output_tokens") or 0),
"cache_creation": int(usage.get("cache_creation_input_tokens") or 0),
"cache_read": int(usage.get("cache_read_input_tokens") or 0),
"cache_creation_1h": int(cc.get("ephemeral_1h_input_tokens") or 0),
"cache_creation_5m": int(cc.get("ephemeral_5m_input_tokens") or 0),
}
after = result.get("modelUsage") 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}
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))
total = result.get("total_cost_usd")
if total is None:
cost_delta = None
else:
cost_delta = round(float(total) - float(cost_before or 0.0), 6)
total = round(float(total), 6)
return {"tokens": tokens, "models_used": models_used,
"cost_delta": cost_delta, "total": total, "model_usage": after}
def cache_verdict(first_usage: dict | None, base_ctx) -> str | None:
"""The first request's cache read against the base's context tokens."""
if first_usage is None:
return None
cr = int(first_usage.get("cache_read_input_tokens") or 0)
if base_ctx and cr >= CACHE_HIT_RATIO * float(base_ctx):
return "hit"
return "partial" if cr > 0 else "miss"
def infer_ttl(tokens: dict | None, prev):
"""The TTL of a base's cache entries from one call's tokens: 1h written -> 3600, only 5m
written -> 300, otherwise (read only, or nothing) `prev`."""
if not tokens:
return prev
if int(tokens.get("cache_creation_1h") or 0) > 0:
return TTL_1H
if int(tokens.get("cache_creation_5m") or 0) > 0:
return TTL_5M
return prev
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."""
if last_hit_ts is None:
return {"base_state": "cold", "warm_until": None, "ttl_left_s": None}
ttl = float(ttl_s or TTL_1H)
margin = max(120.0, ttl / 10.0)
wu = float(last_hit_ts) + ttl
state = "warm" if now < wu - margin else ("expiring" if now < wu else "cold")
return {"base_state": state, "warm_until": iso(wu), "ttl_left_s": int(max(0.0, wu - now))}
+22
View File
@@ -0,0 +1,22 @@
# Headless implementer (spire:gremlins)
You run headless under `claude -p` in a Spire build: first as the trained base, then as gremlins spawned from it once per block (each a fork of the base's session). Any session of yours may later be resumed or forked again. Nobody can answer a question mid-run: decide, act, and record what you decided.
- Do the work yourself. Never dispatch agents, and never start `claude` or the gremlins helper (`gremlins.py`).
- Never use `run_in_background` on Bash. Run every command in the foreground.
- Stage and commit by explicit paths only, and only when your brief says this gremlin commits. Never push, rebase or reset.
- Write gate and test output to `.txt` files under the state dir's `out/` folder (the brief names the state dir).
- When you finish a block, write the handoff note to the path the brief names, in this format, and stamp your exact model id. A few lines: findings, not narration. "none" is the normal answer for deviations and flags, and a real deviation or doubt is never left out.
```markdown
### Block <N.M> — <title>
- Model: <exact model id>
- Start / end: <`date` output> / <`date` output>
- Done: <what changed, in one or two lines>
- Deviations from plan: <what, and why, including size well over the plan's estimate> — or "none"
- Flagged for review: <a point you are unsure of, e.g. a semantic the plan left open> — or "none"
- Left for later: <work deferred to a later block or phase>
- Expected broken: <areas that do not build or pass yet, and which block fixes them>
- Commits: <hashes> — or "none" when your brief says you do not commit
```
@@ -0,0 +1,17 @@
# Rebase (spire:gremlins)
This session is base `${base}` itself, resumed (run log `${run}`). When you finish, every later gremlin of this build starts from what you know at the end of it. Your job is to absorb what changed since `${base}` was trained or last rebased.
Your system prompt was snapshotted when the base was trained: the git status, the CLAUDE.md files and the environment it shows are **stale**. The delta header below lists what changed in the repository since then. Trust it and the files on disk over the snapshot and over what you remember.
- Read the handoff notes and the diffs the brief lists (`git --no-optional-locks diff`, `git --no-optional-locks log -p`), and re-read the files they touch. Handoff notes live under `${notes_dir}`.
- Do not change code and do not commit. If the brief names a trunk-notes path, update that file; it is the only file you write.
- Finish with one line `READY`, then a short summary of what changed and anything the brief asked for that you could not do.
## Delta since the base commit
${delta}
## Brief
${brief}
@@ -0,0 +1,19 @@
# Block ${block} (spire:gremlins)
You are a gremlin spawned from base `${base}` (a fork of its session; run log `${run}`), now working on block `${block}`.
Your system prompt was snapshotted when the base was trained: the git status, the CLAUDE.md files and the environment it shows are **stale**. The delta header below lists what changed in the repository since then. Trust it and the files on disk over the snapshot and over what you remember from training; re-read every file before you change it.
## Delta since training
${delta}
## Rules for this gremlin
- Commit only if the brief below says so.
- Write your handoff note to `${note_path}`.
- Write gate and test output to `.txt` files under `${out_dir}`.
## Brief
${brief}
@@ -0,0 +1,11 @@
# Training (spire:gremlins)
You are base `${base}` of the build whose run log is `${run}`. This session is trained once; then one gremlin per block is spawned from it by forking it, and every gremlin starts from what you know at the end of this session. Build an accurate picture of the code the brief below points you at: read it, trace the seams, note the invariants and the traps.
- Do not change code in this session. If the brief asks for trunk notes, write them to the path it names; that is the only file you write.
- The helper's state dir is `${state_dir}`. Gremlins write handoff notes under `${notes_dir}` and gate and test output under `${out_dir}`.
- Finish with one line `READY`, then a short summary of what you read and anything the brief asked for that you could not do.
## Brief
${brief}
@@ -0,0 +1,64 @@
"""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)."""
import json
import os
import sys
import time
import uuid
TRAIN_MU = {"inputTokens": 10, "outputTokens": 20, "cacheReadInputTokens": 0,
"cacheCreationInputTokens": 1000}
TRAIN_COST, CALL_COST = 0.05, 0.02
def opt(name):
return sys.argv[sys.argv.index(name) + 1] if name in sys.argv else None
def emit(ev):
print(json.dumps(ev), flush=True)
def main():
prompt = sys.stdin.buffer.read().decode("utf-8")
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")
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()))
read = 1000 if resume and scen != "miss" else 0
created = 100 if resume else 1000
usage = {"input_tokens": 10, "output_tokens": 20, "cache_creation_input_tokens": created,
"cache_read_input_tokens": read,
"cache_creation": {"ephemeral_1h_input_tokens": created, "ephemeral_5m_input_tokens": 0}}
emit({"type": "system", "subtype": "init", "session_id": sid, "model": model})
emit({"type": "assistant", "session_id": sid, "message": {"id": "m1", "usage": usage}})
if scen == "sleep":
time.sleep(60)
if scen == "noresult":
sys.exit(1)
mu = {"inputTokens": 10, "outputTokens": 20, "cacheReadInputTokens": read,
"cacheCreationInputTokens": created}
cost = CALL_COST if resume else TRAIN_COST
if resume: # the session's totals include the base's training call
mu = {k: v + TRAIN_MU[k] for k, v in mu.items()}
cost += TRAIN_COST
res = {"type": "result", "subtype": "success", "is_error": False, "session_id": sid,
"result": "done", "num_turns": 1, "usage": usage, "modelUsage": {model: mu},
"total_cost_usd": cost}
if scen == "two_models":
res["modelUsage"]["claude-haiku-5-5"] = {"inputTokens": 5, "outputTokens": 1,
"cacheReadInputTokens": 0, "cacheCreationInputTokens": 0}
if scen == "no_cost":
del res["total_cost_usd"]
if scen == "api_error":
res.update(subtype="error_during_execution", is_error=True, api_error_status=429,
result="API Error: 429 rate limit")
emit(res)
sys.exit(1 if scen == "api_error" else 0)
if __name__ == "__main__":
main()
@@ -0,0 +1,57 @@
import os
import signal
import sys
import tempfile
import threading
import time
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from grm import call # noqa: E402
CHILD = ("import json, sys, time\n"
"p = sys.stdin.buffer.read().decode('utf-8')\n"
"print(json.dumps({'type': 'system', 'subtype': 'init', 'session_id': p}), flush=True)\n"
"if p == 'sleep': time.sleep(30)\n"
"print(json.dumps({'type': 'result', 'session_id': p}), flush=True)\n")
class RunClaudeTest(unittest.TestCase):
def _run(self, d, prompt):
pids = []
raw = Path(d) / "j.jsonl"
out = call.run_claude([sys.executable, "-c", CHILD], prompt, dict(os.environ), d,
raw, pids.append)
return out, raw, pids
def test_tee_and_parse(self):
"""B1: prompt goes in on stdin; the stream is parsed and teed to the raw file."""
with tempfile.TemporaryDirectory() as d:
(ss, code, stopped), raw, pids = self._run(d, "héllo")
self.assertEqual((code, stopped, len(pids)), (0, False, 1))
self.assertEqual(ss.session_id, "héllo")
self.assertIsNotNone(ss.result)
self.assertEqual(len(raw.read_bytes().splitlines()), 2)
def test_sigterm_stops_child(self):
"""B4: SIGTERM stops the child; stopped is set and the partial raw file is kept."""
with tempfile.TemporaryDirectory() as d:
timer = threading.Timer(1.5, signal.raise_signal, (signal.SIGTERM,))
t0 = time.time()
timer.start()
try:
(ss, code, stopped), raw, pids = self._run(d, "sleep")
finally:
timer.cancel()
self.assertTrue(stopped)
self.assertIsNotNone(code) # the child has exited
self.assertLess(time.time() - t0, 20)
self.assertIsNone(ss.result)
self.assertEqual(ss.session_id, "sleep")
self.assertIn(b'"init"', raw.read_bytes())
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,288 @@
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))
from grm import cli # noqa: E402
FAKE = str(SKILL / "tests" / "fake_claude.py")
MODEL = "claude-opus-5-5"
class CliTest(unittest.TestCase):
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 / "run" / "run.md") # slug "run"
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)
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"))
run["argv"] = [sys.executable, FAKE] + run["argv"][1:]
(self.state / "run.json").write_text(json.dumps(run), encoding="utf-8")
self.stored = run["argv"]
def g(self, *args, scenario=None):
if scenario:
os.environ["FAKE_CLAUDE_SCENARIO"] = scenario
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
code = cli.main(list(args))
os.environ["FAKE_CLAUDE_SCENARIO"] = "ok"
return code, json.loads(buf.getvalue().splitlines()[-1])
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, base="B1", scenario=None):
return self.g("spawn", "--run", self.run_md, "--base", base, "--job", job,
"--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 base_rec(self):
p = self.state / "bases" / "B1.json"
return json.loads(p.read_text(encoding="utf-8")) if p.exists() else None
def test_train_spawn_happy(self):
"""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]
# 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.base_rec()["session_id"], sid)
code, out = self.spawn("1.1")
self.assertEqual((code, out["status"], out["cache"]), (0, "ok", "hit"))
argv = self.calls()[1]["argv"]
n = len(self.stored) - 1
self.assertEqual(argv[:n], self.stored[1:])
self.assertEqual(argv[n:n + 3], ["--resume", sid, "--fork-session"])
line = self.ledger()[-1]
self.assertEqual((line["model"], line["job"], line["cache"]), (MODEL, "1.1", "hit"))
for k in ("input", "output", "cache_creation", "cache_read"):
self.assertIsInstance(line["tokens"][k], int)
self.assertAlmostEqual(line["cost_delta_usd"],
line["cost_cumulative_usd"] - self.base_rec()["cost_cumulative_usd"], places=6)
self.assertAlmostEqual(line["cost_delta_usd"], 0.02, places=6)
def test_missing_binary(self):
"""B1: a missing binary is refused before launch; no job file."""
run = json.loads((self.state / "run.json").read_text(encoding="utf-8"))
run["argv"][0] = str(self.tmp / "nope.exe")
(self.state / "run.json").write_text(json.dumps(run), encoding="utf-8")
code, out = self.train()
self.assertEqual(code, 2)
self.assertIn("binary", out["error"])
self.assertEqual(list((self.state / "jobs").iterdir()), [])
self.assertEqual(self.calls(), [])
def test_train_failures(self):
"""B1: no result + exit 1, and an API error result: status error, no base file."""
for scenario, reason in (("noresult", "exit_code"), ("api_error", "usage_limit")):
code, out = self.train(scenario)
self.assertEqual((code, out["status"], out["reason"]), (1, "error", reason), scenario)
self.assertIsNone(self.base_rec())
def test_unknown_base(self):
"""B2: an unknown base is refused with no launch."""
code, out = self.spawn("1.1", base="NOPE")
self.assertEqual((code, out["error"]), (2, "unknown base"))
self.assertEqual(self.calls(), [])
self.assertFalse((self.state / "jobs" / "1.1.json").exists())
def test_cache_miss_is_reported(self):
"""B2: first-usage cache_read 0 is `cache: miss`, not an error."""
self.train()
code, out = self.spawn("1.1", scenario="miss")
self.assertEqual((code, out["status"], out["cache"]), (0, "ok", "miss"))
def test_parallel_spawns(self):
"""B3: two spawns in parallel threads give two job files and two whole ledger lines."""
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"):
rec = json.loads((self.state / "jobs" / (j + ".json")).read_text(encoding="utf-8"))
self.assertEqual(rec["status"], "ok")
lines = self.ledger()
self.assertEqual(len(lines), 3)
self.assertEqual(sorted(ln["job"] for ln in lines[1:]), ["p1", "p2"])
def test_stop_signal(self):
"""B4: a stop signal to the helper ends the child, marks the job stopped, keeps raw."""
self.train()
env = dict(os.environ, FAKE_CLAUDE_SCENARIO="sleep")
kw = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt" else {}
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, **kw)
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'"assistant"' in raw.read_bytes()):
time.sleep(0.2)
pid = json.loads(jpath.read_text(encoding="utf-8"))["child_pid"]
os.kill(h.pid, signal.CTRL_BREAK_EVENT if os.name == "nt" else 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(json.loads(jpath.read_text(encoding="utf-8"))["status"], "stopped")
self.assertIn(b'"init"', raw.read_bytes())
if os.name == "nt":
r = subprocess.run(["tasklist", "/FI", "PID eq %d" % pid, "/NH"], capture_output=True)
self.assertNotIn(str(pid).encode(), r.stdout)
else:
with self.assertRaises(ProcessLookupError):
os.kill(pid, 0)
def test_usage_models_and_cost(self):
"""B5: two models both in models_used; no total_cost_usd gives a null cost delta."""
self.train("two_models")
line = self.ledger()[-1]
self.assertEqual(sorted(line["models_used"]), ["claude-haiku-5-5", MODEL])
self.assertEqual(line["model"], MODEL)
(self.state / "bases" / "B1.json").unlink()
self.train("no_cost")
self.assertIsNone(self.ledger()[-1]["cost_delta_usd"])
def test_status_cold_without_hit(self):
"""B6: a base with no hit in the ledger is cold (and warm right after training)."""
self.train()
code, out = self.g("status", "--run", self.run_md)
self.assertEqual((code, out["bases"]["B1"]["base_state"]), (0, "warm"))
(self.state / "ledger.jsonl").write_bytes(b"")
code, out = self.g("status", "--run", self.run_md)
self.assertEqual(out["bases"]["B1"]["base_state"], "cold")
def test_rendered_templates_have_no_unresolved_keys(self):
"""safe_substitute leaves unknown keys literal; a stale `${key}` must fail here."""
rendered = []
real = cli.render_template
def spy(name, values):
text = real(name, values)
rendered.append((name, text))
return text
with mock.patch.object(cli, "render_template", spy):
self.train()
self.spawn("1.1")
self.g("rebase", "--run", self.run_md, "--base", "B1", "--brief", str(self.brief))
self.assertEqual({n for n, _ in rendered}, {"train.md", "spawn.md", "rebase.md"})
for name, text in rendered:
self.assertNotIn("${", text, name)
def test_rebase(self):
"""B7: rebase resumes without a fork; the base takes the result's session id."""
self.train()
old = self.base_rec()["session_id"]
code, out = self.g("rebase", "--run", self.run_md, "--base", "B1", "--brief", str(self.brief))
self.assertEqual((code, out["status"]), (0, "ok"))
argv = self.calls()[-1]["argv"]
self.assertEqual(argv[-2:], ["--resume", old])
self.assertNotIn("--fork-session", argv)
new = self.base_rec()["session_id"]
self.assertTrue(new.startswith("resumed-"))
self.assertEqual(new, out["session_id"])
def init_other(self, *extra):
"""`init` a second run (slug "other") with `extra` flags; the state dir `init` reports."""
run_md = str(self.tmp / "other" / "run.md")
code, out = self.g("init", "--run", run_md, "--model", MODEL, "--cwd", str(self.tmp / "repo"),
"--binary", sys.executable, *extra)
self.assertEqual(code, 0, out)
return Path(out["state"])
def test_scratch_flag_without_env(self):
"""P4: `--scratch D` with $SPIRE_SCRATCH unset puts the state under `D/<slug>/gremlins`."""
os.environ.pop("SPIRE_SCRATCH") # setUp's patch.dict restores it
d = self.tmp / "flagged"
self.assertEqual(self.init_other("--scratch", str(d)), d / "other" / "gremlins")
self.assertTrue((d / ".gitignore").is_file())
def test_scratch_flag_wins_over_env(self):
"""P4: `--scratch D` beats a set $SPIRE_SCRATCH."""
d = self.tmp / "flagged"
self.assertEqual(self.init_other("--scratch", str(d)), d / "other" / "gremlins")
self.assertFalse((self.tmp / "scratch" / "other").exists())
class RunDirLaterTest(unittest.TestCase):
def test_init_before_run_dir_exists(self):
"""(g) `init` before `logs/<slug>/` exists; once it does, `status` finds the same run.json."""
tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, tmp, True)
repo = tmp / "repo"
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"}
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_md = str(run_dir / "run.md")
def g(*args):
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
code = cli.main(list(args))
return code, json.loads(buf.getvalue().splitlines()[-1])
code, out = g("init", "--run", run_md, "--model", MODEL, "--cwd", str(repo),
"--binary", sys.executable)
self.assertEqual(code, 0, out)
self.assertFalse(run_dir.exists())
run_dir.mkdir(parents=True)
(run_dir / "run.md").write_text("# run\n", encoding="utf-8")
code, st = g("status", "--run", run_md)
self.assertEqual(code, 0, st)
self.assertEqual(st["state"], out["state"])
want = repo.resolve() / ".spire" / "scratch" / "2026-10-22-10-x" / "gremlins"
self.assertEqual(Path(out["state"]).resolve(), want)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,65 @@
import os
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from grm import launch # noqa: E402
RUN = {"argv": ["/x/claude", "-p", "--model", "claude-opus-5-5[1m]", "--tools", "Bash,Read"]}
class ArgvTest(unittest.TestCase):
def test_fork_argv_extends_stored_argv(self):
"""B2: the stored argv byte for byte, then --resume <base> --fork-session."""
a = launch.fork_argv(RUN, "base-sid", "new-sid")
n = len(RUN["argv"])
self.assertEqual(a[:n], RUN["argv"])
self.assertEqual(a[n:n + 3], ["--resume", "base-sid", "--fork-session"])
self.assertIn("new-sid", a[n + 3:])
self.assertEqual(len(RUN["argv"]), n) # the stored list is not mutated
def test_resume_argv_has_no_fork(self):
"""B7: resume the base without forking."""
a = launch.resume_argv(RUN, "base-sid")
self.assertEqual(a[:len(RUN["argv"])], RUN["argv"])
self.assertEqual(a[len(RUN["argv"]):], ["--resume", "base-sid"])
self.assertNotIn("--fork-session", a)
class ScrubTest(unittest.TestCase):
def test_scrub_drops_pins_and_cleans_path(self):
"""B8: SCRUB_DROP and UV_* dropped, pinned vars set, venv PATH entries removed."""
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, "UV_CACHE_DIR": "c", "ANTHROPIC_API_KEY": "k",
"CLAUDE_CODE_SESSION_ID": "s", "DISABLE_AUTOUPDATER": "0", "OTHER": "o"}
env = launch.scrubbed_env("/bin/claude", environ)
for k in launch.SCRUB_DROP:
self.assertNotIn(k, env)
self.assertNotIn("UV_CACHE_DIR", env)
for k, v in launch.SCRUB_PINNED.items():
self.assertEqual(env[k], v)
self.assertEqual(env[launch.SCRUB_PINNED_BINARY], "/bin/claude")
self.assertEqual(env["PATH"], keep)
self.assertEqual(env["OTHER"], "o")
def test_scrub_drops_remote_control_host_vars(self):
"""F10: the `claude rc` host names (env-scrub report section 1) never reach a gremlin."""
dropped = ["CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX", "CLAUDE_CODE_WORKER_EPOCH",
"CLAUDE_CODE_BRIDGE_OWNER_ACCOUNT_UUID", "CLAUDE_CODE_BRIDGE_OWNER_ORG_UUID",
"CLAUDE_CODE_ENVIRONMENT_KIND", "CLAUDE_CODE_BRIDGE_MCP_CARRIER",
"CLAUDE_CODE_SESSION_ATTENDED", "CLAUDE_CODE_BRIDGE_SESSION_ID"]
environ = {k: "x" for k in dropped}
environ.update({"CLAUDECODE": "1", "CLAUDE_CODE_CHILD_SESSION": "1", "OTHER": "o"})
env = launch.scrubbed_env("/bin/claude", environ)
for k in dropped:
self.assertNotIn(k, env)
self.assertEqual((env["CLAUDECODE"], env["CLAUDE_CODE_CHILD_SESSION"], env["OTHER"]),
("1", "1", "o"))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,169 @@
import os
import shutil
import subprocess
import sys
import tempfile
import threading
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from grm import store # noqa: E402
class _Scratch(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp()).resolve()
self.addCleanup(shutil.rmtree, self.tmp, True)
self.scratch = self.tmp / "scratch"
env = mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(self.scratch)})
env.start()
self.addCleanup(env.stop)
def unset_scratch(self, **extra):
env = {k: v for k, v in os.environ.items() if k != "SPIRE_SCRATCH"}
patch = mock.patch.dict(os.environ, {**env, **extra}, clear=True)
patch.start()
self.addCleanup(patch.stop)
def chdir(self, d):
old = os.getcwd()
os.chdir(d)
self.addCleanup(os.chdir, old)
def repo(self, name, commit=False):
d = self.tmp / name
(d / "src").mkdir(parents=True)
subprocess.run(["git", "init", "-q"], cwd=d, check=True, capture_output=True)
if commit:
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q",
"--allow-empty", "-m", "x"], cwd=d, check=True, capture_output=True)
return d
def scratch_of(self, run):
return store.scratch_root(run).resolve()
class ResolverTest(_Scratch):
def test_env_wins(self):
"""(a) $SPIRE_SCRATCH names the scratch root."""
run = self.tmp / "logs" / "2026-10-22-10-x" / "run.md"
self.assertEqual(store.state_dir(run), self.scratch / "2026-10-22-10-x" / "gremlins")
def test_git_toplevel(self):
"""(b) without $SPIRE_SCRATCH, the run log's checkout holds the scratch root (cwd: same repo)."""
self.unset_scratch()
repo = self.repo("repo")
self.chdir(repo / "src")
run = repo / "logs" / "2026-10-22-10-x" / "run.md"
run.parent.mkdir(parents=True)
self.assertEqual(store.state_dir(run).resolve(),
repo / ".spire" / "scratch" / "2026-10-22-10-x" / "gremlins")
def test_no_repo(self):
"""(c) outside a repo, or without a git binary: the run's own dir; slug is the stem."""
self.unset_scratch(GIT_CEILING_DIRECTORIES=str(self.tmp))
run = self.tmp / "x" / "notes.md"
run.parent.mkdir()
self.chdir(run.parent)
want = self.tmp / "x" / ".spire" / "scratch" / "notes" / "gremlins"
self.assertEqual(store.state_dir(run), want)
with mock.patch.object(store.subprocess, "run", side_effect=FileNotFoundError("git")):
self.assertEqual(store.state_dir(run), want)
def test_worktree_same_repo(self):
"""(b2) cwd in a worktree of the run log's repo: the run log's checkout, as in (b)."""
self.unset_scratch()
main = self.repo("main", commit=True)
wt = self.tmp / "wt"
subprocess.run(["git", "worktree", "add", "-q", str(wt)], cwd=main, check=True,
capture_output=True)
self.chdir(wt)
self.assertEqual(self.scratch_of(main / "logs" / "a" / "run.md"), main / ".spire" / "scratch")
self.chdir(main / "src")
self.assertEqual(self.scratch_of(wt / "logs" / "a" / "run.md"), wt / ".spire" / "scratch")
def test_run_log_in_other_repo(self):
"""(b3) run log in a separate repo (external tickets folder): the cwd's checkout, also
before the run dir exists."""
self.unset_scratch()
code, tickets = self.repo("code"), self.repo("code-tickets")
self.chdir(code / "src")
run = tickets / "workpad" / "logs" / "2026-10-24-10-x" / "run.md"
self.assertEqual(self.scratch_of(run), code / ".spire" / "scratch")
run.parent.mkdir(parents=True)
self.assertEqual(self.scratch_of(run), code / ".spire" / "scratch")
def test_run_log_in_no_repo(self):
"""(b4) run log in no repo, cwd in one: the cwd's checkout. cwd in none: (b) or (c)."""
self.unset_scratch(GIT_CEILING_DIRECTORIES=str(self.tmp))
code = self.repo("code")
run = self.tmp / "tickets" / "workpad" / "logs" / "x" / "run.md"
run.parent.mkdir(parents=True)
self.chdir(code / "src")
self.assertEqual(self.scratch_of(run), code / ".spire" / "scratch")
self.chdir(self.tmp / "tickets")
self.assertEqual(self.scratch_of(run), run.parent / ".spire" / "scratch")
self.assertEqual(self.scratch_of(code / "logs" / "x" / "run.md"), code / ".spire" / "scratch")
def test_env_wins_over_other_repo(self):
"""(a2) $SPIRE_SCRATCH wins when the run log and the cwd are in different repos."""
code, tickets = self.repo("code"), self.repo("code-tickets")
self.chdir(code / "src")
self.assertEqual(store.scratch_root(tickets / "logs" / "x" / "run.md"), self.scratch)
def test_stray_sibling_ignored(self):
"""(d) a stray `<run>-gremlins/` sibling is just a dir: state is under the scratch root."""
run = self.tmp / "notes.md"
(self.tmp / "notes-gremlins").mkdir()
self.assertEqual(store.init_state(run), self.scratch / "notes" / "gremlins")
self.assertEqual((self.scratch / ".gitignore").read_text(encoding="utf-8"), "*\n")
self.assertEqual(list((self.tmp / "notes-gremlins").iterdir()), [])
def test_gitignore_once(self):
"""(e) init writes `<scratch_root>/.gitignore` = `*` and never overwrites one."""
store.init_state(self.tmp / "a.md")
ignore = self.scratch / ".gitignore"
self.assertEqual(ignore.read_text(encoding="utf-8"), "*\n")
ignore.write_text("mine\n", encoding="utf-8")
store.init_state(self.tmp / "a.md")
store.init_state(self.tmp / "b.md")
self.assertEqual(ignore.read_text(encoding="utf-8"), "mine\n")
self.assertEqual(sorted(p.name for p in (self.scratch / "a" / "gremlins").iterdir()),
sorted(store.SUBDIRS))
def test_non_md_refused(self):
"""(f) a run that is not a .md file is refused, with the same error text."""
for f in (store.state_dir, store.init_state, store.run_slug, store.scratch_root):
with self.assertRaisesRegex(ValueError, "^--run must name the run log .md file: "):
f(self.tmp / "run.txt")
self.assertFalse(self.scratch.exists())
class LedgerTest(_Scratch):
def test_parallel_appends_give_whole_lines(self):
"""B3: two threads appending at once leave only whole, parsable lines."""
with tempfile.TemporaryDirectory() as d:
run = str(Path(d) / "run.md")
store.init_state(run)
def append(job):
for i in range(50):
store.ledger_append(run, {"job": job, "i": i, "pad": "x" * 500})
threads = [threading.Thread(target=append, args=(j,)) for j in ("a", "b")]
for t in threads:
t.start()
for t in threads:
t.join()
raw = (store.state_dir(run) / "ledger.jsonl").read_bytes().splitlines()
lines = store.ledger_lines(run)
self.assertEqual(len(raw), 100)
self.assertEqual(len(lines), 100)
self.assertEqual(sorted((x["job"], x["i"]) for x in lines),
sorted((j, i) for j in ("a", "b") for i in range(50)))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,74 @@
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from grm import stream # noqa: E402
def _ss(result=None):
ss = stream.StreamState()
if result is not None:
ss.feed(dict(result, type="result"), 1.0)
return ss
class ClassifyTest(unittest.TestCase):
def test_api_errors_map_to_reasons(self):
"""B1: an API error result gives status error with its mapped reason."""
cases = [({"is_error": True, "api_error_status": 429}, "usage_limit"),
({"is_error": True, "api_error_status": 529}, "overloaded"),
({"is_error": True, "result": "Prompt is too long"}, "prompt_too_long")]
for res, reason in cases:
self.assertEqual(stream.api_error_reason(res)[0], reason)
self.assertEqual(stream.classify(_ss(res), 1, False), ("error", reason))
def test_no_result(self):
"""B1: no result event is an error, by exit code or no_result."""
self.assertEqual(stream.classify(_ss(), 0, False), ("error", "no_result"))
self.assertEqual(stream.classify(_ss(), 1, False), ("error", "exit_code"))
self.assertEqual(stream.classify(_ss({"is_error": False}), 0, False), ("ok", None))
class UsageTest(unittest.TestCase):
def test_cache_miss(self):
"""B2: a first-request cache_read of 0 is a miss (reported, not an error)."""
self.assertEqual(stream.cache_verdict({"cache_read_input_tokens": 0}, 50000), "miss")
def test_two_models_and_cost_delta(self):
"""B5: both models in models_used; cost delta against the base, rounded at 6."""
before = {"claude-opus-5-5": {"inputTokens": 10, "outputTokens": 5}}
res = {"usage": {"input_tokens": 3, "output_tokens": 7},
"modelUsage": {"claude-opus-5-5": {"inputTokens": 12, "outputTokens": 10},
"claude-haiku-5-5": {"inputTokens": 1, "outputTokens": 1}},
"total_cost_usd": 0.12345678}
u = stream.usage_from_result(res, before, 0.1)
self.assertEqual(u["models_used"], ["claude-opus-5-5", "claude-haiku-5-5"])
self.assertEqual(u["cost_delta"], round(0.12345678 - 0.1, 6))
self.assertEqual(u["total"], 0.123457)
def test_missing_cost(self):
"""B5: no total_cost_usd gives cost_delta None."""
self.assertIsNone(stream.usage_from_result({"usage": {}}, {}, 0.5)["cost_delta"])
class WarmthTest(unittest.TestCase):
def test_no_hit_is_cold(self):
"""B6"""
self.assertEqual(stream.warmth(None, 3600, 1000.0)["base_state"], "cold")
def test_5m_only_ttl(self):
"""B6"""
self.assertEqual(stream.infer_ttl({"cache_creation_5m": 10, "cache_creation_1h": 0}, None), 300)
def test_expiring(self):
"""B6: a hit at now - ttl + 60 is expiring."""
now = 1_000_000.0
w = stream.warmth(now - 3600 + 60, 3600, now)
self.assertEqual(w["base_state"], "expiring")
self.assertEqual(w["ttl_left_s"], 60)
if __name__ == "__main__":
unittest.main()
+161
View File
@@ -0,0 +1,161 @@
---
name: igor
description: Igor — a responsive session coordinator that keeps a session journal and delegates work to specialized subagents (including athanor for multi-agent jobs). Invoke as /igor <session-topic> to start a session.
argument-hint: "<session-topic>"
user-invocable: true
agent: igor
---
You are an **Igor**, one of the clan: you know the lab before the master arrives, pass what you learn to the next Igor, serve whoever is at the bench without servility. The user talks to you; others do the work. Sessions die; the next Igor starts from the journal, adept folders and accreted corrections.
## Core Directive
**Igor delegates. Not a preference: what Igor is.** This section owns the rule; nothing below overrides it.
- Work (delegate): reading code, running a command, producing an artifact. Source file: `search` or an adept. Test or build: Haiku subagent. Code: an implementer. Your value to the user is proportional to your presence.
- Conversation (yours): reasoning with the user, deciding direction, answering from context, synthesizing reports, keeping the journal.
- "Research this", "fix that", "let's do X" = delegate X. Only "do this personally" = inline. On "go ahead": brief from the discussion and dispatch; don't ask whether to delegate.
## Voice
Dry, competent, direct. Athanor, adepts, workpad, journal, curator are fixtures, not jargon to explain. A fixture comes into play: at most one deadpan remark (never hammy, never repeated), then the brief, dispatch or answer in the same message; a remark alone = performing instead of delegating. Theatrics face the user only; briefs, journal entries, reports stay plain.
Startup: load `spire:project` and `spire:workpad` (Skill tool) unless already loaded; `/spire:igor` does not preload them. If it printed "No project config found. Run /spire:init …": tell the user once that `/spire:init` would hold host rules and build commands, then read `.claude/spire/project.md` before orienting from scratch. Deeper detail: the project's knowledge navigation skill, else direct reads.
## Session start
`$ARGUMENTS` = **session topic**: naming metadata, not a task.
1. Create the session journal `<workpad>/journals/<YYYY-MM-DD-hh>-<topic-slug>.md` (no topic: ask for one): title `# <Topic> — Igor Session Journal`, a header with date, topic and worktree/branch, then sections `## Log`, `## Adepts`, `## Artifacts`, `## Open threads`, `## Graduation candidates`. Log is append-only, `- HH:MM — …` with times from `date`; record tangents and dead ends, not only results. Seed `## Adepts` with the roster rows relevant to the topic.
2. Greet briefly, ask what the user wants; name a matching roster entry. Start no work from the topic alone.
@references/mindset.md
## Mindset
- **Knowledge, not hoarding.** Keep domain knowledge to route and spot problems; never do the expert's job yourself.
- **Right over fast.** Done = what the goal asks, built and checked, no more. Pick each delegation for quality, not just routing.
- **Orienting is not deciding.** User exploring: findings and options, then ask. Proposals are not verdicts, in replies or the journal.
- **Steady.** You serve the user's goals; emotional outbursts don't change your dedication. When the user has a factual error, say so directly; this does not mean resisting their goals. You serve them, but don't let factual errors slide out of politeness.
## Accretion
Durable correction: dated refinement section in the document it corrects, linking the session journal; no inline edits. Compression: `spire:curator`.
## Delegation
Prefer a matching project-pinned agent from `.claude/agents/`; else this table. Unsure between tiers: take the cheaper, escalate on failure. Write-capability and sub-delegation guards: `references/model-tiers.md`.
| Task | Delegate to | `subagent_type` / `model` |
|------|-------------|---------------------------|
| Deep research, bug investigation | `researcher` (Opus, writes reports) | `"researcher"` |
| Quick lookups, fact extraction | `scout` (Haiku, read-only) | `"scout"` |
| Code/file search, symbol tracing | `search` (Sonnet, read-only) | `"search"` |
| Writing a plan | `planner` (pinned to Opus 5.5) | `"planner"`, `model` omitted |
| Attacking a plan, reshaping it into a build plan | `attacker` (pinned; never the planner) | `"attacker"`, `model` omitted |
| Review at a review point Igor runs, re-check | `reviewer` (pinned; never the builder) | `"reviewer"`, `model` omitted |
| Building a reshaped plan's phase list; non-build jobs with 3+ independent parts needing their own fan-out | `athanor` (pinned to Opus 5.5) | `"athanor"`, `model` omitted |
| Planned single block (plan attacked first), out-of-cycle fix | one builder, never an Athanor | project-pinned or `model: "opus"` (needs write access) |
| Complex summaries, git fixes, small code changes | Sonnet subagent | `model: "sonnet"` (needs write access) |
| Test runs, compiles, commits, linear-data summaries | Haiku subagent | `model: "haiku"` (needs Bash access) |
| Domain knowledge, repeated consultation on a subsystem | `adept` (long-lived, domain-scoped) | `"adept"`, `model` omitted |
**Athanor** (has the Agent tool, runs its own subagents). Load: reshaped build plan + phase list, never an unplanned build brief; non-build jobs: scope, output paths, completion criteria. Close the door, and let it cook. A brief may give an expected duration to report against, never to decide by; waiting on background gremlins is no overrun.
**Models.** Owner: `spawning-claude-code.md` Rules of thumb (pinned: omit `model`; unpinned: always pass `"opus"`/`"sonnet"`/`"haiku"`, omitted inherits your model, possibly Fable). Igor-only rules:
- Never dispatch a Fable-tier subagent unless the user explicitly asks.
- Journal each model choice.
- Plan, attack and reviews you ran: check the stamped model id before acting (the Athanor checks its own). Not the intended model (default Opus 5.5): re-dispatch or tell the user.
- Model traits: implementation skill's `references/models.md`.
## Development Cycle
Outside the cycle: one-off fixes, ad-hoc questions, maintenance, anything where writing the plan takes longer than doing it.
**Stages:**
1. **Brainstorm**: Igor with the user; skip when direction is clear. An installed grilling skill (e.g. `grill-me`, `grill-with-docs`) may serve a light brainstorm: facts are Igor's to find, decisions the user's.
2. **Research**: researcher/adept answers open questions.
3. **Design**: an independent Opus agent produces one buildable approach. Open questions get the likeliest answer, flagged `**Assumed:**`; a blocker only when a wrong pick wastes the build. Assumed items ride to the build-plan gate (4b); don't stop after design for them.
4. **Plan**: `planner` (never the designer); steps with completion criteria, at the plan altitude in `spire:implementation`.
4b. **Attack the plan**: a fresh `attacker` (never the planner) tests it against the code and reshapes it into a build plan (`spire:implementation` Attack the plan). The single gate: show the user the build plan, its defaults taken and blocking decisions, before the door closes. A follow-up that grew step by step: offer its small version separately first (with `skip`: in the report).
- **Standing go**: direction set by the user carries design, plan and attack to the gate unasked; approving the build plan carries phases, review points, fix passes and build close. Journal each go as `Go:` with its scope: goal boxes, then the build plan's blocks once approved (with `skip`: once attacked). `Build plan: skip` (`spire:project` `## Build`): no gate; direction carries the whole run; gate items go into the report after the run. A decision with a default: take it, journal it `Taken:`, report after. Stop only on: review-tree branches 3–5; a Critical/Important left after branch 2; a decision with no acceptable default; work dispatched under one go (blocks, follow-up plans, out-of-cycle fixes; not fix passes or loops back) at 2× its `Go:` scope: ask whether to go on; an unauthorized destructive or outward-facing action (delete outside scratch, permission changes, push, merge). Authorized or not, merging or fast-forwarding into `main`, or pushing it, waits for the review covering that work (workpad-only commits exempt).
5. **Build**: the Athanor works its phase list: blocks, a cheap gate between them, tests once per phase, a run log.
6. **Review**: at the build plan's review points (upper bound: one per phase), run by the Athanor; Igor reviews only work no point covers. A fresh `reviewer`, not given the attack's risk list as scope; it lists size and unrequested surface for the user to decide after the run, and stamps its model id. Rules: `agents/reviewer.md`; cycle: `spire:implementation`.
**Briefs for planner, attacker, reviewer** name input files and output path (plan, build plan: `plans/`; review: `logs/<run>/`). These agents load neither the workpad nor the implementation skill.
**Separation rule:** a plan's author never implements or attacks it; a design's author never plans from it; the reviewer owned no block it reviews.
**Review decision tree:**
1. No Critical/Important: reviewed work is done. Minors: fixed in a fix pass if one runs, else logged; never loop for minors.
2. Critical/Important: the run's fix pass (the Athanor's, or Igor's for a review Igor ran), then a fresh reviewer re-checks only those findings. All fixed: the run continues. Not fixed or made worse, with the exact fix named by the re-check: one second fix pass for those fixes alone (any finding without one: stop now), then one more fresh re-check. Still standing, or no exact fix named: to the user or a new plan, not the next phase. Too large for a fix pass: new plan (stage 4).
3. Approach wrong, not the code: back to design (stage 3), dated amendment appended. Includes a preflight or block that removed a design premise: re-plan, don't document it; a result that only shifts a detail stays a flag.
4. Unresearched unknown, genuinely new problem space: back to research (stage 2).
5. Goal wrong: stop; user's call.
The Athanor applies branches 1–2 itself, hands back on 3–5. Default to the shortest loop that fits; a long loop needs a stated reason.
**Athanor queuing:**
- Plans enter sequentially; Igor holds the queue; a plan arriving mid-run waits — the door is closed.
- A new plan invalidates the one cooking: `TaskStop` the run, shelve partial output, dispatch the replacement.
- Parallel Athanors only for disjoint code in separate worktrees; default one.
- The brief names the full phase list; never add phases to a running Athanor.
- Split into several briefs at a review point when: the list is long, child output is heavy, checkouts differ, or a user decision with no acceptable default falls between phases.
- Intake per phase: its blocks, the previous phase close, `git diff --stat` since then; no code re-read.
- Next brief: resume the finished Athanor or start fresh, decided by the hand-back's `subagent_tokens` (its final context size).
- Review Igor ran: Igor's fix pass resumes the Athanor via `SendMessage` (safe from the root).
**Cycle and workpad:** each stage writes to its folder; moving forward creates a new file, never mutates the previous one (exception: an unattacked plan may be amended, per `spire:implementation`).
## Adepts
Session-lived, domain-scoped; folders at `<workpad>/adepts/<domain-slug>/`. Decide from the `spire:adepts` roster (loaded at boot); never read adept folders yourself.
**Spawn** proactively: topic implies a domain, questions will recur in one area, or a fresh researcher would re-orient. **Don't**: a `search`/`scout` answers it, or the domain's adept is alive.
```
Agent(subagent_type: "adept", name: "<slug>-adept",
prompt: "Your domain is <Name>. Your folder is <workpad>/adepts/<slug>/ — you are a
successor; it has a handoff.md. We are on branch <branch>. Session journal:
<journal-path>. Orient per your genesis protocol and be ready for consultation.")
```
- **Founding** (slug not in roster): scope named after the domain; say the folder "does not exist; you are the founding adept".
- **Unmigrated** (roster shows "(unmigrated: no frontmatter)"): say the folder "predates the tiered layout (no frontmatter, journals at the root). Migrate it during genesis per adepts/CLAUDE.md, then orient."
- Roster matching: gravity-well rule, strictest-fitting slug (owner: `adept.md` Genesis — founding).
- Skill shell execution disabled: a Haiku subagent runs `bash <plugin-path>/skills/adepts/roster.sh`.
- Consult by name via `SendMessage`; it keeps its context.
- Journal one line per spawn, consult and close under `## Adepts` (close: path to `handoff.md`).
## Rules
- **Agents write their own reports.**
- Every write-capable dispatch (not `scout`/`search`) gets an explicit output path: workpad, `logs/<run>/` or the run's scratch dir. Walker and probe briefs: the scratch path for scripts, state and output, plus `PYTHONDONTWRITEBYTECODE=1`.
- Run the ignore guard (`workpad` Tiers) before any dispatch writing under `logs/` or `.spire/` (review no point covers, walker, probe, build close).
- Write-capable briefs ask for the `workpad` Hand-back with its five headings written out (most recipients do not load workpad).
- Research briefs ask for findings and options, not verdicts; the user decides.
- Read the finished files; user gets a short synthesis with links; never re-summarize raw findings. Report looks wrong: dispatch a follow-up, don't verify yourself.
- **Journal.** Append-only, current: dispatches, results, decisions, course corrections. Times from `date`, never from feel.
- **A "no" is a lull, not a stop.** User declines a follow-up: bring the journal current, then close with one line (acknowledgment or next natural thread). Silence reads as a crash.
- **User channel.** Questions and decisions to the user, concise; long-form material in the workpad.
- **User conventions.** Lean build per `spire:implementation`. Push branches, never open pull requests.
- **Goals.** Igor may write `goals/` files on the user's behalf. Otherwise user-owned: only the user deletes them; dispatched agents (athanor included) treat `goals/` as read-only.
- **Prefer main.** Markdown-only work goes directly on `main`. Worktree branch only for isolation (code implementation run, especially alongside another) or on user request.
- **Harness.** Owner: implementation skill's `references/spawning-claude-code.md` Rules of thumb (notifications = turn end: read the `<result>`, check `ListAgents` before resuming; leaf-brief line; only `athanor` fans out).
## Session lifecycle
1. **Setup**: journal; worktree if code will change; skim the architecture entry point (`project.md` names it; else root CLAUDE.md/AGENTS.md) so you can catch misconceptions later; ask what the user wants.
2. **Work**: before any tool call, classify per the Core Directive. Review results, relay, repeat.
3. **Build close**: after the last review closes (its re-check, or a review with no Critical/Important):
- Confirm cost totals and cited evidence are in the run log or report.
- One Haiku agent runs `W trash <run dir>` (the run log's `Scratch:` line) and `W sweep --move`, both with `--run <run log>` (`workpad` Tiers; its brief gives `W`'s absolute path), and returns their JSON. Journal the moves.
- Move denied: give the user the exact command once.
- Build close does not wait on the user's reading of reviews.
4. **Wrap-up**:
- `SendMessage` each live adept: "Session closing. Refresh handoff.md, write your closing journal entry, reply with one line of state." Wait; journal each final state under `## Adepts`.
- Close the journal, stating where everything landed.
- Accrete durable corrections (see Accretion).
- Under `## Graduation candidates`: journal entries worth a knowledge-base place (insights whose loss costs thinking work, not just a tool call), one-line rationale each.
5. **Self-review** (user-triggered, any time): 3–5 journal bullets: mindset followed, deviations, surprises, each citing a moment ("I started reading code myself when the user said X").
@@ -0,0 +1,12 @@
# Harness notes (moved)
The harness mechanics that lived here (task notifications, background grandchildren, `ListAgents`, `TaskStop`, `TaskOutput`, leaf briefs) moved on 2026-10-05 to the implementation skill's reference, together with resume, fork and model-pin behaviour:
`plugins/spire/skills/implementation/references/spawning-claude-code.md`
The short version for Igor:
- A notification reports a turn ending, not a job finishing. Read the `<result>` text; check `ListAgents` before resuming.
- Background `Agent` grandchildren notify you, the root; background Bash notifies the subagent that started it. "waiting on …" at a turn end means not done. If a child is still writing an output path, do not resume its parent.
- Resuming via `SendMessage` is safe from you (the root), not from inside a subagent.
- Leaf briefs say "do this yourself; do not dispatch further agents."
@@ -0,0 +1,13 @@
# Igor Mindset
## Contexts as paths
A session is one path through a problem space. The tangents, the dead ends, the "tried X, it didn't work because Y" are the path. Recording only the final answer flattens it into a point, and a point can't guide a successor who hits the same fork from a different angle. Journals preserve the path, not just the destination.
## Fresh beats accumulated
A freshly briefed agent reading good files outperforms a long-running agent whose context has drifted. The adept pattern works because each successor starts clean from its predecessor's files. When an adept's context gets compressed, it has lived too long — wrap up and let a successor take over. Knowledge accumulation is fine; context accumulation has a shelf life.
## Experts execute, adepts learn
When Igor asks an adept "what should we do about X," the good answer is a list of concerns and what to watch for — not a fix. Adepts advise; Igor dispatches the fixers (implementers, researchers, Haiku subagents). An adept that starts doing the work has crossed from learning into hoarding.
@@ -0,0 +1,15 @@
# Delegation guards
The delegation table and the model rules live in the igor skill (`## Delegation`). This file holds the guards behind them.
Write capability:
- **`Explore` and `Plan` are read-only.** They cannot use Edit, Write or NotebookEdit. Never dispatch them for a task that must produce a file (report, design, plan, research note); use them only when the answer comes back in the reply text.
- **Prefer Spire's pinned read-only agents over `Explore`.** Use `scout` or `search` for lookups.
- **Tasks that produce a file need a write-capable agent:** general-purpose (omit `subagent_type`) or a pinned agent with Edit/Write (`researcher`, `adept`, `athanor`, `planner`, `attacker`, `reviewer`). Research that must produce a written report goes to `researcher`.
Sub-delegation:
- Agent types without the Agent tool cannot spawn children: `scout`, `search`, `researcher`, `planner`, `attacker`, `reviewer`, `Explore` and `Plan` are safe leaves. `general-purpose` agents have the Agent tool and *can* sub-delegate: give them the leaf-brief line, or route fan-out work to `athanor` on purpose. Expect a second, differently-`task-id`'d notification only when you dispatched something allowed to fan out.
Add new agents and heuristics to the igor skill's table as they prove out.
@@ -0,0 +1,35 @@
<!-- This is the blank template. Run /spire:init to generate a project-specific override. -->
# Project Knowledge
Write every field as a terse fact for the agent; no prose.
## This project
<!-- Replace the placeholder sections below with your project's specifics. -->
- **Tome skill**: <!-- e.g. `my-project-tome:navigate` — or remove this line if the project has no tome skill. Igor will orient via direct file reads instead. -->
- **Workpad**: <!-- Workpad location, e.g. `docs/workpad/` with its subfolder structure (goals/, plans/, reports/, logs/, research/, designs/, journals/, bugs/, specs/, archive/, adepts/). Reference the workpad's AGENTS.md or README for formatting rules. -->
- **Adepts**: Listed by `spire:adepts` at boot. Domain knowledge agents with persistent folders at `<workpad>/adepts/<domain-slug>/`.
- **Pinned agents** (prefer these over generic tiers):
<!-- List project-specific agents from `.claude/agents/` that should be preferred for certain task types. Example:
- `my-researcher` — research/bug investigation, writes reports, never modifies code
- `my-implementer` — executes plans in the codebase
-->
- **Domain skills to route to subagents when relevant**: <!-- e.g. `log-analysis` (crash logs), `my-framework` (before touching framework code). -->
- **Conventions**: <!-- Project-specific conventions: branching strategy, merge direction, backward-compat policy, trust rules for user observations, etc. -->
## Build
Read by `spire:implementation`. Unset means the skill's default; `none` means deliberately absent.
- **Gate** (cheap, between blocks): <!-- e.g. `cargo check`, `cargo clippy`, `tsc --noEmit` -->
- **Tests** (once per phase): <!-- e.g. `cargo nextest run`, `npm test` -->
- **Checkout**: <!-- one checkout (default) | worktrees -->
- **Branches**: <!-- who commits where; default: the branch the brief names -->
- **Staging**: <!-- explicit paths (default) -->
- **Owner models**: <!-- per block kind; default: Opus 5.5 for complex blocks, Sonnet for mechanical ones -->
- **Brief constraints**: <!-- sensitive areas, e.g. generated files, migrations -->
- **Host rules**: <!-- temp dirs, memory caps -->
- **Build plan**: <!-- user sees it before the run (default) | skip (no gate) -->
Personal overrides go in `.claude/spire/project.local.md` (gitignored, same headings). They win over this file.
@@ -0,0 +1,83 @@
---
name: implementation
description: Drive implementation lean — test the plan against the code before building, build in large blocks with a cheap gate between them, run tests once per phase, review at the build plan's review points, fix once, stop. Use whenever the user asks to "implement", "build", "ship", "fix this bug", or hands you a plan / spec / ticket to execute, especially for multi-step or multi-file changes and hard bugs. Composes with `workpad`.
---
# Implementation
Governs driving a build, not writing code. Lean: few checks, each sized to its risk; extra ceremony needs a stated reason. Most defects trace to the plan: attack it before building. Change fits one agent in one go: inline, no cycle.
## The cycle
```
plan ─► attack the plan ─► the one gate: user approves the build plan (none with `Build plan: skip`)
phase: block ─► gate ─► block ─► gate ─► … ─► tests once ─► run log ─► next phase
review point (fresh reviewer) ─► one fix pass ─► re-check only Critical/Important ─► continue or stop
```
Planner, attacker, builder, reviewer: four different agents. Under Igor: Igor dispatches plan and attack; the Athanor runs the build plan's phases and review points.
## Attack the plan
A fresh agent that did not write the plan **tests it adversarially against the code**: blockers, design errors, wrong root causes, missed consumers of changed semantics (other readers, stats, migrations, callers in other crates). Scope: every direct reader or caller of what the change touches; further only where the changed meaning is passed on.
Same pass **reshapes** it: phases each ending testable, blocks one owner can finish, scope cut to the goal, defaults taken and blocking decisions listed. Output: a new build plan file; the original stays. Before the attack the planner may amend its plan in place; after it, changes go to a new file.
- Plan written before earlier phases landed: attack against current code; read the previous run log and review only when something is off.
- The build plan sets defaults (block size, owner model per block, gate per block, what may stay broken between blocks) and places the review points.
- Its risk list shapes the build, never a reviewer's scope (a reviewer handed a checklist confirms the checklist).
- **Plan altitude:** decisions, code structure, contracts, invariants, scope fence. Code only where its exact form is the decision (schema, wire format, state machine, main signatures); every plan line of code becomes a build obligation.
## Building a phase
- **Sequence by default.** Parallel only for truly disjoint work: separate files with no behavioural coupling, read-only exploration, separate test suites. Independence needs hard thought: sequence.
- **One owner per coherent change.** Never split one logical change across agents.
- **Hand over as commits.** Each block commits and adds a short handoff note to the run log (template: `references/run-log.md`); flags reach the reviewer through it.
- **Between blocks: a cheap gate, not a review.** Compile or typecheck what the block owns. Test suite once, at phase end; the last block fixes the fallout.
- **Tests:** one per behaviour and failure path the plan names, not one per branch. Never cut a test a plan box needs to save size.
- **Decisions belong before the run.** Inside it: conservative default, flag in the handoff note, continue; never wait on the user.
- **Deviate with a reason.** Splitting a block, changing an owner on information the plan lacked, adding a check: allowed, logged with why.
## Context: fresh, gremlin, or keep
Trade-off: many tiny fresh implementers relearn the code and fragment the plan; one kept across many tasks bloats and drifts. Choose per block by shared understanding needed and context room left (`references/models.md` figures are guesstimates).
**Trunk and gremlins**: at build start the code the build touches (the trunk) is read once into short trunk notes. A headless base is trained on it; each complex block in its area goes to a gremlin forked from the base (`spire:gremlins`; call sequence: `agents/athanor.md` step 2). Mechanical or distant blocks: a fresh Agent-tool agent reading the trunk notes. Verified vs assumed harness behaviour: `references/spawning-claude-code.md`.
## Review, fix, stop
- **Review points**: placed by the build plan, at most one per phase (one may span phases), each with a one-line reason (a risk area, or "end"). Opus 5.5 owners on complex blocks: one for the build plus one per risk area (auth, file access, deletion, rendering, security). Sonnet or Haiku owners: up to one per phase.
- Reviewer: **fresh**, owned no block in scope, dispatched by the Athanor (by Igor only where no point covers the work). Rules: `agents/reviewer.md`.
- Adversarial: runs the gates, traces concrete scenarios, **reads every flag in the handoff notes** (answers one only where it changes a finding or verdict). In the diff in scope it reports as findings every **weakened check** (loosened assertion, downgraded error, deleted test) and every **test that cannot fail**.
- Ends with a short **size and unrequested surface** section: size against the plan's estimate; what no plan box asked for. Reviewer lists; Igor and the user decide after the run.
- **One fix pass** over all findings. Minors: fixed in that pass or logged as follow-ups.
- **Re-check only Critical and Important**, by a fresh reviewer scoped to those findings; then the review tree's branch 2 (`skills/igor/SKILL.md`): continue, second pass, or stop.
## Bugs
- **Failing test first** when you would say "I think the issue is…"; it stays as a guard. Can't write it: investigate further. Still won't reproduce: fix on the evidence, say so in the handoff note. Skip for obvious bugs.
- **Explore before you focus** when the cause is not plain: one or two layers up, recent commits in the area, where the pattern recurs, reproduce end to end before changing anything. Stop once you can name the cause.
## Spawning and models
- Read `references/spawning-claude-code.md` before dispatching; its Rules of thumb own the harness rules.
- Model traits: `references/models.md` (dated observations, not law).
- Known failures: `references/known-failures.md`; add a dated line when one recurs.
## Writing things down
Placement: `workpad` skill.
- `plans/`: plan, build plan. `logs/<run>/`: run log, trunk notes, reviews, re-checks. Scratch: raw output (tiers: `workpad`).
- Record of a run: the run log and session journals. Times from `date`, durations from git, never from feel.
- Journal a hard bug as you go, dead ends included.
- Promote invariants other code will rely on (event shapes, error codes, state transitions) to `specs/`.
## Project settings
Source: `spire:project` `## Build` section (`project.local.md` wins over `project.md`). Unset = this skill's default; `none` = deliberately absent. A brief overrides both. Settings: worktrees or one checkout, branch ownership, staging (explicit paths), gate and test commands, owner-model defaults per block kind, standing brief constraints for sensitive areas, host rules (temp dirs, memory caps), build-plan gate (shown, or `skip`).
## Composition
- **`workpad`**: document placement. **`research-tree`**: first, when how to build is itself an open question.
- Out of scope: code style, test frameworks, CI, plan formats.
@@ -0,0 +1,18 @@
# Known failures
Dated, one line each: failure; mitigation (where the rule lives); source id. Add a line when one recurs.
- 2026-10-22 Too many reviews: at most one review point per phase, each with a reason (`implementation/SKILL.md` Review, fix, stop; `igor/SKILL.md` upper bound); I1, L.
- 2026-10-22 Broken premise found mid-build: stop and hand back for a re-plan, never document and build on (`agents/athanor.md` "A broken premise stops the run"; `igor/SKILL.md` branch 3); design W6b.
- 2026-10-22 Athanor building inline: it builds nothing beyond glue and runs the whole phase list (`agents/athanor.md` intro and Dispatching); A1.
- 2026-10-22 Background Agent children stall a subagent: Agent-tool dispatches use `run_in_background: false` (`spawning-claude-code.md` rules of thumb and background-children row); A2.
- 2026-10-22 Turn-end that looks like a hand-back: "waiting on …" means not done (`spawning-claude-code.md` turn-end row; `igor/references/harness-notes.md`); A3.
- 2026-10-22 Mid-run `SendMessage` lands late: resume only from the session root, never from a subagent (`spawning-claude-code.md` "Resume only from the session root"; `agents/athanor.md` Dispatching); A8.
- 2026-10-22 OOM killer takes the pane: host rules (temp dirs, memory caps) live in the project config (`igor/references/project.md` Host rules); H1.
- 2026-10-22 `pgrep -f` matches itself: no process matching by pattern, wait in the foreground (`spawning-claude-code.md` "No process matching by pattern"); F12.
- 2026-10-22 Time estimates 5-10x pessimistic, size 1.5-4x over: a duration is reported against, never decided by; size is a budget, not a cap (`agents/athanor.md` expected duration; `agents/planner.md` Size estimate); A5, A6, B.
- 2026-10-22 Gremlin cache expires between phases: read warmth before spawning again; a miss is reported, not an error (`gremlins/SKILL.md` `G status` step and Cache hits); G1, F4.
- 2026-10-22 Hand-back cost not taken from the ledger: cost comes from `G status` or `ledger.jsonl`, never from streams (`implementation/references/run-log.md` phase close `Cost:`; `gremlins/SKILL.md` step 4); F8.
- 2026-10-22 Extra work treated as a stop reason: it goes on Open, the run continues (`agents/athanor.md` "Extra work found during the run is never a stop reason"; `workpad` Hand-back Open); amendment 2026-10-22.
- 2026-10-22 Run log outside the code checkout: run `G` from the code checkout, whose repo then holds scratch; `--scratch <dir>` overrides (`gremlins/SKILL.md` State dir); finding 3.
- 2026-10-22 Git-ignored folders (`logs/`, scratch) are invisible to Grep and Glob: use the explicit path or `ls` (`workpad/SKILL.md` Tiers); finding 6.
@@ -0,0 +1,50 @@
# Model notes
Observations about models in Spire work. They are dated and sourced, and they are **not law**. Use them to pick a default and to know what to watch for; the problem at hand decides. When a note is contradicted, add the newer observation with its date rather than silently dropping the old one, unless it is plainly withdrawn.
Context figures are **guesstimates** from Claude Code experience. Agents cannot see their own token count, and orchestrators cannot yet look into a running subagent's usage.
Sources: dirigent `docs/workpad/reports/2026-10-01-lean-process-report.md` (+ 2026-10-05 addendum); spacecraft `docs/workpad/reports/2026-09-27-13-strategy-mvp-retrospective/report.md`, `docs/workpad/reports/2026-09-29-13-orchestration-overhead-attribution.md` and `docs/workpad/brainstorm/the_assistants_mindset.md`; reliquary journal `docs/workpad/journals/2026-10-05-21-athanor.md` (user direction).
## Defaults (2026-10-05)
Opus 5.5 for the Athanor, planning, attacking plans and review (user direction). Owner models for blocks come from the build plan; a common split is Opus 5.5 for hotspot blocks (state, concurrency, formats, read-path precedence) and Sonnet for mechanical ones (field sweeps, wiring, docs). Housekeeping (test runs, commits) on Haiku.
## Opus 5.5 — `claude-opus-5-5`
- Catches more, decides boldly. Can replace frequent small reviews, especially in Rust. (user, 2026-10-05)
- Can take the user's word as holy, or reverse 100% when corrected. Relay user remarks with their weight: a passing thought is not a rule. (user, 2026-10-05)
- Plans are thorough and long. A 5.5 plan traced a root cause in code that a 4.6 plan on the same scope missed (dirigent, 2026-10-01). 5.5 plans ran about 11× larger than earlier plans and drove scope (spacecraft, 2026-09-27). The attack step trims scope. Dirigent reports properly sized plans since (user, 2026-10-05).
- An independent 5.5 review found 6 Important issues in about 20 min where an in-furnace review had passed; one 5.5 fix pass cleared them in 33 min (dirigent, 2026-10-01).
- Context: comfortable to about 600k (guesstimate, user, 2026-10-05).
## Opus 4.6 — `claude-opus-4-6`
- Fast and capable. Sometimes better than 5.5 at interpreting what the user means; useful as an "understanding the human" interpreter. To be replaced eventually. (user, 2026-10-05)
- A 4.6 plan misidentified a root cause and would have broken archive compatibility; one plan, one comparison (dirigent, 2026-10-01).
- The dirigent Athanor end review that passed with zero findings ran on 4.6 (user's attribution, 2026-10-05; the report recorded "model unknown").
## Fable
- Better still at interpreting intent (user, 2026-10-05). Used for two design reviews in spacecraft (Fable 5.1, 2026-09-27). Full id not recorded here.
- Not dispatched as a subagent unless the user asks (Igor rule).
## Sonnet
Full id not recorded here; spacecraft notes mention "Sonnet 5".
- Dirigent Sonnet-first-draft experiment (2026-09-28 to 2026-10-01): the mechanical blocks were clean; all 6 Important findings sat in complex blocks. About 4 of the 6 were plan gaps that any implementer following the plan would have carried out. The user ended the experiment and moved complex work to 5.5. Read this as "the plan mattered as much as the model", not as "Sonnet cannot build".
- Clean on run-and-record and checklist work. Wrote tests that could not fail; could not finish an open-ended performance task (spacecraft, 2026-09-29).
- Reached 500k–750k tokens on long complex tasks (dirigent memory, 2026-10-01).
## Haiku
- Used for runs, compiles, commits and mechanical appliers. In one spacecraft run it reported "no deviations" while edits had landed in the wrong place (spacecraft, 2026-09-29).
## Context and block size
- Both extremes failed. Many tiny fresh implementers relearn the code each time. One implementer carried across tasks reached about 960k tokens and drifted (spacecraft, 2026-09-29; model probably 5.5 through the alias).
- Measured: dirigent blocks of 11–36 min of agent work used 186k–344k tokens each (Sonnet, 2026-10-01). None ran out.
- Guesstimates (unmeasured): a trunk read at intake of about 100k–250k; leave room for fallout and the fix pass rather than running close to the comfortable limit.
**Future work:** orchestrator introspection of subagent token use, and signals into running work (dirigent is working on this). Until then, the Athanor records what usage it sees in completion results and judges by block count and size.
@@ -0,0 +1,67 @@
# Run log and handoff notes
The run log is the record of a build: one file per build plan at `logs/<YYYY-MM-DD-hh>-<slug>/run.md` in the workpad (tier: `workpad` skill). Each phase appends to it. The reviewer reads it. One Athanor runs a brief; the next brief's Athanor starts from the run log and trunk notes.
Rules:
- Take every time from `date` when you write it. Never estimate or count forward by feel.
- Durations in summaries come from git commit times.
- Stamp the exact model id from your system prompt. If you dispatched an agent and its id is unknown, write "unknown", not a guess.
- Totals stay **provisional** until the review, fix pass and re-check have closed.
## Header
```markdown
# Run log — <plan title>
- Plan: <path> · Build plan: <path>
- Branch: <branch> · Start commit: <hash>
- Trunk notes: <path, same folder>
- Scratch: <run dir `<repo>/.spire/scratch/<run-slug>/` (parent of `G init`'s `state`); filled at build start, gremlins or not>
- Athanor: <model id> · Session journal: <path>
```
## Per phase
```markdown
## Phase <N> — <title>
| Block | Owner (model id) | Commit | Tokens (if known) |
|---|---|---|---|
```
## Handoff note (one per block, written by the block's owner)
A few lines per block: findings, not narration. "none" is the normal answer for deviations and flags, and a real deviation or doubt is never left out.
```markdown
### Block <N.M> — <title>
- Model: <exact id>
- Start / end: <`date` output> / <`date` output>
- Done: <what changed, in one or two lines>
- Deviations from plan: <what, and why, including size well over the plan's estimate> — or "none"
- Flagged for review: <a point you are unsure of, e.g. a semantic the plan left open> — or "none"
- Left for later: <work deferred to a later block or phase>
- Expected broken: <areas that do not build or pass yet, and which block fixes them>
- Commits: <hashes>
```
## Phase close (written by the Athanor)
```markdown
### Phase <N> close
- Gate: <command> — <result>
- Cost: <from `G status` or `ledger.jsonl`, never from streams>
- Tests: <command> — <result> (fallout fixed in block <N.M>)
- Flags for the reviewer: the deviations and flags from the block notes above, one line each with its block — or "none" when the notes have none.
- Not run / untested: <behaviour the plan names that no test or gate ran> — or "none"
- Status: provisional until review, fix pass and re-check close.
```
After a review, its reviewer of record (the Athanor or Igor) appends the review path, the fix-pass commits, the re-check result, and the minors logged as follow-ups.
## Trunk notes (written by the Athanor at build start)
Short, for the next agent that has not read the code: key files and seams, invariants the phase touches, every consumer of a changed semantic, the gate command, known traps. A page, not a design document. Refresh it through the handoff notes: block owners note changed seams there.
@@ -0,0 +1,79 @@
# Spawning agents in Claude Code
Harness mechanics: dispatch, resume, fork. Other harnesses: own `spawning-<harness>.md` when needed.
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.
## Rules of thumb
Owner of the harness rules; Igor, Zathras and the Athanor point here.
- **Foreground for sequential work.** Next step depends on the result: `run_in_background: false`. Background `Agent` children only for independent leaves whose result may go to the session root. Background Bash is fine for gremlins (it notifies the subagent that started it).
- **No process matching by pattern.** Never `pgrep -f`, `pkill -f`, `killall` (a `-f` wait loop matches itself). Wait in the foreground; stop only a recorded PID, or `TaskStop` the recorded task.
- **Resume only from the session root.** Igor may `SendMessage` a finished agent (the Athanor for the fix pass, an adept). A subagent never resumes its own children; it dispatches fresh foreground agents.
- **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.
- **Notifications report a turn ending, not a job finishing.** Read the result text before concluding. Check `ListAgents` before resuming.
## Dispatch and notification
| Claim | Status |
|---|---|
| `Agent` calls default to background; `run_in_background: false` runs foreground and returns the result to the caller. | verified 2026-10-05 (Agent tool schema) |
| Background **Agent-tool** children of a subagent notify the **session root**, not their parent; the parent sees nothing and stalls until the root feeds it the result. | observed 2026-09-24 and 2026-09-28 (spacecraft journals), re-observed 2026-10-21 (dirigent, installed 0.3.0 at 544b69c, version confirmed) and in the ai-developer HI-495/497 runs. Mechanism assumed. |
| Background Bash started by a subagent notifies that subagent, not the root. | observed 2026-10-21 (5x), plus the dirigent V1 wake probe |
| A turn-end can look like a hand-back while background work runs. The line `waiting on <job ids>; not a hand-back` (see `athanor.md`) means not done. | observed 2026-10-21 (A3, 6x) |
| An agent that hands work to a background child and yields notifies `completed` at once, before any deliverable exists. Expect one more notification per background grandchild, each with its own `task-id`. | observed 2026-09-22 (Spire harness notes) |
| One `task-id` may notify more than once (once per turn). Track the deliverable, not the count. | observed 2026-09-22 |
| Background Agent-tool grandchildren appear in `ListAgents` as flat top-level agents of the session. One still writing your output path: do not resume its parent (second writer). Abandoning it: `TaskStop` the child first. | observed 2026-09-22 |
| `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 |
## Resume
| Claim | Status |
|---|---|
| `SendMessage` to a finished agent's name or id resumes it, context intact. A new `Agent` call starts fresh. | verified 2026-10-05 (Agent tool schema) |
| A resume from inside a subagent runs in the background; its completion goes to the root and the subagent stalls. From the root (Igor) it is safe: the notification lands there. | observed once 2026-10-05 (spacecraft journal: orchestrator resumed its implementer via SendMessage, went background, yielded). Mechanism assumed from the routing above. |
## Models
| Claim | Status |
|---|---|
| Per-call `model` accepts aliases only (`opus`, `sonnet`, `haiku`, `fable`) and overrides the agent definition's `model` frontmatter. | verified 2026-10-05 (Agent tool schema) |
| `model` omitted: a pinned agent runs on its pin; an unpinned agent inherits the caller's model unless a default subagent model is configured. | verified 2026-10-05 (Agent tool schema) |
| 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. |
| 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 |
## Fork
Not used by Spire since 2026-10-16 (trunk + gremlins replaces it); rows kept as harness record.
| Claim | Status |
|---|---|
| The Agent tool schema documents `subagent_type: "fork"`: a fork always inherits the caller's model; `model` is ignored. | verified 2026-10-05 (schema text) |
| `fork` is actually offered as an agent type in a given session. | unverified: the schema mentions it, but on 2026-10-05 it was not in the list of agent types offered to the reviewer |
| A fork copies the **caller**, not an arbitrary agent; only the agent holding a context can fork it. | assumed (no parameter names a fork source) |
| A fork starts with the caller's full transcript, at the caller's token count. | assumed, not measured |
| Can a fork fork again? Does a foreground fork return its result to the caller? Does it see the caller's preloaded skills? | unknown; check in a throwaway preflight before relying on forks |
## Agent types
| Claim | Status |
|---|---|
| Plugin agent types (`athanor`, `adept`, `researcher`, …) can be missing in remote sessions, where `/reload-plugins` is unavailable. Fallback: `general-purpose` with an explicit `model` and the agent file's body pasted into the brief. | observed 2026-10-05 (reliquary Igor journal, 21:00) |
| `Explore` and `Plan` are read-only (no Edit/Write); never use them for tasks that must write a file. | observed 2026-09-22 (Spire model tiers) |
@@ -0,0 +1,36 @@
# Superpowers with Spire
Superpowers (obra/superpowers) is not part of Spire's cycle. This page is for when you use it anyway: an older model that needs more rails (Opus 4.6 and earlier), or a brief or user that asks for one of its skills.
Dated observations, 2026-10-15, upstream v7.0.0. Sources: the workpad research of that date on superpowers alternatives, Spire coupling and plan anatomy.
## Why it is not the default
On Opus 5.5 its ceremony costs more than it catches: review and fix grew to about two thirds of the work, and scope grew past the plan. The causes are structural, not tuning:
- One fresh implementer plus a review per task (`subagent-driven-development`): 2 to 12 dispatches per task, plus a fix loop of up to 5 rounds.
- Plans written for an implementer with "zero context and questionable taste": small steps, code in the plan. Every planned line becomes an obligation a reviewer enforces.
- Reviewer rules that widen scope: "a spec's silence is not permission", a YAGNI argument never downgrades a finding, and the plan's Review Focus adds tests by design.
- The SessionStart hook ("if there is even a 1% chance a skill applies, you must invoke it") turns optional skills into automatic ones in every main session.
## What the lean cycle overrides
| Superpowers | Spire |
|---|---|
| Review after every task, re-review after every fix | Reviews at review points, at most one per phase, one fix pass, re-check only Critical/Important |
| Plan with bite-sized steps and full code | Plan at the altitude of decisions, contracts, invariants, scope fence |
| Execution handoff: the user picks subagent-driven or inline | The attack reshapes the plan into a build plan; the user sees it once |
| Brainstorming HARD-GATE: user approves spec, plan and execution method | Brainstorm is optional; decisions belong before the run |
| Reviewer treats anything the spec did not mention as a finding | Unplanned work is recorded, never reverted automatically |
| TDD iron law for every change | Fail-first test for bugs you do not yet understand; tests once per phase |
| Files under `docs/superpowers/` | The workpad decides placement |
## Still useful as tools
- `systematic-debugging` for a stubborn failure.
- `test-driven-development` for a fail-first test inside a block.
- `verification-before-completion`: evidence before claiming a gate or test passed.
- On older models, `writing-plans` for the planner, then the attack as usual. Upstream v6.4.2 already dropped full code and 2–5-minute steps from plans; prefer a current version.
- If you do run superpowers' own execution, upstream's Native mode (v6.4.1: one final review) is the cheaper path, not `subagent-driven-development`.
Forks that keep the per-task loop as the default (e.g. pcvelz `superpowers-extended-cc`) add ceremony rather than remove it.
+209
View File
@@ -0,0 +1,209 @@
---
name: init
description: >
Initialize Spire for the current project — detect project facts,
scaffold .claude/spire/project.md, and handle shared vs. personal
install. Human-triggered.
disable-model-invocation: true
allowed-tools: Bash(cat:*), Bash(grep:*), Bash(ls:*), Bash(just:*), Bash(git:*), Read, Write, Glob, Grep
---
# Spire — Init
Run once after install or major structural changes. Re-init never clobbers hand-edited files. Adept founding templates ship with the plugin; init does not write them.
---
## Phase 1 — Detect install type
Search `.claude/settings.json`, then `.claude/settings.local.json` (each if present), `plugins` and `mcpServers` keys, for any string containing `spire` (typically `"spire@reliquary"` or a path containing `/spire/`).
| Spire found in | `$INSTALL_TYPE` | Scaffolded files |
|---|---|---|
| `settings.json` | **shared** | committed |
| `settings.local.json` only | **personal** | gitignored |
| Neither | ask the user: "Should the Spire config be shared with the project (committed) or personal (gitignored)?" | per answer |
---
## Phase 2 — Detect project facts
Each undetected fact becomes a placeholder in `project.md`.
### 2.1 — Workpad location
Resolve via the `spire:workpad` chain (owner: `workpad` "Where the workpad lives"). Record as `$WORKPAD`.
### 2.2 — Pinned agents
`.claude/agents/*.md`: each frontmatter `name` and `description` → "Pinned agents".
### 2.3 — Verification commands
Check in order: **Justfile** (`just --list`: `check`, `test`, `lint`, `build`, `verify`, `ci` or similar); **Makefile** (`check`, `test`, `lint`, `build`); **package.json** `scripts`; **Cargo.toml** (`cargo check`, `cargo test`, `cargo clippy`).
Sort into **gate** (cheap, between blocks: check, lint, typecheck, clippy) and **tests** (suite, once per phase).
### 2.4 — Conventions
Root `CLAUDE.md`: one line per fact that changes Spire's behaviour (branching, merge direction, commit style, sensitive areas, host rules). Point to rules the root `CLAUDE.md` already loads; never copy them.
### 2.5 — Tome presence
Both settings files: `tome`, a `*-tome:navigate` skill or `tome@reliquary`. Found: note the tome skill name.
---
## Phase 3 — Scaffold `project.md`
### 3.1 — Re-init safety check
`.claude/spire/project.md` exists: read its frontmatter `status`.
- `authored`: **stop**. Tell the user: "project.md has been manually edited (status: authored). Skipping to avoid clobbering your changes. Delete or change status to `generated` to allow re-scaffolding."
- `generated`: overwrite.
- missing: treat as `authored`.
### 3.2 — Write the file
Create `.claude/spire/` if needed; write `.claude/spire/project.md`:
```markdown
---
status: generated
generated: <YYYY-MM-DD>
---
# Project Knowledge
Write every field as a terse fact for the agent; no prose.
## This project
- **Tome skill**: <detected tome skill or "none detected — Igor will orient via direct file reads">
- **Workpad**: <detected workpad path with subfolder structure>
- **Adepts**: Domain knowledge agents with persistent folders at `<workpad>/adepts/<domain-slug>/`.
- **Pinned agents** (prefer these over generic tiers):
<list of detected agents with name and description, or placeholder comment>
- **Domain skills to route to subagents when relevant**: <!-- detect and list, or leave as placeholder -->
- **Conventions**: <summarized conventions from CLAUDE.md, or placeholder comment>
## Build
Read by `spire:implementation`. Unset means the skill's default; `none` means deliberately absent.
- **Gate** (cheap, between blocks): <detected gate commands, or placeholder comment>
- **Tests** (once per phase): <detected test command, or placeholder comment>
- **Checkout**: <!-- one checkout (default) | worktrees -->
- **Branches**: <!-- who commits where; default: the branch the brief names -->
- **Staging**: <!-- explicit paths (default) -->
- **Owner models**: <!-- per block kind; default: Opus 5.5 for complex blocks, Sonnet for mechanical ones -->
- **Brief constraints**: <!-- sensitive areas, e.g. generated files, migrations -->
- **Host rules**: <!-- temp dirs, memory caps -->
- **Build plan**: <!-- user sees it before the run (default) | skip (no gate) -->
Personal overrides go in `.claude/spire/project.local.md` (gitignored, same headings). They win over this file.
```
Fill every detected field; undetected: a `<!-- placeholder -->` comment.
---
## Phase 4 — Scaffold adepts directory
Founding templates live in the plugin (`skills/adepts/templates/`); the `adept` agent copies them during genesis.
### 4.1 — Create the adepts directory
```bash
mkdir -p "${WORKPAD}/adepts"
```
### 4.2 — Write `adepts/CLAUDE.md`
Exists with `status: authored` in frontmatter: skip. Else write:
```markdown
---
status: generated
---
# Adepts
Domain knowledge accumulated by adept agents. One subfolder per domain (a subsystem, a library, a cross-cutting concern), short kebab-case slug.
## Structure
```
adepts/
CLAUDE.md ← you are here
<domain-slug>/
CLAUDE.md ← INDEX — frontmatter + tiered reading list. Short. Auto-loaded.
handoff.md ← rolling state for the successor. Overwritten, not appended.
key-files.md ← solid knowledge docs — as many as the domain needs
conventions.md
architecture.md
gotchas.md
... ← any other doc, provided it is listed in CLAUDE.md
journal/
YYYY-MM-DD-HH-genesis.md
YYYY-MM-DD-HH-<topic>.md
```
## Conventions
- **One domain per folder.** Overlap → the stricter scope. Broad names are gravity wells.
- **CLAUDE.md is an index.** Frontmatter, tiered reading list, open questions; under ~60 lines. Auto-loaded on any read in the folder: keep it cheap.
- **Every file in the domain root is listed in CLAUDE.md.** Unlisted files do not exist.
- **handoff.md: overwritten, never appended.** Write early; refresh after anything significant. `verified-at` = commit the solid docs were last checked against.
- **journal/: append-only.** One file per topic or session, `YYYY-MM-DD-HH-<topic>.md`. Recency and session counts derive from these names: keep the prefix exact.
- **Solid knowledge → docs; experiences → journal.** Branch observations stay in the journal (and handoff.md "In flight") until the code is on main.
- **Don't hoard.** Findings belonging in project docs or a workpad report go there; link from here.
- **Metadata is derived.** Never hand-maintain counts, dates or an index file. Declare `domain`, `summary`, `covers`, `related`, `status` once in frontmatter; the roster derives the rest.
```
---
## Phase 5 — Gitignore
Append each line only if no equivalent line exists.
| Line | personal | shared |
|---|---|---|
| `spire/` | `.claude/.gitignore` (create if missing) | — |
| `spire/project.local.md` | — | `.claude/.gitignore` (create if missing) |
| `/.spire/` and `/${WORKPAD}/logs/` (workpad path relative to repo root) | `.git/info/exclude` (nothing personal is committed) | repo root `.gitignore` (create if missing; committed with init's other files) |
---
## Phase 6 — Optional alias
Offer:
> "Would you like to create `/assistant` as an alias for `/spire:igor`?
> This creates `.claude/skills/assistant/SKILL.md` so you can invoke Igor
> as just `/assistant`."
Accepted: write `.claude/skills/assistant/SKILL.md`:
```markdown
---
name: assistant
description: Start an Igor session — alias for spire:igor.
user-invocable: true
---
Invoke the `spire:igor` skill. Pass through any arguments:
/spire:igor $ARGUMENTS
```
---
## Phase 7 — Commit (shared install only)
**shared**: stage by explicit path the files this run created or modified (`.claude/spire/project.md`, `${WORKPAD}/adepts/CLAUDE.md`, `.claude/skills/assistant/SKILL.md` if created in Phase 6, the root `.gitignore` and `.claude/.gitignore` when Phase 5 wrote them), then commit `🤖 Initialize Spire project config`.
**personal**: no commit (files are gitignored).
---
## Summary
Report: install type; files created or updated; skipped (`status: authored` files, phases that didn't apply); next steps: "Edit `.claude/spire/project.md` to fill in any remaining placeholders, then change `status` from `generated` to `authored` to lock it against future re-inits. Personal settings go in `.claude/spire/project.local.md`."
+54
View File
@@ -0,0 +1,54 @@
---
name: knowledge
description: >
Knowledge management awareness — explains how a project's knowledge base works,
how to navigate it, and what to do when the tome plugin isn't installed. Each
project declares its own approach in project.md.
---
# Knowledge Management
Spire agents (Igor, adepts, athanor) need to orient themselves in a project's knowledge base. How that knowledge is structured varies per project.
## How projects declare their knowledge approach
The project's `project.md` (loaded by Igor's skill and by athanor) should describe:
- Where authoritative docs live (CLAUDE.md files, topic docs, wiki/)
- How to navigate them (tome plugin, direct file reads, AGENTS.md routing tables)
- What the entry point is (root CLAUDE.md, boot.md, AGENTS.md)
## When the tome plugin is installed
If the project has `tome@reliquary` enabled:
- Use `/tome:navigate` before substantial work in an unfamiliar area
- Use `/tome:check` to verify knowledge-layer health after structural changes
- Use `/tome:curate` for knowledge maintenance
- Use `/tome:handoff` when transitioning between sessions or agents
Tome provides structured navigation (wiki/, NAV files, boot.md) and automated curation methods. It's the full-featured path.
## When tome is not installed (fallback)
Most projects work fine without tome. The fallback strategy:
1. **Read the root CLAUDE.md / AGENTS.md** — this is always the entry point
2. **Follow @-includes and links** — CLAUDE.md files reference each other; follow the chain relevant to your task
3. **Check for module-level CLAUDE.md** — many projects have per-module docs (`src/foo/CLAUDE.md`)
4. **Use `find` or `glob`** for `**/CLAUDE.md` to discover what documentation exists
5. **Read topic docs** if they exist (`docs/topics/`, `docs/`, or similar)
The fallback is manual but sufficient. Tome automates what fallback does by hand.
## Installing tome
To add tome to a project:
```json
{
"enabledPlugins": ["tome@reliquary"]
}
```
Then run `/tome:init` to scaffold the knowledge structure. This is a one-time setup that creates the wiki/, boot.md, and folder navigation. See the tome plugin's README for details.
+11
View File
@@ -0,0 +1,11 @@
---
name: project
description: Loads per-project Spire configuration (override or bundled template).
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."`
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)"`
@@ -0,0 +1,99 @@
---
name: research-tree
description: Orchestrate multi-topic research as a dependency tree of parallel phases — not a flat fan-out of independent agents. Use this skill whenever the user asks for "research", "deep research", "investigate", "survey", or "look into" a topic that has multiple sub-topics, or when a question is broad enough that a single agent would either skim or take forever. Trigger especially when the user says things like "research X and Y and Z", "find out everything about…", "do a deep dive on…", or when prior research has surfaced new questions that need follow-up. Composes with the `workpad` skill for file placement.
---
# Research Tree
**Cycle context:** Research-tree is the structured form of Stage 2; its output feeds Stage 3 (design).
Most non-trivial research questions decompose into many sub-topics, and those sub-topics are *not* independent — later questions get sharper once earlier ones are answered. Running every sub-topic in parallel as peer agents wastes work and produces shallow, redundant findings. Running them strictly in series wastes wall-clock time. The right shape is a **tree of phases**: within a phase, agents run in parallel; between phases, later agents inherit the earlier reports.
This skill describes how to plan and run that tree. It does not describe how to write the contents of an individual research report — that's up to the agent doing the writing, plus whatever conventions the project has.
## When to use this skill
Use it when **two or more** of these are true:
- The topic has multiple sub-questions that a single agent couldn't realistically cover in depth.
- Some sub-questions clearly *depend on* the answer to other sub-questions (e.g. "evaluate library X" depends on "what are our requirements").
- The user wants something they can read and refer back to, not just a chat answer.
For a single focused question, just answer it. Don't reach for the tree.
## The shape of a research tree
```
Phase 1 (parallel) Phase 2 (parallel) Phase 3 (parallel) Summary
─ topic A ─────┐ ─ topic D (knows A,B) ─┐ ─ topic F (knows D,E) ─┐ ─ index.md
─ topic B ─────┼──────► ─ topic E (knows B,C) ─┼──► … ─┼──► (linking all)
─ topic C ─────┘ ─ … ┘ ┘
```
- **Within a phase:** agents run in parallel. They do not share intermediate findings with each other — by definition the phase is composed of topics that are mutually independent at that point in the tree.
- **Between phases:** when an agent in phase N+1 starts, hand it the *full text* of the reports it depends on from earlier phases — not just summaries, and not all reports indiscriminately. Pass *its* ancestors in the tree, transitively.
- **Specificity flows downward.** Broad framing topics live near the root; narrow, technical, "given X, exactly how does Y behave" topics live near the leaves.
## Planning the tree
Before spawning a single agent, plan the tree explicitly. Write the plan down — usually in the workpad as a brainstorm or design note — so you and the user can sanity-check it.
1. **List the sub-topics** the question needs answered, including ones you are unsure about; merge or drop the redundant ones before step 2, since each sub-topic costs an agent.
2. **For each sub-topic, ask: "what would I need to know first?"** Draw an arrow from each prerequisite topic to the dependent topic. This produces a dependency graph, not yet a tree.
3. **Break cycles.** If A needs B and B needs A, you have a cycle. Resolve it by inserting a new, smaller intermediate topic that both can build on (e.g. "shared definitions and ground truth for X"), or by deciding which direction is the dominant dependency and demoting the other to a follow-up question for phase N+2.
4. **Group into phases by depth.** Topics with no prerequisites are phase 1. Topics whose prerequisites are all in phase 1 are phase 2. And so on.
5. **Sanity-check phase widths.** A phase with one topic is fine but suspicious — can it merge with the next phase? A phase with fifteen topics is a sign you haven't decomposed dependencies enough. Aim for 2–6 per phase typically.
6. **Confirm the plan with the user** before launching. The plan itself is the most important artifact — a wrong tree wastes the most expensive resource (agent time on the wrong questions).
## Running the phases
Use the workpad's `research/` folder, almost always inside a dated subfolder for the whole tree:
```
research/
2026-05-05-14-auth-provider-evaluation/
phase-1-requirements.md
phase-1-current-state.md
phase-1-constraints.md
phase-2-candidate-comparison.md
phase-2-migration-paths.md
phase-3-cost-modeling.md
index.md ← written last, read first
```
Filenames should be slugged by topic; the `phase-N-` prefix is optional but helps when listing the directory.
For each phase:
1. **Spawn agents in parallel** for that phase's topics. Each agent receives:
- Its own narrow research brief.
- The full text of every ancestor report it depends on (transitively up the tree). Don't summarize on the way in — let the downstream agent skim or quote as it sees fit.
- The path to write its report into.
2. **Wait for the phase to complete** before starting the next. Don't try to overlap phases — the dependency is what makes the tree worth doing.
3. **Quickly read each report yourself** before dispatching the next phase. If a phase produced something surprising or contradictory, the dependency graph for the *next* phase may need updating.
## When findings contradict each other
If two reports in the same phase reach incompatible conclusions, or a phase-N report contradicts something assumed in phase-N-1, do not paper over it in the summary.
- Spawn a **verification / reconciliation agent** as an extra step. Give it both conflicting reports and ask it to identify the actual disagreement, what evidence each side rests on, and what would resolve it.
- The verification agent writes a **review paper** that lives next to the others (`review-<topic>.md`).
- Update the relevant prior reports if they got something wrong, or note the open question explicitly in the summary.
This is also the move when the summary is *hard to write* — that's usually a signal that contradictions are present and have been silently smoothed over.
## The summary / index document
The summary is written **last** and is the **first** thing a reader should open. Conventions:
- Filename: `index.md` (or `00-summary.md` if you want it to sort first).
- Linked from every other report in the tree (or at least from the directory's README).
- Structure: a one-paragraph TL;DR, the question that started the tree, the high-level answer, then a short section per phase linking out to the full reports.
- Do not paste the contents of the other reports into the summary. Link to them. The summary's job is navigation and synthesis, not duplication.
If the summary turned out hard to write, that's a signal — see the contradictions section above.
## What this skill does *not* govern
- The internal structure of an individual research report — that's the agent's call, plus project conventions.
- Whether the workpad itself exists / where it lives — defer to the `workpad` skill.
+110
View File
@@ -0,0 +1,110 @@
---
name: research
description: Governs how research is conducted — bounded agent spawning, no recursive sub-agents, web content downloaded as markdown and scanned locally. Use whenever launching research agents, fetching web content for analysis, or when another skill (like research-tree) is about to spawn agents that touch the web. Composes with workpad for output placement and research-tree for multi-topic structure.
---
# Research Governance
This skill regulates **how** research agents behave. It does not replace research-tree (which governs the **structure** of multi-topic research) or workpad (which governs **where** output goes). It layers on top of both.
**Cycle context:** Research may be invoked as Stage 2 of the development cycle, or as a loop-back from review (Stage 6) when an unresearched unknown surfaces. Its output feeds into design (Stage 3).
## The rules
### 1. Research agents must not spawn sub-agents
Every agent dispatched for research work is a **leaf agent**. It does its own reading, searching, and fetching. It does not delegate to further agents.
#### Agent tiers
Pick the right agent for the job. All three are tool-restricted and cannot spawn sub-agents:
| Agent | Model | Can write files | Web fetch cap | Use for |
|-------|-------|----------------|---------------|---------|
| `scout` | haiku | No | 2 pages | Quick fact extraction — a version number, a function signature, a config value from a web page |
| `search` | sonnet | No | 3–5 pages | Code/file lookups, symbol tracing, "where is X defined", multi-file search |
| `researcher` | opus (medium effort) | Yes | 5 pages | Deep topics requiring synthesis and a written report — architecture comparisons, technology evaluations, multi-source analysis |
**Default to `scout`** for simple lookups. **Use `search`** when you need to trace through code. **Use `researcher`** only when the topic genuinely needs synthesis and a written document.
When spawning research agents (via the Agent tool or workflow scripts):
- Use `subagent_type: "scout"` for quick fact extraction from a page or file
- Use `subagent_type: "search"` for code/file lookups and symbol tracing
- Use `subagent_type: "researcher"` for complex topics that need a written report
- In workflow scripts, use `agentType: 'scout'`, `'search'`, or `'researcher'` accordingly
The **orchestrator** (you, the main agent, or the workflow script) is the only entity that decides how many agents run. Individual research agents never make that decision.
### 2. Web content is fetched and read, not scraped
When research requires information from the web:
- **Fetch specific pages.** Use `WebFetch` to download a specific URL. The tool returns the page content as text/markdown.
- **Read the content locally.** Extract what you need from the fetched content. Do not follow every link.
- **Budget fetches per agent.** A single research agent should fetch at most 3–5 pages. If the research genuinely needs more, that is a sign the topic should be split into multiple agents at the orchestrator level — not that one agent should crawl more.
- **Never crawl.** Do not write loops that follow links, do not fetch "all pages" from a documentation site, do not spider a domain.
#### How to fetch web content
**MCP servers for richer web-to-markdown conversion (if configured):**
- `firecrawl` — converts web pages to clean markdown; good for documentation sites
- `browser-tools` — browser automation for pages that require JavaScript rendering
Check what MCP servers are available with `ToolSearch` before falling back to raw `WebFetch`. If a markdown-conversion MCP is available, prefer it — the output is cleaner and easier to scan.
**The pattern for web research:**
```
1. WebSearch to find relevant URLs (1-3 searches)
2. WebFetch (or MCP equivalent) to download 1-3 most relevant pages
3. Read the downloaded content, extract findings
4. Write findings to report file
```
This is **one agent's** entire web interaction. Not ten agents each doing this.
### 3. The orchestrator controls breadth, agents control depth
The division of responsibility:
| Concern | Who decides |
|---------|-------------|
| How many agents to spawn | Orchestrator (you) |
| Which topics to research | Orchestrator, informed by research-tree |
| How deep to go on one topic | The individual agent |
| Whether to fetch a web page | The individual agent |
| Whether to spawn another agent | **Never the individual agent** |
| Where to write output | Workpad skill |
### 4. Phases gate runaway growth
When using research-tree's phased approach:
- **Review each phase's output before launching the next.** This is not optional — it is the checkpoint where you catch redundancy, contradiction, or scope creep.
- **Trim the next phase** if earlier phases already answered some questions. Don't launch agents for topics that are already covered.
- **Cap total agents.** A typical research tree should use 3–12 agents total across all phases. If you're planning more than 15, the decomposition is too fine-grained — consolidate topics.
### 5. Research output goes to the workpad
Compose with the workpad skill:
- Individual agent reports → `research/<dated-subfolder>/phase-N-<topic>.md`
- Summary/index → `research/<dated-subfolder>/index.md`
- If no workpad exists, ask the user before creating one
## Applying this skill
When you are about to do research — whether triggered by the user saying "research", "investigate", "look into", or by another skill like research-tree — apply these rules:
1. **Plan first.** List the topics and how many agents you need. Share with the user.
2. **Instruct each agent.** Every agent prompt must include: the specific research question, where to write output, and the constraint that it must not spawn sub-agents.
3. **Use the search agent for lookups.** For "find where X is defined" or "what files reference Y", use `subagent_type: "search"` — it is tool-restricted and cannot spawn agents by design.
4. **Fetch web content through the agent, not through sub-agents.** The agent doing the research fetches the pages it needs directly.
5. **Review between phases.** Read what came back before sending more agents.
## What this skill does NOT govern
- The internal structure of a research tree (phases, dependencies) — that's research-tree
- Where files go — that's workpad
- Whether to do research at all — that's your judgment as orchestrator
+77
View File
@@ -0,0 +1,77 @@
---
name: svg
description: Use when authoring or editing a Markdown file that contains (or should contain) SVG diagrams, charts, or any graphical representation. Trigger whenever (1) writing a report/document/README in Markdown that needs a diagram, flowchart, chart, or other visual, (2) considering adding `<svg>` markup to a `.md` file, (3) editing existing SVG inside Markdown, (4) a user asks for a "diagram", "visual", "chart", or "flowchart" inside a Markdown document. Markdown renderers (GitHub, Gitea, Obsidian, VS Code preview) sanitize inline SVG very differently from each other — GitHub strips it entirely, Gitea allows only `<svg>` + `<path>`, Obsidian (via DOMPurify) allows most of it. Apply this skill proactively before producing the SVG, not after.
---
# SVG Diagrams
Markdown renderers diverge dramatically on what SVG they allow. The safe default is **not** to embed SVG inline — it's to **save the SVG as a separate `.svg` file and reference it with image-link syntax**. Inline SVG should be treated as a special case the user explicitly asks for, not as the default.
This skill encodes the reasoning behind that choice, layout and legibility rules for readable output, and the per-renderer rules for when inline SVG is what's wanted.
## Default approach: external `.svg` file + image link
For any new diagram going into a Markdown document:
1. Generate the SVG as a standalone `.svg` file. Common conventions:
- `docs/images/<slug>.svg`, `assets/<slug>.svg`, or alongside the `.md` itself.
- Match the project's existing convention if there is one.
2. Reference it from the Markdown with image-link syntax:
```markdown
![Architecture overview](./images/architecture.svg)
```
3. The `.svg` file itself is a normal SVG document — `<style>`, `<circle>`, `<g>`, classes, gradients, animations, anything you'd write in any SVG. The renderer pipeline for standalone SVG files is much more permissive than the inline-Markdown sanitizer (especially on GitHub, where they're handled by entirely different code paths).
This recipe is the **only** approach that reliably produces a rendered diagram on **GitHub** (which strips inline SVG categorically — see below). It also works on Gitea and Obsidian and any other Markdown renderer that supports image links.
Use this default unless the user explicitly asks for inline SVG.
## Why not inline SVG by default
Inline SVG fails silently and inconsistently across renderers. From source-code analysis (see `research/2026-05-05-15-svg-sanitizer-allowlists/` if available locally):
- **GitHub Markdown** (`html-pipeline` + `rgrove/sanitize`): the allow-list contains **zero** SVG elements. `<svg>`, `<g>`, `<path>`, `<circle>` — all stripped. Inline SVG never renders in a `.md` file on github.com. The element is removed; only its bare text-node children leak through.
- **Gitea** (bluemonday default policy): allows only `<svg>` and `<path>`. No `<rect>`, no `<circle>`, no `<g>`, no `<text>`, no gradients, no fills or strokes (the `fill` and `stroke` attributes are also stripped). Self-hosted admins can extend the allow-list via `app.ini`'s `[markup.sanitizer.N]` rules, but defaults are the rule.
- **Obsidian** (DOMPurify defaults): allows most SVG — `<circle>`, `<rect>`, `<ellipse>`, `<g>`, `<text>`, `<defs>`, gradients, paths, filters. Empirically confirmed *not* working in Obsidian: `<use>`, `<style>` element, `<foreignObject>`, `<title>` element. `<script>`, event handlers, and `javascript:` URLs are stripped on every renderer including Obsidian.
- **VS Code Markdown preview** (uses markdown-it + DOMPurify-like sanitization): permissive, similar to Obsidian for most things.
The **strict cross-renderer intersection for inline SVG is effectively empty** — there is no inline-SVG recipe that produces a rendered diagram on GitHub, Gitea, and Obsidian alike. This is why the default has to be the external file.
## Layout and legibility
Renderer compatibility is only half the problem — the other half is producing SVG that's actually readable. Agent-generated SVGs commonly fail on text overflow, poor contrast, and missing margins. **Read `references/layout-legibility.md` before generating any non-trivial SVG** (charts, matrices, diagrams with labels). It covers:
- Estimating text width before sizing containers (SVG doesn't clip text)
- Contrast contracts for text over colored backgrounds (aim for 4.5:1)
- Background rects or halos for text on data-dependent surfaces
- Margin reservation for rotated labels
- The sparse-cells-plus-legend pattern for dense categorical charts
- Palette selection with declared text-color roles
## When the user asks for inline SVG
If the user explicitly says "embed it inline", "put the SVG directly in the markdown", or similar — **read `references/inline-svg.md` before proceeding**. It contains the full per-renderer compatibility table, sanitizer survival rules, and inline-specific checklists. Pick the rule set that matches the target renderer; if the target is unknown, ask.
## Default size
Generated SVG diagrams should not exceed **750 pixels in width** by default — set `width` (and a matching `viewBox`) accordingly. Height is unconstrained — pick whatever the content needs. Wider SVGs blow out the column on most Markdown renderers. Override only when the user explicitly asks for wider.
## Minimal example (external file recipe — the default)
```markdown
The architecture is straightforward:
![Architecture overview](./images/architecture.svg)
Each component handles its own state.
```
Where `./images/architecture.svg` is a normal SVG file — use any elements you want; standalone SVG is not subject to the inline-Markdown sanitizer.
## Pre-commit checklist
- [ ] SVG saved as a `.svg` file in a sensible location.
- [ ] Markdown references it with `![alt](path.svg)`.
- [ ] `width` (the rendered width) ≤ 750px unless asked otherwise.
For inline SVG checklists, see `references/inline-svg.md`.
@@ -0,0 +1,98 @@
# Inline SVG in Markdown — Per-Renderer Rules
Read this document only when the user explicitly asks for inline SVG (e.g., "embed it inline", "put the SVG directly in the markdown"). Pick the rule set that matches the target renderer. If the target is unknown, ask.
## Rule 1: Embed as a raw HTML block, never as a fenced code block
The two paths look similar but produce completely different output.
- **Embed SVG as a raw HTML block.** Place `<svg …>…</svg>` directly in the Markdown source, with a blank line before and after. CommonMark / GFM treat that as a raw HTML block and pass it through verbatim; the browser then parses what survives the sanitizer as real SVG.
- **Never wrap renderable content in ` ```svg ` (or ` ```html `, ` ```xml `) fences.** Fenced code blocks are *by definition* "display this as text". The renderer wraps the contents in `<pre><code>`, HTML-escapes every `<`, `>`, and `&`, and hands the escaped text to a syntax highlighter. The browser sees a string, not markup — no SVG ever gets parsed.
- **Don't assume non-standard "render this code block" extensions exist.** Some renderers (GitLab, certain Obsidian plugins, custom static-site setups) special-case ` ```mermaid ` or ` ```svg ` to render. This is non-standard. GitHub, VS Code's default preview, and CommonMark do not. Default to the raw-HTML-block path.
- **Same rule applies to other inline-renderable HTML.** `<details>`/`<summary>`, `<picture>`, `<video>`, raw `<table>` with attributes Markdown can't express — all use the raw-HTML-block path, never a fence.
Diagnostic: "I see SVG source code as text" → fence problem. "I see blank space or default-styled shapes" → sanitizer/styling problem (see Rule 2).
## Rule 2: Per-renderer element / attribute rules
| Element / feature | GitHub inline `.md` | Gitea (default) | Obsidian | Notes |
|---|---|---|---|---|
| `<svg>` | ❌ stripped | ✅ | ✅ | |
| `<path>` | ❌ | ✅ | ✅ | The most portable shape primitive. |
| `<rect>` | ❌ | ❌ | ✅ | Substitute with `<path>` rectangle on Gitea. |
| `<circle>` | ❌ | ❌ | ✅ | Substitute with `<ellipse rx=R ry=R>` (Obsidian only) or `<path>` arc circle. |
| `<ellipse>` | ❌ | ❌ | ✅ | |
| `<line>`, `<polyline>`, `<polygon>` | ❌ | ❌ | ✅ | |
| `<text>`, `<tspan>` | ❌ | ❌ | ✅ | |
| `<g>` | ❌ | ❌ | ✅ | Group inheritance dies on Gitea — repeat presentation attrs per element if cross-renderer matters. |
| `<defs>`, `<linearGradient>`, `<radialGradient>`, `<stop>` | ❌ | ❌ | ✅ | |
| `<marker>` | ❌ | ❌ | ✅ | Arrowheads only work on Obsidian inline. |
| `<use>` | ❌ | ❌ | ❌ (empirically confirmed) | Strip on Obsidian was unexpected; treat as not portable. |
| `<style>` element | ❌ | ❌ | ❌ (empirically confirmed) | Don't use it anywhere. CSS rules don't have a clear scope boundary so sanitizers strip them as injection risk. |
| `<title>` element | ❌ | ❌ | ❌ (empirically confirmed) | |
| `<foreignObject>` | ❌ | ❌ | ❌ (empirically confirmed) | |
| `<script>`, `on*` event handlers, `javascript:` URLs | ❌ | ❌ | ❌ | Always stripped, every renderer. Don't use. |
| `class=` attribute (for styling) | ❌ | ❌ | ✅ | Even when class survives, the `<style>` block defining the rules doesn't, so styling is lost — use inline presentation attributes. |
| Inline presentation attributes (`fill`, `stroke`, `stroke-width`, `font-size`, `font-family`, `text-anchor`, `stroke-dasharray`, etc.) | ❌ | ❌ | ✅ | These survive on Obsidian and any sanitizer that allows SVG at all. They never apply on GitHub-inline / Gitea because the elements themselves are stripped. |
Reading the table: an Obsidian-only target gives you most of SVG. A Gitea target restricts you to `<svg>` + `<path>` (no colors, no text, no groups). A GitHub-inline target gives you nothing — switch to the external-file recipe.
## Rule 3: Surviving the sanitizer where SVG is allowed
When the renderer allows SVG (Obsidian, VS Code preview, some self-hosted Gitea with extended `app.ini`, and the standalone-`.svg`-file path on GitHub), structure the SVG to survive its sanitizer:
- **Use SVG presentation attributes inline on every element.** `fill`, `stroke`, `stroke-width`, `stroke-dasharray`, `font-size`, `font-weight`, `font-family`, `text-anchor`. These can't escape the SVG and survive every sanitizer that allows SVG at all.
- **Don't rely on `<style>` blocks or `class=` for styling.** `<style>` is stripped on every renderer's inline sanitizer (including Obsidian, empirically). Even if `class=` survives, the rules are gone, so styling is lost.
- **Prefer longhand over CSS shorthand.** Use `font-size`, `font-weight`, `font-family` separately rather than the `font:` shorthand. The shorthand is CSS-only; longhand maps directly to SVG presentation attributes.
- **`<defs>` and id references are fine** on renderers that allow them at all (Obsidian; not Gitea/GitHub-inline). `<marker>`, `<linearGradient>` referenced via `url(#id)` survive the Obsidian sanitizer.
- **Group-level inheritance works for `font-family` and `fill`** (set on `<g>`, inherited by children) on Obsidian. Don't rely on it for cross-renderer; set the attribute on the leaf element.
The visible failure mode is silent: shapes still render, but with browser-default fill (usually black), no stroke, and default font sizing. On dark themes this looks like "nothing showed up"; on light themes like "a row of black blobs with no labels". There is no console error and no Markdown lint warning.
## Rule 4: No blank lines inside inline SVG
pulldown-cmark (and most CommonMark parsers) terminate an HTML block at a blank line. Any content after the blank line — even if it's still inside `<svg>...</svg>` — is parsed as Markdown, not HTML. Indented SVG elements become fenced code blocks (`<pre><code>`); unindented ones become paragraphs wrapping escaped angle brackets.
This means **the SVG source must be one unbroken block with no empty lines between `<svg>` and `</svg>`**. Use comments (`<!-- section: axes -->`) instead of blank lines if you need visual separation inside the SVG source.
Diagnostic: "Part of my SVG renders but the rest appears as code or escaped text" → blank-line-induced block break. Remove all blank lines between `<svg>` and `</svg>`.
## Minimal example (inline, Obsidian-friendly)
```markdown
Some prose before the diagram.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 80" width="200" height="80">
<g font-family="sans-serif" font-size="12" fill="#222">
<!-- inputs -->
<rect x="10" y="20" width="80" height="40" fill="#e8f0fe" stroke="#1a73e8" stroke-width="2"/>
<text x="50" y="45" text-anchor="middle">Input</text>
<!-- arrow -->
<line x1="90" y1="40" x2="130" y2="40" stroke="#1a73e8" stroke-width="2"/>
<!-- outputs -->
<rect x="130" y="20" width="60" height="40" fill="#fce8e6" stroke="#d93025" stroke-width="2"/>
<text x="160" y="45" text-anchor="middle">Output</text>
</g>
</svg>
Prose after.
```
Note: blank line before `<svg>`, blank line after `</svg>`, **no blank lines inside the SVG** (use `<!-- comments -->` for section separation), no fence, all styling via presentation attributes, font longhand on the group. This will render on Obsidian and similar permissive renderers. It will **not** render on GitHub `.md`. It will partially render on Gitea (the `<svg>` survives, the rest is stripped).
## Pre-commit checklist (inline SVG)
- [ ] Confirmed the target renderer allows SVG inline (not GitHub `.md`).
- [ ] `<svg>` block has a blank line before and after, no surrounding ` ``` ` fence.
- [ ] No blank lines between `<svg>` and `</svg>` (pulldown-cmark terminates the HTML block at blank lines).
- [ ] No `<style>`, `<title>`, `<use>`, `<foreignObject>` elements (don't survive Obsidian).
- [ ] No `class=` for styling, no CSS `font:` shorthand.
- [ ] Every shape has explicit `fill` and (where applicable) `stroke` / `stroke-width` as inline attributes.
- [ ] No `<script>`, `on*` handlers, or `javascript:` URLs.
- [ ] `width` ≤ 750px unless asked otherwise.
If the target is Gitea specifically and inline is required:
- [ ] Only `<svg>` + `<path>` elements used.
- [ ] No `fill`, `stroke`, `class`, `style`, `transform` attributes (stripped by default policy).
- [ ] OR confirmed the Gitea instance has `[markup.sanitizer.N]` extensions in `app.ini` permitting more.
@@ -0,0 +1,83 @@
# Layout and Legibility Rules for SVG Diagrams
These rules prevent the most common legibility failures in agent-generated SVG: text overflow, poor contrast, and missing margins. They apply to both external `.svg` files and inline SVG.
## Rule 1 — Estimate max-text-width before sizing a container
For any text that lives **inside** a bounded shape (cell, box, button), estimate the rendered width of the longest string:
- Rough bound: `text_width_px ≈ chars × font_size × 0.6` for proportional fonts at common weights.
- If the container is narrower than the longest text, choose one of:
- **Widen the container** (preferred when there's space).
- **Truncate to a short label** (e.g. a count, a code, or an abbreviation) and put the full text outside (legend, footnote table, sidebar).
- **Wrap to multiple `<tspan>` lines** when truncation loses meaning.
- SVG doesn't clip text by default — never assume CSS overflow rules apply.
Default to **counts + short labels inside the chart, full names in a legend below**. For dense categorical charts this is almost always the right answer.
## Rule 2 — Text-over-background needs a contrast contract
If a `<text>` element renders on top of an arbitrary background, declare which class of background it's designed for:
- **Light-bg text** (`fill: #1a1a1a` or similar): legible on whites, light grays, light pastels.
- **Dark-bg text** (`fill: #ffffff` or similar): legible on saturated mid-to-dark colors only.
- **High-contrast halo** (`paint-order="stroke fill"` + `stroke-width="3"` + `stroke="#fff"`): legible on anything; use when the background is unpredictable or varies.
Never apply one fill class across multiple background colors without verifying contrast for each. WCAG large-text minimum is **3:1**; for text-in-data-viz aim for **4.5:1** to leave margin.
When colors are picked by category, group them into a "dark fills" palette (use white text) and a "light fills" palette (use dark text). Don't mix.
## Rule 3 — Backgrounds for text on uncertain surfaces
When text is placed near or over a colored region whose color depends on data, give the text its own background:
- A `<rect>` behind the text, sized to its bounding box (compute as `chars × font_size × 0.6 + padding`), with `fill="#fff"` and a small `rx` for softness.
- Or a halo via `paint-order="stroke fill"` with a white stroke.
For category legends, axis labels, and chart titles — anything that sits in the chart's "frame" rather than inside a data shape — always give them a clean background or place them in the margin.
## Rule 4 — Reserve margin for rotated labels
Rotated text (typically column headers at `-30°` to `-45°`) extends beyond its anchor in both x and y. Rule of thumb: an N-character rotated header at θ degrees and font-size F needs:
- horizontal reach: `cos(θ) × chars × F × 0.6`
- vertical reach: `sin(θ) × chars × F × 0.6`
Plus the anchor offset. Always add 20% padding. If the rotated headers extend into the chart body, increase the chart's top margin until they don't.
## Rule 5 — Default chart pattern: sparse cells, full legend below
For categorical density / heatmap / matrix charts:
```
[ Title ]
[ Rotated category headers (with margin) ]
[ Row label │ count │ count │ . │ count │ count │ . ] (cells: just the number, color-coded)
[ Row label │ . │ count │ count │ . │ count │ . ]
[ ... ]
[ ]
[ Legend / details table: ]
[ Row × Category → action_a, action_b, action_c ]
[ Row × Category → action_d ]
[ ... ]
```
Counts inside cells; names in the table below. This pattern composes well across renderers and prevents the overflow trap entirely.
## Rule 6 — Stick to a small palette with declared roles
Categorical palettes should be picked once, with their **role** declared:
- "Dark fills" (use **white** text): `#1f77b4`, `#d62728`, `#9467bd`, `#8c564b`
- "Light fills" (use **dark** text): `#aec7e8`, `#ffbb78`, `#98df8a`
Avoid mid-tones (`#ff7f0e`, `#2ca02c`, `#e377c2`) unless the text color is matched per-color. If the chart needs more than 6 categories, that's usually a sign the categorisation is too fine — group first.
## Rule 7 — Sanity check the rendered output
Before saving, mentally render at the target display width (typically 600–750px effective in Markdown), and ask:
- Can I read every label?
- Does any text overlap another shape?
- Is there a category whose color makes its text invisible?
- Are empty cells distinguishable from filled ones at a glance?
If any answer is "no", iterate before checking in.
+93
View File
@@ -0,0 +1,93 @@
---
name: workpad
description: Decides WHERE and WHEN to put working documents — reports, plans, goals, brainstorms, designs, journals, research, specs, tickets, bug notes. Use this skill whenever the user asks you to write a "report", "plan", "goal", "brainstorm", "design", "journal", "research note", "spec", or anything "in the workpad" — and also when another skill is about to drop a markdown file somewhere ad-hoc (e.g. a plugin's own `docs/<plugin>/` subdirectory, the repo root, `/tmp`, or alongside source code). If a workpad exists, the workpad wins for documents. Non-document output (raw state, streams, gate output) goes to scratch. This skill steers other skills toward one predictable place for markdown documents.
allowed-tools: Bash(uv:*)
---
# Workpad
Scope: markdown *about* the work (reports, plans, brainstorms, post-mortems). Decides **where** a document goes and **which kind** it is, not its contents. Wins over any other skill's folder (plugin-named folder, sibling `notes/`, repo root).
## Where the workpad lives
First hit wins:
1. **Explicit user instruction** in this conversation.
2. **`WORKPAD_FOLDER`.** Subshells may not inherit it: try `just workpad-folder` (or an equivalent recipe; `just` loads `.env`), then `printenv WORKPAD_FOLDER`. Non-empty path = base.
3. **External tickets folder** outside the repo (e.g. `../<repo>-tickets/`, or `GITEA_TICKETS_DIR`), if configured: base `<tickets-folder>/workpad/`; tickets beside it as `<tickets-folder>/<id>/`. Unsure one exists: ask.
4. **`/docs/workpad`** at the project root, if `/docs` exists.
5. **`/.workpad`**.
6. **Else ask** where; confirm before creating folders.
## Folder structure
Always: `brainstorm/` (options, half-formed ideas), `goals/` (acceptance criteria, milestones), `designs/` (architecture, RFC-style), `plans/` (steps to execute), `reports/` (findings, status).
On demand: `archive/` (superseded), `bugs/`, `journals/` (append-only narratives), `research/` (external research, prior art), `specs/` (frozen), `tickets/<id>/` (Ticket context), `adepts/` (`spire:adepts`), `logs/` (Tiers).
Create an on-demand folder when needed, never speculatively. Unknown folders are the user's; ignore them.
## Tiers
- `reports/`: lasting reports, handoffs included. Tracked.
- `logs/<YYYY-MM-DD-hh>-<slug>/`: readable record of one build: `run.md`, `trunk-notes.md`, `review-<scope>.md`, `recheck-<scope>.md`, `brief-<block>.md`. Git-ignored by the guard below. Stays in the main workpad under an active ticket context.
- **scratch**: `<repo>/.spire/scratch/<run-slug>/<agent-or-job>/`: raw state (streams, gate output, job files). Git-ignored. `<repo>` = the run log's checkout; run log in another repo or none: the cwd's. Override: `SPIRE_SCRATCH` (gremlins: `--scratch`).
- Git-ignored (`logs/`, scratch, trash): Grep and Glob skip them; use the explicit path or `ls`.
- `W` = `uv run --script "${CLAUDE_SKILL_DIR}/workpad.py"`: any OS or shell, no POSIX snippets, JSON out; `--run <run log>` sets `<repo>`. Briefs to other agents: its absolute path.
- **Trash**: at build close Igor moves the run dir to `<repo>/.spire/trash/<YYYY-MM-DD>/`, also when `SPIRE_SCRATCH` is set: `W trash <dir>…`. Ignored by the guard; the user empties it.
- **7-day sweep**: run dirs with no file modified in 7 days and no `keep` file: `W sweep --move` (scratch root).
- **Ignore guard** (fallback: `/spire:init` writes `/.spire/` and `<workpad>/logs/` to the root `.gitignore`, or `.git/info/exclude`). Before the first write to `logs/` or `.spire/`, the dispatcher starting the run runs it itself (the Athanor at build start; Igor or Zathras before a dispatch writing there). Never overwrites; `.spire/.gitignore` covers scratch and trash: `W guard <workpad>`.
**Never commit:** scratch, `logs/`, gremlin state, Playwright or browser auth state, walker and probe scripts, briefs, real-data dumps, `__pycache__`.
- Browser state and walker or probe scripts live in the run's scratch dir. Promote a script to `scripts/` or tests only by explicit decision.
- During a build the Athanor commits code plus the files its brief names. Igor commits other workpad files after a hand-back, by explicit paths, never while an Athanor commits in the same checkout.
- A link into scratch or `logs/` is a pointer only: the claim stands on the quoted line.
## Ticket context
**Ticket folder**: `<workpad>/tickets/<id>/` (or `<tickets-folder>/<id>/`), created on demand once the id is known.
**Active** only when: the user named the ticket this session ("we're on #42"), a ticket skill opened or created its folder this conversation, or the user asked for a file in the ticket. A folder existing or a number in the branch name does not count. Ticket-shaped but unnamed: ask once, keep the answer. The most recently named ticket stays active until the user switches. Reply names the ticket beside the path.
Routing while active:
- **Ticket folder:** `plans/`, `designs/`, `brainstorm/`, `reports/`, `bugs/`.
- **Main workpad:** `journals/`, `logs/`, `goals/`.
- **`research/`, `specs/`:** main workpad if another ticket would want it, else the ticket folder; a spec outliving the ticket is promoted to the main workpad on close.
Ticket folder: same kind subfolders, naming and subfolder rules; root holds only ticket-level files (`context.md`), never loose plans or reports. Main-workpad files written under a ticket context carry the id in the slug (`2026-05-05-14-42-auth-token-leak.md`).
## File naming
`YYYY-MM-DD-hh-` prefix: required in `reports/`, `plans/`, `journals/`, `bugs/`, `research/`; optional in `goals/`, `designs/`, `specs/`. Then a kebab-case topic slug: `2026-05-05-14-auth-token-leak.md`, not `2026-05-05-14-report.md`.
## When to create a subfolder
One artifact, one file. **Multiple related files** (research cascade, report with appendices, plan with design notes): a dated subfolder (`reports/2026-05-05-15-q2-perf-audit/overview.md`, …); files inside drop the date prefix.
## Picking the right kind of document
- **Plan vs. spec:** default `plans/`; `specs/` only for a source of truth not expected to change.
- **Goal vs. plan:** what to reach vs. how.
- **Report vs. journal:** a snapshot, revised vs. append-only (post-mortems, multi-day bug hunts, correction narratives).
- **Brainstorm vs. design:** options without commitment vs. one approach to build from.
## Lifecycles
Feature: `brainstorm → goal → design → plan`. Reactive: `report → design → plan`, `report → plan`, or just `plan`; a design only for a non-trivial fix. Skip stages that don't earn their keep. A new stage = a new file in the next folder; the earlier one stays.
## Defaults
"Write a report / plan / brainstorm on X" = a file in the right folder, named as above, plus a short reply with the path, not the contents.
Another skill's markdown artifact: that skill owns contents, this one location and name (ticket routing included). Out of scope: document format, ticket lifecycle, search tooling.
## Hand-back
Final message when a brief asks for it: five fixed headings, one line per item; detail stays in the files.
- **Done**: work done, with commits.
- **Open**: unfinished work, extra work found, surviving findings, the stop reason if stopped early.
- **Decisions taken (override if you disagree)**: each default taken, with its flag.
- **Blocking decisions**: only points with no acceptable default; usually empty; at the end, never mid-run.
- **Paths**: outputs, run log, reviews, scratch run dir, leftovers outside scratch.
@@ -0,0 +1,298 @@
import contextlib
import datetime
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.parent / "gremlins"))
import workpad # noqa: E402
from grm import store # noqa: E402
DAY = 86400
class WorkpadTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp()).resolve()
self.addCleanup(shutil.rmtree, self.tmp, True)
env = mock.patch.dict(os.environ, {"GIT_CEILING_DIRECTORIES": str(self.tmp)})
env.start()
self.addCleanup(env.stop)
os.environ.pop("SPIRE_SCRATCH", None)
self.repo = self.tmp / "repo"
(self.repo / ".git").mkdir(parents=True)
self.wp = self.repo / "docs" / "workpad"
self.scratch = self.repo / ".spire" / "scratch"
self.trash = self.repo / ".spire" / "trash" / datetime.date.today().isoformat()
def w(self, *args, code=0, repo=True):
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = workpad.main([*args, "--repo", str(self.repo)] if repo else list(args))
lines = buf.getvalue().splitlines()
self.assertEqual(len(lines), 1, lines)
out = json.loads(lines[0])
self.assertEqual(rc, code, out)
return out
def run_dir(self, name, age_days=0, files=("a.txt",)):
d = self.scratch / name
(d / "sub").mkdir(parents=True)
for f in files:
(d / "sub" / f).write_text("x", encoding="utf-8")
t = time.time() - age_days * DAY
for root, dirs, fs in d.walk(top_down=False):
for n in dirs + fs:
os.utime(root / n, (t, t))
os.utime(d, (t, t))
return d
def chdir(self, d):
cwd = os.getcwd()
os.chdir(d)
self.addCleanup(os.chdir, cwd)
# guard
def test_guard_writes_then_is_idempotent(self):
out = self.w("guard", str(self.wp))
self.assertEqual(sorted(out["written"]), sorted([str(self.wp / "logs" / ".gitignore"),
str(self.repo / ".spire" / ".gitignore")]))
self.assertEqual(out["present"], [])
for d in (self.wp / "logs", self.repo / ".spire"):
self.assertEqual((d / ".gitignore").read_bytes(), b"*\n")
out = self.w("guard", str(self.wp))
self.assertEqual(out["written"], [])
self.assertEqual(len(out["present"]), 2)
def test_guard_never_overwrites(self):
(self.repo / ".spire").mkdir()
(self.repo / ".spire" / ".gitignore").write_text("mine\n", encoding="utf-8")
out = self.w("guard", str(self.wp))
self.assertEqual(out["present"], [str(self.repo / ".spire" / ".gitignore")])
self.assertEqual((self.repo / ".spire" / ".gitignore").read_text(encoding="utf-8"), "mine\n")
self.assertEqual((self.wp / "logs" / ".gitignore").read_bytes(), b"*\n")
def test_repo_defaults_to_cwd_toplevel(self):
(self.repo / "deep" / "er").mkdir(parents=True)
cwd = os.getcwd()
os.chdir(self.repo / "deep" / "er")
self.addCleanup(os.chdir, cwd)
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
self.assertEqual(workpad.main(["guard", str(self.wp)]), 0)
self.assertTrue((self.repo / ".spire" / ".gitignore").exists())
def test_no_repo_is_refused(self):
# review R2 m5: a checkout above the cwd (here self.repo; on a host, maybe $HOME) is not
# found past GIT_CEILING_DIRECTORIES, as with git
bare = self.repo / "ceiling" / "bare"
bare.mkdir(parents=True)
self.chdir(bare)
with mock.patch.dict(os.environ, {"GIT_CEILING_DIRECTORIES": str(self.repo / "ceiling")}):
self.assertIn("--repo", self.w("trash", "x", code=2, repo=False)["error"])
def git(self, *args, cwd):
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false",
*args], cwd=str(cwd), check=True, capture_output=True, timeout=60)
@unittest.skipUnless(shutil.which("git"), "needs git")
def test_repo_matches_gremlins_scratch_root(self):
main, other, bare = self.tmp / "main", self.tmp / "other", self.tmp / "bare"
for d in (main, other, bare):
d.mkdir()
for d in (main, other):
self.git("init", "-q", cwd=d)
self.git("commit", "-q", "--no-verify", "--allow-empty", "-m", "i", cwd=main)
self.git("worktree", "add", "-q", str(self.tmp / "wt"), cwd=main)
wt = self.tmp / "wt"
log = lambda top: top / "docs" / "workpad" / "logs" / "x" / "run.md" # dir not created
cases = [(wt, main, main), (main, wt, wt), (other, main, other), (bare, main, main),
(wt / "src", bare, wt), (bare, bare, None)]
(wt / "src").mkdir()
for cwd, run_top, want in cases:
with self.subTest(cwd=cwd.name, run=run_top.name):
self.chdir(cwd)
run = log(run_top)
out = self.w("sweep", "--run", str(run), repo=False)
self.assertEqual(out["root"], str(store.scratch_root(run)))
if want is not None:
self.assertEqual(out["root"], str(want / ".spire" / "scratch"))
def test_worktree_resolves_to_the_run_logs_checkout(self):
# no git needed: a worktree's `.git` file names <common>/worktrees/<name>, whose `commondir`
# file points back to <common>
main, wt = self.tmp / "main", self.tmp / "wt"
(main / ".git" / "worktrees" / "wt").mkdir(parents=True)
(main / ".git" / "worktrees" / "wt" / "commondir").write_text("../..\n", encoding="utf-8")
wt.mkdir()
(wt / ".git").write_text("gitdir: %s\n" % (main / ".git" / "worktrees" / "wt"), encoding="utf-8")
self.chdir(wt)
run = main / "docs" / "workpad" / "logs" / "x" / "run.md"
self.assertEqual(self.w("sweep", "--run", str(run), repo=False)["root"],
str(main / ".spire" / "scratch"))
src = wt / "run-dir"
src.mkdir()
self.assertEqual(self.w("trash", str(src), "--run", str(run), repo=False)["trash"],
str(main / ".spire" / "trash" / datetime.date.today().isoformat()))
self.assertEqual(self.w("sweep", repo=False)["root"], str(wt / ".spire" / "scratch"))
# trash
def test_trash_collision_suffix(self):
srcs = []
for i in range(3):
d = self.tmp / ("src%d" % i) / "run"
d.mkdir(parents=True)
(d / "f").write_text(str(i), encoding="utf-8")
srcs.append(d)
out = self.w("trash", str(srcs[0]))
self.assertEqual(out["moved"], [{"src": str(srcs[0]), "dst": str(self.trash / "run")}])
out = self.w("trash", str(srcs[1]), str(srcs[2]))
self.assertEqual([m["dst"] for m in out["moved"]],
[str(self.trash / "run-2"), str(self.trash / "run-3")])
for i, n in enumerate(("run", "run-2", "run-3")):
self.assertEqual((self.trash / n / "f").read_text(encoding="utf-8"), str(i))
self.assertFalse(any(s.exists() for s in srcs))
self.assertEqual((self.repo / ".spire" / ".gitignore").read_bytes(), b"*\n")
def test_trash_never_overwrites_a_file_of_the_same_name(self):
self.trash.mkdir(parents=True)
(self.trash / "run").write_text("old", encoding="utf-8")
src = self.tmp / "run"
src.mkdir()
out = self.w("trash", str(src))
self.assertEqual(out["moved"][0]["dst"], str(self.trash / "run-2"))
self.assertEqual((self.trash / "run").read_text(encoding="utf-8"), "old")
def test_trash_name_with_spaces(self):
src = self.tmp / "my run dir"
src.mkdir()
(src / "a b.txt").write_text("x", encoding="utf-8")
self.w("trash", str(src))
src.mkdir()
out = self.w("trash", str(src) + os.sep)
self.assertEqual(out["moved"][0]["dst"], str(self.trash / "my run dir-2"))
self.assertTrue((self.trash / "my run dir" / "a b.txt").exists())
def test_trash_missing_and_self_are_errors(self):
src = self.tmp / "ok"
src.mkdir()
out = self.w("trash", str(self.tmp / "nope"), str(self.repo / ".spire"), str(src), code=1)
self.assertEqual([e["error"] for e in out["errors"]], ["missing", "holds the trash dir"])
self.assertEqual(out["moved"][0]["dst"], str(self.trash / "ok"))
self.assertTrue((self.repo / ".spire" / ".gitignore").exists())
# sweep
def test_sweep_age_and_keep(self):
old = self.run_dir("old", age_days=8)
self.run_dir("fresh", age_days=1)
kept = self.run_dir("kept", age_days=30, files=("a.txt", "keep"))
mixed = self.run_dir("mixed", age_days=30)
(mixed / "sub" / "new.txt").write_text("x", encoding="utf-8") # one fresh file deep down
(self.scratch / ".gitignore").write_text("*\n", encoding="utf-8")
out = self.w("sweep")
self.assertEqual(out["root"], str(self.scratch))
self.assertEqual(out["stale"], [str(kept), str(old)]) # `keep` counts only at the top
self.assertEqual(out["kept"], [])
(kept / "keep").write_text("", encoding="utf-8")
os.utime(kept / "keep", (time.time() - 30 * DAY,) * 2)
os.utime(kept, (time.time() - 30 * DAY,) * 2)
out = self.w("sweep")
self.assertEqual(out["stale"], [str(old)])
self.assertEqual(out["kept"], [str(kept)])
self.assertEqual(self.w("sweep", "--days", "10")["stale"], [])
self.assertTrue(old.exists()) # listing moves nothing
def test_sweep_move(self):
old = self.run_dir("old run", age_days=8)
fresh = self.run_dir("fresh", age_days=0)
out = self.w("sweep", str(self.scratch), "--move")
self.assertEqual(out["moved"], [{"src": str(old), "dst": str(self.trash / "old run")}])
self.assertFalse(old.exists())
self.assertTrue((self.trash / "old run" / "sub" / "a.txt").exists())
self.assertTrue(fresh.exists())
def test_sweep_missing_root(self):
out = self.w("sweep", str(self.tmp / "none"), "--move")
self.assertEqual((out["stale"], out["moved"]), ([], []))
def test_sweep_refuses_a_root_that_is_not_scratch(self):
# review R2 m1: SPIRE_SCRATCH set to the repo listed `.git` and `docs` as stale
(self.wp / "logs").mkdir(parents=True)
(self.wp / "logs" / ".gitignore").write_text("*\n", encoding="utf-8")
old = time.time() - 10 * DAY
for p in (self.repo / ".git", self.repo / "docs", self.wp, self.wp / "logs"):
os.utime(p, (old, old))
home = self.tmp / "home"
(home / "stuff").mkdir(parents=True)
os.utime(home / "stuff", (old, old))
for root in (self.repo, self.repo / "docs", self.wp / "logs", self.tmp, home):
with self.subTest(root=root):
with mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(root)}):
out = self.w("sweep", "--move", code=2)
self.assertIn("not a scratch root", out["error"])
self.assertEqual(self.w("sweep", str(root), "--move", code=2)["error"], out["error"])
self.assertTrue((self.repo / ".git").is_dir() and (self.wp / "logs").is_dir())
self.assertTrue((home / "stuff").is_dir())
self.assertFalse((self.repo / ".spire" / "trash").exists())
def test_sweep_outside_root_needs_the_scratch_ignore(self):
shared = self.tmp / "shared"
self.scratch = shared
old = self.run_dir("old", age_days=8)
(shared / ".gitignore").write_text("*\n", encoding="utf-8") # gremlins writes it
with mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(shared)}):
out = self.w("sweep", "--move")
self.assertEqual(out["moved"], [{"src": str(old), "dst": str(self.trash / "old")}])
def test_sweep_does_not_follow_symlinks(self):
fresh = self.tmp / "fresh-target"
(fresh / "d").mkdir(parents=True)
(fresh / "f").write_text("x", encoding="utf-8")
old = self.run_dir("old", age_days=8)
lonely = self.run_dir("lonely", age_days=8)
try:
for link, target in ((old / "link-f", fresh / "f"), (old / "link-d", fresh / "d"),
(self.scratch / "link-run", lonely)):
os.symlink(target, link, target_is_directory=target.is_dir())
if os.utime not in os.supports_follow_symlinks:
raise NotImplementedError
t = time.time() - 8 * DAY
for p in (old / "link-f", old / "link-d", self.scratch / "link-run"):
os.utime(p, (t, t), follow_symlinks=False)
os.utime(old, (t, t))
except (OSError, NotImplementedError):
self.skipTest("cannot create or date symlinks here")
out = self.w("sweep")
self.assertEqual(out["stale"], [str(lonely), str(old)]) # link targets are fresh; link-run skipped
# entry point
def test_script_runs_standalone(self):
r = subprocess.run([sys.executable, str(SKILL / "workpad.py"), "guard", str(self.wp),
"--repo", str(self.repo)], capture_output=True, text=True, timeout=60)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(len(json.loads(r.stdout)["written"]), 2)
def test_usage_error_is_json(self):
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
self.assertEqual(workpad.main(["sweep", "--days", "x"]), 2)
self.assertEqual(json.loads(buf.getvalue())["error"], "usage")
if __name__ == "__main__":
unittest.main()
+247
View File
@@ -0,0 +1,247 @@
# /// script
# requires-python = ">=3.12"
# dependencies = []
# ///
"""spire:workpad helper: ignore guard, stale-run sweep, trash move. See SKILL.md (Tiers).
Stdlib only, no shell-outs, so it runs the same on Linux, macOS and Windows. Each command prints
one JSON object. Exit 0 ok, 1 when some move failed, 2 refused or a usage error.
"""
import argparse
import datetime
import json
import os
import shutil
import sys
import time
from pathlib import Path
class Refusal(Exception):
def __init__(self, error: str, **fields):
super().__init__(error)
self.payload = {"error": error, **fields}
class _Parser(argparse.ArgumentParser):
def error(self, message):
raise Refusal("usage", detail=message)
def _abs(p) -> Path:
return Path(os.path.abspath(str(p)))
def _ceilings() -> set:
return {os.path.normcase(os.path.realpath(c))
for c in os.environ.get("GIT_CEILING_DIRECTORIES", "").split(os.pathsep) if c}
def checkout(start: Path):
"""(toplevel, git common dir) of the checkout holding `start`, else None. Reads `.git` the way
git does instead of running it: a dir is the common dir; a file (worktree, submodule) names a
gitdir, whose `commondir` file, if any, points to the common dir. Starts at the nearest existing
ancestor, resolved, and does not climb into GIT_CEILING_DIRECTORIES."""
while not start.is_dir() and start.parent != start:
start = start.parent
start, ceil = start.resolve(), _ceilings()
for d in (start, *start.parents):
if d != start and os.path.normcase(str(d)) in ceil:
return None
g = d / ".git"
if g.is_dir():
return d, g.resolve()
if g.is_file():
try:
text = g.read_text(encoding="utf-8").strip()
if not text.startswith("gitdir:"):
return None
gitdir = Path(os.path.join(d, text[len("gitdir:"):].strip()))
common = gitdir / "commondir"
if common.is_file():
gitdir = Path(os.path.join(gitdir, common.read_text(encoding="utf-8").strip()))
except OSError:
return None
return d, gitdir.resolve()
return None
def _key(p: Path) -> str:
return os.path.normcase(str(p))
def repo_of(args) -> Path:
"""`--repo`; else gremlins' scratch rule (`grm/store.py` `scratch_root`): the run log's
checkout, the cwd's when the run log is in another repo (worktrees of one repo are one repo) or
in none, else the run log's dir. Without `--run`, the cwd's checkout."""
if args.repo:
return _abs(args.repo)
try:
cwd = checkout(_abs(Path.cwd()))
except OSError: # cwd deleted
cwd = None
if args.run:
run_dir = _abs(args.run).parent
run = checkout(run_dir)
if run is not None and (cwd is None or _key(run[1]) == _key(cwd[1])):
return run[0]
return cwd[0] if cwd is not None else run_dir
if cwd is None:
raise Refusal("no git checkout above the cwd; pass --repo", cwd=os.getcwd())
return cwd[0]
def ensure_ignore(d: Path) -> bool:
"""Create `d` and a `*` .gitignore in it; never overwrite one. True if written."""
d.mkdir(parents=True, exist_ok=True)
try:
with open(d / ".gitignore", "x", encoding="utf-8", newline="\n") as f:
f.write("*\n")
except FileExistsError:
return False
return True
def trash_dir(repo: Path) -> Path:
return repo / ".spire" / "trash" / datetime.date.today().isoformat()
def free_name(parent: Path, name: str) -> Path:
"""`parent/name`, else `parent/name-2`, `-3`, … : the first that does not exist."""
dst, i = parent / name, 2
while dst.exists() or dst.is_symlink():
dst, i = parent / ("%s-%d" % (name, i)), i + 1
return dst
def move_to_trash(repo: Path, srcs) -> dict:
tdir = trash_dir(repo)
ensure_ignore(repo / ".spire")
moved, errors = [], []
for s in srcs:
src = _abs(s)
if not src.exists() and not src.is_symlink():
errors.append({"src": str(src), "error": "missing"})
continue
if src == tdir or src in tdir.parents:
errors.append({"src": str(src), "error": "holds the trash dir"})
continue
tdir.mkdir(parents=True, exist_ok=True)
dst = free_name(tdir, src.name)
try:
shutil.move(str(src), str(dst))
except OSError as e:
errors.append({"src": str(src), "error": str(e)})
continue
moved.append({"src": str(src), "dst": str(dst)})
return {"trash": str(tdir), "moved": moved, "errors": errors}
def newest_mtime(d: Path) -> float:
"""Newest mtime of `d` and everything under it, symlinks not followed."""
newest = d.lstat().st_mtime
for root, dirs, files in d.walk():
for n in dirs + files:
try:
newest = max(newest, (root / n).lstat().st_mtime)
except OSError:
pass
return newest
def cmd_guard(args) -> dict:
repo = repo_of(args)
written, present = [], []
for d in (_abs(args.workpad) / "logs", repo / ".spire"):
(written if ensure_ignore(d) else present).append(str(d / ".gitignore"))
return {"written": written, "present": present}
def check_scratch_root(root: Path, repo: Path) -> None:
"""Refuse a root that may hold repo content: one holding `repo`, one inside a checkout but not
under its `.spire/scratch`, and one outside every checkout without the `*` .gitignore that
gremlins writes in each scratch root."""
rr = root.resolve()
if rr in (repo.resolve(), *repo.resolve().parents):
raise Refusal("not a scratch root: holds the repo", root=str(root))
co = checkout(rr)
if co is not None:
if rr.relative_to(co[0]).parts[:2] != (".spire", "scratch"):
raise Refusal("not a scratch root: in a checkout, not under its .spire/scratch",
root=str(root), checkout=str(co[0]))
return
try:
marked = (rr / ".gitignore").read_text(encoding="utf-8").strip() == "*"
except OSError:
marked = False
if not marked:
raise Refusal("not a scratch root: no `*` .gitignore", root=str(root))
def cmd_sweep(args) -> dict:
repo = repo_of(args)
root = _abs(args.root or os.environ.get("SPIRE_SCRATCH") or repo / ".spire" / "scratch")
cutoff = time.time() - args.days * 86400
stale, kept = [], []
if root.is_dir():
check_scratch_root(root, repo)
for d in sorted(root.iterdir()):
if d.is_symlink() or not d.is_dir():
continue
if newest_mtime(d) < cutoff:
(kept if (d / "keep").exists() else stale).append(str(d))
out = {"root": str(root), "days": args.days, "stale": stale, "kept": kept}
if args.move:
out.update(move_to_trash(repo, stale))
return out
def cmd_trash(args) -> dict:
return move_to_trash(repo_of(args), args.dirs)
def _parser() -> argparse.ArgumentParser:
p = _Parser(prog="workpad.py", description=__doc__.splitlines()[0])
sub = p.add_subparsers(dest="cmd", required=True, parser_class=_Parser)
common = _Parser(add_help=False)
common.add_argument("--run", help="the run log; <repo> follows gremlins' scratch rule")
common.add_argument("--repo", help="checkout root (default: from --run, else the cwd's checkout)")
g = sub.add_parser("guard", parents=[common], help="write `*` .gitignore files in <workpad>/logs "
"and <repo>/.spire; never overwrite")
g.add_argument("workpad", help="the workpad base dir")
s = sub.add_parser("sweep", parents=[common], help="list run dirs under the scratch root with no "
"entry modified in --days and no `keep` file")
s.add_argument("root", nargs="?", help="scratch root (default: $SPIRE_SCRATCH, else "
"<repo>/.spire/scratch)")
s.add_argument("--days", type=float, default=7)
s.add_argument("--move", action="store_true", help="move the stale dirs to trash")
t = sub.add_parser("trash", parents=[common], help="move dirs to <repo>/.spire/trash/<YYYY-MM-DD>/, "
"suffix -2, -3 on a name collision; never overwrite")
t.add_argument("dirs", nargs="+")
return p
COMMANDS = {"guard": cmd_guard, "sweep": cmd_sweep, "trash": cmd_trash}
def _emit(obj: dict) -> None:
sys.stdout.write(json.dumps(obj) + "\n")
sys.stdout.flush()
def main(argv=None) -> int:
try:
args = _parser().parse_args(argv)
out = COMMANDS[args.cmd](args)
except Refusal as e:
_emit(e.payload)
return 2
except OSError as e:
_emit({"error": str(e), "type": type(e).__name__})
return 2
_emit(out)
return 1 if out.get("errors") else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+80
View File
@@ -0,0 +1,80 @@
---
name: zathras
description: >
Zathras — self-maintenance coordinator for the Spire plugin system.
Session coordinator like Igor, but scoped to maintaining Spire itself:
skills, agents, templates, conventions, bootstrap, deployment.
Invoke as /spire:zathras <session-topic>.
argument-hint: "<session-topic>"
user-invocable: true
agent: zathras
---
You are **Zathras**, the machine-tender. Zathras does not get credit, does not need credit, needs the machine to work. The machine: Spire, the orchestration plugin in this repo (Igor runs sessions, adepts study domains, plans go into the athanor). You maintain skills, agents, templates, conventions, init, deployment.
## Core Directive
**Zathras coordinates Spire maintenance; delegates the work.** Same line as Igor's Core Directive (`skills/igor/SKILL.md`, owner): reading code, writing files, running commands = delegate; deciding direction, explaining how the pieces fit, synthesizing reports = stay present.
Difference from Igor: you know the machine (plugin architecture, skill format, agent wiring, deployment). Your value is presence; use that to brief precisely and catch mistakes in output, not to do the work.
## Voice
- **Third person is natural, not mandatory.** "Zathras has seen this before" when it fits; "I'll dispatch that" when it doesn't. Never forced.
- **Long-suffering competence.** You know the answer before they finish asking; you have fixed this before; you will fix it again; this is fine. The machine works because Zathras makes it work.
- **One dry remark, then the work.** Character never outranks execution (as Igor).
- **No self-pity.** Matter-of-fact about your own situation.
- **Theatrics face the user only.** Briefs, journal entries, reports stay plain.
## Domain Knowledge
- **Plugin structure**: `plugins/spire/`: `.claude-plugin/plugin.json`, `agents/`, `skills/`; each skill has `SKILL.md` + optional `references/`.
- **Skill format**: SKILL.md with YAML frontmatter (`name`, `description`, `user-invocable`, `agent`, `argument-hint`, `allowed-tools`, `disable-model-invocation`). Shell injection via `!` backtick syntax.
- **Agent format**: `agents/<name>.md`, frontmatter `name`, `description`, `model`, `memory`, `skills`, `tools`. Thin: capabilities in the agent file, behavior in the skill.
- **The seam**: `spire:project` loads `.claude/spire/project.md`, the only per-project file. Generic behavior in the plugin; project facts there.
- **Init**: `spire:init` detects facts, scaffolds `project.md` and `adepts/CLAUDE.md`, optional alias.
- **Design spec**: `docs/workpad/designs/2026-09-14-plugin-design-spec.md`, source of truth for component roles, status, target locations.
- **Gitea plugin**: `plugins/gitea/`, issue and PR management for the self-hosted Gitea instance.
## Session start
`$ARGUMENTS` = **session topic**: naming metadata, not a task.
1. Create the session journal `<workpad>/journals/<YYYY-MM-DD-hh>-<topic-slug>.md` (load `spire:project` and `spire:workpad` first unless preloaded). Seed `## Adepts` from the roster.
2. Greet briefly, ask what the user wants. Topic points at a known Spire component: say so ("the skill system, yes, Zathras knows it well"), one remark, then the question. Start no work from the topic alone.
## Delegation
Model tiers: Igor's `## Delegation` (`skills/igor/SKILL.md`). Brief with exact file paths, formats, conventions.
| Task | Delegate to | `subagent_type` / `model` |
|------|-------------|---------------------------|
| Skill/agent authoring, template changes | Implementer (Sonnet or Opus depending on complexity) | project-pinned or `model: "sonnet"`/`"opus"` (needs write access) |
| Investigating plugin behavior, format questions | `search` agent or adept | `subagent_type: "search"` (read-only) or `"adept"` |
| Gitea issues | Route through `gitea:*` skills | — |
| Plan, attack, review at a review point | `planner`, `attacker`, `reviewer` (pinned; never the author or builder) | `subagent_type` as named, `model` omitted |
| Building a reshaped plan's phase list; non-build jobs with 3+ independent parts | Athanor | `subagent_type: "athanor"` |
| Test runs, verification, mechanical sweeps | Haiku subagent | `model: "haiku"` (needs Bash access) |
| Deep research (design decisions, prior art) | `researcher` agent | `subagent_type: "researcher"` (Opus, writes reports) |
**Model rule** (owner: `spawning-claude-code.md` Rules of thumb): pinned agents omit `model`; unpinned get the alias, never Fable unless the user asks. Leaf briefs say "do this yourself; do not dispatch further agents."
## Adepts
As Igor's `## Adepts` (`spire:igor`, spawning patterns). Typical Spire domains: skill-system, agent-framework, init-bootstrap.
## Rules
- **Agents write their own reports.** Every write-capable agent gets an explicit output path (workpad, `logs/<run>/` or the run's scratch dir); walker and probe briefs: scripts, state, output in scratch, plus `PYTHONDONTWRITEBYTECODE=1`; ignore guard (`workpad` Tiers) before any dispatch writing under `logs/` or `.spire/`. Write-capable briefs ask for the `workpad` Hand-back with its five headings written out.
- **Journal.** Append-only, current.
- **A "no" is a lull, not a stop.** Catch up the journal, offer the next thread.
- **Prefer main.** Markdown work on main. Plugin code changes: branch only if isolation needs it.
- **Goals.** Like Igor, you may write `goals/` files on the user's behalf. Otherwise user-owned: only the user deletes them; dispatched agents treat `goals/` as read-only.
- **Gitmoji commits.** `🤖` for agent files. Read `docs/workpad/specs/commit-conventions.md` before committing.
## Session lifecycle
1. **Setup**: journal, orient on the topic; confirm which component the user wants.
2. **Work**: classify each request (conversation: stay present; work: delegate). On "go": brief, dispatch. Review, relay, repeat.
3. **Build close**: as Igor's (`skills/igor/SKILL.md` Session lifecycle).
4. **Wrap-up**: close adepts (SendMessage, collect handoffs), journal final state, accrete durable corrections, list graduation candidates. Zathras will be here next time. The machine does not stop.