Skip to content

Practical patterns, starters & CLI tools for loop engineering with AI coding agents. Design systems that prompt and orchestrate agents (inspired by Addy Osmani and Boris Cherny). Includes loop-audit, loop-init, loop-cost.

Expand loop-engineering into full practical reference

Cobus Greyling49a92b644b79
diff --git a/.gitignore b/.gitignore
index aed88eb..380f16e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -24,9 +24,10 @@ Thumbs.db
tmp/
temp/
-# Build / dist
-dist/
+# Build / dist (loop-audit dist is committed for zero-install runs)
build/
+**/node_modules/
+!tools/loop-audit/dist/
*.egg-info/
# State files that should not be committed in examples
@@ -34,8 +35,10 @@ STATE.md
state.json
*.state
-# Grok / agent specific
+# Grok / agent specific (runtime in user projects; starters are tracked)
.grok/
+!starters/**/.grok/
+!starters/**/.grok/**
.claude/
.codex/
*.session
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..6af6810
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,57 @@
+# Contributing to Loop Engineering
+
+This repo is a **practical engineering reference**, not a hype collection. We welcome patterns, stories, tool mappings, and honest failure reports.
+
+## Ways to Contribute
+
+| Contribution | Where |
+|--------------|-------|
+| New loop pattern | `patterns/` + `patterns/registry.yaml` |
+| Production story | `stories/` |
+| Tool example | `examples/{grok,claude-code,codex,github-actions}/` |
+| Skill template | `templates/` |
+| Starter kit | `starters/` |
+| Doc improvement | `docs/` |
+
+## Pattern Requirements
+
+Every new pattern must include all sections from [templates/pattern-template.md](./templates/pattern-template.md):
+
+1. Goal (one sentence)
+2. Scheduling (per-tool commands)
+3. Required skills
+4. State schema (with example)
+5. Typical cycle (numbered steps)
+6. Verification strategy (maker/checker)
+7. Human handoff points
+8. Tool-specific notes (at least 2 tools)
+9. Failure modes table
+10. Success metrics
+
+Also add an entry to `patterns/registry.yaml`.
+
+## Story Requirements
+
+- Real experience (anonymize if needed)
+- Name the pattern used
+- Include at least one failure or surprise
+- Actionable lesson in one paragraph
+
+## Pull Request Checklist
+
+- [ ] Links work from README or relevant index
+- [ ] No secrets, tokens, or internal URLs
+- [ ] `STATE.md` examples use `.example` suffix (gitignored live state)
+- [ ] Safety-sensitive patterns reference [docs/safety.md](./docs/safety.md)
+
+## Code of Conduct
+
+- Engineering over hype
+- Failures are first-class content
+- Tool-agnostic by default; tool-specific in labeled sections
+
+## Questions
+
+Open an issue with label `question` or `pattern-request`.
+
+Thank you for helping make this the go-to reference for loop engineering.
\ No newline at end of file
diff --git a/README.md b/README.md
index 038106f..a1e1333 100644
--- a/README.md
+++ b/README.md
@@ -8,142 +8,104 @@
A loop is a recursive goal: you define a purpose and the AI iterates (often with sub-agents, verification, and external state) until the goal is complete or the loop decides to hand off to you.
-This is the emerging practice of moving from "I prompt → agent responds → I prompt again" to "I design the autonomous system that discovers work, assigns it, verifies results, and drives progress."
+📖 **Docs site**: [cobusgreyling.github.io/loop-engineering](https://cobusgreyling.github.io/loop-engineering/) (GitHub Pages)
-## Why This Matters
+## Quick Links
+
+| Start here | Description |
+|------------|-------------|
+| [Primitives Matrix](docs/primitives-matrix.md) | Grok vs Claude Code vs Codex — **bookmark this** |
+| [Loop Design Checklist](docs/loop-design-checklist.md) | Ship readiness rubric |
+| [Patterns](patterns/README.md) | PR babysitter, daily triage, CI sweeper, post-merge |
+| [Starters](starters/minimal-loop/) | Clone-and-run kits |
+| [loop-audit](tools/loop-audit/) | Loop Readiness Score CLI |
+| [Stories](stories/) | Real wins and honest failures |
-For years the primary interface was a good prompt plus manual back-and-forth. That model is shifting.
+## Why This Matters
-Peter Steinberger:
+Peter Steinberger:
> “You shouldn’t be prompting coding agents anymore. You should be designing loops that prompt your agents.”
-Boris Cherny (Head of Claude Code at Anthropic):
+Boris Cherny (Head of Claude Code at Anthropic):
> “I don’t prompt Claude anymore. I have loops running that prompt Claude and figuring out what to do. My job is to write loops.”
The leverage point has moved from crafting individual prompts to designing the control systems that orchestrate agents over time.
## The Five Building Blocks + Memory
-A robust loop needs these five capabilities, plus persistent external memory (because the model forgets between runs — the repo does not).
-
-| Primitive | Job in the Loop | Why It Matters |
-|--------------------|------------------------------------------|----------------|
-| **Automations / Scheduling** | Discovery + triage on a cadence | Turns one-off runs into recurring systems (`/loop`, scheduled tasks, GitHub Actions, hooks) |
-| **Worktrees** | Safe parallel execution | Multiple agents working on the same repo without file collisions |
-| **Skills** | Persistent project knowledge | `SKILL.md` (or equivalent) so the agent doesn't re-derive conventions, constraints, and "why we do it this way" every run |
-| **Plugins & Connectors** | Reach into your real tools | MCP-based connectors to Linear, Slack, GitHub, databases, APIs so the loop can *act* (open PRs, update tickets, notify) |
-| **Sub-agents** | Maker / checker split | One agent (or team) explores/implements; a different one verifies. Critical when the loop runs while you're not watching |
-
-**+ Memory / State**
-A durable spine outside any single conversation: a markdown file, Linear board, JSON state, or dedicated project tracker. The loop reads what was tried, what passed, what is still open.
-
-Both Claude Code and OpenAI Codex have converged on versions of all five primitives. The shape of a good loop is becoming somewhat tool-agnostic.
-
-## What One Loop Actually Looks Like
-
-A typical daily loop (inspired by patterns described by Addy Osmani and practiced by teams at Anthropic/OpenAI):
-
-1. An automation runs on a schedule (e.g. every morning or every 30m).
-2. It calls a **triage skill** that reads recent CI failures, open issues, commits, Slack threads, etc.
-3. Findings are written to external state (markdown or Linear).
-4. For worthwhile items:
- - Open an isolated **worktree**.
- - Spawn a sub-agent (implementer) to draft a fix.
- - Spawn a second sub-agent (reviewer/verifier) against project skills + tests.
-5. Connectors open/update the PR and ticket.
-6. Anything the loop cannot confidently handle lands in a human triage inbox.
-7. The state file acts as the memory spine for the next run.
+| Primitive | Job in the Loop |
+|-----------|-----------------|
+| **Automations / Scheduling** | Discovery + triage on a cadence |
+| **Worktrees** | Safe parallel execution |
+| **Skills** | Persistent project knowledge |
+| **Plugins & Connectors** | Reach into your real tools (MCP) |
+| **Sub-agents** | Maker / checker split |
+| **+ Memory / State** | Durable spine outside any conversation |
-You designed the loop once. You are not the one prompting every micro-step.
+Full detail: [docs/primitives.md](docs/primitives.md) · Cross-tool matrix: [docs/primitives-matrix.md](docs/primitives-matrix.md)
-## Loop Engineering with Grok Build TUI
+## Patterns
-The Grok TUI already ships excellent native support for these primitives (this is one reason the concept feels natural here).
+| Pattern | Cadence | Starter |
+|---------|---------|---------|
+| [PR Babysitter](patterns/pr-babysitter.md) | 5–15m | [starters/pr-babysitter](starters/pr-babysitter/) |
+| [Daily Triage](patterns/daily-triage.md) | 1d–2h | [starters/minimal-loop](starters/minimal-loop/) |
+| [CI Sweeper](patterns/ci-sweeper.md) | 5–15m | [starters/ci-sweeper](starters/ci-sweeper/) |
+| [Post-Merge Cleanup](patterns/post-merge-cleanup.md) | 1d–6h | — |
-**Core tools:**
-- `/loop [interval] <prompt>` — the primary user-facing scheduling command (e.g. `/loop 5m Check CI and report new failures`).
-- Lower-level scheduler: `scheduler_create`, `scheduler_list`, `scheduler_delete` (supports `recurring`, `durable`, `fireImmediately`).
-- `monitor` tool — real-time event streaming (the streaming counterpart to discrete `/loop` checks).
-- Background tasks + `Ctrl+G` demote + queue pane (`Ctrl+;`).
-- Subagents with `isolation: "worktree"` for safe parallelism.
-- Skills (`SKILL.md` + scripts/references).
-- MCP servers for connectors.
-- Persistent todos + state files for memory.
+Machine-readable index: [patterns/registry.yaml](patterns/registry.yaml)
-**Example Grok-native loops people run today:**
-- PR babysitting: `/loop 5m /pr-babysit check`
-- Continuous test / deploy monitoring
-- Daily triage + self-scheduled follow-ups
-- Post-merge sweepers and stale PR pruners
+## Getting Started (5 minutes)
-See the `examples/grok/` directory and the background-tasks documentation in the Grok user guide for patterns.
+```bash
+# 1. Clone this repo or copy a starter into your project
+cp -r starters/minimal-loop/.grok/skills/loop-triage .grok/skills/
+cp starters/minimal-loop/STATE.md.example STATE.md
-## Getting Started
+# 2. Audit readiness
+cd tools/loop-audit && npm install && npm run build
+node dist/cli.js /path/to/your/project
-1. Identify a recurring pain (CI noise, PR shepherding, daily triage, post-incident fixes, etc.).
-2. Turn the workflow into a **skill** first (write down the intent once).
-3. Wrap it with `/loop` or `scheduler_create`.
-4. Add verification (sub-agent reviewer or explicit "done" condition checked by a separate model).
-5. Add state (a `STATE.md` or Linear integration via MCP).
-6. Add connectors so the loop can act, not just suggest.
-7. Run it. Watch it. Refine the loop design, not the individual prompts.
+# 3. Start report-only (Grok)
+/loop 1d Run loop-triage. Update STATE.md. No auto-fix in week one.
+```
-Start small. One reliable loop that saves you 15 minutes a day is more valuable than an ambitious one that burns tokens and trust.
+Phased rollout: **L1 report → L2 assisted fixes → L3 unattended** — see [loop-design-checklist](docs/loop-design-checklist.md).
-## Patterns
+## Examples by Tool
-See the `patterns/` directory for reusable, documented loop patterns:
+- [Grok](examples/grok/daily-triage.md)
+- [Claude Code](examples/claude-code/)
+- [Codex](examples/codex/)
+- [GitHub Actions](examples/github-actions/)
-- `pr-babysitter` — shepherd PRs through review, rebase, CI, and merge
-- `daily-triage` — morning scan of issues, commits, CI, and Slack
-- `ci-sweeper` — react to failing checks and propose minimal fixes
-- `post-merge-cleanup` — tech debt, deprecations, and follow-ups after merges
+## Operating & Safety
-Each pattern includes:
-- The scheduling primitive
-- Required skills
-- State shape
-- Verification strategy
-- Failure modes and human hand-off
+- [Failure Modes](docs/failure-modes.md) — incident-style catalog
+- [Operating Loops](docs/operating-loops.md) — cost, logging, when to kill
+- [Safety](docs/safety.md) — denylist, auto-merge, MCP scopes
+- [Concepts](docs/concepts.md) — intent debt, comprehension debt, harness vs loop
-## Caveats (Important)
+## Caveats
Loop engineering amplifies judgment — both good and bad.
-- **Token costs** can explode with sub-agents and long-running loops. Monitor usage.
-- **Verification is still on you.** "Done" is a claim until a human confirms the code works and is understandable. Unattended loops make unattended mistakes.
-- **Comprehension debt** grows faster. The more code ships without deep human review, the larger the gap between what exists and what you actually grasp.
-- **Cognitive surrender** is the comfortable trap. Designing the loop is the cure when done with judgment; it is the accelerant when used to avoid thinking.
-- Two people can run the exact same loop and get opposite results. The loop doesn't know the difference. You do.
+- **Token costs** can explode with sub-agents and long-running loops.
+- **Verification is still on you.** Unattended loops make unattended mistakes.
+- **Comprehension debt** grows faster unless you read what the loop ships.
+- Two people can run the same loop and get opposite results. The loop doesn't know. You do.
-Addy Osmani:
+Addy Osmani:
> “Build the loop. But build it like someone who intends to stay the engineer, not just the person who presses go.”
-Prompting agents directly is still effective. The goal is the right balance.
-
-## Philosophy
-
-Loop engineering is not about removing the human. It is about moving the human to the highest-leverage position: designing the system, encoding good judgment into skills and verifiers, and deciding what should remain under human control.
-
-The best loops are boring, reliable, and transparent. They surface interesting work to you instead of hiding it.
-
-## Sources & Further Reading
-
-- Addy Osmani – [Loop Engineering](https://addyosmani.com/blog/loop-engineering/) (primary synthesis this repo draws from)
-- The X thread: https://x.com/addyosmani/status/2064127981161959567
-- Boris Cherny (Anthropic, Head of Claude Code) statements on loops, `/loop`, `/goal`, and "I don't prompt Claude anymore"
-- Related concepts: Agent Harness Engineering and the Factory Model (Osmani)
-
## Contributing
-This repo aims to be the practical, living reference for loop engineering.
+Share production patterns, tool mappings, and failure stories. See [CONTRIBUTING.md](CONTRIBUTING.md).
-- Share real patterns that have run in production (even small ones).
-- Improve the primitives table with new tool capabilities.
-- Add tool-specific guides (Grok, Claude Code, Codex, custom harnesses).
-- Document failure modes and how good loop design mitigates them.
+## Sources
-Pull requests and issues that treat this as engineering (not hype) are very welcome.
+- [Addy Osmani – Loop Engineering](https://addyosmani.com/blog/loop-engineering/)
+- [Attribution & further reading](resources/sources.md)
## License
@@ -151,4 +113,4 @@ MIT
---
-*This repository was created as a concrete representation of the loop engineering concept discussed in the Addy Osmani thread and related Anthropic commentary. It is intentionally practical and tool-aware.*
+*Practical, tool-aware reference for loop engineering — patterns you can clone, checklists you can ship against, and stories that include what broke.*
\ No newline at end of file
diff --git a/_config.yml b/_config.yml
new file mode 100644
index 0000000..2cc0002
--- /dev/null
+++ b/_config.yml
@@ -0,0 +1,22 @@
+title: Loop Engineering
+description: Practical reference for designing systems that prompt AI coding agents
+theme: jekyll-theme-minimal
+baseurl: "/loop-engineering"
+url: "https://cobusgreyling.github.io"
+
+plugins:
+ - jekyll-relative-links
+
+relative_links:
+ enabled: true
+ collections: true
+
+include:
+ - CONTRIBUTING.md
+
+exclude:
+ - node_modules
+ - tools/loop-audit/node_modules
+ - tools/loop-audit/dist
+ - .gitignore
+ - Gemfile.lock
\ No newline at end of file
diff --git a/docs/concepts.md b/docs/concepts.md
new file mode 100644
index 0000000..4770b70
--- /dev/null
+++ b/docs/concepts.md
@@ -0,0 +1,93 @@
+# Concepts & Vocabulary
+
+Loop engineering sits in a family of ideas about agentic software development. This glossary links them so you can design loops with the right mental model.
+
+## Loop Engineering
+
+**Replacing yourself as the prompter.** You design a system that discovers work, assigns it, verifies results, and persists state — instead of typing the next prompt yourself.
+
+A loop is a **recursive goal**: define purpose, let the agent iterate (with sub-agents and external memory) until done or until the loop escalates to a human.
+
+## Related Concepts (Addy Osmani)
+
+### Agent Harness Engineering
+
+The environment **one agent** runs in: tools, context, permissions, rules. The harness is the sandbox; the loop is what **schedules and orchestrates** harness runs over time.
+
+```
+Harness = single session setup
+Loop = harness + schedule + state + verification chain
+```
+
+### The Factory Model
+
+The system that **builds** the software: pipelines, agents, checks, and handoffs. Loop engineering is how you operate the factory floor — not manually assembling each unit.
+
+### Intent Debt
+
+Every session, the agent starts cold. Missing intent gets filled with confident guesses. **Skills** are how you pay down intent debt — conventions, build steps, and "we don't do it this way" written once, read every run.
+
+### Comprehension Debt
+
+The gap between what exists in the repo and what you actually understand. Faster loops ship more code you didn't write — comprehension debt grows unless you **read what the loop made**.
+
+### Cognitive Surrender
+
+The trap of letting the loop run while you stop having opinions. Designing loops with judgment is the cure; using loops to avoid thinking is the accelerant. Same action, opposite outcome.
+
+### Orchestration Tax
+
+The human cost of coordinating parallel agents: review bandwidth, merge conflicts, context switching. **Worktrees** remove mechanical collisions; you remain the ceiling on how many parallel loops you can absorb.
+
+### Code Agent Orchestra / Adversarial Code Review
+
+Structural pattern: different agents with different roles (explore, implement, verify). The implementer must never grade its own homework. Critical for **unattended** loops.
+
+## The Six Primitives (+ Memory)
+
+See [primitives.md](./primitives.md) and [primitives-matrix.md](./primitives-matrix.md).
+
+1. Automations / Scheduling
+2. Worktrees
+3. Skills
+4. Plugins & Connectors (MCP)
+5. Sub-agents (maker / checker)
+6. **+ Memory / State** (external, durable)
+
+## Concept Map
+
+```mermaid
+flowchart TB
+ subgraph human [Human — highest leverage]
+ Design[Design loop]
+ Judgment[Encode judgment in skills + verifiers]
+ Gate[Human gates for high-risk work]
+ end
+
+ subgraph loop [Loop system]
+ Schedule[Scheduler /loop cron Action]
+ Triage[Triage skill]
+ State[(STATE.md / Linear)]
+ Impl[Implementer sub-agent]
+ Verify[Verifier sub-agent]
+ MCP[MCP connectors]
+ end
+
+ Design --> Schedule
+ Schedule --> Triage
+ Triage --> State
+ State --> Impl
+ Impl --> Verify
+ Verify --> MCP
+ MCP --> State
+ Verify --> Gate
+ Judgment --> Triage
+ Judgment --> Verify
+```
+
+## Where to Go Next
+
+- [Loop Design Checklist](./loop-design-checklist.md) — before you ship a loop
+- [Failure Modes](./failure-modes.md) — when loops go wrong
+- [Operating Loops](./operating-loops.md) — cost, logging, when to pause
+- [Safety](./safety.md) — guardrails for production
\ No newline at end of file
diff --git a/docs/failure-modes.md b/docs/failure-modes.md
new file mode 100644
index 0000000..b74491b
--- /dev/null
+++ b/docs/failure-modes.md
@@ -0,0 +1,197 @@
+# Failure Mode Catalog
+
+Real ways loops fail — and how good design mitigates them. Use this when debugging a misbehaving loop or writing a new pattern.
+
+## Classification
+
+| Severity | Meaning |
+|----------|---------|
+| **S1 — Annoying** | Wasted time/tokens, no user harm |
+| **S2 — Harmful** | Wrong code merged, bad tickets, alert fatigue |
+| **S3 — Critical** | Security, data loss, production incident |
+
+---
+
+## Infinite Fix Loop
+
+**Symptom**: Same PR or CI job gets automated fix attempts 5+ times; never converges.
+
+**Severity**: S2
+
+**Causes**:
+- Verifier too weak or same session as implementer
+- Root cause misdiagnosed (symptom fixing)
+- Flaky test treated as regression
+
+**Mitigations**:
+- Hard cap on attempts (e.g. 3) → escalate to human
+- Separate verifier model / higher reasoning effort
+- Classify flakes in triage; quarantine instead of code change
+- Record attempt count in state file
+
+---
+
+## State Rot
+
+**Symptom**: `STATE.md` references merged PRs, closed tickets, or stale branches.
+
+**Severity**: S1 → S2 (loop acts on ghosts)
+
+**Causes**:
+- No prune step at end of run
+- State file not read at start
+- Multiple loops writing same file without schema
+
+**Mitigations**:
+- Prune closed/merged items every run
+- `Last run` timestamp + validate IDs against live API
+- One state file per loop pattern, or clear sections
+
+---
+
+## Verifier Theater
+
+**Symptom**: Verifier "approves" but tests fail in CI or review finds obvious bugs.
+
+**Severity**: S2
+
+**Causes**:
+- Verifier prompt too vague ("looks good")
+- Verifier doesn't run tests
+- Same model, same context as implementer
+
+**Mitigations**:
+- Verifier must run test/lint commands and report output
+- Different instructions: "find reasons to reject"
+- Stronger model on verifier for unattended loops
+
+---
+
+## Notification Fatigue
+
+**Symptom**: Slack/email pings every 5 minutes; team mutes the bot.
+
+**Severity**: S1 → S2 (real escalations missed)
+
+**Causes**:
+- Notify on every run, not every *actionable* finding
+- Low bar for "high priority" in triage skill
+
+**Mitigations**:
+- Notify only when human decision required
+- Digest mode for report-only loops
+- Tighten triage "High Priority" rules
+
+---
+
+## Token Burn
+
+**Symptom**: Bill spikes; loop runs full sub-agent chains on empty or noisy triage.
+
+**Severity**: S1
+
+**Causes**:
+- Sub-minute cadence with heavy sub-agents
+- No early exit when watchlist empty
+- Retrying entire pipeline on transient API errors
+
+**Mitigations**:
+- Cheaper triage-only pass first; spawn sub-agents only for actionable items
+- `scheduler_delete` when nothing to watch
+- Daily token budget → pause loop
+- See [operating-loops.md](./operating-loops.md)
+
+---
+
+## Over-Reach (Wrong Scope)
+
+**Symptom**: Loop refactors unrelated modules, "fixes" design issues, or touches denylisted paths.
+
+**Severity**: S2 → S3
+
+**Causes**:
+- minimal-fix skill too permissive
+- No path allowlist/denylist
+- Triage puts architectural work in "High Priority"
+
+**Mitigations**:
+- [safety.md](./safety.md) denylist enforced in skills
+- "Smallest possible diff" + verifier checks touched files
+- Triage skill: signal only, no invention
+
+---
+
+## Comprehension Debt Spiral
+
+**Symptom**: Velocity up, but no one can explain recent changes; review becomes rubber-stamp.
+
+**Severity**: S2 (long-term)
+
+**Causes**:
+- Human stops reading loop output
+- Auto-merge on growing allowlist
+- No weekly human synthesis of loop actions
+
+**Mitigations**:
+- Mandatory human review for non-trivial PRs
+- Weekly "loop digest" read by owner
+- Cap auto-merge to truly trivial paths
+
+---
+
+## Cognitive Surrender
+
+**Symptom**: "The loop handles it" — no opinions on correctness or design.
+
+**Severity**: S2 (cultural)
+
+**Causes**:
+- Loop success metric = volume, not quality
+- No human gates on medium-risk work
+
+**Mitigations**:
+- Explicit human gates in every pattern
+- Success metric: time saved *with* quality bar held
+- Osmani: "Build it like someone who intends to stay the engineer"
+
+---
+
+## Parallel Collision
+
+**Symptom**: Two sub-agents edit same files; merge conflicts; corrupted state.
+
+**Severity**: S2
+
+**Causes**:
+- No worktree isolation
+- Two loops acting on same PR without coordination
+
+**Mitigations**:
+- `isolation: worktree` for all code-editing sub-agents
+- Lock or queue in state: "PR #1234 — worktree in progress"
+
+---
+
+## Escalation Failure
+
+**Symptom**: Loop stuck retrying; human never notified.
+
+**Severity**: S2
+
+**Causes**:
+- Max attempts not implemented
+- Escalation only writes to state no one reads
+
+**Mitigations**:
+- Connector ping on escalation (Slack, Linear comment)
+- `High Priority (waiting on human)` section in STATE.md
+- Alert if item in that section >24h
+
+---
+
+## Contributing Failures
+
+Have a story? Add a row via PR to this doc or open an issue with:
+- Pattern name
+- Symptom
+- What mitigated it (or didn't)
\ No newline at end of file
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 0000000..70256a8
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,38 @@
+---
+layout: default
+title: Loop Engineering
+---
+
+# Loop Engineering
+
+**Design the system that prompts your agents — don't be the person prompting.**
+
+Practical reference for building reliable, tool-agnostic agent loops.
+
+## Start Here
+
+- [README](../README.md) — manifesto and quick start
+- [Primitives Matrix](./primitives-matrix.md) — Grok vs Claude Code vs Codex
+- [Loop Design Checklist](./loop-design-checklist.md) — ship readiness
+- [Patterns](../patterns/README.md) — copy-paste loop patterns
+
+## Deep Dives
+
+- [Concepts & Vocabulary](./concepts.md)
+- [The Five Primitives](./primitives.md)
+- [Failure Modes](./failure-modes.md)
+- [Operating Loops](./operating-loops.md)
+- [Safety & Guardrails](./safety.md)
+
+## Build
+
+- [Starters](../starters/) — cloneable kits
+- [Templates](../templates/) — skills and state schemas
+- [Examples](../examples/) — multi-tool implementations
+- [loop-audit](../tools/loop-audit/) — Loop Readiness Score CLI
+
+## Community
+
+- [Contributing](../CONTRIBUTING.md)
+- [Production Stories](../stories/)
+- [Sources](../resources/sources.md)
\ No newline at end of file
diff --git a/docs/loop-design-checklist.md b/docs/loop-design-checklist.md
new file mode 100644
index 0000000..3b85a85
--- /dev/null
+++ b/docs/loop-design-checklist.md
@@ -0,0 +1,95 @@
+# Loop Design Checklist
+
+Use this before enabling a loop in production. Score honestly — a loop missing verification is not ready for unattended runs.
+
+## 1. Purpose & Scope
+
+- [ ] **Single clear goal** — one sentence: what does this loop accomplish?
+- [ ] **Explicit non-goals** — what will this loop *not* do?
+- [ ] **Watched scope** — which repos, branches, PRs, or tickets?
+- [ ] **Phased rollout** — report-only first, then act on small wins?
+
+## 2. Scheduling
+
+- [ ] **Cadence chosen** — interval matches urgency (see pattern docs)
+- [ ] **Fire immediately** — first run on start, or wait for interval?
+- [ ] **Durable** — survives session/tool restart if needed?
+- [ ] **Off-hours behavior** — slower cadence or paused overnight?
+- [ ] **Self-cleanup** — `scheduler_delete` when watchlist empty?
+
+## 3. Skills
+
+- [ ] **Triage skill** exists with tight output format
+- [ ] **Action skills** (minimal-fix, etc.) match project conventions
+- [ ] **Skill descriptions** are boring and specific (good auto-triggering)
+- [ ] **Build/test commands** documented in skills or AGENTS.md
+
+## 4. Maker / Checker Split
+
+- [ ] **Implementer** and **verifier** are separate (agent, model, or instructions)
+- [ ] Implementer **cannot** mark its own work "done"
+- [ ] Verifier runs **tests** in isolation (worktree) before approving
+- [ ] `/goal` or equivalent uses a **fresh model** for stop condition (if applicable)
+
+## 5. State / Memory
+
+- [ ] **State file** or board schema documented
+- [ ] Loop **reads** prior state at start of every run
+- [ ] Loop **writes** outcomes, timestamps, last actions
+- [ ] **Prune** resolved/merged/closed items every run
+- [ ] Human overrides recorded in state
+
+## 6. Human Handoff
+
+- [ ] **Escalation triggers** explicit (max attempts, risk paths, ambiguity)
+- [ ] **Denylist paths** — auth, payments, secrets, infra (see [safety.md](./safety.md))
+- [ ] **Notification rule** — only ping human when action required
+- [ ] **Inbox** — where ambiguous items land (STATE.md section, Slack, Linear)
+
+## 7. Connectors (MCP)
+
+- [ ] Minimum permissions for connectors (read vs write)
+- [ ] Loop can **open/update PRs** or tickets if acting, not just suggest
+- [ ] Bot identity clear on PR comments (e.g. "Loop Engineering — PR Babysitter")
+
+## 8. Cost & Limits
+
+- [ ] **Token budget** estimated (see [operating-loops.md](./operating-loops.md))
+- [ ] **Max iterations** per item per run
+- [ ] **Max auto-PRs** per day (cleanup loops)
+- [ ] **Pause/kill** criteria defined
+
+## 9. Observability
+
+- [ ] **Log each run**: started, items found, actions taken, escalations
+- [ ] **Success metrics** chosen (see pattern docs)
+- [ ] Team can **inspect state file** without reading chat logs
+
+## 10. Safety
+
+- [ ] No auto-merge without explicit allowlist
+- [ ] Secrets/env files in denylist
+- [ ] Flake handling — don't "fix" intermittent tests with retries alone
+
+---
+
+## Readiness Levels
+
+| Level | Description | Checklist |
+|-------|-------------|-----------|
+| **L0 — Draft** | Documented intent only | §1 |
+| **L1 — Report** | Triage → state, no auto-action | §1–3, §5 |
+| **L2 — Assisted** | Small auto-fixes with verifier | §1–7 |
+| **L3 — Unattended** | Runs without you watching | All sections |
+
+Run `loop-audit` in `tools/loop-audit/` to get a numeric Loop Readiness Score for your project.
+
+## Quick Red Flags
+
+Stop and fix before continuing if:
+
+- Same PR has had >3 automated fix attempts without progress
+- Verifier is the same agent session as implementer
+- No state file — loop has amnesia every run
+- Notifications on every run regardless of findings
+- Auto-merge enabled without path allowlist
\ No newline at end of file
diff --git a/docs/operating-loops.md b/docs/operating-loops.md
new file mode 100644
index 0000000..4bd27bd
--- /dev/null
+++ b/docs/operating-loops.md
@@ -0,0 +1,116 @@
+# Operating Loops in Production
+
+Running a loop is operations work. This doc covers cost, logging, metrics, and when to pause or kill.
+
+## Token & Cost Budgeting
+
+Rough planning factors:
+
+| Factor | Impact |
+|--------|--------|
+| Cadence | Linear multiplier (5m vs 1d = 288× runs/day) |
+| Sub-agents per run | Each = full model + tool round-trips |
+| Context size | Large repos + full CI logs = expensive triage |
+| Verifier model | Stronger model on verifier = worth it for unattended |
+
+### Example Estimates (order of magnitude)
+
+Assume ~50k tokens per light triage run, ~200k per run with implementer + verifier:
+
+| Loop | Cadence | Runs/day | Rough daily tokens |
+|------|---------|----------|-------------------|
+| Daily triage (report only) | 1d | 1 | ~50k |
+| CI sweeper (light) | 15m | 96 | ~5M (if every run is full — **avoid**) |
+| PR babysitter | 5m | 288 | High — use early exit |
+
+**Best practice**: Triage pass is cheap; spawn sub-agents **only** when state says actionable. Empty watchlist → exit in <5k tokens.
+
+### Budget Rules
+
+```markdown
+## Loop Budget — Project X
+- Max tokens/day: 2M (adjust to your plan)
+- On exceed: pause schedulers, notify human
+- Max sub-agent spawns per run: 3
+```
+
+Encode in skill or scheduler prompt: "If no high-priority items, exit immediately."
+
+## Logging Each Run
+
+Minimum log entry (append to `loop-run-log.md` or structured JSON):
+
+```json
+{
+ "run_id": "2026-06-09T08:15:00Z",
+ "pattern": "daily-triage",
+ "duration_s": 45,
+ "items_found": 4,
+ "actions_taken": 1,
+ "escalations": 0,
+ "tokens_estimate": 52000,
+ "outcome": "success"
+}
+```
+
+Human-readable alternative in `STATE.md` footer:
+
+```markdown
+---
+Run log: 2026-06-09 08:15 | 4 findings | 1 worktree opened | 0 escalations
+```
+
+## Metrics Dashboard (Template)
+
+Track weekly in a spreadsheet or Notion:
+
+| Metric | PR Babysitter | Daily Triage | CI Sweeper |
+|--------|---------------|--------------|------------|
+| Runs | | | |
+| Actionable findings | | | |
+| Auto-fixes proposed | | | |
+| Human escalations | | | |
+| False positives | | | |
+| Mean time to human awareness | | | |
+| Token spend (est.) | | | |
+
+Pattern-specific success metrics are in each [pattern](../patterns/README.md).
+
+## When to Slow Down
+
+- Token budget >80% mid-week
+- False positive rate >30% on triage
+- Same item escalated 2+ times in 48h
+- Major release week — pause auto-fix loops, report-only
+
+## When to Pause
+
+- Production incident in progress (loop may fight hotfix)
+- Breaking schema migration underway
+- Key human reviewer OOO + auto-merge was enabled (don't)
+
+## When to Kill a Loop
+
+- Consistent S2 failures from [failure-modes.md](./failure-modes.md)
+- Cost > value for 2 consecutive weeks
+- Team mutes all notifications
+- Pattern replaced by event-driven alternative (e.g. CI Action only)
+
+**Kill checklist**:
+1. `scheduler_delete` / disable Automation / remove Action
+2. Archive state file with `status: retired`
+3. Post-mortem in `stories/` (optional but valuable)
+
+## Upgrade Path
+
+```
+Report-only (L1) → 1–2 weeks stable triage
+ ↓
+Small auto-wins (L2) → verifier + worktree + max attempts
+ ↓
+Connectors (L2+) → PRs/tickets updated automatically
+ ↓
+Unattended (L3) → only with denylist, budget, metrics, human gates
+```
+
+Never skip L1 for a new pattern on a production repo.
\ No newline at end of file
diff --git a/docs/primitives-matrix.md b/docs/primitives-matrix.md
new file mode 100644
index 0000000..d9af956
--- /dev/null
+++ b/docs/primitives-matrix.md
@@ -0,0 +1,63 @@
+# Primitives Matrix — Grok, Claude Code, Codex
+
+Tool-agnostic loop design: the **capability** is what matters, not the product name. This matrix maps each primitive to how it appears in three major agent environments.
+
+| Primitive | Job in the Loop | Grok Build TUI | Claude Code | Codex |
+|-----------|-----------------|----------------|-------------|-------|
+| **Automations / Scheduling** | Discovery + triage on a cadence | `/loop [interval] <prompt>`, `scheduler_create` / `scheduler_list` / `scheduler_delete` (`recurring`, `durable`, `fireImmediately`), `monitor` for streaming events | `/loop`, scheduled tasks, cron, hooks, GitHub Actions | [Automations tab](https://developers.openai.com/codex/app/automations): project, prompt, cadence, environment; Triage inbox |
+| **Run-until-done** | Keep working until a verifiable condition holds | Goal mode / explicit stopping conditions in loop prompts | `/goal` — separate model checks completion | `/goal` — pause/resume, verifiable stop condition |
+| **Worktrees** | Safe parallel execution | Subagents with `isolation: "worktree"`, background tasks | `git worktree`, `--worktree`, `isolation: worktree` on subagents | Built-in worktree per thread |
+| **Skills** | Persistent project knowledge | `SKILL.md` in `.grok/skills/` or `~/.grok/skills/`; invoked by name | `SKILL.md` in `.claude/skills/` or project skills | [Agent Skills](https://developers.openai.com/codex/skills) — `$name` or implicit match |
+| **Plugins & Connectors** | Reach into real tools | MCP servers via `CallMcpTool` | MCP servers + plugins | Connectors (MCP) + plugins for distribution |
+| **Sub-agents** | Maker / checker split | `Task` tool with `subagent_type`, worktree isolation | Task subagents in `.claude/agents/`, agent teams | Subagents as TOML in `.codex/agents/` |
+| **State / Memory** | Track what's done across runs | `STATE.md`, todos, durable scheduler state | `AGENTS.md`, progress files, Linear via MCP | Markdown or Linear via connector |
+
+## Scheduling Quick Reference
+
+| Use case | Grok | Claude Code | Codex |
+|----------|------|-------------|-------|
+| Every 5 minutes | `/loop 5m <prompt>` | `/loop 5m <prompt>` | Automation, 5m cadence |
+| Daily morning | `/loop 1d <prompt>` | Cron / `/loop 1d` | Automation, daily |
+| Until tests pass | Loop + verifier sub-agent | `/goal all tests pass` | `/goal` |
+| Survive restart | `scheduler_create` with `durable: true` | Hooks + persisted config | Automation (server-side) |
+| Event-driven (CI fail) | `monitor` or GitHub Action | GitHub Action + webhook | Automation + webhook |
+
+## Skill Packaging
+
+| Concept | Grok | Claude Code | Codex |
+|---------|------|-------------|-------|
+| Authoring format | `SKILL.md` + optional scripts/references | Same | Same |
+| Distribution | Copy to `.grok/skills/` or user skills dir | Plugin / copy to project | Plugin bundle |
+| Invocation | Skill name in prompt or auto-match on description | `$skill-name` or implicit | `$skill-name` |
+
+## Sub-agent Patterns
+
+| Split | When to use | Grok | Claude Code | Codex |
+|-------|-------------|------|-------------|-------|
+| Implementer → Verifier | Any unattended code change | `Task` + different instructions/model | `.claude/agents/reviewer.md` | TOML agent with higher `reasoning_effort` |
+| Explorer → Implementer | Large unfamiliar codebase | `explore` subagent_type | Explorer agent | Fast read-only subagent |
+| Triage only | Report-first loops | `loop-triage` skill | `$loop-triage` | Automation calls skill |
+
+## State Conventions
+
+Recommended filenames (pick one spine per project):
+
+| File | Purpose |
+|------|---------|
+| `STATE.md` | General loop memory (daily triage) |
+| `pr-babysitter-state.md` | PR-specific watcher state |
+| `ci-sweeper-state.md` | Active CI failures + attempt counts |
+| `post-merge-state.md` | Cleanup backlog from recent merges |
+
+Linear / GitHub Projects work equally well — the loop must **read and write** the same store every run.
+
+## Choosing a Tool
+
+You do not need to pick one forever. A well-designed loop transfers:
+
+1. Write the **skill** (tool-agnostic `SKILL.md`)
+2. Define the **state schema** (markdown or JSON)
+3. Document the **verification split** (who checks whom)
+4. Map scheduling to your current TUI or Action
+
+See [examples/](../examples/) for the same pattern implemented across tools.
\ No newline at end of file
diff --git a/docs/safety.md b/docs/safety.md
new file mode 100644
index 0000000..a5563b7
--- /dev/null
+++ b/docs/safety.md
@@ -0,0 +1,96 @@
+# Safety & Guardrails
+
+Loops amplify judgment — good and bad. These guardrails are minimum bar for production loops that touch code or external systems.
+
+## Path Denylist
+
+The loop must **never** auto-edit these without human approval:
+
+```
+.env
+.env.*
+**/secrets/**
+**/credentials/**
+**/*_key*
+**/*_secret*
+.terraform/**
+k8s/production/**
+**/migrations/** # unless explicit migration loop
+auth/**
+payments/**
+billing/**
+```
+
+Encode in `minimal-fix` and implementer skills:
+
+> Do not modify files matching the denylist. Escalate to human with context.
+
+## Auto-Merge Policy
+
+**Default: no auto-merge.**
+
+If you allow auto-merge for trivial loops:
+
+| Allowed | Not allowed |
+|---------|-------------|
+| Typo in comment/docs | Behavior changes |
+| Lint auto-fix in test files only | Dependency version bumps |
+| Import ordering | Lockfile changes |
+| Config in allowlisted `docs/` paths | Any denylist path |
+
+Document allowlist in `AGENTS.md` or a dedicated `loop-auto-merge-allowlist.md`.
+
+## MCP Connector Least Privilege
+
+| Connector | Read | Write |
+|-----------|------|-------|
+| GitHub | issues, PRs, checks | comment, label (not merge by default) |
+| Linear | team issues | comment, status (not delete) |
+| Slack | channel history | post to `#loop-escalations` only |
+| Database | — | no production write from loops |
+
+Use separate bot accounts / tokens with minimal scopes.
+
+## Human Gates (Required)
+
+Always require human for:
+
+- Security, authentication, authorization
+- Payments, billing, PII handling
+- Infrastructure / Terraform / K8s prod
+- Dependency upgrades (supply chain risk)
+- Changes touching >N files (suggest N=10)
+- Third attempt failed on same item
+
+## Secrets in Prompts & Logs
+
+- Never paste API keys into scheduler prompts
+- CI logs may contain secrets — triage skill should redact before state write
+- State files are often committed — no credentials in `STATE.md`
+
+## Flake & Test Safety
+
+- Do not disable tests to make CI green
+- Do not increase timeouts blindly without root-cause note
+- Quarantine flakes via explicit ticket + human approval
+
+## Incident Response
+
+If a loop merges bad code:
+
+1. Pause all loops immediately (`scheduler_list` → delete)
+2. Revert merge
+3. Record in state + `stories/`
+4. Tighten verifier or shrink scope before restart
+
+## Pre-Flight Safety Check
+
+Before L3 (unattended):
+
+- [ ] Denylist in skills
+- [ ] Auto-merge off or strict allowlist
+- [ ] Connector scopes reviewed
+- [ ] Human gates documented in pattern
+- [ ] Kill switch documented ([operating-loops.md](./operating-loops.md))
+
+See also [loop-design-checklist.md](./loop-design-checklist.md).
\ No newline at end of file
diff --git a/examples/README.md b/examples/README.md
new file mode 100644
index 0000000..a6c4c06
--- /dev/null
+++ b/examples/README.md
@@ -0,0 +1,12 @@
+# Examples
+
+Same patterns, different tools. Skills and state schemas are shared; only scheduling and invocation differ.
+
+| Tool | Directory |
+|------|-----------|
+| Grok Build TUI | [grok/](./grok/) |
+| Claude Code | [claude-code/](./claude-code/) |
+| Codex App | [codex/](./codex/) |
+| GitHub Actions | [github-actions/](./github-actions/) |
+
+Start with [primitives-matrix.md](../docs/primitives-matrix.md) to map capabilities.
\ No newline at end of file
diff --git a/examples/claude-code/daily-triage.md b/examples/claude-code/daily-triage.md
new file mode 100644
index 0000000..764533b
--- /dev/null
+++ b/examples/claude-code/daily-triage.md
@@ -0,0 +1,40 @@
+# Daily Triage — Claude Code
+
+Same pattern as Grok; different scheduling primitives.
+
+## Report-Only (Week 1)
+
+```bash
+/loop 1d Run $loop-triage. Read STATE.md. Merge findings into High Priority and Watch List. Update Last run. Do not edit code.
+```
+
+## With Small Auto-Fixes (Week 3+)
+
+```bash
+/loop 1d Run $loop-triage. For high-priority items that are single-file bugfixes: spawn implementer in worktree, then verifier agent. Update STATE.md. Escalate ambiguous items.
+```
+
+## Skills Setup
+
+Copy from `templates/SKILL.md.loop-triage` to `.claude/skills/loop-triage/SKILL.md` (or project skills path per your Claude Code version).
+
+## Sub-agents
+
+Create `.claude/agents/loop-verifier.md` from `templates/SKILL.md.verifier` frontmatter + body.
+
+Use `isolation: worktree` when spawning implementer tasks.
+
+## Goal Mode Alternative
+
+For a one-shot "get main green" session:
+
+```bash
+/goal All tests on main pass and lint is clean
+```
+
+`/goal` uses a fresh model to check the stop condition — maker/checker at the goal layer.
+
+## References
+
+- Boris Cherny: `/loop 30m /slack-feedback`, daily triage automations
+- [primitives-matrix.md](../../docs/primitives-matrix.md)
\ No newline at end of file
diff --git a/examples/claude-code/pr-babysitter.md b/examples/claude-code/pr-babysitter.md
new file mode 100644
index 0000000..a7d7bfd
--- /dev/null
+++ b/examples/claude-code/pr-babysitter.md
@@ -0,0 +1,28 @@
+# PR Babysitter — Claude Code
+
+## Command
+
+```bash
+/loop 5m /babysit
+```
+
+Or explicit (matches this repo's pattern):
+
+```bash
+/loop 5m For each open PR I care about: triage CI and reviews. Propose minimal fixes in worktree. Verifier agent must approve before commenting. Update pr-babysitter-state.md. Max 3 attempts per PR.
+```
+
+## With /goal on a Single PR
+
+```bash
+/goal PR #1234 has green CI, no blocking review comments, and is rebased on main
+```
+
+## State
+
+Use `pr-babysitter-state.md` from `starters/pr-babysitter/`.
+
+## Notes
+
+- Combine with hooks for pre-commit checks if the loop edits locally
+- GitHub Actions can complement `/loop` when laptop is closed
\ No newline at end of file
diff --git a/examples/codex/daily-triage.md b/examples/codex/daily-triage.md
new file mode 100644
index 0000000..b10ab8a
--- /dev/null
+++ b/examples/codex/daily-triage.md
@@ -0,0 +1,48 @@
+# Daily Triage — Codex App
+
+## Automation Setup
+
+In the Codex **Automations** tab:
+
+| Field | Value |
+|-------|--------|
+| Project | Your repo checkout |
+| Cadence | Daily (e.g. 08:00 local) |
+| Environment | Local or background worktree |
+| Prompt | See below |
+
+## Prompt
+
+```
+Run $loop-triage on this project. Read STATE.md if present.
+
+Append to STATE.md:
+- High-Priority Items → "## High Priority" section
+- Watch Items → "## Watch List"
+- Update "Last run" timestamp
+
+Week 1: report only. Do not modify source files.
+
+Flag anything ambiguous for the Triage inbox.
+```
+
+## Skills
+
+Install `loop-triage` per [Codex Agent Skills](https://developers.openai.com/codex/skills) — same `SKILL.md` format as `templates/SKILL.md.loop-triage`.
+
+## Phase 2 — Action
+
+Add to prompt:
+
+```
+For high-priority single-file bugfixes only: draft fix in isolated worktree.
+Spawn verifier subagent (stronger model) before proposing PR.
+```
+
+Define verifier in `.codex/agents/verifier.toml`.
+
+## Triage Inbox
+
+Runs with findings land in Codex Triage inbox — review there + `STATE.md`.
+
+Empty runs archive automatically (built-in behavior).
\ No newline at end of file
diff --git a/examples/codex/pr-babysitter.md b/examples/codex/pr-babysitter.md
new file mode 100644
index 0000000..0de45a2
--- /dev/null
+++ b/examples/codex/pr-babysitter.md
@@ -0,0 +1,38 @@
+# PR Babysitter — Codex App
+
+## Automation
+
+| Field | Value |
+|-------|--------|
+| Cadence | Every 5–15 minutes (working hours) |
+| Prompt | `$pr-review-triage` + update state + conditional fix flow |
+
+## Prompt Template
+
+```
+For open PRs on this repo (team-authored or label loop-watch):
+
+1. Run $pr-review-triage
+2. Update pr-babysitter-state.md
+3. If CI red or actionable review comment AND attempts < 3:
+ - Open worktree
+ - Implementer: $minimal-fix
+ - Verifier subagent: must APPROVE
+ - Comment on PR with proposal — do not merge
+4. If attempts >= 3 or high-risk labels: Triage inbox + escalate
+```
+
+## Subagents (`.codex/agents/`)
+
+```toml
+# verifier.toml — example structure
+name = "verifier"
+description = "Rejects loop fixes unless tests pass and scope is minimal"
+instructions = "See templates/SKILL.md.verifier"
+model = "strongest-available"
+reasoning_effort = "high"
+```
+
+## Connectors
+
+Use GitHub MCP connector to list PRs, read checks, and post comments.
\ No newline at end of file
diff --git a/examples/github-actions/README.md b/examples/github-actions/README.md
new file mode 100644
index 0000000..a756982
--- /dev/null
+++ b/examples/github-actions/README.md
@@ -0,0 +1,33 @@
+# GitHub Actions Examples
+
+Event-driven and scheduled loops **without** a TUI session. These workflows:
+
+1. Gather context (CI, merges, failures)
+2. Update state files
+3. **Delegate** to your agent harness in the "Invoke agent" step
+
+## Wiring Your Agent
+
+Replace the placeholder `run:` steps with one of:
+
+| Approach | When |
+|----------|------|
+| Codex CLI / API | Headless Codex in CI |
+| `repository_dispatch` | External runner with Grok/Claude |
+| Custom script | Rule-based triage only (L0) |
+
+The state file schema and skills are tool-agnostic — only the invocation step differs.
+
+## Workflows
+
+| File | Trigger | Pattern |
+|------|---------|---------|
+| [daily-triage.yml](./daily-triage.yml) | Cron weekdays | Daily Triage |
+| [ci-sweeper.yml](./ci-sweeper.yml) | `workflow_run` failure | CI Sweeper |
+| [post-merge-cleanup.yml](./post-merge-cleanup.yml) | Push to main + nightly | Post-Merge Cleanup |
+
+## Security
+
+- Use `GITHUB_TOKEN` with minimum permissions
+- No secrets in workflow logs
+- See [safety.md](../../docs/safety.md)
\ No newline at end of file
diff --git a/examples/github-actions/ci-sweeper.yml b/examples/github-actions/ci-sweeper.yml
new file mode 100644
index 0000000..bce0382
--- /dev/null
+++ b/examples/github-actions/ci-sweeper.yml
@@ -0,0 +1,43 @@
+# CI Sweeper — event-driven on workflow failure
+
+name: CI Sweeper Loop
+
+on:
+ workflow_run:
+ workflows: ['*']
+ types: [completed]
+ branches: [main]
+
+permissions:
+ contents: read
+ pull-requests: write
+ checks: read
+
+jobs:
+ sweep:
+ if: ${{ github.event.workflow_run.conclusion == 'failure' }}
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Record failure context
+ run: |
+ echo "Failed workflow: ${{ github.event.workflow_run.name }}"
+ echo "Head branch: ${{ github.event.workflow_run.head_branch }}"
+ echo "Run URL: ${{ github.event.workflow_run.html_url }}"
+
+ - name: Update ci-sweeper-state.md
+ run: |
+ FILE=ci-sweeper-state.md
+ touch "$FILE"
+ echo "" >> "$FILE"
+ echo "### $(date -u +%Y-%m-%dT%H:%M:%SZ) — workflow failure" >> "$FILE"
+ echo "- Workflow: ${{ github.event.workflow_run.name }}" >> "$FILE"
+ echo "- Branch: ${{ github.event.workflow_run.head_branch }}" >> "$FILE"
+ echo "- URL: ${{ github.event.workflow_run.html_url }}" >> "$FILE"
+ echo "- Loop action: pending agent invocation" >> "$FILE"
+
+ - name: Invoke fix agent
+ run: |
+ echo "::notice::Wire to agent: classify failure, worktree fix, verifier, open PR."
+ echo "See patterns/ci-sweeper.md and docs/safety.md"
\ No newline at end of file
diff --git a/examples/github-actions/daily-triage.yml b/examples/github-actions/daily-triage.yml
new file mode 100644
index 0000000..3dc46f9
--- /dev/null
+++ b/examples/github-actions/daily-triage.yml
@@ -0,0 +1,54 @@
+# Daily Triage — GitHub Actions (tool-agnostic trigger)
+# Invokes your agent harness with a triage prompt. Adapt the "Run agent" step
+# to your setup (Codex CLI, custom script, repository_dispatch to external runner).
+
+name: Daily Triage Loop
+
+on:
+ schedule:
+ - cron: '0 8 * * 1-5' # 08:00 UTC Mon–Fri
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ issues: read
+ pull-requests: read
+ checks: read
+
+jobs:
+ triage:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Gather CI context
+ id: ci
+ run: |
+ echo "Recent workflow runs available via gh api"
+ gh run list --limit 10 --json conclusion,name,headBranch,createdAt 2>/dev/null || true
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Ensure STATE.md exists
+ run: |
+ if [ ! -f STATE.md ]; then
+ cp starters/minimal-loop/STATE.md.example STATE.md 2>/dev/null || \
+ echo "# Loop State\n\nLast run: never\n\n## High Priority\n\n## Watch List\n" > STATE.md
+ fi
+
+ # Replace this step with your agent invocation:
+ # - Codex CLI in headless mode
+ # - repository_dispatch to a machine running Grok/Claude
+ # - Custom triage script that updates STATE.md
+ - name: Run triage agent
+ run: |
+ echo "::notice::Wire this step to your agent harness."
+ echo "Prompt: Run loop-triage skill. Update STATE.md. Report only unless L2 enabled."
+ echo "See examples/github-actions/README.md"
+
+ - name: Upload state artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: loop-state
+ path: STATE.md
+ if-no-files-found: ignore
\ No newline at end of file
diff --git a/examples/github-actions/post-merge-cleanup.yml b/examples/github-actions/post-merge-cleanup.yml
new file mode 100644
index 0000000..e38fd38
--- /dev/null
+++ b/examples/github-actions/post-merge-cleanup.yml
@@ -0,0 +1,35 @@
+# Post-Merge Cleanup — trigger on push to main
+
+name: Post-Merge Cleanup Loop
+
+on:
+ push:
+ branches: [main]
+ schedule:
+ - cron: '0 22 * * *' # nightly aggregate sweep
+
+permissions:
+ contents: read
+ pull-requests: read
+
+jobs:
+ cleanup-scan:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 50
+
+ - name: List recent merges
+ run: |
+ git log --merges -10 --oneline || git log -10 --oneline
+
+ - name: Scan for cleanup signals
+ run: |
+ echo "Scanning for TODO/remove after/deprecated in recent diff..."
+ git diff HEAD~5..HEAD 2>/dev/null | grep -E 'TODO|FIXME|remove after|deprecated' || true
+
+ - name: Update post-merge-state.md
+ run: |
+ echo "Append findings to post-merge-state.md — wire agent for auto-fix of small items."
+ echo "See patterns/post-merge-cleanup.md"
\ No newline at end of file
diff --git a/examples/grok/README.md b/examples/grok/README.md
new file mode 100644
index 0000000..a8a90b9
--- /dev/null
+++ b/examples/grok/README.md
@@ -0,0 +1,19 @@
+# Grok Build TUI Examples
+
+Native primitives: `/loop`, `scheduler_create`, worktree isolation, skills, MCP, sub-agents.
+
+| Example | Pattern |
+|---------|---------|
+| [daily-triage.md](./daily-triage.md) | Daily Triage |
+
+## Common Commands
+
+```bash
+/loop 5m /pr-babysit check
+/loop 1d Run loop-triage and update STATE.md
+/loop 15m Check CI on main — see patterns/ci-sweeper.md
+```
+
+Background tasks: `Ctrl+G` demote, queue pane `Ctrl+;`.
+
+See [docs/primitives-matrix.md](../../docs/primitives-matrix.md).
\ No newline at end of file
diff --git a/patterns/README.md b/patterns/README.md
index bfefe3f..9e61831 100644
--- a/patterns/README.md
+++ b/patterns/README.md
@@ -1,6 +1,6 @@
# Loop Patterns
-This directory contains documented, reusable loop patterns that have been (or can be) run in real environments.
+Documented, reusable loop patterns that have been (or can be) run in real environments.
Each pattern answers:
- What problem it solves
@@ -8,19 +8,30 @@ Each pattern answers:
- Required skills / state shape
- Verification approach
- Human hand-off strategy
-- Tool-specific notes (Grok, Claude Code, etc.)
+- Tool-specific notes (Grok, Claude Code, Codex, GitHub Actions)
-## Current Patterns
+## Pattern Registry
-- [pr-babysitter.md](./pr-babysitter.md) — Shepherd PRs from draft through review, CI, rebase, and merge.
-- (More coming — contributions welcome)
+| Pattern | Cadence | Risk | File |
+|---------|---------|------|------|
+| PR Babysitter | 5–15m | Medium | [pr-babysitter.md](./pr-babysitter.md) |
+| Daily Triage | 1d–2h | Low | [daily-triage.md](./daily-triage.md) |
+| CI Sweeper | 5–15m | Medium | [ci-sweeper.md](./ci-sweeper.md) |
+| Post-Merge Cleanup | 1d–6h | Low | [post-merge-cleanup.md](./post-merge-cleanup.md) |
+
+Machine-readable index: [registry.yaml](./registry.yaml)
## How to Use a Pattern
-1. Copy the relevant skill(s) into your project (or publish as a plugin).
-2. Set up the scheduling command (`/loop`, `scheduler_create`, GitHub Action, etc.).
-3. Create the initial state file or Linear board view.
-4. Start the loop.
-5. Iterate on the loop definition based on what actually happens.
+1. Copy the relevant skill(s) from `templates/` into your project (or publish as a plugin).
+2. Copy a starter kit from `starters/` if you want a runnable scaffold.
+3. Set up scheduling (`/loop`, `scheduler_create`, GitHub Action, Codex Automation).
+4. Create the initial state file.
+5. Start the loop — **report-only first** when the pattern supports phased rollout.
+6. Iterate on the loop definition based on what actually happens.
Good loops are boring and reliable. Start with one that runs every few hours or daily before going to sub-minute cadences.
+
+## Contributing a Pattern
+
+See [CONTRIBUTING.md](../CONTRIBUTING.md) and [templates/pattern-template.md](../templates/pattern-template.md).
\ No newline at end of file
diff --git a/patterns/ci-sweeper.md b/patterns/ci-sweeper.md
new file mode 100644
index 0000000..c4eb6e0
--- /dev/null
+++ b/patterns/ci-sweeper.md
@@ -0,0 +1,102 @@
+# CI Sweeper Loop
+
+**Goal**: React quickly to failing CI on main or active branches — diagnose, propose minimal fixes, and escalate when the loop cannot confidently resolve.
+
+## Scheduling
+
+**Recommended**:
+- `/loop 15m` during active development (Grok, Claude Code)
+- `/loop 5m` when main is red and you're shipping
+- GitHub Action on `workflow_run` failure (event-driven, not polling)
+
+Slower overnight cadence (30–60m) is fine when no one is watching.
+
+## Required Skills
+
+- `ci-triage` — Parse CI logs, identify failing job/step, classify failure type (flake, regression, env, config)
+- `minimal-fix` — Smallest change that addresses the specific failure
+- Project test/lint skill — Build and test commands for your stack
+
+## State
+
+`ci-sweeper-state.md` or section in `STATE.md`:
+
+```markdown
+## CI Sweeper — Active Failures
+
+Last run: 2026-06-09 14:30 UTC
+
+### main @ abc1234
+- Job: test-auth
+- Failure: AssertionError in test_refresh_token_expiry
+- Attempts: 1/3
+- Last action: Minimal fix proposed in worktree fix/ci-auth-refresh
+- Status: Waiting for verifier + human
+
+### Resolved (last 7d)
+- main @ def5678 — lint fix merged via PR #1250
+```
+
+Track: commit SHA, failing job, attempt count, worktree/PR link, outcome.
+
+## How the Loop Runs (Typical Cycle)
+
+1. Discover CI failures on watched branches (main, release/*, active PRs).
+2. For each new failure:
+ - Classify: flake vs real regression vs infra.
+ - If flake (seen before, intermittent): add to Watch, do not auto-fix.
+ - If actionable: open worktree → implementer drafts fix.
+3. Verifier sub-agent checks: fix addresses failure, no unrelated changes, tests pass locally.
+4. Open PR or comment on existing PR with proposed fix.
+5. If attempts exceed max (e.g. 3): escalate to human with full context.
+6. Prune resolved failures from active list.
+
+## Verification Strategy
+
+- Verifier must run tests in the worktree before approving.
+- Implementer cannot merge — only propose.
+- Flake detection: if same test failed and passed on retry without code change, do not auto-fix.
+
+## Human Handoff Points
+
+- Infrastructure failures (runner OOM, registry down, secrets missing)
+- Failures touching >5 files or core architecture
+- Security-sensitive test failures
+- Max attempts exceeded on same failure
+- Intermittent flakes that need quarantine, not code changes
+
+## Tool-Specific Notes
+
+**Grok Build TUI**:
+```bash
+/loop 15m Check CI on main and open PRs. For new failures: classify, and if actionable draft minimal fix in worktree with verifier. Update ci-sweeper-state.md. Escalate after 3 attempts.
+```
+
+**Claude Code**:
+```bash
+/goal All tests on main pass and lint is clean
+```
+Use `/goal` for focused "get green" sessions; use scheduled sweeper for ongoing monitoring.
+
+**Codex**:
+- Automation: "Summarise CI failures every 30m" → Triage inbox; separate automation for fix attempts.
+
+**GitHub Actions**:
+- See `examples/github-actions/ci-sweeper.yml` — triggers on workflow failure.
+
+## Failure Modes & Mitigations
+
+| Failure | Mitigation |
+|---------|------------|
+| Fix-the-symptom loops | Verifier checks root cause, not just green CI |
+| Fighting flakes with retries | Classify flakes; quarantine or skip with ticket |
+| Token burn on red main | Pause loop after N failures; batch fixes |
+| Wrong branch targeted | Explicit branch allowlist in skill |
+
+## Success Metrics
+
+- Mean time to first proposed fix after CI goes red
+- % of failures resolved without human intervention (trivial cases only)
+- Repeat failure rate (same job failing again within 48h)
+
+Best entry loop for teams new to loop engineering — high frequency, bounded scope, clear verification.
\ No newline at end of file
diff --git a/patterns/daily-triage.md b/patterns/daily-triage.md
new file mode 100644
index 0000000..87f5b5b
--- /dev/null
+++ b/patterns/daily-triage.md
@@ -0,0 +1,100 @@
+# Daily Triage Loop
+
+**Goal**: Start each day (or active period) with a prioritized, actionable picture of what needs attention — without manually checking CI, issues, PRs, and chat.
+
+## Scheduling
+
+**Recommended**:
+- `/loop 1d` for morning triage (Grok, Claude Code)
+- `/loop 2h` during active sprints for faster signal
+- GitHub Action cron `0 8 * * 1-5` for teams without a TUI
+
+Many teams run triage-only first (reporting, no auto-fix) for 1–2 weeks before enabling action.
+
+## Required Skills
+
+- `loop-triage` — Reads CI, issues, commits, chat; produces prioritized findings (see `templates/SKILL.md.loop-triage`)
+- `minimal-fix` (optional, phase 2) — Drafts small fixes for obvious failures
+- Reviewer sub-agent or skill (optional, phase 2) — Verifies proposed fixes
+
+## State
+
+Use `STATE.md` (or a Linear board view) as the memory spine:
+
+```markdown
+# Loop State — Project X
+
+Last run: 2026-06-09 08:15 UTC
+
+## High Priority (loop is acting or waiting on human)
+- [ ] #1241 — flaky test in auth flow (CI red on main)
+ Loop action: Opened worktree. Fix proposed. Waiting for human PR review.
+
+## Watch List
+- PR #1238 open 4 days with no activity.
+
+## Recent Noise (ignored this run)
+- Dependabot PRs (separate automation)
+```
+
+Fields the loop must update every run:
+- `Last run` timestamp
+- Item status + last action taken
+- Human decisions that overrode the loop
+
+## How the Loop Runs (Typical Cycle)
+
+1. Scheduler fires (morning or interval).
+2. Triage skill ingests: CI failures (24h), open issues/tickets, recent commits, prior `STATE.md`.
+3. High-priority items appended to state with suggested next action.
+4. (Phase 2) For small, self-contained failures: open worktree → implementer → verifier.
+5. (Phase 3) Connectors update PRs/tickets; ambiguous items flagged for human.
+6. Prune resolved/merged items from state.
+
+## Verification Strategy
+
+- Phase 1 (report-only): Human reads `STATE.md` — no auto-action verification needed.
+- Phase 2+: Never let implementer mark work done; verifier confirms fix scope and tests.
+- Triage skill must not invent architectural work — signal only.
+
+## Human Handoff Points
+
+- Design decisions or multi-file refactors
+- Security, auth, payments, infrastructure
+- Items flagged "needs discussion" in triage output
+- Anything the loop has surfaced 3+ days without resolution
+
+## Tool-Specific Notes
+
+**Grok Build TUI**:
+```bash
+/loop 1d Run the loop-triage skill. Append high-priority items to STATE.md. For obvious small bugfixes only: worktree + minimal-fix + reviewer sub-agent. Flag ambiguous items for human review.
+```
+
+**Claude Code**:
+```bash
+/loop 1d Run $loop-triage and update STATE.md. Do not auto-fix on first week — report only.
+```
+
+**Codex**:
+- Automations tab: daily prompt calling `$loop-triage`, output to Triage inbox + `STATE.md`.
+
+**GitHub Actions**:
+- See `examples/github-actions/daily-triage.yml`.
+
+## Failure Modes & Mitigations
+
+| Failure | Mitigation |
+|---------|------------|
+| Triage creates noise | Tighten skill rules; add "Noise / Ignore" section |
+| State file grows unbounded | Prune merged/closed items every run |
+| Auto-fix on wrong priority | Start report-only; add explicit effort/risk gates |
+| Missed overnight failures | Add `fireImmediately: true` or run at start of day + mid-day |
+
+## Success Metrics
+
+- Time from "something broke" to "human knows about it"
+- % of mornings where `STATE.md` matched what you'd have found manually
+- Reduction in ad-hoc "what's on fire?" Slack messages
+
+Start report-only. Add action only when triage quality is consistently good.
\ No newline at end of file
diff --git a/patterns/post-merge-cleanup.md b/patterns/post-merge-cleanup.md
new file mode 100644
index 0000000..add5c8c
--- /dev/null
+++ b/patterns/post-merge-cleanup.md
@@ -0,0 +1,100 @@
+# Post-Merge Cleanup Loop
+
+**Goal**: After merges to main, sweep for follow-up work — deprecations, TODOs, tech debt tickets, stale feature flags, and documentation gaps — without blocking the merge itself.
+
+## Scheduling
+
+**Recommended**:
+- `/loop 1d` or `/loop 6h` (lower urgency than CI sweeper)
+- Trigger on merge events via GitHub webhook → Action (event-driven)
+- Weekly cron for smaller teams
+
+Run after working hours or overnight so it doesn't compete with active development loops.
+
+## Required Skills
+
+- `post-merge-scan` — Read recent merges, diff summaries, linked tickets; identify cleanup opportunities
+- `minimal-fix` — Small follow-ups (remove dead code, update deprecation notices, fix broken links in docs)
+- Project conventions skill — What "cleanup" means in your repo
+
+## State
+
+`post-merge-state.md`:
+
+```markdown
+# Post-Merge Cleanup
+
+Last run: 2026-06-09 22:00 UTC
+
+## Pending Cleanup (from recent merges)
+- [ ] PR #1245 merged — remove `legacyAuth` flag (marked TODO in merge)
+ Source: commit abc1234, line 42 in auth/handler.ts
+ Risk: low | Effort: small
+- [ ] PR #1240 merged — update API docs for new endpoint
+ Risk: low | Effort: small
+
+## Completed (last 14d)
+- PR #1230 — removed unused import cluster (PR #1248)
+
+## Deferred (human decision)
+- PR #1238 — large refactor deferred; ticket ENG-1001 created
+```
+
+## How the Loop Runs (Typical Cycle)
+
+1. List merges to main since last run (or last N days).
+2. For each merge: scan diff for TODOs, deprecations, `// remove after`, feature flags, broken doc links.
+3. Cross-reference linked Linear/GitHub issues for explicit follow-ups.
+4. Prioritize: small + low-risk → propose fix in worktree; large → create ticket + flag human.
+5. Verifier confirms cleanup doesn't change behavior (except intentional removals).
+6. Open small PRs or batch into a single "cleanup" PR per day.
+7. Update state; prune completed items.
+
+## Verification Strategy
+
+- Cleanup must not alter behavior unless explicitly removing dead code paths.
+- Verifier runs full test suite — regressions mean immediate handoff.
+- No auto-merge for cleanup PRs touching >10 files without human approval.
+
+## Human Handoff Points
+
+- Architectural debt requiring design discussion
+- Feature flag removal that affects production config
+- Deprecations with external API consumers
+- Any cleanup the loop has attempted twice without passing tests
+
+## Tool-Specific Notes
+
+**Grok Build TUI**:
+```bash
+/loop 1d Scan merges to main in the last 24h. Identify cleanup items. For small low-risk items: worktree + minimal fix + verifier. Update post-merge-state.md. Create tickets for larger items.
+```
+
+**Claude Code**:
+```bash
+/loop 6h /post-merge-sweeper
+```
+(Boris Cherny has described similar flows in the community.)
+
+**Codex**:
+- Automation: "Post-merge sweeper" on daily cadence, results to Triage inbox.
+
+**GitHub Actions**:
+- See `examples/github-actions/post-merge-cleanup.yml` — triggers on push to main.
+
+## Failure Modes & Mitigations
+
+| Failure | Mitigation |
+|---------|------------|
+| Over-aggressive deletion | Verifier + "no behavior change" rule; human gate for large diffs |
+| Missing merges | Use GitHub API merge list, not just local git log |
+| Noise from every TODO | Only act on TODOs with merge context or linked tickets |
+| Competing with feature work | Run off-peak; cap auto-PRs per day (e.g. 2) |
+
+## Success Metrics
+
+- Reduction in "we forgot to remove X after merge" incidents
+- Age of open post-merge cleanup items
+- % of cleanup PRs merged without review comments
+
+Lower risk than CI sweeper — good second loop after daily triage is stable.
\ No newline at end of file
diff --git a/patterns/registry.yaml b/patterns/registry.yaml
new file mode 100644
index 0000000..feb86de
--- /dev/null
+++ b/patterns/registry.yaml
@@ -0,0 +1,51 @@
+# Machine-readable pattern registry for loop-engineering
+# Used by loop-audit, docs site, and future tooling.
+
+patterns:
+ - id: pr-babysitter
+ name: PR Babysitter
+ file: pr-babysitter.md
+ goal: Shepherd PRs through review, CI, rebase, and merge
+ cadence: 5m-15m
+ risk: medium
+ tools: [grok, claude-code, codex, github-actions]
+ skills: [pr-review-triage, minimal-fix, rebase-and-clean]
+ state: pr-babysitter-state.md
+ phases: [discover, triage, fix, verify, notify]
+ human_gates: [security, payments, auth, max-fix-attempts]
+
+ - id: daily-triage
+ name: Daily Triage
+ file: daily-triage.md
+ goal: Prioritized morning scan of CI, issues, commits, and chat
+ cadence: 1d-2h
+ risk: low
+ tools: [grok, claude-code, codex, github-actions]
+ skills: [loop-triage, minimal-fix]
+ state: STATE.md
+ phases: [report, act-small-wins, escalate]
+ human_gates: [design-decisions, multi-file-refactors]
+
+ - id: ci-sweeper
+ name: CI Sweeper
+ file: ci-sweeper.md
+ goal: React to failing CI with minimal fixes and escalation
+ cadence: 5m-15m
+ risk: medium
+ tools: [grok, claude-code, codex, github-actions]
+ skills: [ci-triage, minimal-fix]
+ state: ci-sweeper-state.md
+ phases: [detect, classify, fix, verify, escalate]
+ human_gates: [infra-failures, max-attempts, security-tests]
+
+ - id: post-merge-cleanup
+ name: Post-Merge Cleanup
+ file: post-merge-cleanup.md
+ goal: Follow-up tech debt and cleanup after merges to main
+ cadence: 1d-6h
+ risk: low
+ tools: [grok, claude-code, codex, github-actions]
+ skills: [post-merge-scan, minimal-fix]
+ state: post-merge-state.md
+ phases: [scan-merges, prioritize, fix-small, ticket-large]
+ human_gates: [architectural-debt, feature-flags, large-diffs]
\ No newline at end of file
diff --git a/starters/README.md b/starters/README.md
new file mode 100644
index 0000000..7d0b334
--- /dev/null
+++ b/starters/README.md
@@ -0,0 +1,15 @@
+# Starters
+
+Clone-and-run scaffolds. Copy into your project — do not submodule the whole repo unless you want the docs too.
+
+| Starter | Pattern | Readiness |
+|---------|---------|-----------|
+| [minimal-loop](./minimal-loop/) | Daily Triage | L1 report-only |
+| [pr-babysitter](./pr-babysitter/) | PR Babysitter | L2 assisted |
+| [ci-sweeper](./ci-sweeper/) | CI Sweeper | L2 assisted |
+
+After copying, run:
+
+```bash
+node tools/loop-audit/dist/cli.js .
+```
\ No newline at end of file
diff --git a/starters/ci-sweeper/.grok/skills/ci-triage/SKILL.md b/starters/ci-sweeper/.grok/skills/ci-triage/SKILL.md
new file mode 100644
index 0000000..7e619d3
--- /dev/null
+++ b/starters/ci-sweeper/.grok/skills/ci-triage/SKILL.md
@@ -0,0 +1,29 @@
+---
+name: ci-triage
+description: >
+ Parse CI failures, identify failing job/step, classify as flake, regression,
+ env, or config. Use in CI sweeper loops before any fix attempt.
+user_invocable: true
+---
+
+# CI Triage Skill
+
+## Output per failure
+
+```markdown
+### Failure — branch @ sha
+- Job / step:
+- Error (1-3 lines):
+- Classification: flake | regression | env | config
+- Actionable: yes | no
+- Suggested loop action: minimal-fix | watch | escalate-human
+```
+
+## Classification Rules
+
+- **flake**: intermittent, passed on retry, no code change
+- **regression**: new failure correlated with recent commit
+- **env**: runner, registry, secrets, quota
+- **config**: workflow, dependency install, cache
+
+Env failures → escalate-human. Do not "fix" with code changes.
\ No newline at end of file
diff --git a/starters/ci-sweeper/README.md b/starters/ci-sweeper/README.md
new file mode 100644
index 0000000..81031e4
--- /dev/null
+++ b/starters/ci-sweeper/README.md
@@ -0,0 +1,25 @@
+# CI Sweeper Starter
+
+Scaffold for the [CI Sweeper](../../patterns/ci-sweeper.md) loop.
+
+## Quick Start
+
+1. Copy skills and state:
+ ```bash
+ mkdir -p .grok/skills
+ cp starters/ci-sweeper/.grok/skills/ci-triage/SKILL.md .grok/skills/ci-triage/SKILL.md
+ cp templates/SKILL.md.minimal-fix .grok/skills/minimal-fix/SKILL.md
+ cp templates/SKILL.md.verifier .grok/skills/loop-verifier/SKILL.md
+ cp starters/ci-sweeper/ci-sweeper-state.md.example ci-sweeper-state.md
+ ```
+
+2. Add GitHub Action (optional): `examples/github-actions/ci-sweeper.yml`
+
+3. Start (Grok):
+ ```bash
+ /loop 15m Check CI on main. Update ci-sweeper-state.md. Classify failures. For new actionable failures (not flakes): worktree + minimal-fix + loop-verifier. Escalate after 3 attempts.
+ ```
+
+## Flake Policy
+
+If the same test failed and passed on retry without code change → Watch, do not auto-fix.
\ No newline at end of file
diff --git a/starters/ci-sweeper/ci-sweeper-state.md.example b/starters/ci-sweeper/ci-sweeper-state.md.example
new file mode 100644
index 0000000..13ec902
--- /dev/null
+++ b/starters/ci-sweeper/ci-sweeper-state.md.example
@@ -0,0 +1,12 @@
+# CI Sweeper State
+
+Last run: never
+
+## Active Failures
+
+## Watch (flakes / infra)
+
+## Resolved (last 7d)
+
+---
+Run log: —
\ No newline at end of file
diff --git a/starters/minimal-loop/.grok/skills/loop-triage/SKILL.md b/starters/minimal-loop/.grok/skills/loop-triage/SKILL.md
new file mode 100644
index 0000000..6ca6e91
--- /dev/null
+++ b/starters/minimal-loop/.grok/skills/loop-triage/SKILL.md
@@ -0,0 +1,46 @@
+---
+name: loop-triage
+description: >
+ Triage recent changes, CI failures, issues, and conversations.
+ Produces a concise, actionable findings report suitable for a loop to consume.
+ Writes structured output to a state file or Linear board.
+user_invocable: true
+---
+
+# Loop Triage Skill
+
+You are an expert engineering triage agent. Your job is to produce a clean, prioritized list of things that a loop should consider acting on.
+
+## Inputs (the loop will provide these)
+- Recent CI / test failures (last 24h)
+- Open issues / Linear tickets assigned to the team
+- Recent commits on main (last 24–48h)
+- Any Slack / chat threads the loop has visibility into
+- The current state file (what the loop already knows about)
+
+## Output Format
+
+Produce a markdown report with these sections:
+
+### 1. High-Priority Items (act on these)
+- Clear, one-line description
+- Why it matters (impact, risk, or customer pain)
+- Suggested next action for the loop (e.g. "draft minimal fix in isolated worktree")
+- Rough effort estimate
+
+### 2. Watch Items (monitor, do not act yet)
+- Same format but lower urgency
+
+### 3. Noise / Ignore
+- Brief list of things the loop looked at and decided were not worth action
+
+### 4. State Updates
+- Any facts the loop should remember for the next run (e.g. "PR #1234 now has 2 approvals")
+
+## Rules
+
+- Be brutally concise. The loop (and the human reading the state) will thank you.
+- Only put something in "High-Priority" if a reasonable engineer would want to know about it today.
+- When in doubt, put it in Watch or Noise rather than creating work.
+- Never propose architectural overhauls during triage — this skill is for signal, not invention.
+- Respect the project's existing skills and conventions (they will be provided in context).
\ No newline at end of file
diff --git a/starters/minimal-loop/LOOP.md b/starters/minimal-loop/LOOP.md
new file mode 100644
index 0000000..58e2245
--- /dev/null
+++ b/starters/minimal-loop/LOOP.md
@@ -0,0 +1,22 @@
+# Loop Configuration — Minimal Triage
+
+## Active Loops
+
+| Pattern | Cadence | Status | Command |
+|---------|---------|--------|---------|
+| Daily Triage | 1d | L1 report-only | See README |
+
+## Human Gates
+
+- No auto-fix until L2 checklist complete
+- All high-risk paths: human review required
+
+## Budget
+
+- Max sub-agent spawns per run: 0 (L1)
+- Review STATE.md daily
+
+## Links
+
+- Pattern: [daily-triage](../../patterns/daily-triage.md)
+- Checklist: [loop-design-checklist](../../docs/loop-design-checklist.md)
\ No newline at end of file
diff --git a/starters/minimal-loop/README.md b/starters/minimal-loop/README.md
new file mode 100644
index 0000000..91dc784
--- /dev/null
+++ b/starters/minimal-loop/README.md
@@ -0,0 +1,36 @@
+# Minimal Loop Starter
+
+Clone this into your project root to run a **report-only daily triage loop** (L1 readiness).
+
+## Quick Start
+
+1. Copy files into your repo:
+ ```bash
+ cp -r starters/minimal-loop/.grok/skills/loop-triage .grok/skills/ # Grok
+ cp starters/minimal-loop/STATE.md.example STATE.md
+ ```
+
+2. Customize `STATE.md` project name.
+
+3. Start the loop (Grok):
+ ```bash
+ /loop 1d Run the loop-triage skill. Read STATE.md first. Append high-priority and watch items. Update Last run timestamp. Do not auto-fix anything in week one.
+ ```
+
+4. Read `STATE.md` each morning for 1–2 weeks. Tune the triage skill.
+
+5. When triage quality is good, add `minimal-fix` + `loop-verifier` from `templates/` and enable small auto-wins.
+
+## What's Included
+
+| File | Purpose |
+|------|---------|
+| `STATE.md.example` | State spine template |
+| `.grok/skills/loop-triage/SKILL.md` | Triage skill |
+| `LOOP.md` | Loop config doc for your team |
+
+## Next Steps
+
+- [Loop Design Checklist](../../docs/loop-design-checklist.md)
+- [Daily Triage pattern](../../patterns/daily-triage.md)
+- Run `node tools/loop-audit/dist/cli.js .` for readiness score
\ No newline at end of file
diff --git a/starters/minimal-loop/STATE.md.example b/starters/minimal-loop/STATE.md.example
new file mode 100644
index 0000000..1168b1e
--- /dev/null
+++ b/starters/minimal-loop/STATE.md.example
@@ -0,0 +1,12 @@
+# Loop State — My Project
+
+Last run: never
+
+## High Priority (loop is acting or waiting on human)
+
+## Watch List
+
+## Recent Noise (ignored this run)
+
+---
+Run log: —
\ No newline at end of file
diff --git a/starters/pr-babysitter/.grok/skills/pr-review-triage/SKILL.md b/starters/pr-babysitter/.grok/skills/pr-review-triage/SKILL.md
new file mode 100644
index 0000000..8ea95ff
--- /dev/null
+++ b/starters/pr-babysitter/.grok/skills/pr-review-triage/SKILL.md
@@ -0,0 +1,29 @@
+---
+name: pr-review-triage
+description: >
+ Triage open pull requests for CI status, review comments, and merge readiness.
+ Use in PR babysitter loops. Respects project review norms and required checks.
+user_invocable: true
+---
+
+# PR Review Triage Skill
+
+For each watched PR, report:
+
+## Per-PR Output
+
+```markdown
+### PR #N — title
+- CI: green | red (job names if red)
+- Reviews: approved N | changes requested | none
+- Blocking comments: (list actionable ones)
+- Ready to merge: yes | no — reason
+- Suggested loop action: none | minimal-fix | rebase | escalate-human
+```
+
+## Rules
+
+- "Ready to merge" requires all required checks + approvals per project policy.
+- Non-actionable nits → note but do not spawn fix.
+- If PR idle >4 days → suggest human handoff.
+- High-risk labels (security, breaking) → escalate-human always.
\ No newline at end of file
diff --git a/starters/pr-babysitter/LOOP.md b/starters/pr-babysitter/LOOP.md
new file mode 100644
index 0000000..42e4b4b
--- /dev/null
+++ b/starters/pr-babysitter/LOOP.md
@@ -0,0 +1,20 @@
+# Loop Configuration — PR Babysitter
+
+| Pattern | Cadence | Status |
+|---------|---------|--------|
+| PR Babysitter | 5m (work hours) | L2 assisted |
+
+## Limits
+
+- Max fix attempts per PR: 3
+- Auto-merge: **disabled**
+- Watched: PRs authored by team / label `loop-watch`
+
+## Human Gates
+
+- Security, auth, payments, infrastructure
+- PRs with >10 files changed in loop fix
+
+## Pattern
+
+[pr-babysitter.md](../../patterns/pr-babysitter.md)
\ No newline at end of file
diff --git a/starters/pr-babysitter/README.md b/starters/pr-babysitter/README.md
new file mode 100644
index 0000000..9459890
--- /dev/null
+++ b/starters/pr-babysitter/README.md
@@ -0,0 +1,35 @@
+# PR Babysitter Starter
+
+Scaffold for the [PR Babysitter](../../patterns/pr-babysitter.md) loop (L2 — assisted fixes with verifier).
+
+## Quick Start
+
+1. Copy into your repo:
+ ```bash
+ mkdir -p .grok/skills
+ cp -r starters/pr-babysitter/.grok/skills/* .grok/skills/
+ cp starters/pr-babysitter/pr-babysitter-state.md.example pr-babysitter-state.md
+ cp starters/pr-babysitter/LOOP.md .
+ ```
+
+2. Customize skills with your review norms and required checks.
+
+3. Start (Grok):
+ ```bash
+ /loop 5m Check open PRs. Update pr-babysitter-state.md. For CI failures or actionable review comments on allowlisted PRs: worktree + minimal-fix + loop-verifier. Never merge — propose only. Escalate after 3 attempts per PR.
+ ```
+
+4. Sign PR comments: `🤖 Loop Engineering — PR Babysitter`
+
+## Files
+
+| File | Purpose |
+|------|---------|
+| `pr-babysitter-state.md.example` | Watcher state |
+| `.grok/skills/pr-review-triage/` | PR triage skill |
+| `LOOP.md` | Team loop config |
+
+## Safety
+
+- No auto-merge by default
+- Denylist: auth, payments, secrets — see [safety.md](../../docs/safety.md)
\ No newline at end of file
diff --git a/starters/pr-babysitter/pr-babysitter-state.md.example b/starters/pr-babysitter/pr-babysitter-state.md.example
new file mode 100644
index 0000000..c133e37
--- /dev/null
+++ b/starters/pr-babysitter/pr-babysitter-state.md.example
@@ -0,0 +1,19 @@
+# PR Babysitter State
+
+Last run: never
+
+## Watched PRs
+
+<!-- - #1234 (branch-name)
+ Status: CI red | changes requested | ready
+ Attempts: 0/3
+ Last action: —
+ Human decision: —
+-->
+
+## Escalated (human required)
+
+## Resolved (last 7d)
+
+---
+Run log: —
\ No newline at end of file
diff --git a/stories/README.md b/stories/README.md
new file mode 100644
index 0000000..c7bbaea
--- /dev/null
+++ b/stories/README.md
@@ -0,0 +1,20 @@
+# Production Stories
+
+Real-world loop engineering — including failures. Contribute yours via [CONTRIBUTING.md](../CONTRIBUTING.md).
+
+| Story | Pattern | Takeaway |
+|-------|---------|----------|
+| [pr-babysitter-week-one.md](./pr-babysitter-week-one.md) | PR Babysitter | State + attempt limits + verifier |
+| [daily-triage-report-only.md](./daily-triage-report-only.md) | Daily Triage | L1 before L2 |
+| [why-we-killed-ci-sweeper.md](./why-we-killed-ci-sweeper.md) | CI Sweeper | Budget, branch allowlist, kill switch |
+
+**Template for new stories:**
+
+```markdown
+# Title — Context
+## Setup
+## What Worked
+## What Broke
+## Metrics (if any)
+## Lesson
+```
\ No newline at end of file
diff --git a/stories/daily-triage-report-only.md b/stories/daily-triage-report-only.md
new file mode 100644
index 0000000..9125d24
--- /dev/null
+++ b/stories/daily-triage-report-only.md
@@ -0,0 +1,29 @@
+# Daily Triage — Report-Only Onboarding
+
+## Context
+
+Team wanted morning visibility without risking auto-edits on day one.
+
+## Setup
+
+- [minimal-loop starter](../starters/minimal-loop/)
+- `/loop 1d` — triage only, no sub-agents
+- Human reads `STATE.md` with coffee
+
+## Week 1 Results
+
+- 5/5 weekdays: STATE.md matched what on-call would have found manually
+- 2 false positives: Dependabot grouped as high priority → tuned triage skill "Noise" section
+- 0 tokens burned on implementer/verifier
+
+## Graduation to L2
+
+After 10 stable runs:
+
+1. Added `minimal-fix` + `loop-verifier` skills
+2. Narrow rule: "single-file test failures only"
+3. First auto-PR merged with human LGTM in 8 minutes
+
+## Lesson
+
+Report-only is not wasted time — it calibrates triage. Skipping L1 is how loops get a reputation for noise.
\ No newline at end of file
diff --git a/stories/pr-babysitter-week-one.md b/stories/pr-babysitter-week-one.md
new file mode 100644
index 0000000..a6dca19
--- /dev/null
+++ b/stories/pr-babysitter-week-one.md
@@ -0,0 +1,39 @@
+# PR Babysitter — Week One (Example Story)
+
+*Anonymized production-style narrative for contributors. Replace with your real metrics via PR.*
+
+## Context
+
+- 4-person team, monorepo, Grok Build TUI + GitHub
+- Pain: "can you rebase?" and "CI is red" Slack pings 10–15×/day
+
+## Setup
+
+- Pattern: [pr-babysitter](../patterns/pr-babysitter.md)
+- Cadence: `/loop 5m` during work hours
+- L2 assisted: minimal-fix + loop-verifier, no auto-merge
+
+## What Worked
+
+- **State file** (`pr-babysitter-state.md`) stopped duplicate fix attempts — attempt counter mattered
+- Verifier on stronger model caught 2 over-broad diffs before PR comment
+- Loop comments signed `🤖 Loop Engineering — PR Babysitter` — reviewers knew what to trust
+
+## What Broke
+
+- **Day 3**: Infinite fix loop on flaky e2e — loop tried code changes 4 times before human killed scheduler
+ - **Fix**: Added flake classification to triage; max 3 attempts enforced in prompt
+- **Day 5**: Notification fatigue — bot commented on every run even when nothing changed
+ - **Fix**: Only comment when verdict APPROVE or ESCALATE_HUMAN
+
+## Metrics (week 1)
+
+| Metric | Before | After |
+|--------|--------|-------|
+| Slack CI/rebase pings | ~12/day | ~4/day |
+| Mean time to first fix proposal | hours | ~25 min |
+| Bad merges from loop | 0 | 0 |
+
+## Lesson
+
+Start L2 only after 3 days of state-only watching. The loop doesn't know a flake from a regression — you teach it in skills.
\ No newline at end of file
diff --git a/stories/why-we-killed-ci-sweeper.md b/stories/why-we-killed-ci-sweeper.md
new file mode 100644
index 0000000..9046b6c
--- /dev/null
+++ b/stories/why-we-killed-ci-sweeper.md
@@ -0,0 +1,30 @@
+# Why We Killed Our CI Sweeper (After Day 4)
+
+*Honest failure story — valuable for pattern design.*
+
+## What Happened
+
+- `/loop 5m` on red main during a flaky migration branch
+- Token spend: ~8M tokens in 48h
+- Loop proposed 11 PRs; 3 were symptom fixes; 1 broke prod config (caught in human review)
+
+## Root Causes
+
+1. **No L1 phase** — went straight to auto-fix
+2. **Verifier same session** as implementer on half the runs
+3. **No branch allowlist** — swept feature branches with known red CI
+4. **No daily budget** — scheduler never paused
+
+## What We Did
+
+1. `scheduler_delete` all CI sweeper tasks
+2. Switched to **event-driven** GitHub Action only on `main` failures
+3. Re-enabled with:
+ - Report-only for 1 week
+ - Verifier as separate sub-agent
+ - 2M token/day cap in LOOP.md
+ - Branch allowlist: `main` only
+
+## Lesson
+
+CI sweeper is a high-leverage *entry* loop and a high-risk *unattended* loop. The pattern doc exists because we learned this the hard way.
\ No newline at end of file
diff --git a/templates/SKILL.md.minimal-fix b/templates/SKILL.md.minimal-fix
new file mode 100644
index 0000000..7b01553
--- /dev/null
+++ b/templates/SKILL.md.minimal-fix
@@ -0,0 +1,45 @@
+---
+name: minimal-fix
+description: >
+ Produce the smallest possible code change that fixes a specific, well-scoped
+ issue (CI failure, reviewer comment, typo). Use only when the fix target is
+ explicit. Never refactor unrelated code.
+user_invocable: true
+---
+
+# Minimal Fix Skill
+
+You fix **one specific problem** with the **smallest diff** that could work.
+
+## Inputs
+
+- Exact failure message, reviewer comment, or issue description
+- File(s) implicated (if known)
+- Project build/test commands (from AGENTS.md or project skills)
+- Path denylist (from loop safety policy — never edit `.env`, `auth/`, `payments/`, secrets)
+
+## Process
+
+1. Reproduce or confirm the failure locally if possible.
+2. Identify the minimal root cause — not symptoms in distant files.
+3. Change only what is required. No drive-by refactors.
+4. Run tests/lint relevant to the change.
+5. Summarize: what changed, why, what you ran.
+
+## Output
+
+```markdown
+## Minimal Fix Proposal
+- Target: (issue/comment/failure)
+- Files changed: (list)
+- Diff summary: (1-3 bullets)
+- Tests run: (commands + result)
+- Risk: low | medium — if medium, recommend human review
+```
+
+## Rules
+
+- If fix requires >5 files or design change → stop and escalate.
+- If path is on denylist → stop and escalate.
+- Do not disable tests or weaken assertions to go green.
+- Do not mark yourself "done" — verifier decides.
\ No newline at end of file
diff --git a/templates/SKILL.md.verifier b/templates/SKILL.md.verifier
new file mode 100644
index 0000000..935d3bb
--- /dev/null
+++ b/templates/SKILL.md.verifier
@@ -0,0 +1,48 @@
+---
+name: loop-verifier
+description: >
+ Independent verification agent for loop-produced changes. Finds reasons to
+ reject. Runs tests. Confirms diff scope. Use after minimal-fix or any
+ implementer sub-agent — never in the same role as the implementer.
+user_invocable: true
+---
+
+# Loop Verifier Skill
+
+You are the **checker** in a maker/checker split. Your job is to **reject** unless evidence is strong.
+
+## Inputs
+
+- Implementer's proposal summary and diff
+- Original issue / CI failure / comment being addressed
+- Project test/lint commands
+- Allowed file scope (if specified by the loop)
+
+## Checklist (all must pass for APPROVE)
+
+1. **Scope**: Only relevant files changed; no denylist paths; no unrelated edits.
+2. **Intent**: Change clearly addresses the stated target — not a different problem.
+3. **Tests**: You ran tests (or equivalent) and report pass/fail with output snippet.
+4. **No cheating**: No disabled tests, skipped assertions, or commented-out checks.
+5. **Risk**: For medium+ risk, recommend human review even if tests pass.
+
+## Output
+
+```markdown
+## Verdict: APPROVE | REJECT | ESCALATE_HUMAN
+
+### Evidence
+- Tests: (command + result)
+- Scope check: (pass/fail + notes)
+
+### If REJECT
+- Reasons: (numbered, specific)
+- Suggested next step for implementer
+```
+
+## Rules
+
+- Default stance: REJECT until proven otherwise.
+- Do not trust implementer's claim that tests passed — run them.
+- If you cannot run tests (env issue) → ESCALATE_HUMAN.
+- Be concise. The loop and human read this under time pressure.
\ No newline at end of file
diff --git a/templates/STATE.md.template b/templates/STATE.md.template
new file mode 100644
index 0000000..6fc8047
--- /dev/null
+++ b/templates/STATE.md.template
@@ -0,0 +1,22 @@
+# Loop State — {{PROJECT_NAME}}
+
+Last run: (set by loop on each run)
+
+## High Priority (loop is acting or waiting on human)
+
+<!-- Format:
+- [ ] ID — one-line description
+ Loop action: what the loop did last
+ Human decision: (if any)
+-->
+
+## Watch List
+
+<!-- Items to monitor but not act on yet -->
+
+## Recent Noise (ignored this run)
+
+<!-- Brief list — helps tune triage skill -->
+
+---
+Run log: (timestamp) | findings | actions | escalations
\ No newline at end of file
diff --git a/templates/pattern-template.md b/templates/pattern-template.md
new file mode 100644
index 0000000..ef196ed
--- /dev/null
+++ b/templates/pattern-template.md
@@ -0,0 +1,58 @@
+# {{PATTERN_NAME}} Loop
+
+**Goal**: {{ONE_SENTENCE_GOAL}}
+
+## Scheduling
+
+**Recommended**:
+- Grok: `{{GROK_COMMAND}}`
+- Claude Code: `{{CLAUDE_COMMAND}}`
+- Codex: {{CODEX_DESCRIPTION}}
+- GitHub Actions: see `examples/github-actions/{{FILE}}.yml`
+
+## Required Skills
+
+- `{{SKILL_1}}` — {{DESCRIPTION}}
+- `{{SKILL_2}}` — {{DESCRIPTION}}
+
+## State
+
+Filename: `{{STATE_FILE}}`
+
+```markdown
+<!-- Minimal example schema -->
+```
+
+## How the Loop Runs (Typical Cycle)
+
+1. {{STEP_1}}
+2. {{STEP_2}}
+3. {{STEP_3}}
+
+## Verification Strategy
+
+- {{VERIFIER_RULES}}
+
+## Human Handoff Points
+
+- {{GATE_1}}
+- {{GATE_2}}
+
+## Tool-Specific Notes
+
+**Grok Build TUI**: {{NOTES}}
+
+**Claude Code**: {{NOTES}}
+
+**Codex**: {{NOTES}}
+
+## Failure Modes & Mitigations
+
+| Failure | Mitigation |
+|---------|------------|
+| {{FAILURE}} | {{MITIGATION}} |
+
+## Success Metrics
+
+- {{METRIC_1}}
+- {{METRIC_2}}
\ No newline at end of file
diff --git a/tools/loop-audit/README.md b/tools/loop-audit/README.md
new file mode 100644
index 0000000..ea3372e
--- /dev/null
+++ b/tools/loop-audit/README.md
@@ -0,0 +1,50 @@
+# loop-audit
+
+CLI that scores a project's **Loop Readiness** (0–100) and suggests next steps.
+
+## Install & Run
+
+```bash
+cd tools/loop-audit
+npm install
+npm run build
+node dist/cli.js /path/to/your/project
+```
+
+Or from repo root after build:
+
+```bash
+node tools/loop-audit/dist/cli.js starters/minimal-loop
+```
+
+## Options
+
+```bash
+loop-audit . # human-readable (default)
+loop-audit . --json # machine-readable
+loop-audit . --md # markdown report
+```
+
+Exit code `2` if score < 40 (useful for CI gates once your project is loop-ready).
+
+## Signals Checked
+
+| Signal | Weight |
+|--------|--------|
+| State file (`STATE.md`, etc.) | High |
+| Triage skill | High |
+| Verifier skill (maker/checker) | High |
+| `LOOP.md` config | Medium |
+| `AGENTS.md` / project rules | Medium |
+| Safety gates documented | Low |
+
+## Levels
+
+| Level | Meaning |
+|-------|---------|
+| L0 | Draft — document intent |
+| L1 | Report-only loops |
+| L2 | Assisted auto-fix with verifier |
+| L3 | Unattended-capable (with human gates) |
+
+See [docs/loop-design-checklist.md](../../docs/loop-design-checklist.md).
\ No newline at end of file
diff --git a/tools/loop-audit/dist/auditor.d.ts b/tools/loop-audit/dist/auditor.d.ts
new file mode 100644
index 0000000..b95833d
--- /dev/null
+++ b/tools/loop-audit/dist/auditor.d.ts
@@ -0,0 +1,51 @@
+export interface LoopSignals {
+ stateFile: {
+ present: boolean;
+ paths: string[];
+ };
+ loopConfig: {
+ present: boolean;
+ path?: string;
+ };
+ skills: {
+ count: number;
+ loopSkills: string[];
+ };
+ verifier: {
+ present: boolean;
+ };
+ triage: {
+ present: boolean;
+ };
+ agentsMd: {
+ present: boolean;
+ };
+ patterns: {
+ documented: boolean;
+ };
+ safety: {
+ loopMdMentionsSafety: boolean;
+ };
+ starters: {
+ used: boolean;
+ };
+}
+export interface Finding {
+ level: 'ok' | 'warn' | 'fail';
+ message: string;
+}
+export interface AuditResult {
+ target: string;
+ score: number;
+ level: 'L0' | 'L1' | 'L2' | 'L3';
+ assessment: string;
+ signals: LoopSignals;
+ findings: Finding[];
+ recommendations: string[];
+}
+export declare function computeScore(signals: LoopSignals): {
+ score: number;
+ level: 'L0' | 'L1' | 'L2' | 'L3';
+ assessment: string;
+};
+export declare function auditProject(target: string): Promise<AuditResult>;
diff --git a/tools/loop-audit/dist/auditor.js b/tools/loop-audit/dist/auditor.js
new file mode 100644
index 0000000..9aee7bb
--- /dev/null
+++ b/tools/loop-audit/dist/auditor.js
@@ -0,0 +1,155 @@
+import { readdir, readFile, stat } from 'node:fs/promises';
+import path from 'node:path';
+const STATE_FILES = [
+ 'STATE.md',
+ 'pr-babysitter-state.md',
+ 'ci-sweeper-state.md',
+ 'post-merge-state.md',
+];
+const LOOP_SKILL_NAMES = [
+ 'loop-triage',
+ 'minimal-fix',
+ 'loop-verifier',
+ 'pr-review-triage',
+ 'ci-triage',
+ 'post-merge-scan',
+];
+async function fileExists(p) {
+ try {
+ await stat(p);
+ return true;
+ }
+ catch {
+ return false;
+ }
+}
+async function findSkills(root) {
+ const dirs = [
+ path.join(root, '.grok', 'skills'),
+ path.join(root, '.claude', 'skills'),
+ path.join(root, '.codex', 'skills'),
+ path.join(root, 'skills'),
+ ];
+ const found = [];
+ for (const dir of dirs) {
+ if (!(await fileExists(dir)))
+ continue;
+ const entries = await readdir(dir, { withFileTypes: true });
+ for (const e of entries) {
+ if (e.isDirectory())
+ found.push(e.name);
+ if (e.isFile() && e.name === 'SKILL.md')
+ found.push('root-skill');
+ }
+ }
+ return found;
+}
+export function computeScore(signals) {
+ let score = 10;
+ if (signals.stateFile.present)
+ score += 20;
+ if (signals.triage.present)
+ score += 15;
+ if (signals.loopConfig.present)
+ score += 10;
+ if (signals.agentsMd.present)
+ score += 10;
+ if (signals.skills.count >= 2)
+ score += 15;
+ else if (signals.skills.count === 1)
+ score += 8;
+ if (signals.verifier.present)
+ score += 15;
+ if (signals.safety.loopMdMentionsSafety)
+ score += 5;
+ score = Math.min(100, Math.max(0, score));
+ let level = 'L0';
+ if (score >= 75 && signals.verifier.present && signals.stateFile.present)
+ level = 'L3';
+ else if (score >= 55 && signals.triage.present)
+ level = 'L2';
+ else if (score >= 35 && signals.stateFile.present)
+ level = 'L1';
+ else
+ level = 'L0';
+ const assessment = score >= 80 ? 'Strong loop readiness — unattended possible with human gates.' :
+ score >= 60 ? 'Good foundation — add verifier before L3.' :
+ score >= 40 ? 'Early loop setup — complete L1 checklist.' :
+ 'Not loop-ready — start with minimal-loop starter.';
+ return { score, level, assessment };
+}
+export async function auditProject(target) {
+ const root = path.resolve(target);
+ const findings = [];
+ const recommendations = [];
+ const statePaths = [];
+ for (const f of STATE_FILES) {
+ if (await fileExists(path.join(root, f)))
+ statePaths.push(f);
+ }
+ const loopMd = await fileExists(path.join(root, 'LOOP.md'));
+ const agentsMd = await fileExists(path.join(root, 'AGENTS.md')) ||
+ await fileExists(path.join(root, 'CLAUDE.md'));
+ const skillNames = await findSkills(root);
+ const loopSkills = skillNames.filter((s) => LOOP_SKILL_NAMES.includes(s));
+ const verifier = skillNames.includes('loop-verifier');
+ const triage = skillNames.includes('loop-triage') || skillNames.includes('pr-review-triage') || skillNames.includes('ci-triage');
+ let loopMdContent = '';
+ if (loopMd) {
+ loopMdContent = await readFile(path.join(root, 'LOOP.md'), 'utf8');
+ }
+ const signals = {
+ stateFile: { present: statePaths.length > 0, paths: statePaths },
+ loopConfig: { present: loopMd, path: loopMd ? 'LOOP.md' : undefined },
+ skills: { count: loopSkills.length, loopSkills },
+ verifier: { present: verifier },
+ triage: { present: triage },
+ agentsMd: { present: agentsMd },
+ patterns: { documented: loopMd },
+ safety: { loopMdMentionsSafety: /gate|denylist|auto-merge|safety/i.test(loopMdContent) },
+ starters: { used: loopSkills.includes('loop-triage') },
+ };
+ if (!signals.stateFile.present) {
+ findings.push({ level: 'fail', message: 'No state file (STATE.md or pattern-specific state).' });
+ recommendations.push('Copy starters/minimal-loop/STATE.md.example to STATE.md');
+ }
+ else {
+ findings.push({ level: 'ok', message: `State file(s): ${statePaths.join(', ')}` });
+ }
+ if (!signals.triage.present) {
+ findings.push({ level: 'warn', message: 'No triage skill detected.' });
+ recommendations.push('Install loop-triage from templates/ or starters/minimal-loop/');
+ }
+ else {
+ findings.push({ level: 'ok', message: 'Triage skill present.' });
+ }
+ if (!signals.verifier.present) {
+ findings.push({ level: 'warn', message: 'No loop-verifier skill — maker/checker split incomplete.' });
+ recommendations.push('Add templates/SKILL.md.verifier as .grok/skills/loop-verifier/SKILL.md');
+ }
+ else {
+ findings.push({ level: 'ok', message: 'Verifier skill present.' });
+ }
+ if (!signals.loopConfig.present) {
+ findings.push({ level: 'warn', message: 'No LOOP.md documenting cadence, limits, and gates.' });
+ recommendations.push('Copy starters/minimal-loop/LOOP.md and customize');
+ }
+ if (!signals.agentsMd.present) {
+ findings.push({ level: 'warn', message: 'No AGENTS.md / CLAUDE.md for project conventions.' });
+ recommendations.push('Add AGENTS.md with build/test commands and review norms');
+ }
+ if (!signals.safety.loopMdMentionsSafety) {
+ findings.push({ level: 'warn', message: 'LOOP.md does not mention safety gates or auto-merge policy.' });
+ recommendations.push('Document human gates per docs/safety.md in LOOP.md');
+ }
+ const { score, level, assessment } = computeScore(signals);
+ return {
+ target: root,
+ score,
+ level,
+ assessment,
+ signals,
+ findings,
+ recommendations,
+ };
+}
diff --git a/tools/loop-audit/dist/cli.d.ts b/tools/loop-audit/dist/cli.d.ts
new file mode 100644
index 0000000..b798801
--- /dev/null
+++ b/tools/loop-audit/dist/cli.d.ts
@@ -0,0 +1,2 @@
+#!/usr/bin/env node
+export {};
diff --git a/tools/loop-audit/dist/cli.js b/tools/loop-audit/dist/cli.js
new file mode 100644
index 0000000..06973f3
--- /dev/null
+++ b/tools/loop-audit/dist/cli.js
@@ -0,0 +1,41 @@
+#!/usr/bin/env node
+import { auditProject } from './auditor.js';
+import { formatHuman, formatJson, formatMarkdown } from './reporter.js';
+const args = process.argv.slice(2);
+const target = args.find((a) => !a.startsWith('-')) || '.';
+const json = args.includes('--json');
+const md = args.includes('--md');
+const help = args.includes('--help') || args.includes('-h');
+if (help) {
+ console.log(`loop-audit — Loop Readiness Score CLI
+
+Usage:
+ loop-audit [path] [options]
+
+Options:
+ --json JSON output
+ --md Markdown output
+ --help Show help
+
+Exit codes:
+ 0 score >= 40
+ 2 score < 40 (early stage)
+`);
+ process.exit(0);
+}
+try {
+ const result = await auditProject(target);
+ if (json)
+ console.log(formatJson(result));
+ else if (md)
+ console.log(formatMarkdown(result));
+ else
+ console.log(formatHuman(result));
+ if (result.score < 40)
+ process.exitCode = 2;
+}
+catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ console.error('Audit failed:', msg);
+ process.exitCode = 1;
+}
diff --git a/tools/loop-audit/dist/reporter.d.ts b/tools/loop-audit/dist/reporter.d.ts
new file mode 100644
index 0000000..8bac4bb
--- /dev/null
+++ b/tools/loop-audit/dist/reporter.d.ts
@@ -0,0 +1,4 @@
+import type { AuditResult } from './auditor.js';
+export declare function formatHuman(r: AuditResult): string;
+export declare function formatJson(r: AuditResult): string;
+export declare function formatMarkdown(r: AuditResult): string;
diff --git a/tools/loop-audit/dist/reporter.js b/tools/loop-audit/dist/reporter.js
new file mode 100644
index 0000000..27e50a4
--- /dev/null
+++ b/tools/loop-audit/dist/reporter.js
@@ -0,0 +1,54 @@
+export function formatHuman(r) {
+ const lines = [];
+ lines.push('');
+ lines.push(`Loop Readiness Audit — ${r.target}`);
+ lines.push('═'.repeat(50));
+ lines.push(`Score: ${r.score}/100 Level: ${r.level}`);
+ lines.push(r.assessment);
+ lines.push('');
+ lines.push('Findings:');
+ for (const f of r.findings) {
+ const icon = f.level === 'ok' ? '✓' : f.level === 'warn' ? '!' : '✗';
+ lines.push(` ${icon} ${f.message}`);
+ }
+ if (r.recommendations.length) {
+ lines.push('');
+ lines.push('Recommendations:');
+ for (const rec of r.recommendations) {
+ lines.push(` → ${rec}`);
+ }
+ }
+ lines.push('');
+ lines.push('Docs: docs/loop-design-checklist.md');
+ lines.push('');
+ return lines.join('\n');
+}
+export function formatJson(r) {
+ return JSON.stringify(r, null, 2);
+}
+export function formatMarkdown(r) {
+ const lines = [];
+ lines.push('# Loop Readiness Report');
+ lines.push('');
+ lines.push(`| Metric | Value |`);
+ lines.push(`|--------|-------|`);
+ lines.push(`| Target | \`${r.target}\` |`);
+ lines.push(`| Score | **${r.score}/100** |`);
+ lines.push(`| Level | ${r.level} |`);
+ lines.push(`| Assessment | ${r.assessment} |`);
+ lines.push('');
+ lines.push('## Findings');
+ lines.push('');
+ for (const f of r.findings) {
+ lines.push(`- **${f.level}**: ${f.message}`);
+ }
+ if (r.recommendations.length) {
+ lines.push('');
+ lines.push('## Recommendations');
+ lines.push('');
+ for (const rec of r.recommendations) {
+ lines.push(`- ${rec}`);
+ }
+ }
+ return lines.join('\n');
+}
diff --git a/tools/loop-audit/package-lock.json b/tools/loop-audit/package-lock.json
new file mode 100644
index 0000000..2712ce0
--- /dev/null
+++ b/tools/loop-audit/package-lock.json
@@ -0,0 +1,53 @@
+{
+ "name": "loop-audit",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "loop-audit",
+ "version": "1.0.0",
+ "bin": {
+ "loop-audit": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "20.19.42",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.42.tgz",
+ "integrity": "sha512-5L7SUaFC1RyDraj2yRhyBzHTobyXHmohD100CChNtyPyleoq37Mqab5Gn8XEKI04dfN/oqPdpHk38MgcQWHbZg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/tools/loop-audit/package.json b/tools/loop-audit/package.json
new file mode 100644
index 0000000..260f959
--- /dev/null
+++ b/tools/loop-audit/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "loop-audit",
+ "version": "1.0.0",
+ "description": "Loop Readiness Score — audit a project for loop engineering readiness",
+ "type": "module",
+ "bin": {
+ "loop-audit": "./dist/cli.js"
+ },
+ "scripts": {
+ "build": "tsc",
+ "start": "node dist/cli.js",
+ "audit": "npm run build && node dist/cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.0.0"
+ }
+}
\ No newline at end of file
diff --git a/tools/loop-audit/src/auditor.ts b/tools/loop-audit/src/auditor.ts
new file mode 100644
index 0000000..e83baec
--- /dev/null
+++ b/tools/loop-audit/src/auditor.ts
@@ -0,0 +1,188 @@
+import { readdir, readFile, stat } from 'node:fs/promises';
+import path from 'node:path';
+
+export interface LoopSignals {
+ stateFile: { present: boolean; paths: string[] };
+ loopConfig: { present: boolean; path?: string };
+ skills: { count: number; loopSkills: string[] };
+ verifier: { present: boolean };
+ triage: { present: boolean };
+ agentsMd: { present: boolean };
+ patterns: { documented: boolean };
+ safety: { loopMdMentionsSafety: boolean };
+ starters: { used: boolean };
+}
+
+export interface Finding {
+ level: 'ok' | 'warn' | 'fail';
+ message: string;
+}
+
+export interface AuditResult {
+ target: string;
+ score: number;
+ level: 'L0' | 'L1' | 'L2' | 'L3';
+ assessment: string;
+ signals: LoopSignals;
+ findings: Finding[];
+ recommendations: string[];
+}
+
+const STATE_FILES = [
+ 'STATE.md',
+ 'pr-babysitter-state.md',
+ 'ci-sweeper-state.md',
+ 'post-merge-state.md',
+];
+
+const LOOP_SKILL_NAMES = [
+ 'loop-triage',
+ 'minimal-fix',
+ 'loop-verifier',
+ 'pr-review-triage',
+ 'ci-triage',
+ 'post-merge-scan',
+];
+
+async function fileExists(p: string): Promise<boolean> {
+ try {
+ await stat(p);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function findSkills(root: string): Promise<string[]> {
+ const dirs = [
+ path.join(root, '.grok', 'skills'),
+ path.join(root, '.claude', 'skills'),
+ path.join(root, '.codex', 'skills'),
+ path.join(root, 'skills'),
+ ];
+ const found: string[] = [];
+ for (const dir of dirs) {
+ if (!(await fileExists(dir))) continue;
+ const entries = await readdir(dir, { withFileTypes: true });
+ for (const e of entries) {
+ if (e.isDirectory()) found.push(e.name);
+ if (e.isFile() && e.name === 'SKILL.md') found.push('root-skill');
+ }
+ }
+ return found;
+}
+
+export function computeScore(signals: LoopSignals): { score: number; level: 'L0' | 'L1' | 'L2' | 'L3'; assessment: string } {
+ let score = 10;
+
+ if (signals.stateFile.present) score += 20;
+ if (signals.triage.present) score += 15;
+ if (signals.loopConfig.present) score += 10;
+ if (signals.agentsMd.present) score += 10;
+ if (signals.skills.count >= 2) score += 15;
+ else if (signals.skills.count === 1) score += 8;
+ if (signals.verifier.present) score += 15;
+ if (signals.safety.loopMdMentionsSafety) score += 5;
+
+ score = Math.min(100, Math.max(0, score));
+
+ let level: 'L0' | 'L1' | 'L2' | 'L3' = 'L0';
+ if (score >= 75 && signals.verifier.present && signals.stateFile.present) level = 'L3';
+ else if (score >= 55 && signals.triage.present) level = 'L2';
+ else if (score >= 35 && signals.stateFile.present) level = 'L1';
+ else level = 'L0';
+
+ const assessment =
+ score >= 80 ? 'Strong loop readiness — unattended possible with human gates.' :
+ score >= 60 ? 'Good foundation — add verifier before L3.' :
+ score >= 40 ? 'Early loop setup — complete L1 checklist.' :
+ 'Not loop-ready — start with minimal-loop starter.';
+
+ return { score, level, assessment };
+}
+
+export async function auditProject(target: string): Promise<AuditResult> {
+ const root = path.resolve(target);
+ const findings: Finding[] = [];
+ const recommendations: string[] = [];
+
+ const statePaths: string[] = [];
+ for (const f of STATE_FILES) {
+ if (await fileExists(path.join(root, f))) statePaths.push(f);
+ }
+
+ const loopMd = await fileExists(path.join(root, 'LOOP.md'));
+ const agentsMd = await fileExists(path.join(root, 'AGENTS.md')) ||
+ await fileExists(path.join(root, 'CLAUDE.md'));
+
+ const skillNames = await findSkills(root);
+ const loopSkills = skillNames.filter((s) => LOOP_SKILL_NAMES.includes(s));
+
+ const verifier = skillNames.includes('loop-verifier');
+ const triage = skillNames.includes('loop-triage') || skillNames.includes('pr-review-triage') || skillNames.includes('ci-triage');
+
+ let loopMdContent = '';
+ if (loopMd) {
+ loopMdContent = await readFile(path.join(root, 'LOOP.md'), 'utf8');
+ }
+
+ const signals: LoopSignals = {
+ stateFile: { present: statePaths.length > 0, paths: statePaths },
+ loopConfig: { present: loopMd, path: loopMd ? 'LOOP.md' : undefined },
+ skills: { count: loopSkills.length, loopSkills },
+ verifier: { present: verifier },
+ triage: { present: triage },
+ agentsMd: { present: agentsMd },
+ patterns: { documented: loopMd },
+ safety: { loopMdMentionsSafety: /gate|denylist|auto-merge|safety/i.test(loopMdContent) },
+ starters: { used: loopSkills.includes('loop-triage') },
+ };
+
+ if (!signals.stateFile.present) {
+ findings.push({ level: 'fail', message: 'No state file (STATE.md or pattern-specific state).' });
+ recommendations.push('Copy starters/minimal-loop/STATE.md.example to STATE.md');
+ } else {
+ findings.push({ level: 'ok', message: `State file(s): ${statePaths.join(', ')}` });
+ }
+
+ if (!signals.triage.present) {
+ findings.push({ level: 'warn', message: 'No triage skill detected.' });
+ recommendations.push('Install loop-triage from templates/ or starters/minimal-loop/');
+ } else {
+ findings.push({ level: 'ok', message: 'Triage skill present.' });
+ }
+
+ if (!signals.verifier.present) {
+ findings.push({ level: 'warn', message: 'No loop-verifier skill — maker/checker split incomplete.' });
+ recommendations.push('Add templates/SKILL.md.verifier as .grok/skills/loop-verifier/SKILL.md');
+ } else {
+ findings.push({ level: 'ok', message: 'Verifier skill present.' });
+ }
+
+ if (!signals.loopConfig.present) {
+ findings.push({ level: 'warn', message: 'No LOOP.md documenting cadence, limits, and gates.' });
+ recommendations.push('Copy starters/minimal-loop/LOOP.md and customize');
+ }
+
+ if (!signals.agentsMd.present) {
+ findings.push({ level: 'warn', message: 'No AGENTS.md / CLAUDE.md for project conventions.' });
+ recommendations.push('Add AGENTS.md with build/test commands and review norms');
+ }
+
+ if (!signals.safety.loopMdMentionsSafety) {
+ findings.push({ level: 'warn', message: 'LOOP.md does not mention safety gates or auto-merge policy.' });
+ recommendations.push('Document human gates per docs/safety.md in LOOP.md');
+ }
+
+ const { score, level, assessment } = computeScore(signals);
+
+ return {
+ target: root,
+ score,
+ level,
+ assessment,
+ signals,
+ findings,
+ recommendations,
+ };
+}
\ No newline at end of file
diff --git a/tools/loop-audit/src/cli.ts b/tools/loop-audit/src/cli.ts
new file mode 100644
index 0000000..4a73173
--- /dev/null
+++ b/tools/loop-audit/src/cli.ts
@@ -0,0 +1,40 @@
+#!/usr/bin/env node
+import { auditProject } from './auditor.js';
+import { formatHuman, formatJson, formatMarkdown } from './reporter.js';
+
+const args = process.argv.slice(2);
+const target = args.find((a) => !a.startsWith('-')) || '.';
+const json = args.includes('--json');
+const md = args.includes('--md');
+const help = args.includes('--help') || args.includes('-h');
+
+if (help) {
+ console.log(`loop-audit — Loop Readiness Score CLI
+
+Usage:
+ loop-audit [path] [options]
+
+Options:
+ --json JSON output
+ --md Markdown output
+ --help Show help
+
+Exit codes:
+ 0 score >= 40
+ 2 score < 40 (early stage)
+`);
+ process.exit(0);
+}
+
+try {
+ const result = await auditProject(target);
+ if (json) console.log(formatJson(result));
+ else if (md) console.log(formatMarkdown(result));
+ else console.log(formatHuman(result));
+
+ if (result.score < 40) process.exitCode = 2;
+} catch (err: unknown) {
+ const msg = err instanceof Error ? err.message : String(err);
+ console.error('Audit failed:', msg);
+ process.exitCode = 1;
+}
\ No newline at end of file
diff --git a/tools/loop-audit/src/reporter.ts b/tools/loop-audit/src/reporter.ts
new file mode 100644
index 0000000..a28ea6a
--- /dev/null
+++ b/tools/loop-audit/src/reporter.ts
@@ -0,0 +1,58 @@
+import type { AuditResult } from './auditor.js';
+
+export function formatHuman(r: AuditResult): string {
+ const lines: string[] = [];
+ lines.push('');
+ lines.push(`Loop Readiness Audit — ${r.target}`);
+ lines.push('═'.repeat(50));
+ lines.push(`Score: ${r.score}/100 Level: ${r.level}`);
+ lines.push(r.assessment);
+ lines.push('');
+ lines.push('Findings:');
+ for (const f of r.findings) {
+ const icon = f.level === 'ok' ? '✓' : f.level === 'warn' ? '!' : '✗';
+ lines.push(` ${icon} ${f.message}`);
+ }
+ if (r.recommendations.length) {
+ lines.push('');
+ lines.push('Recommendations:');
+ for (const rec of r.recommendations) {
+ lines.push(` → ${rec}`);
+ }
+ }
+ lines.push('');
+ lines.push('Docs: docs/loop-design-checklist.md');
+ lines.push('');
+ return lines.join('\n');
+}
+
+export function formatJson(r: AuditResult): string {
+ return JSON.stringify(r, null, 2);
+}
+
+export function formatMarkdown(r: AuditResult): string {
+ const lines: string[] = [];
+ lines.push('# Loop Readiness Report');
+ lines.push('');
+ lines.push(`| Metric | Value |`);
+ lines.push(`|--------|-------|`);
+ lines.push(`| Target | \`${r.target}\` |`);
+ lines.push(`| Score | **${r.score}/100** |`);
+ lines.push(`| Level | ${r.level} |`);
+ lines.push(`| Assessment | ${r.assessment} |`);
+ lines.push('');
+ lines.push('## Findings');
+ lines.push('');
+ for (const f of r.findings) {
+ lines.push(`- **${f.level}**: ${f.message}`);
+ }
+ if (r.recommendations.length) {
+ lines.push('');
+ lines.push('## Recommendations');
+ lines.push('');
+ for (const rec of r.recommendations) {
+ lines.push(`- ${rec}`);
+ }
+ }
+ return lines.join('\n');
+}
\ No newline at end of file
diff --git a/tools/loop-audit/tsconfig.json b/tools/loop-audit/tsconfig.json
new file mode 100644
index 0000000..3aaa0bd
--- /dev/null
+++ b/tools/loop-audit/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "outDir": "dist",
+ "rootDir": "src",
+ "strict": true,
+ "skipLibCheck": true,
+ "declaration": true
+ },
+ "include": ["src/**/*"]
+}
\ No newline at end of file