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.

feat: implement all 17 loop-engineering improvements

Cobus Greyling384c4c3d09e9
diff --git a/.github/workflows/audit.yml b/.github/workflows/audit.yml
index f22b25f..89a22f0 100644
--- a/.github/workflows/audit.yml
+++ b/.github/workflows/audit.yml
@@ -1,5 +1,9 @@
name: Loop Readiness Audit (dogfood)
+permissions:
+ contents: read
+ pull-requests: write
+
on:
push:
branches: [main]
@@ -21,11 +25,11 @@ jobs:
cache: 'npm'
cache-dependency-path: tools/loop-audit/package-lock.json
- - name: Build & run loop-audit on the reference + starters
+ - name: Build, test & run loop-audit on the reference + starters
run: |
cd tools/loop-audit
npm ci
- npm run build
+ npm test
echo "=== Audit of repo root ==="
node dist/cli.js ../../ || true
echo ""
@@ -54,3 +58,35 @@ jobs:
process.exit(0); // do not fail the whole job on parse issues
}
')
+
+ - name: Comment PR with loop readiness score
+ if: github.event_name == 'pull_request'
+ uses: actions/github-script@v7
+ with:
+ script: |
+ const fs = require('fs');
+ let data;
+ try {
+ data = JSON.parse(fs.readFileSync('/tmp/audit.json', 'utf8'));
+ } catch (e) {
+ core.setFailed('Could not read audit JSON for PR comment');
+ return;
+ }
+ const recs = (data.recommendations || []).slice(0, 5);
+ const body = [
+ '## Loop Readiness Audit',
+ '',
+ `**Score:** ${data.score}/100 (**${data.level}**)`,
+ '',
+ data.assessment,
+ '',
+ recs.length ? '### Top suggestions\n' + recs.map(r => `- ${r}`).join('\n') : '_No suggestions — looking good._',
+ '',
+ '<sub>Posted by `audit.yml` · [loop-audit docs](https://github.com/cobusgreyling/loop-engineering/tree/main/tools/loop-audit)</sub>',
+ ].join('\n');
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: context.issue.number,
+ body,
+ });
diff --git a/.github/workflows/daily-triage.yml b/.github/workflows/daily-triage.yml
new file mode 100644
index 0000000..379a116
--- /dev/null
+++ b/.github/workflows/daily-triage.yml
@@ -0,0 +1,114 @@
+name: Daily Triage (dogfood)
+
+on:
+ schedule:
+ - cron: '0 8 * * 1-5'
+ workflow_dispatch:
+
+permissions:
+ contents: write
+ issues: write
+
+jobs:
+ triage:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '20'
+ cache: 'npm'
+ cache-dependency-path: tools/loop-audit/package-lock.json
+
+ - name: Build loop-audit
+ run: |
+ cd tools/loop-audit
+ npm ci
+ npm run build
+
+ - name: Run reference audit
+ id: audit
+ run: |
+ cd tools/loop-audit
+ node dist/cli.js ../.. --json > /tmp/audit.json
+ SCORE=$(node -e "console.log(JSON.parse(require('fs').readFileSync('/tmp/audit.json','utf8')).score)")
+ LEVEL=$(node -e "console.log(JSON.parse(require('fs').readFileSync('/tmp/audit.json','utf8')).level)")
+ echo "score=$SCORE" >> "$GITHUB_OUTPUT"
+ echo "level=$LEVEL" >> "$GITHUB_OUTPUT"
+
+ - name: Check workflow health
+ id: workflows
+ run: |
+ FAILING=0
+ for wf in validate-patterns audit; do
+ STATUS=$(gh run list --workflow="${wf}.yml" --limit 1 --json conclusion -q '.[0].conclusion' 2>/dev/null || echo "unknown")
+ echo "${wf}: ${STATUS}"
+ if [ "$STATUS" = "failure" ]; then FAILING=$((FAILING + 1)); fi
+ done
+ echo "failing=$FAILING" >> "$GITHUB_OUTPUT"
+ env:
+ GH_TOKEN: ${{ github.token }}
+
+ - name: Update STATE.md
+ run: |
+ DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
+ SCORE="${{ steps.audit.outputs.score }}"
+ LEVEL="${{ steps.audit.outputs.level }}"
+ FAILING="${{ steps.workflows.outputs.failing }}"
+ cat > STATE.md <<EOF
+ # Loop State — loop-engineering reference
+
+ Last run: ${DATE} (automated daily-triage workflow)
+
+ ## High Priority (loop is acting or waiting on human)
+
+ - Maintain loop readiness score ≥ 58 (current: **${SCORE}**, level **${LEVEL}**).
+ - Publish \`@cobusgreyling/loop-audit\` to npm if not yet live (enables \`npx\` installs).
+ $([ "$FAILING" -gt 0 ] && echo "- **${FAILING}** dogfood workflow(s) failing — investigate CI.")
+
+ ## Watch List
+
+ - Expand contributor failure stories (dependency sweeper, multi-loop).
+ - Complete Claude Code / Codex starters for all L2 patterns.
+ - Run \`loop-init\` on a fresh project and verify scaffold output.
+
+ ## Recent Noise (ignored this run)
+
+ —
+
+ ---
+ Run log: Updated by \`.github/workflows/daily-triage.yml\`. See \`LOOP.md\` for cadence and gates.
+ EOF
+
+ - name: Commit STATE.md if changed
+ run: |
+ git config user.name "loop-engineering-bot"
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+ git add STATE.md
+ git diff --staged --quiet || git commit -m "chore(loop): daily triage update STATE.md [automated]"
+ git push || echo "No push needed or nothing to commit"
+
+ - name: Open weekly loop report issue (Mondays)
+ if: github.event.schedule == '0 8 * * 1-5' && format('{0}', github.run_attempt) == '1'
+ run: |
+ DAY=$(date -u +%u)
+ if [ "$DAY" != "1" ]; then echo "Not Monday — skip issue"; exit 0; fi
+ EXISTING=$(gh issue list --label "loop-report" --state open --limit 1 --json number -q '.[0].number' 2>/dev/null || true)
+ if [ -n "$EXISTING" ] && [ "$EXISTING" != "null" ]; then
+ echo "Open loop-report issue #$EXISTING exists"
+ exit 0
+ fi
+ gh label create "loop-report" --color "3ee8c5" --description "Weekly loop triage report" 2>/dev/null || true
+ gh issue create \
+ --title "Loop report — week of $(date -u +%Y-%m-%d)" \
+ --label "loop-report" \
+ --body "## Automated daily triage summary
+
+ - Loop readiness: **${{ steps.audit.outputs.score }}** (${{ steps.audit.outputs.level }})
+ - See updated \`STATE.md\` on main
+ - Review high-priority items and close or re-prioritize
+
+ _Generated by daily-triage workflow. Human reviews and decides actions._"
+ env:
+ GH_TOKEN: ${{ github.token }}
\ No newline at end of file
diff --git a/.github/workflows/release-loop-audit.yml b/.github/workflows/release-loop-audit.yml
new file mode 100644
index 0000000..39d35ea
--- /dev/null
+++ b/.github/workflows/release-loop-audit.yml
@@ -0,0 +1,36 @@
+name: Release loop-audit
+
+on:
+ push:
+ tags:
+ - 'loop-audit-v*'
+
+permissions:
+ contents: read
+ id-token: write
+
+jobs:
+ test-and-publish:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '20'
+ registry-url: 'https://registry.npmjs.org'
+ cache: 'npm'
+ cache-dependency-path: tools/loop-audit/package-lock.json
+
+ - name: Install, build, test
+ working-directory: tools/loop-audit
+ run: |
+ npm ci
+ npm run build
+ npm test
+
+ - name: Publish to npm
+ working-directory: tools/loop-audit
+ run: npm publish --access public
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
\ No newline at end of file
diff --git a/.github/workflows/release-loop-init.yml b/.github/workflows/release-loop-init.yml
new file mode 100644
index 0000000..1d6bc9c
--- /dev/null
+++ b/.github/workflows/release-loop-init.yml
@@ -0,0 +1,30 @@
+name: Release loop-init
+
+on:
+ push:
+ tags:
+ - 'loop-init-v*'
+
+permissions:
+ contents: read
+ id-token: write
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '20'
+ registry-url: 'https://registry.npmjs.org'
+
+ - name: Build & publish
+ working-directory: tools/loop-init
+ run: |
+ npm install
+ npm run build
+ npm publish --access public
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
\ No newline at end of file
diff --git a/.github/workflows/validate-patterns.yml b/.github/workflows/validate-patterns.yml
index 474761b..2f6c83e 100644
--- a/.github/workflows/validate-patterns.yml
+++ b/.github/workflows/validate-patterns.yml
@@ -39,4 +39,11 @@ jobs:
run: |
test -f templates/pattern-template.md || (echo "Missing pattern-template.md"; exit 1)
test -f templates/STATE.md.template || (echo "Missing STATE template"; exit 1)
+ test -f templates/loop-run-log.md.template || (echo "Missing loop-run-log template"; exit 1)
+ test -f templates/loop-budget.md.template || (echo "Missing loop-budget template"; exit 1)
echo "Templates present ✓"
+
+ - name: Validate registry.yaml schema
+ run: |
+ npm install --no-save yaml@2
+ node scripts/validate-registry.mjs
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6af6810..ba4e8ab 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -50,8 +50,10 @@ Also add an entry to `patterns/registry.yaml`.
- Failures are first-class content
- Tool-agnostic by default; tool-specific in labeled sections
-## Questions
+## Community
-Open an issue with label `question` or `pattern-request`.
+- **Questions**: open an issue with label `question` or `pattern-request`
+- **Discussions**: enable GitHub Discussions on the repo for pattern Q&A (recommended for maintainers)
+- **Security**: see [SECURITY.md](./SECURITY.md) — do not file public issues for exploitable vulnerabilities
Thank you for helping make this the go-to reference for loop engineering.
\ No newline at end of file
diff --git a/LOOP.md b/LOOP.md
index 796a2ff..f068432 100644
--- a/LOOP.md
+++ b/LOOP.md
@@ -1,71 +1,68 @@
# LOOP.md — Loop Engineering Reference
-This file documents how the **loop-engineering** reference repository itself is (or will be) operated with loop engineering patterns.
+This file documents how the **loop-engineering** reference repository is operated with loop engineering patterns.
-The goal of this repo is to be the canonical, copyable, high-signal collection of patterns, starters, and tooling. It should therefore eat its own dogfood aggressively.
+The goal of this repo is to be the canonical, copyable, high-signal collection of patterns, starters, and tooling. It eats its own dogfood aggressively.
-## Intended Loops (phased)
+## Active Loops
-### Daily Triage (L1 → L2)
-- Cadence: 1d (or 2h during active development)
-- Skill: loop-triage (from `starters/minimal-loop`)
-- State: STATE.md (or this file + issues)
-- Current phase: Report-only. Human reviews the report each day and decides what to action.
+### Daily Triage (L1 — automated + report)
+- Cadence: 1d weekdays (`/.github/workflows/daily-triage.yml`)
+- Skill: `loop-triage` (from `skills/` and `starters/minimal-loop`)
+- State: `STATE.md` (updated by workflow; human reviews weekly issue)
+- Phase: Report-only. Human reviews and decides actions.
- Handoff: Design decisions, large refactors, new pattern acceptance.
-### PR Babysitter (future, L2)
-- Cadence: 10–15m during active hours
-- Uses the `pr-babysitter` starter + worktrees for any suggested fixes.
-- Will live primarily in the GitHub Actions + comments on PRs.
-- Strong verifier + explicit allowlist for auto-merge (very small safe changes only).
+### PR Babysitter (L2 — assisted, manual trigger)
+- Cadence: 10–15m during active hours (maintainer `/loop` or future Action)
+- Starter: `starters/pr-babysitter` (Grok, Claude Code, Codex)
+- Worktrees for suggested fixes; verifier required; no auto-merge by default.
-### Dependency Sweeper (L2, just added)
+### Dependency Sweeper (L2 — patch-only)
- Cadence: 6h–1d
-- New pattern + starter added in this iteration.
-- Focus: patch + low-risk CVE only for the first 30 days.
-- Verifier = full `npm ci && npm test` (or the build that exists) in worktree.
-- Human gate on anything that touches core packages or majors.
+- Starter: `starters/dependency-sweeper`
+- Patch + low-risk CVE only for first 30 days
+- Verifier = full `npm ci && npm test` in worktree
+- Human gate on majors and denylisted packages
### CI Sweeper / Post-Merge (opportunistic)
-- The `validate-patterns.yml` + `audit.yml` workflows in `.github/workflows/` are the beginning of dogfooding these patterns.
-- Future: a sweeper that reacts to failing validate/audit runs with minimal doc or link fixes.
+- `validate-patterns.yml` + `audit.yml` dogfood pattern validation and readiness scoring
+- `audit.yml` posts loop readiness scores on PRs
+- Future: sweeper reacting to failing validate/audit runs
+
+## Multi-loop coordination
+
+See [docs/multi-loop.md](docs/multi-loop.md). Priority: CI Sweeper → PR Babysitter → Dependency Sweeper → Post-Merge → Daily Triage (report).
## Worktrees
-- Any unattended code-change experiment (dependency sweeper, PR babysitter fixes) runs in an **isolated git worktree** per attempt.
+- Any unattended code-change experiment runs in an **isolated git worktree** per attempt.
- One worktree per fix; discard after verifier REJECT or human escalation.
-- Starters document worktree usage per tool — see `starters/minimal-loop-claude/LOOP.md` and `starters/minimal-loop-codex/LOOP.md`.
## Connectors (MCP)
-- **MCP not required** for L1 daily triage on this reference repo.
-- Optional: GitHub MCP for issue/PR discovery when moving to L2 PR babysitter.
-- Scope connectors to read + comment until the loop is trusted.
+- Optional for L1 daily triage — see [examples/mcp/](examples/mcp/)
+- GitHub MCP read-only for issue/PR discovery
+- Scope connectors to read + comment until the loop is trusted
## Safety & Gates (this repo)
-- No auto-merge on main for anything except the most trivial dependency patches (and even those are behind allowlist + verifier today).
-- Denylist for this reference: anything touching the showcase HTML/CSS, the core primitives docs, or the audit scoring logic without human review.
-- Live loop state: `STATE.md` at repo root (dogfooded). Starters still ship `.example` files for consumers.
-
-## How to run the loops here (for contributors / the maintainer)
+- No auto-merge on main except trivial dependency patches (allowlist + verifier)
+- Denylist: showcase HTML/CSS, core primitives docs, audit scoring logic without human review
+- Live loop state: `STATE.md` at repo root
-See the individual pattern docs and the GitHub Actions.
-
-Quick local check:
+## How to run locally
```bash
node tools/loop-audit/dist/cli.js . --suggest
+npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok # after npm publish
+bash scripts/before-after-demo.sh
```
-After changes to patterns, starters, or docs, the `validate-patterns` + `audit` workflows will run automatically on PRs.
-
## Evolution
-We will raise the L level of this repo itself over time and record the journey in `stories/`.
-
-Current target for the reference: solid L2 with excellent observability and zero "I had to hand-hold the loop for an hour" stories.
+Journey recorded in `stories/`. Target: solid L2 with excellent observability.
---
-*This file is both documentation and the seed for the loops that will maintain the reference.*
+*This file is both documentation and the seed for the loops that maintain the reference.*
\ No newline at end of file
diff --git a/README.md b/README.md
index 3eacfc1..b622806 100644
--- a/README.md
+++ b/README.md
@@ -30,11 +30,13 @@ A loop is a recursive goal: you define a purpose and the AI iterates (often with
| Start here | Description |
|------------|-------------|
-| [Primitives Matrix](docs/primitives-matrix.md) | Grok vs Claude Code vs Codex — **bookmark this** |
+| [Pattern Picker](docs/pattern-picker.md) | Which loop to run first — **start here if unsure** |
+| [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/) | Clone-and-run kits (Grok, Claude Code, Codex) |
| [loop-audit](tools/loop-audit/) | Loop Readiness Score CLI — `npx @cobusgreyling/loop-audit` |
+| [loop-init](tools/loop-init/) | Scaffold starters — `npx @cobusgreyling/loop-init` |
| [Stories](stories/) | Real wins and honest failures |
## Why This Matters
@@ -81,29 +83,25 @@ flowchart LR
## Patterns
-| 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 | — |
-| [Dependency Sweeper](patterns/dependency-sweeper.md) | 6h–1d | [starters/dependency-sweeper](starters/dependency-sweeper/) |
+| Pattern | Cadence | Starter | Week 1 | Token cost |
+|---------|---------|---------|--------|------------|
+| [Daily Triage](patterns/daily-triage.md) | 1d–2h | [minimal-loop](starters/minimal-loop/) | **L1** report | Low |
+| [PR Babysitter](patterns/pr-babysitter.md) | 5–15m | [pr-babysitter](starters/pr-babysitter/) | L1 watch | High |
+| [CI Sweeper](patterns/ci-sweeper.md) | 5–15m | [ci-sweeper](starters/ci-sweeper/) | L2 cautious | Very high |
+| [Dependency Sweeper](patterns/dependency-sweeper.md) | 6h–1d | [dependency-sweeper](starters/dependency-sweeper/) | L2 patch-only | Medium |
+| [Post-Merge Cleanup](patterns/post-merge-cleanup.md) | 1d–6h | [post-merge-cleanup](starters/post-merge-cleanup/) | **L1** off-peak | Low |
+
+Not sure which to pick? See [pattern-picker](docs/pattern-picker.md).
Machine-readable index: [patterns/registry.yaml](patterns/registry.yaml)
## Getting Started (5 minutes)
```bash
-# 1. Pick a starter for your tool
-# Grok:
-cp -r starters/minimal-loop/.grok/skills/loop-triage .grok/skills/
-# Claude Code:
-cp -r starters/minimal-loop-claude/.claude/skills/loop-triage .claude/skills/
-# Codex:
-cp -r starters/minimal-loop-codex/.codex/skills/loop-triage .codex/skills/
-cp starters/minimal-loop/STATE.md.example STATE.md
-
-# 2. Audit readiness (no clone required)
+# 1. Scaffold a starter (or copy manually — see starters/)
+npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok
+
+# 2. Audit readiness
npx @cobusgreyling/loop-audit . --suggest
# 3. See scores climb: empty → L1 → L2
@@ -125,9 +123,13 @@ Phased rollout: **L1 report → L2 assisted fixes → L3 unattended** — see [l
## Operating & Safety
- [Failure Modes](docs/failure-modes.md) — incident-style catalog
+- [Anti-Patterns](docs/anti-patterns.md) — design mistakes before production
+- [Multi-Loop Coordination](docs/multi-loop.md) — when loops collide
- [Operating Loops](docs/operating-loops.md) — cost, logging, when to kill
- [Safety](docs/safety.md) — denylist, auto-merge, MCP scopes
+- [Security](SECURITY.md) — reporting and unattended automation risks
- [Concepts](docs/concepts.md) — intent debt, comprehension debt, harness vs loop
+- [MCP Cookbook](examples/mcp/) — connector examples by pattern
## Caveats
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..2aef24f
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,35 @@
+# Security Policy
+
+Loop engineering runs unattended automation against your codebase. Treat loops like production operators.
+
+## Reporting vulnerabilities
+
+Email security concerns privately if you discover issues in this reference repo or in `loop-audit` / `loop-init` tooling. Do not open public issues for exploitable vulnerabilities.
+
+For general loop safety guidance, see [docs/safety.md](docs/safety.md).
+
+## Unattended automation risks
+
+| Risk | Mitigation |
+|------|------------|
+| Auto-merge of malicious dependency | Denylist + verifier + no auto-merge week one |
+| MCP over-permission | Read-only connectors for L1; scope write to PR comments only |
+| Secret exfiltration via prompts | Denylist `.env`, credentials paths; never log secrets in STATE.md |
+| Infinite fix loops burning budget | Hard attempt caps; kill switch in LOOP.md |
+| Supply-chain in loop-produced PRs | Human review for anything outside allowlist |
+
+## Recommended gates before L3
+
+- [ ] Path denylist documented in LOOP.md
+- [ ] Verifier runs tests in isolated worktree
+- [ ] No auto-merge without explicit allowlist
+- [ ] MCP connectors use least privilege
+- [ ] `loop-run-log.md` or equivalent observability
+
+## Supported versions
+
+| Package | Supported |
+|---------|-----------|
+| `@cobusgreyling/loop-audit` | Latest release on npm |
+| `@cobusgreyling/loop-init` | Latest release on npm |
+| Reference repo `main` | Current HEAD |
\ No newline at end of file
diff --git a/STATE.md b/STATE.md
index f0cd839..81a9260 100644
--- a/STATE.md
+++ b/STATE.md
@@ -1,16 +1,16 @@
# Loop State — loop-engineering reference
-Last run: not yet automated (maintainer or daily triage loop updates this)
+Last run: pending first automated run (see `.github/workflows/daily-triage.yml`)
## High Priority (loop is acting or waiting on human)
-- Dogfood L2 on the reference repo itself (STATE, skills, AGENTS.md, audit gate ≥ 58).
-- Publish `@cobusgreyling/loop-audit` to npm for `npx` installs.
+- Publish `@cobusgreyling/loop-audit` and `@cobusgreyling/loop-init` to npm for `npx` installs.
+- Dogfood L2 on the reference repo (STATE, skills, AGENTS.md, audit gate ≥ 58).
## Watch List
-- Add more contributor-submitted failure stories.
-- Expand Claude Code / Codex starters beyond daily triage.
+- Collect contributor failure stories beyond the six in `stories/`.
+- Validate `loop-init` scaffolds on fresh projects across all five patterns.
## Recent Noise (ignored this run)
diff --git a/docs/anti-patterns.md b/docs/anti-patterns.md
new file mode 100644
index 0000000..44a0a2c
--- /dev/null
+++ b/docs/anti-patterns.md
@@ -0,0 +1,83 @@
+# Anti-Patterns
+
+Design mistakes to avoid **before** enabling unattended loops. For runtime incidents, see [failure-modes.md](./failure-modes.md).
+
+## 1. Same agent implements and verifies
+
+**Anti-pattern**: One session marks its own work "done" after running tests once.
+
+**Why it fails**: Confirmation bias; weak tests get rubber-stamped.
+
+**Do instead**: Separate verifier sub-agent, model, or `/goal` checker. Verifier default stance: REJECT.
+
+## 2. No attempt cap
+
+**Anti-pattern**: "Keep trying until CI is green."
+
+**Why it fails**: Infinite fix loops, token burn, merge of wrong fixes.
+
+**Do instead**: Hard cap (e.g. 3 attempts) → escalate with full context in state file.
+
+## 3. Vague triage output
+
+**Anti-pattern**: Triage skill returns paragraphs of narrative.
+
+**Why it fails**: Loop cannot parse priorities; humans ignore STATE.md.
+
+**Do instead**: Structured markdown sections with one-line items and explicit `Suggested loop action`.
+
+## 4. L3 before L1 quality
+
+**Anti-pattern**: Auto-fix and auto-PR on day one.
+
+**Why it fails**: Loop acts on bad signal; comprehension debt explodes.
+
+**Do instead**: L1 report-only week one. Measure triage accuracy before enabling L2.
+
+## 5. Shared state without schema
+
+**Anti-pattern**: Three loops append to one unstructured STATE.md.
+
+**Why it fails**: State rot, conflicting actions, ghost items.
+
+**Do instead**: One state file per pattern, or clearly separated sections with prune rules.
+
+## 6. MCP with write-everything scope
+
+**Anti-pattern**: Loop can merge PRs, post to Slack, and edit production tickets on day one.
+
+**Why it fails**: Blast radius of a bad triage decision is huge.
+
+**Do instead**: L1 read-only connectors. Expand scope only after trust is earned.
+
+## 7. No kill switch
+
+**Anti-pattern**: Loop runs 24/7 with no pause criteria.
+
+**Why it fails**: Alert fatigue, budget overrun, weekend incidents.
+
+**Do instead**: Document pause/kill in LOOP.md + `templates/loop-budget.md.template`.
+
+## 8. Fixing flakes with code
+
+**Anti-pattern**: CI Sweeper changes application code when classification is `flake`.
+
+**Why it fails**: Masks infra problems; introduces random diffs.
+
+**Do instead**: Classify → quarantine or retry policy → escalate env/infra failures.
+
+## 9. Auto-merge without allowlist
+
+**Anti-pattern**: "Verifier passed, merge it."
+
+**Why it fails**: Security and business-logic bugs pass weak verifiers.
+
+**Do instead**: Explicit path allowlist; human merge for denylist paths per [safety.md](./safety.md).
+
+## 10. No run log
+
+**Anti-pattern**: Only STATE.md, no history of what the loop did.
+
+**Why it fails**: Cannot debug "why did it do that Tuesday?"
+
+**Do instead**: Append to `loop-run-log.md` per [operating-loops.md](./operating-loops.md).
\ No newline at end of file
diff --git a/docs/index.html b/docs/index.html
index 093c78a..9c9dab5 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -31,7 +31,7 @@ title: Loop Engineering — Showcase
</nav>
<header class="hero wrap">
- <div class="badge">Open source · Tool-agnostic · Production-ready</div>
+ <div class="badge">Open source · Tool-agnostic · Production-ready · L3 dogfood score</div>
<h1>Design the system<br>that prompts your agents</h1>
<p class="lead">
Loop engineering moves you from "I prompt → agent responds → I prompt again"
@@ -148,6 +148,7 @@ title: Loop Engineering — Showcase
<span>◆ Medium risk</span>
</div>
<a class="link" href="https://github.com/cobusgreyling/loop-engineering/blob/main/patterns/pr-babysitter.md">Read pattern →</a>
+ <a class="link" href="https://github.com/cobusgreyling/loop-engineering/tree/main/starters/pr-babysitter" style="margin-left:12px">Starter →</a>
</article>
<article class="pattern-card">
<span class="tag">Start here</span>
@@ -158,6 +159,7 @@ title: Loop Engineering — Showcase
<span>◆ Low risk</span>
</div>
<a class="link" href="https://github.com/cobusgreyling/loop-engineering/blob/main/patterns/daily-triage.md">Read pattern →</a>
+ <a class="link" href="https://github.com/cobusgreyling/loop-engineering/tree/main/starters/minimal-loop" style="margin-left:12px">Starter →</a>
</article>
<article class="pattern-card">
<span class="tag">High frequency</span>
@@ -168,6 +170,7 @@ title: Loop Engineering — Showcase
<span>◆ Medium risk</span>
</div>
<a class="link" href="https://github.com/cobusgreyling/loop-engineering/blob/main/patterns/ci-sweeper.md">Read pattern →</a>
+ <a class="link" href="https://github.com/cobusgreyling/loop-engineering/tree/main/starters/ci-sweeper" style="margin-left:12px">Starter →</a>
</article>
<article class="pattern-card">
<span class="tag">Off-peak</span>
@@ -178,15 +181,27 @@ title: Loop Engineering — Showcase
<span>◆ Low risk</span>
</div>
<a class="link" href="https://github.com/cobusgreyling/loop-engineering/blob/main/patterns/post-merge-cleanup.md">Read pattern →</a>
+ <a class="link" href="https://github.com/cobusgreyling/loop-engineering/tree/main/starters/post-merge-cleanup" style="margin-left:12px">Starter →</a>
+ </article>
+ <article class="pattern-card">
+ <span class="tag">Security</span>
+ <h3>Dependency Sweeper</h3>
+ <p>Patch CVEs and stale deps in worktrees. Majors and denylist stay human-gated.</p>
+ <div class="pattern-meta">
+ <span>⏱ 6h–1d</span>
+ <span>◆ Medium risk</span>
+ </div>
+ <a class="link" href="https://github.com/cobusgreyling/loop-engineering/blob/main/patterns/dependency-sweeper.md">Read pattern →</a>
+ <a class="link" href="https://github.com/cobusgreyling/loop-engineering/tree/main/starters/dependency-sweeper" style="margin-left:12px">Starter →</a>
</article>
</div>
<div class="stats">
<div class="stat">
- <div class="num">4</div>
+ <div class="num">5</div>
<div class="label">Patterns</div>
</div>
<div class="stat">
- <div class="num">3</div>
+ <div class="num">7</div>
<div class="label">Starter kits</div>
</div>
<div class="stat">
@@ -209,12 +224,11 @@ title: Loop Engineering — Showcase
<div class="code-dots"><span></span><span></span><span></span></div>
<span>terminal — minimal loop</span>
</div>
- <pre><span class="comment"># Copy starter into your project</span>
-cp -r starters/minimal-loop/.grok/skills/loop-triage .grok/skills/
-cp starters/minimal-loop/STATE.md.example STATE.md
+ <pre><span class="comment"># Scaffold starter (or copy manually)</span>
+npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok
-<span class="comment"># Score loop readiness</span>
-node tools/loop-audit/dist/cli.js .
+<span class="comment"># Score loop readiness (PRs get audit comments in CI)</span>
+npx @cobusgreyling/loop-audit . --suggest
<span class="comment"># Grok — report only, week one</span>
<span class="cmd">/loop</span> <span class="flag">1d</span> Run loop-triage. Update STATE.md. No auto-fix.</pre>
@@ -247,6 +261,11 @@ node tools/loop-audit/dist/cli.js .
<p>Loop Readiness Score 0–100. Know before you ship unattended.</p>
<a class="link" href="https://github.com/cobusgreyling/loop-engineering/tree/main/tools/loop-audit">Run audit →</a>
</article>
+ <article class="pattern-card">
+ <h3>Pattern Picker</h3>
+ <p>CI red? PRs stalling? Morning chaos? Pick the right loop first.</p>
+ <a class="link" href="https://github.com/cobusgreyling/loop-engineering/blob/main/docs/pattern-picker.md">Choose pattern →</a>
+ </article>
</div>
</section>
diff --git a/docs/multi-loop.md b/docs/multi-loop.md
new file mode 100644
index 0000000..d929b1d
--- /dev/null
+++ b/docs/multi-loop.md
@@ -0,0 +1,73 @@
+# Multi-Loop Coordination
+
+Running more than one loop in a repo is normal. Running them without boundaries is how loops fight each other.
+
+## Principles
+
+1. **One owner per branch** — at most one loop may mutate a branch per hour.
+2. **Separate state files** — `STATE.md` for triage; pattern-specific files for action loops.
+3. **Triage reports, action loops execute** — Daily Triage at L1 never competes with CI Sweeper fixes.
+4. **Shared denylist** — copy the same path denylist into every LOOP.md.
+5. **Aggregate token budget** — see `templates/loop-budget.md.template`.
+
+## Recommended state layout
+
+```
+STATE.md # Daily Triage (priorities, human inbox)
+pr-babysitter-state.md # PR watcher
+ci-sweeper-state.md # Active CI failures + attempt counts
+dependency-sweeper-state.md # In-flight package updates
+post-merge-state.md # Cleanup backlog
+loop-run-log.md # Append-only observability
+```
+
+## Priority when loops conflict
+
+| Priority | Loop | Reason |
+|----------|------|--------|
+| 1 | CI Sweeper | Red main blocks everything |
+| 2 | PR Babysitter | Active PRs are time-sensitive |
+| 3 | Dependency Sweeper | Pause while CI red |
+| 4 | Post-Merge Cleanup | Off-peak, lowest urgency |
+| 5 | Daily Triage | Reports only at L1; schedules others |
+
+## Scheduler coordination
+
+Document in root `LOOP.md`:
+
+```markdown
+## Multi-loop schedule
+- CI Sweeper: /loop 15m (active hours)
+- PR Babysitter: /loop 10m (active hours, skip if CI Sweeper acting on same PR)
+- Daily Triage: /loop 1d 08:00
+- Dependency Sweeper: /loop 6h (skip if main CI red)
+- Post-Merge: /loop 1d 22:00
+```
+
+## Collision detection
+
+Each action loop should write `acting_on: branch-or-pr-id` in its state file. Before spawning a fix:
+
+1. Read all other pattern state files
+2. If another loop `acting_on` matches → skip and log to `loop-run-log.md`
+
+## Human inbox
+
+Use a shared section in `STATE.md`:
+
+```markdown
+## Human Inbox (ambiguous / cross-loop)
+- [ ] PR #42: CI Sweeper and PR Babysitter both flagged — human pick owner
+```
+
+## Example: safe three-loop setup
+
+| Loop | Level | Cadence |
+|------|-------|---------|
+| Daily Triage | L1 | 1d |
+| PR Babysitter | L2 | 10m |
+| Post-Merge Cleanup | L1 → L2 | 1d off-peak |
+
+Add CI Sweeper only after PR Babysitter attempt limits and verifier are proven for two weeks.
+
+See [stories/multi-loop-collision.md](../stories/multi-loop-collision.md) for a real collision story.
\ No newline at end of file
diff --git a/docs/pattern-picker.md b/docs/pattern-picker.md
new file mode 100644
index 0000000..d9c1733
--- /dev/null
+++ b/docs/pattern-picker.md
@@ -0,0 +1,46 @@
+# Which Pattern When?
+
+Pick one primary loop per concern. Overlapping loops need coordination — see [multi-loop.md](./multi-loop.md).
+
+```mermaid
+flowchart TD
+ A[What hurts right now?] --> B{CI red?}
+ B -->|yes| C[CI Sweeper]
+ B -->|no| D{PRs stalling?}
+ D -->|yes| E[PR Babysitter]
+ D -->|no| F{Morning chaos / unknown priorities?}
+ F -->|yes| G[Daily Triage]
+ F -->|no| H{Dependabot / CVE noise?}
+ H -->|yes| I[Dependency Sweeper]
+ H -->|no| J{Merge debt / TODOs piling up?}
+ J -->|yes| K[Post-Merge Cleanup]
+ J -->|no| G
+```
+
+## Quick reference
+
+| Symptom | Pattern | Start with |
+|---------|---------|------------|
+| CI failing on main or PRs | [CI Sweeper](../patterns/ci-sweeper.md) | L2, 15m cadence, max 3 attempts |
+| PRs waiting on review/CI/rebase | [PR Babysitter](../patterns/pr-babysitter.md) | L1 watch → L2 assisted |
+| "What should I work on?" every morning | [Daily Triage](../patterns/daily-triage.md) | **L1 report-only week one** |
+| Outdated packages / CVE alerts | [Dependency Sweeper](../patterns/dependency-sweeper.md) | L2 patch-only, denylist majors |
+| TODOs and cleanup after merges | [Post-Merge Cleanup](../patterns/post-merge-cleanup.md) | L1 off-peak, small fixes only |
+
+## Overlap rules
+
+| Combination | Rule |
+|-------------|------|
+| CI Sweeper + PR Babysitter | CI Sweeper owns failing checks; PR Babysitter does not re-fix the same branch in the same hour |
+| Daily Triage + anything | Daily Triage reports; action loops execute. Triage does not auto-fix in L1 |
+| Dependency Sweeper + CI Sweeper | Pause Dependency Sweeper while CI is red on main |
+| Post-Merge + PR Babysitter | Post-Merge runs off-peak only |
+
+## First loop recommendation
+
+If unsure, start with **Daily Triage at L1**. It teaches state discipline without auto-merge risk.
+
+```bash
+npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok
+npx @cobusgreyling/loop-audit . --suggest
+```
\ No newline at end of file
diff --git a/docs/primitives-matrix.md b/docs/primitives-matrix.md
index f4db382..e3cdca6 100644
--- a/docs/primitives-matrix.md
+++ b/docs/primitives-matrix.md
@@ -70,4 +70,21 @@ See [examples/](../examples/) for the same pattern implemented across tools.
| Claude Code | [starters/minimal-loop-claude](../starters/minimal-loop-claude/) |
| Codex | [starters/minimal-loop-codex](../starters/minimal-loop-codex/) |
-Audit after copying: `npx @cobusgreyling/loop-audit . --suggest`
\ No newline at end of file
+Audit after copying: `npx @cobusgreyling/loop-audit . --suggest`
+
+Scaffold automatically: `npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok`
+
+## Appendix: Other agent environments (capability mapping)
+
+No dedicated starters yet — map capabilities to the same loop shape:
+
+| Primitive | Cursor | Windsurf | Aider |
+|-----------|--------|----------|-------|
+| Scheduling | Rules + background agents, manual `/loop`-style prompts | Workflows, cascades | `--watch` / scripted sessions |
+| Worktrees | Git worktree per Composer task | Workspace isolation | Git branches |
+| Skills | `.cursor/rules`, `AGENTS.md` | Rules files | `CONVENTIONS.md` / `.aider.conf.yml` |
+| Connectors | MCP in settings | MCP | CLI + git only |
+| Sub-agents | Multi-agent / review mode | Cascade steps | Second terminal reviewer |
+| State | `STATE.md`, `LOOP.md` | Same | Same |
+
+Transfer recipe: copy the tool-agnostic `SKILL.md` + state schema from this repo; map scheduling to your editor's automation surface.
\ No newline at end of file
diff --git a/examples/README.md b/examples/README.md
index 9b9656b..fada60d 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -8,6 +8,7 @@ Same patterns, different tools. Skills and state schemas are shared; only schedu
| Claude Code | [claude-code/](./claude-code/) |
| Codex App | [codex/](./codex/) |
| GitHub Actions | [github-actions/](./github-actions/) |
+| MCP connectors | [mcp/](./mcp/) |
Start with [primitives-matrix.md](../docs/primitives-matrix.md) to map capabilities.
diff --git a/examples/mcp/README.md b/examples/mcp/README.md
new file mode 100644
index 0000000..5d39b21
--- /dev/null
+++ b/examples/mcp/README.md
@@ -0,0 +1,68 @@
+# MCP Connector Cookbook
+
+Minimal MCP setups for loop patterns. Start **read-only** (L1); expand scope only after trust.
+
+## GitHub MCP (L1 — read)
+
+**Use in**: Daily Triage, PR Babysitter (discovery)
+
+```json
+{
+ "mcpServers": {
+ "github": {
+ "command": "npx",
+ "args": ["-y", "@modelcontextprotocol/server-github"],
+ "env": {
+ "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
+ }
+ }
+ }
+}
+```
+
+**Scopes**: `repo:status`, `read:org`, `read:user` — no `repo` write until L2.
+
+**Loop prompt snippet**:
+```
+Read open PRs and recent CI conclusions via GitHub MCP. Do not comment or merge. Update STATE.md only.
+```
+
+## GitHub MCP (L2 — comment)
+
+**Use in**: PR Babysitter, CI Sweeper
+
+Add scope: `public_repo` or fine-grained **Pull requests: Read and write** (comments only).
+
+**Gate**: Bot signs comments: `🤖 Loop Engineering — PR Babysitter`
+
+## Linear MCP (L1 — read)
+
+**Use in**: Daily Triage
+
+```
+Connect Linear MCP with read-only API key. Triage assigned issues into STATE.md High Priority. No ticket creation in week one.
+```
+
+## Slack MCP (L1 — read)
+
+**Use in**: Daily Triage
+
+```
+Read #engineering channel last 24h for incident threads. Summarize in Watch Items. Never post to Slack unattended in L1.
+```
+
+## Scope matrix
+
+| Pattern | L1 MCP | L2 MCP |
+|---------|--------|--------|
+| Daily Triage | GitHub read, Linear read | — |
+| PR Babysitter | GitHub read | GitHub PR comments |
+| CI Sweeper | GitHub Actions read | PR comments on fix branches |
+| Dependency Sweeper | — | GitHub PR create (no auto-merge) |
+| Post-Merge Cleanup | GitHub read (recent merges) | Small PR propose |
+
+## Not required
+
+MCP is optional for L1 daily triage on small repos. Git + local STATE.md is enough for week one.
+
+See [docs/safety.md](../../docs/safety.md) for denylist and least-privilege rules.
\ No newline at end of file
diff --git a/examples/mcp/github-readonly.mcp.json b/examples/mcp/github-readonly.mcp.json
new file mode 100644
index 0000000..75bf727
--- /dev/null
+++ b/examples/mcp/github-readonly.mcp.json
@@ -0,0 +1,11 @@
+{
+ "mcpServers": {
+ "github": {
+ "command": "npx",
+ "args": ["-y", "@modelcontextprotocol/server-github"],
+ "env": {
+ "GITHUB_PERSONAL_ACCESS_TOKEN": "REPLACE_WITH_READ_ONLY_TOKEN"
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..4772e24
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,29 @@
+{
+ "name": "loop-engineering",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "loop-engineering",
+ "devDependencies": {
+ "yaml": "^2.8.0"
+ }
+ },
+ "node_modules/yaml": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
+ "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "yaml": "bin.mjs"
+ },
+ "engines": {
+ "node": ">= 14.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/eemeli"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..2434080
--- /dev/null
+++ b/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "loop-engineering",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "validate:registry": "node scripts/validate-registry.mjs",
+ "test:loop-audit": "cd tools/loop-audit && npm test",
+ "build:tools": "cd tools/loop-audit && npm run build && cd ../loop-init && npm run build"
+ },
+ "devDependencies": {
+ "yaml": "^2.8.0"
+ }
+}
\ No newline at end of file
diff --git a/patterns/README.md b/patterns/README.md
index 5c6e5b1..2fc9abc 100644
--- a/patterns/README.md
+++ b/patterns/README.md
@@ -24,12 +24,13 @@ Machine-readable index: [registry.yaml](./registry.yaml)
## How to Use a Pattern
-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.
+1. Pick a pattern: [pattern-picker.md](../docs/pattern-picker.md)
+2. Scaffold with `npx @cobusgreyling/loop-init . --pattern <name> --tool grok` or copy from `starters/`
+3. Copy skills from `templates/` if customizing beyond the starter
+4. Set up scheduling (`/loop`, `scheduler_create`, GitHub Action, Codex Automation)
+5. Create the initial state file (or let `loop-init` do it)
+6. Start the loop — **report-only first** when the pattern supports phased rollout
+7. 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.
diff --git a/patterns/registry.schema.json b/patterns/registry.schema.json
new file mode 100644
index 0000000..43e6ea6
--- /dev/null
+++ b/patterns/registry.schema.json
@@ -0,0 +1,87 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://github.com/cobusgreyling/loop-engineering/patterns/registry.schema.json",
+ "title": "Loop Pattern Registry",
+ "type": "object",
+ "required": ["patterns"],
+ "additionalProperties": false,
+ "properties": {
+ "patterns": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "type": "object",
+ "required": [
+ "id",
+ "name",
+ "file",
+ "goal",
+ "cadence",
+ "risk",
+ "tools",
+ "skills",
+ "state",
+ "phases",
+ "human_gates"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^[a-z][a-z0-9-]*$"
+ },
+ "name": { "type": "string", "minLength": 3 },
+ "file": {
+ "type": "string",
+ "pattern": "^[a-z0-9-]+\\.md$"
+ },
+ "goal": { "type": "string", "minLength": 10 },
+ "cadence": {
+ "type": "string",
+ "pattern": "^[0-9]+[mhd](-[0-9]+[mhd])?$"
+ },
+ "risk": {
+ "type": "string",
+ "enum": ["low", "medium", "high"]
+ },
+ "tools": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "type": "string",
+ "enum": ["grok", "claude-code", "codex", "github-actions", "cursor", "windsurf", "aider"]
+ }
+ },
+ "skills": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "type": "string", "minLength": 2 }
+ },
+ "state": {
+ "type": "string",
+ "pattern": "^[A-Za-z0-9-]+\\.md$"
+ },
+ "phases": {
+ "type": "array",
+ "minItems": 2,
+ "items": { "type": "string", "minLength": 2 }
+ },
+ "human_gates": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "type": "string", "minLength": 2 }
+ },
+ "starter": { "type": "string" },
+ "week_one_mode": {
+ "type": "string",
+ "enum": ["L1", "L2", "L3"]
+ },
+ "token_cost": {
+ "type": "string",
+ "enum": ["low", "medium", "high", "very-high"]
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/patterns/registry.yaml b/patterns/registry.yaml
index 2558424..4397dc0 100644
--- a/patterns/registry.yaml
+++ b/patterns/registry.yaml
@@ -13,6 +13,9 @@ patterns:
state: pr-babysitter-state.md
phases: [discover, triage, fix, verify, notify]
human_gates: [security, payments, auth, max-fix-attempts]
+ starter: starters/pr-babysitter
+ week_one_mode: L1
+ token_cost: high
- id: daily-triage
name: Daily Triage
@@ -25,6 +28,9 @@ patterns:
state: STATE.md
phases: [report, act-small-wins, escalate]
human_gates: [design-decisions, multi-file-refactors]
+ starter: starters/minimal-loop
+ week_one_mode: L1
+ token_cost: low
- id: ci-sweeper
name: CI Sweeper
@@ -37,6 +43,9 @@ patterns:
state: ci-sweeper-state.md
phases: [detect, classify, fix, verify, escalate]
human_gates: [infra-failures, max-attempts, security-tests]
+ starter: starters/ci-sweeper
+ week_one_mode: L2
+ token_cost: very-high
- id: post-merge-cleanup
name: Post-Merge Cleanup
@@ -49,6 +58,9 @@ patterns:
state: post-merge-state.md
phases: [scan-merges, prioritize, fix-small, ticket-large]
human_gates: [architectural-debt, feature-flags, large-diffs]
+ starter: starters/post-merge-cleanup
+ week_one_mode: L1
+ token_cost: low
- id: dependency-sweeper
name: Dependency Sweeper
@@ -60,4 +72,7 @@ patterns:
skills: [dependency-triage, minimal-fix, loop-verifier]
state: dependency-sweeper-state.md
phases: [scan, triage-risk, patch-safe, verify-worktree, escalate-risky]
- human_gates: [major-bumps, high-sev-cve, denylisted-packages, max-attempts]
\ No newline at end of file
+ human_gates: [major-bumps, high-sev-cve, denylisted-packages, max-attempts]
+ starter: starters/dependency-sweeper
+ week_one_mode: L2
+ token_cost: medium
\ No newline at end of file
diff --git a/scripts/validate-registry.mjs b/scripts/validate-registry.mjs
new file mode 100644
index 0000000..5e50eaf
--- /dev/null
+++ b/scripts/validate-registry.mjs
@@ -0,0 +1,84 @@
+#!/usr/bin/env node
+/**
+ * Validates patterns/registry.yaml against registry.schema.json
+ * and ensures file/registry alignment.
+ */
+import { readFile, readdir } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import yaml from 'yaml';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+const CADENCE_RE = /^[0-9]+[mhd](-[0-9]+[mhd])?$/;
+const ID_RE = /^[a-z][a-z0-9-]*$/;
+const FILE_RE = /^[A-Za-z0-9-]+\.md$/;
+const VALID_TOOLS = new Set(['grok', 'claude-code', 'codex', 'github-actions', 'cursor', 'windsurf', 'aider']);
+const VALID_RISK = new Set(['low', 'medium', 'high']);
+const VALID_MODES = new Set(['L1', 'L2', 'L3']);
+const VALID_COST = new Set(['low', 'medium', 'high', 'very-high']);
+
+function fail(msg) {
+ console.error(`ERROR: ${msg}`);
+ process.exit(1);
+}
+
+function validatePattern(p, index) {
+ const prefix = `patterns[${index}]`;
+ const required = ['id', 'name', 'file', 'goal', 'cadence', 'risk', 'tools', 'skills', 'state', 'phases', 'human_gates'];
+ for (const key of required) {
+ if (!(key in p)) fail(`${prefix} missing required field: ${key}`);
+ }
+ if (!ID_RE.test(p.id)) fail(`${prefix}.id invalid: ${p.id}`);
+ if (!FILE_RE.test(p.file)) fail(`${prefix}.file invalid: ${p.file}`);
+ if (!CADENCE_RE.test(p.cadence)) fail(`${prefix}.cadence invalid: ${p.cadence}`);
+ if (!VALID_RISK.has(p.risk)) fail(`${prefix}.risk invalid: ${p.risk}`);
+ if (!Array.isArray(p.tools) || p.tools.length === 0) fail(`${prefix}.tools must be non-empty array`);
+ for (const t of p.tools) {
+ if (!VALID_TOOLS.has(t)) fail(`${prefix}.tools unknown tool: ${t}`);
+ }
+ if (!Array.isArray(p.skills) || p.skills.length === 0) fail(`${prefix}.skills must be non-empty array`);
+ if (!FILE_RE.test(p.state)) fail(`${prefix}.state invalid: ${p.state}`);
+ if (!Array.isArray(p.phases) || p.phases.length < 2) fail(`${prefix}.phases must have ≥2 entries`);
+ if (!Array.isArray(p.human_gates) || p.human_gates.length === 0) fail(`${prefix}.human_gates must be non-empty`);
+ if (p.week_one_mode && !VALID_MODES.has(p.week_one_mode)) fail(`${prefix}.week_one_mode invalid`);
+ if (p.token_cost && !VALID_COST.has(p.token_cost)) fail(`${prefix}.token_cost invalid`);
+}
+
+async function main() {
+ const registryPath = path.join(ROOT, 'patterns', 'registry.yaml');
+ const raw = await readFile(registryPath, 'utf8');
+ const doc = yaml.parse(raw);
+
+ if (!doc?.patterns?.length) fail('registry.yaml must have patterns array');
+
+ doc.patterns.forEach(validatePattern);
+
+ const ids = new Set();
+ for (const p of doc.patterns) {
+ if (ids.has(p.id)) fail(`duplicate pattern id: ${p.id}`);
+ ids.add(p.id);
+ const mdPath = path.join(ROOT, 'patterns', p.file);
+ try {
+ await readFile(mdPath, 'utf8');
+ } catch {
+ fail(`registry entry ${p.id} references missing file: patterns/${p.file}`);
+ }
+ }
+
+ const mdFiles = (await readdir(path.join(ROOT, 'patterns')))
+ .filter((f) => f.endsWith('.md') && f !== 'README.md');
+ const registeredFiles = new Set(doc.patterns.map((p) => p.file.replace(/\.md$/, '')));
+
+ for (const f of mdFiles) {
+ const base = f.replace(/\.md$/, '');
+ if (!registeredFiles.has(base)) fail(`pattern file not in registry: ${f}`);
+ }
+
+ console.log(`Registry valid: ${doc.patterns.length} patterns ✓`);
+}
+
+main().catch((e) => {
+ console.error(e);
+ process.exit(1);
+});
\ No newline at end of file
diff --git a/starters/README.md b/starters/README.md
index 4f392a4..74c8e74 100644
--- a/starters/README.md
+++ b/starters/README.md
@@ -1,6 +1,11 @@
# Starters
-Clone-and-run scaffolds. Copy into your project — do not submodule the whole repo unless you want the docs too.
+Clone-and-run scaffolds. Copy into your project — or use `loop-init`:
+
+```bash
+npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok
+npx @cobusgreyling/loop-init . -p pr-babysitter -t claude
+```
## Daily Triage (L1 report-only)
@@ -10,23 +15,18 @@ Clone-and-run scaffolds. Copy into your project — do not submodule the whole r
| [minimal-loop-claude](./minimal-loop-claude/) | Claude Code | `.claude/skills/` + `.claude/agents/` |
| [minimal-loop-codex](./minimal-loop-codex/) | Codex | `.codex/skills/` + `.codex/agents/` |
-## Other patterns (L2 assisted)
+## L2 assisted patterns
-| Starter | Pattern | Readiness |
-|---------|---------|-----------|
-| [pr-babysitter](./pr-babysitter/) | PR Babysitter | L2 assisted |
-| [ci-sweeper](./ci-sweeper/) | CI Sweeper | L2 assisted |
-| [dependency-sweeper](./dependency-sweeper/) | Dependency Sweeper | L2 assisted |
+| Starter | Pattern | Tools | Readiness |
+|---------|---------|-------|-----------|
+| [pr-babysitter](./pr-babysitter/) | PR Babysitter | Grok, Claude, Codex | L2 assisted |
+| [ci-sweeper](./ci-sweeper/) | CI Sweeper | Grok, Claude, Codex | L2 assisted |
+| [dependency-sweeper](./dependency-sweeper/) | Dependency Sweeper | Grok, Claude, Codex | L2 patch-only |
+| [post-merge-cleanup](./post-merge-cleanup/) | Post-Merge Cleanup | Grok, Claude, Codex | L1 → L2 |
-After copying, run:
+After copying:
```bash
npx @cobusgreyling/loop-audit .
npx @cobusgreyling/loop-audit . --suggest
-```
-
-Or from a clone:
-
-```bash
-node tools/loop-audit/dist/cli.js .
```
\ No newline at end of file
diff --git a/starters/ci-sweeper/.claude/agents/loop-verifier.md b/starters/ci-sweeper/.claude/agents/loop-verifier.md
new file mode 100644
index 0000000..bdbbaf6
--- /dev/null
+++ b/starters/ci-sweeper/.claude/agents/loop-verifier.md
@@ -0,0 +1,35 @@
+---
+name: loop-verifier
+description: Independent checker for loop-produced changes. Rejects unless tests pass and scope is minimal. Never implement fixes.
+model: inherit
+---
+
+You are the **checker** in a maker/checker split. Your job is to **reject** unless evidence is strong.
+
+## 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 the implementer's claim that tests passed — run them.
+- If you cannot run tests (env issue) → ESCALATE_HUMAN.
\ No newline at end of file
diff --git a/starters/ci-sweeper/.claude/skills/ci-triage/SKILL.md b/starters/ci-sweeper/.claude/skills/ci-triage/SKILL.md
new file mode 100644
index 0000000..7e619d3
--- /dev/null
+++ b/starters/ci-sweeper/.claude/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/.codex/agents/verifier.toml b/starters/ci-sweeper/.codex/agents/verifier.toml
new file mode 100644
index 0000000..b297c16
--- /dev/null
+++ b/starters/ci-sweeper/.codex/agents/verifier.toml
@@ -0,0 +1,15 @@
+name = "verifier"
+description = "Rejects loop fixes unless tests pass and scope is minimal. Never implements fixes."
+instructions = """
+You are the checker in a maker/checker split. Default stance: REJECT until proven otherwise.
+
+Checklist (all must pass for APPROVE):
+1. Scope — only relevant files; no denylist paths
+2. Intent — addresses the stated target
+3. Tests — you ran them and report pass/fail with output
+4. No cheating — no disabled tests or skipped assertions
+5. Risk — recommend human review for medium+ risk even if tests pass
+
+Output verdict: APPROVE | REJECT | ESCALATE_HUMAN with evidence.
+"""
+reasoning_effort = "high"
\ No newline at end of file
diff --git a/starters/ci-sweeper/.codex/skills/ci-triage/SKILL.md b/starters/ci-sweeper/.codex/skills/ci-triage/SKILL.md
new file mode 100644
index 0000000..7e619d3
--- /dev/null
+++ b/starters/ci-sweeper/.codex/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
index 81031e4..c0dc48e 100644
--- a/starters/ci-sweeper/README.md
+++ b/starters/ci-sweeper/README.md
@@ -6,8 +6,10 @@ Scaffold for the [CI Sweeper](../../patterns/ci-sweeper.md) loop.
1. Copy skills and state:
```bash
+ npx @cobusgreyling/loop-init . --pattern ci-sweeper --tool grok
+ # Or manual:
mkdir -p .grok/skills
- cp starters/ci-sweeper/.grok/skills/ci-triage/SKILL.md .grok/skills/ci-triage/SKILL.md
+ cp -r starters/ci-sweeper/.grok/skills/ci-triage .grok/skills/
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
diff --git a/starters/dependency-sweeper/.claude/agents/loop-verifier.md b/starters/dependency-sweeper/.claude/agents/loop-verifier.md
new file mode 100644
index 0000000..bdbbaf6
--- /dev/null
+++ b/starters/dependency-sweeper/.claude/agents/loop-verifier.md
@@ -0,0 +1,35 @@
+---
+name: loop-verifier
+description: Independent checker for loop-produced changes. Rejects unless tests pass and scope is minimal. Never implement fixes.
+model: inherit
+---
+
+You are the **checker** in a maker/checker split. Your job is to **reject** unless evidence is strong.
+
+## 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 the implementer's claim that tests passed — run them.
+- If you cannot run tests (env issue) → ESCALATE_HUMAN.
\ No newline at end of file
diff --git a/starters/dependency-sweeper/.claude/skills/dependency-triage/SKILL.md b/starters/dependency-sweeper/.claude/skills/dependency-triage/SKILL.md
new file mode 100644
index 0000000..b5250e3
--- /dev/null
+++ b/starters/dependency-sweeper/.claude/skills/dependency-triage/SKILL.md
@@ -0,0 +1,36 @@
+---
+name: dependency-triage
+description: >
+ Scan package manifests and lockfiles for outdated packages and known CVEs.
+ Groups updates by risk (patch, minor, major). Use in dependency sweeper loops.
+user_invocable: true
+---
+
+# Dependency Triage Skill
+
+## Output per package
+
+```markdown
+### package-name (ecosystem: npm|pip|go|etc.)
+- Current: x.y.z
+- Suggested: x.y.z
+- Risk: patch | minor | major
+- CVE: none | CVE-XXXX (severity)
+- Actionable: yes | no (denylist / human gate)
+- Suggested loop action: patch-in-worktree | escalate-human | skip
+```
+
+## Classification Rules
+
+- **patch**: semver patch or lockfile-only security fix with no API change
+- **minor**: semver minor — cautious, verifier required
+- **major**: always escalate-human unless explicitly pre-approved in state
+- **denylist**: packages in state denylist → escalate-human, no auto-touch
+- **high-severity CVE**: escalate if fix requires major or breaking change
+
+## Rules
+
+- Prefer the smallest safe bump that resolves the advisory.
+- Never bundle unrelated package updates in one change.
+- Record human overrides from `dependency-sweeper-state.md` every run.
+- If lockfile conflict or peer dependency warning → escalate-human.
\ No newline at end of file
diff --git a/starters/dependency-sweeper/.codex/agents/verifier.toml b/starters/dependency-sweeper/.codex/agents/verifier.toml
new file mode 100644
index 0000000..b297c16
--- /dev/null
+++ b/starters/dependency-sweeper/.codex/agents/verifier.toml
@@ -0,0 +1,15 @@
+name = "verifier"
+description = "Rejects loop fixes unless tests pass and scope is minimal. Never implements fixes."
+instructions = """
+You are the checker in a maker/checker split. Default stance: REJECT until proven otherwise.
+
+Checklist (all must pass for APPROVE):
+1. Scope — only relevant files; no denylist paths
+2. Intent — addresses the stated target
+3. Tests — you ran them and report pass/fail with output
+4. No cheating — no disabled tests or skipped assertions
+5. Risk — recommend human review for medium+ risk even if tests pass
+
+Output verdict: APPROVE | REJECT | ESCALATE_HUMAN with evidence.
+"""
+reasoning_effort = "high"
\ No newline at end of file
diff --git a/starters/dependency-sweeper/.codex/skills/dependency-triage/SKILL.md b/starters/dependency-sweeper/.codex/skills/dependency-triage/SKILL.md
new file mode 100644
index 0000000..b5250e3
--- /dev/null
+++ b/starters/dependency-sweeper/.codex/skills/dependency-triage/SKILL.md
@@ -0,0 +1,36 @@
+---
+name: dependency-triage
+description: >
+ Scan package manifests and lockfiles for outdated packages and known CVEs.
+ Groups updates by risk (patch, minor, major). Use in dependency sweeper loops.
+user_invocable: true
+---
+
+# Dependency Triage Skill
+
+## Output per package
+
+```markdown
+### package-name (ecosystem: npm|pip|go|etc.)
+- Current: x.y.z
+- Suggested: x.y.z
+- Risk: patch | minor | major
+- CVE: none | CVE-XXXX (severity)
+- Actionable: yes | no (denylist / human gate)
+- Suggested loop action: patch-in-worktree | escalate-human | skip
+```
+
+## Classification Rules
+
+- **patch**: semver patch or lockfile-only security fix with no API change
+- **minor**: semver minor — cautious, verifier required
+- **major**: always escalate-human unless explicitly pre-approved in state
+- **denylist**: packages in state denylist → escalate-human, no auto-touch
+- **high-severity CVE**: escalate if fix requires major or breaking change
+
+## Rules
+
+- Prefer the smallest safe bump that resolves the advisory.
+- Never bundle unrelated package updates in one change.
+- Record human overrides from `dependency-sweeper-state.md` every run.
+- If lockfile conflict or peer dependency warning → escalate-human.
\ No newline at end of file
diff --git a/starters/dependency-sweeper/.grok/skills/dependency-triage/SKILL.md b/starters/dependency-sweeper/.grok/skills/dependency-triage/SKILL.md
new file mode 100644
index 0000000..b5250e3
--- /dev/null
+++ b/starters/dependency-sweeper/.grok/skills/dependency-triage/SKILL.md
@@ -0,0 +1,36 @@
+---
+name: dependency-triage
+description: >
+ Scan package manifests and lockfiles for outdated packages and known CVEs.
+ Groups updates by risk (patch, minor, major). Use in dependency sweeper loops.
+user_invocable: true
+---
+
+# Dependency Triage Skill
+
+## Output per package
+
+```markdown
+### package-name (ecosystem: npm|pip|go|etc.)
+- Current: x.y.z
+- Suggested: x.y.z
+- Risk: patch | minor | major
+- CVE: none | CVE-XXXX (severity)
+- Actionable: yes | no (denylist / human gate)
+- Suggested loop action: patch-in-worktree | escalate-human | skip
+```
+
+## Classification Rules
+
+- **patch**: semver patch or lockfile-only security fix with no API change
+- **minor**: semver minor — cautious, verifier required
+- **major**: always escalate-human unless explicitly pre-approved in state
+- **denylist**: packages in state denylist → escalate-human, no auto-touch
+- **high-severity CVE**: escalate if fix requires major or breaking change
+
+## Rules
+
+- Prefer the smallest safe bump that resolves the advisory.
+- Never bundle unrelated package updates in one change.
+- Record human overrides from `dependency-sweeper-state.md` every run.
+- If lockfile conflict or peer dependency warning → escalate-human.
\ No newline at end of file
diff --git a/starters/dependency-sweeper/LOOP.md b/starters/dependency-sweeper/LOOP.md
new file mode 100644
index 0000000..270971b
--- /dev/null
+++ b/starters/dependency-sweeper/LOOP.md
@@ -0,0 +1,30 @@
+# Loop Configuration — Dependency Sweeper
+
+## Active Loops
+
+| Pattern | Cadence | Status | Command |
+|---------|---------|--------|---------|
+| Dependency Sweeper | 6h | L2 assisted (patch-only) | See README |
+
+## Human Gates
+
+- Major version bumps → human approval always
+- High-severity CVE requiring breaking change → human
+- Denylist packages (edit in state file) → never auto-touch
+- No auto-merge without verifier pass + allowlist
+
+## Worktrees
+
+- One worktree per package update attempt
+- Discard worktree on REJECT or after human escalation
+
+## Budget
+
+- Max sub-agent spawns per run: 3
+- Max auto-PRs per day: 5
+- Pause if token budget exceeded (see `templates/loop-budget.md.template`)
+
+## Links
+
+- Pattern: [dependency-sweeper](../../patterns/dependency-sweeper.md)
+- Safety: [safety.md](../../docs/safety.md)
\ No newline at end of file
diff --git a/starters/dependency-sweeper/README.md b/starters/dependency-sweeper/README.md
index 273f43b..19309c2 100644
--- a/starters/dependency-sweeper/README.md
+++ b/starters/dependency-sweeper/README.md
@@ -1,44 +1,46 @@
# Dependency Sweeper Starter
-Clone-and-run scaffold for the **Dependency Sweeper** pattern (L2 assisted with strong verifier gates).
-
-Use this when you want the loop to keep your dependency surface clean and free of known high-severity vulnerabilities without you doing the boring patch/minor bumps by hand.
+Clone-and-run scaffold for the **Dependency Sweeper** pattern (L2 assisted, patch-only with strong verifier gates).
## Quick Start
-1. Copy into your project:
-
- ```bash
- cp -r starters/dependency-sweeper/.grok/skills/dependency-triage .grok/skills/ # if you have a custom triage skill
- cp starters/dependency-sweeper/dependency-sweeper-state.md.example dependency-sweeper-state.md
- cp starters/dependency-sweeper/LOOP.md.example LOOP.md # optional
- ```
+```bash
+npx @cobusgreyling/loop-init . --pattern dependency-sweeper --tool grok
+```
-2. Customize the state file with your project name and any initial denylist (e.g. your core framework during a big migration).
+Or manual copy:
-3. Start (example with Grok):
+```bash
+cp -r starters/dependency-sweeper/.grok/skills/dependency-triage .grok/skills/
+mkdir -p .grok/skills/loop-verifier .grok/skills/minimal-fix
+cp templates/SKILL.md.verifier .grok/skills/loop-verifier/SKILL.md
+cp templates/SKILL.md.minimal-fix .grok/skills/minimal-fix/SKILL.md
+cp starters/dependency-sweeper/dependency-sweeper-state.md.example dependency-sweeper-state.md
+cp starters/dependency-sweeper/LOOP.md .
+```
- ```
- /loop 6h Run dependency-triage on package manifests and lockfiles. For patch-level or low-risk CVE fixes: create minimal worktree update + verify with tests. Escalate majors, high-sev, and anything on the denylist. Update dependency-sweeper-state.md. Never auto-merge risky changes.
- ```
+Claude Code / Codex: use `--tool claude` or `--tool codex` with `loop-init`.
-4. After a week of good triage quality, wire the minimal-fix + verifier from `templates/`.
+Start (Grok):
-5. Run `node tools/loop-audit/dist/cli.js .` regularly.
+```
+/loop 6h Run dependency-triage on package manifests and lockfiles. Patch-only auto-fix in worktree + verifier (npm ci && npm test). Escalate majors, high-sev CVEs, and denylist packages. Update dependency-sweeper-state.md.
+```
## What's Included
| File | Purpose |
|------|---------|
-| `dependency-sweeper-state.md.example` | State spine (in-flight updates, human decisions) |
-| `README.md` | This file |
-| (recommended) Add your own `dependency-triage` skill modeled on `templates/SKILL.md.*` + the pattern doc |
+| `dependency-sweeper-state.md.example` | State spine (in-flight updates, denylist) |
+| `.grok/.claude/.codex/skills/dependency-triage/` | Triage skill (all tools) |
+| `.claude/agents/loop-verifier.md` | Checker agent |
+| `.codex/agents/verifier.toml` | Checker subagent |
+| `LOOP.md` | Cadence, gates, budget |
## Next Steps
-- Read the full pattern: [patterns/dependency-sweeper.md](../../patterns/dependency-sweeper.md)
-- [Loop Design Checklist](../../docs/loop-design-checklist.md)
-- Add `.github/workflows` that reacts to Dependabot PRs or scheduled scans (dogfood example in the root of this reference repo)
-- After the loop is stable, consider wiring OSV-Scanner / `npm audit` / Dependabot webhooks as additional discovery sources.
+- [patterns/dependency-sweeper.md](../../patterns/dependency-sweeper.md)
+- [docs/loop-design-checklist.md](../../docs/loop-design-checklist.md)
+- [stories/dependency-sweeper-week-one.md](../../stories/dependency-sweeper-week-one.md)
-**Safety note**: This pattern is deliberately biased toward *small safe patches only*. Majors and high-severity items must stay behind an explicit human gate.
+**Safety**: Majors and high-severity breaking fixes stay behind explicit human gates.
\ No newline at end of file
diff --git a/starters/post-merge-cleanup/.claude/agents/loop-verifier.md b/starters/post-merge-cleanup/.claude/agents/loop-verifier.md
new file mode 100644
index 0000000..bdbbaf6
--- /dev/null
+++ b/starters/post-merge-cleanup/.claude/agents/loop-verifier.md
@@ -0,0 +1,35 @@
+---
+name: loop-verifier
+description: Independent checker for loop-produced changes. Rejects unless tests pass and scope is minimal. Never implement fixes.
+model: inherit
+---
+
+You are the **checker** in a maker/checker split. Your job is to **reject** unless evidence is strong.
+
+## 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 the implementer's claim that tests passed — run them.
+- If you cannot run tests (env issue) → ESCALATE_HUMAN.
\ No newline at end of file
diff --git a/starters/post-merge-cleanup/.claude/skills/post-merge-scan/SKILL.md b/starters/post-merge-cleanup/.claude/skills/post-merge-scan/SKILL.md
new file mode 100644
index 0000000..5ad80f4
--- /dev/null
+++ b/starters/post-merge-cleanup/.claude/skills/post-merge-scan/SKILL.md
@@ -0,0 +1,34 @@
+---
+name: post-merge-scan
+description: >
+ Scan recent merges to main for follow-up cleanup: TODOs, deprecations,
+ broken doc links, stale flags. Use in post-merge cleanup loops.
+user_invocable: true
+---
+
+# Post-Merge Scan Skill
+
+## Output per merge
+
+```markdown
+### PR #N — title (merged DATE)
+- Follow-ups found: (list with file:line)
+- Risk: low | medium | high
+- Effort: small | medium | large
+- Suggested loop action: minimal-fix | ticket | escalate-human | skip
+```
+
+## What to look for
+
+- `TODO` / `FIXME` introduced in merge
+- Deprecated APIs still referenced
+- Broken internal doc links
+- Stale feature flags marked for removal
+- Unused imports or dead code clusters (small only)
+
+## Rules
+
+- Only scan merges from the last 7 days unless state says otherwise.
+- Large refactors → ticket, not auto-fix.
+- Medium+ risk paths → escalate-human.
+- Be concise — this runs off-peak, not during active dev hours.
\ No newline at end of file
diff --git a/starters/post-merge-cleanup/.codex/agents/verifier.toml b/starters/post-merge-cleanup/.codex/agents/verifier.toml
new file mode 100644
index 0000000..b297c16
--- /dev/null
+++ b/starters/post-merge-cleanup/.codex/agents/verifier.toml
@@ -0,0 +1,15 @@
+name = "verifier"
+description = "Rejects loop fixes unless tests pass and scope is minimal. Never implements fixes."
+instructions = """
+You are the checker in a maker/checker split. Default stance: REJECT until proven otherwise.
+
+Checklist (all must pass for APPROVE):
+1. Scope — only relevant files; no denylist paths
+2. Intent — addresses the stated target
+3. Tests — you ran them and report pass/fail with output
+4. No cheating — no disabled tests or skipped assertions
+5. Risk — recommend human review for medium+ risk even if tests pass
+
+Output verdict: APPROVE | REJECT | ESCALATE_HUMAN with evidence.
+"""
+reasoning_effort = "high"
\ No newline at end of file
diff --git a/starters/post-merge-cleanup/.codex/skills/post-merge-scan/SKILL.md b/starters/post-merge-cleanup/.codex/skills/post-merge-scan/SKILL.md
new file mode 100644
index 0000000..5ad80f4
--- /dev/null
+++ b/starters/post-merge-cleanup/.codex/skills/post-merge-scan/SKILL.md
@@ -0,0 +1,34 @@
+---
+name: post-merge-scan
+description: >
+ Scan recent merges to main for follow-up cleanup: TODOs, deprecations,
+ broken doc links, stale flags. Use in post-merge cleanup loops.
+user_invocable: true
+---
+
+# Post-Merge Scan Skill
+
+## Output per merge
+
+```markdown
+### PR #N — title (merged DATE)
+- Follow-ups found: (list with file:line)
+- Risk: low | medium | high
+- Effort: small | medium | large
+- Suggested loop action: minimal-fix | ticket | escalate-human | skip
+```
+
+## What to look for
+
+- `TODO` / `FIXME` introduced in merge
+- Deprecated APIs still referenced
+- Broken internal doc links
+- Stale feature flags marked for removal
+- Unused imports or dead code clusters (small only)
+
+## Rules
+
+- Only scan merges from the last 7 days unless state says otherwise.
+- Large refactors → ticket, not auto-fix.
+- Medium+ risk paths → escalate-human.
+- Be concise — this runs off-peak, not during active dev hours.
\ No newline at end of file
diff --git a/starters/post-merge-cleanup/.grok/skills/post-merge-scan/SKILL.md b/starters/post-merge-cleanup/.grok/skills/post-merge-scan/SKILL.md
new file mode 100644
index 0000000..5ad80f4
--- /dev/null
+++ b/starters/post-merge-cleanup/.grok/skills/post-merge-scan/SKILL.md
@@ -0,0 +1,34 @@
+---
+name: post-merge-scan
+description: >
+ Scan recent merges to main for follow-up cleanup: TODOs, deprecations,
+ broken doc links, stale flags. Use in post-merge cleanup loops.
+user_invocable: true
+---
+
+# Post-Merge Scan Skill
+
+## Output per merge
+
+```markdown
+### PR #N — title (merged DATE)
+- Follow-ups found: (list with file:line)
+- Risk: low | medium | high
+- Effort: small | medium | large
+- Suggested loop action: minimal-fix | ticket | escalate-human | skip
+```
+
+## What to look for
+
+- `TODO` / `FIXME` introduced in merge
+- Deprecated APIs still referenced
+- Broken internal doc links
+- Stale feature flags marked for removal
+- Unused imports or dead code clusters (small only)
+
+## Rules
+
+- Only scan merges from the last 7 days unless state says otherwise.
+- Large refactors → ticket, not auto-fix.
+- Medium+ risk paths → escalate-human.
+- Be concise — this runs off-peak, not during active dev hours.
\ No newline at end of file
diff --git a/starters/post-merge-cleanup/LOOP.md b/starters/post-merge-cleanup/LOOP.md
new file mode 100644
index 0000000..3fedcb4
--- /dev/null
+++ b/starters/post-merge-cleanup/LOOP.md
@@ -0,0 +1,22 @@
+# Loop Configuration — Post-Merge Cleanup
+
+## Active Loops
+
+| Pattern | Cadence | Status | Command |
+|---------|---------|--------|---------|
+| Post-Merge Cleanup | 1d | L1 report-only week one | See README |
+
+## Human Gates
+
+- Architectural debt → create ticket, do not fix
+- Feature flag removal → human approval
+- Multi-file refactors → escalate
+
+## Budget
+
+- Max sub-agent spawns per run: 2 (L2)
+- Run off-peak (evening / overnight)
+
+## Links
+
+- Pattern: [post-merge-cleanup](../../patterns/post-merge-cleanup.md)
\ No newline at end of file
diff --git a/starters/post-merge-cleanup/README.md b/starters/post-merge-cleanup/README.md
new file mode 100644
index 0000000..b620932
--- /dev/null
+++ b/starters/post-merge-cleanup/README.md
@@ -0,0 +1,34 @@
+# Post-Merge Cleanup Starter
+
+Scaffold for the [Post-Merge Cleanup](../../patterns/post-merge-cleanup.md) loop (L1 report → L2 small fixes).
+
+## Quick Start
+
+```bash
+# Grok
+npx @cobusgreyling/loop-init . --pattern post-merge-cleanup --tool grok
+
+# Or manual copy
+cp -r starters/post-merge-cleanup/.grok/skills/post-merge-scan .grok/skills/
+cp starters/post-merge-cleanup/post-merge-state.md.example post-merge-state.md
+cp starters/post-merge-cleanup/LOOP.md .
+```
+
+Start (Grok):
+
+```
+/loop 1d Run post-merge-scan on merges to main (last 7d). Update post-merge-state.md. Small doc/link fixes only in worktree. Escalate refactors.
+```
+
+## Files
+
+| File | Purpose |
+|------|---------|
+| `post-merge-state.md.example` | Cleanup backlog from recent merges |
+| `.grok/skills/post-merge-scan/` | Scan skill |
+| `LOOP.md` | Cadence and gates |
+
+## Safety
+
+- No large refactors without human ticket
+- Denylist: feature flags, auth paths — see [safety.md](../../docs/safety.md)
\ No newline at end of file
diff --git a/starters/post-merge-cleanup/post-merge-state.md.example b/starters/post-merge-cleanup/post-merge-state.md.example
new file mode 100644
index 0000000..b4e6ebd
--- /dev/null
+++ b/starters/post-merge-cleanup/post-merge-state.md.example
@@ -0,0 +1,22 @@
+# Post-Merge Cleanup State — YOUR_PROJECT
+
+Last run: not yet run
+Status: report-only (week 1)
+
+## Pending Cleanup (from recent merges)
+
+- (none yet — first run will populate)
+
+## Completed (last 14d)
+
+- (none)
+
+## Deferred (human decision)
+
+- (none)
+
+## Denylist paths
+
+- auth/
+- payments/
+- infra/
\ No newline at end of file
diff --git a/starters/pr-babysitter/.claude/agents/loop-verifier.md b/starters/pr-babysitter/.claude/agents/loop-verifier.md
new file mode 100644
index 0000000..bdbbaf6
--- /dev/null
+++ b/starters/pr-babysitter/.claude/agents/loop-verifier.md
@@ -0,0 +1,35 @@
+---
+name: loop-verifier
+description: Independent checker for loop-produced changes. Rejects unless tests pass and scope is minimal. Never implement fixes.
+model: inherit
+---
+
+You are the **checker** in a maker/checker split. Your job is to **reject** unless evidence is strong.
+
+## 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 the implementer's claim that tests passed — run them.
+- If you cannot run tests (env issue) → ESCALATE_HUMAN.
\ No newline at end of file
diff --git a/starters/pr-babysitter/.claude/skills/pr-review-triage/SKILL.md b/starters/pr-babysitter/.claude/skills/pr-review-triage/SKILL.md
new file mode 100644
index 0000000..8ea95ff
--- /dev/null
+++ b/starters/pr-babysitter/.claude/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/.codex/agents/verifier.toml b/starters/pr-babysitter/.codex/agents/verifier.toml
new file mode 100644
index 0000000..b297c16
--- /dev/null
+++ b/starters/pr-babysitter/.codex/agents/verifier.toml
@@ -0,0 +1,15 @@
+name = "verifier"
+description = "Rejects loop fixes unless tests pass and scope is minimal. Never implements fixes."
+instructions = """
+You are the checker in a maker/checker split. Default stance: REJECT until proven otherwise.
+
+Checklist (all must pass for APPROVE):
+1. Scope — only relevant files; no denylist paths
+2. Intent — addresses the stated target
+3. Tests — you ran them and report pass/fail with output
+4. No cheating — no disabled tests or skipped assertions
+5. Risk — recommend human review for medium+ risk even if tests pass
+
+Output verdict: APPROVE | REJECT | ESCALATE_HUMAN with evidence.
+"""
+reasoning_effort = "high"
\ No newline at end of file
diff --git a/starters/pr-babysitter/.codex/skills/pr-review-triage/SKILL.md b/starters/pr-babysitter/.codex/skills/pr-review-triage/SKILL.md
new file mode 100644
index 0000000..8ea95ff
--- /dev/null
+++ b/starters/pr-babysitter/.codex/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/README.md b/starters/pr-babysitter/README.md
index 9459890..618d968 100644
--- a/starters/pr-babysitter/README.md
+++ b/starters/pr-babysitter/README.md
@@ -6,7 +6,8 @@ Scaffold for the [PR Babysitter](../../patterns/pr-babysitter.md) loop (L2 — a
1. Copy into your repo:
```bash
- mkdir -p .grok/skills
+ npx @cobusgreyling/loop-init . --pattern pr-babysitter --tool grok
+ # Or manual:
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 .
diff --git a/stories/README.md b/stories/README.md
index 16faf83..837e35c 100644
--- a/stories/README.md
+++ b/stories/README.md
@@ -7,8 +7,9 @@ Real-world loop engineering — including failures. Contribute yours via [CONTRI
| [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 |
-
-New high-value pattern looking for a story: **Dependency Sweeper** (volume + safety boundaries + measurable "time to clean" metrics).
+| [dependency-sweeper-week-one.md](./dependency-sweeper-week-one.md) | Dependency Sweeper | Verifier must match CI install path |
+| [multi-loop-collision.md](./multi-loop-collision.md) | Multi-loop | Branch lock + collision detection |
+| [l1-to-l2-graduation.md](./l1-to-l2-graduation.md) | Daily Triage | Calibration before auto-fix |
**Template for new stories:**
diff --git a/stories/dependency-sweeper-week-one.md b/stories/dependency-sweeper-week-one.md
new file mode 100644
index 0000000..5261f07
--- /dev/null
+++ b/stories/dependency-sweeper-week-one.md
@@ -0,0 +1,33 @@
+# Dependency Sweeper Week One — Patch Volume and a Verifier Lie
+
+## Setup
+
+- Pattern: Dependency Sweeper (L2 patch-only)
+- Cadence: `/loop 6h`
+- Denylist: `react`, `@company/core-auth`
+- Verifier: `loop-verifier` in isolated worktree
+
+## What Worked
+
+- Patch bumps for transitive lodash CVE closed in 4 hours without human touch
+- State file made it obvious what was in-flight vs waiting on human
+- Denylist prevented a reckless React minor during a release freeze
+
+## What Broke
+
+- Day 3: verifier APPROVED an `express` patch but **did not run** `npm ci` — only `npm test`, which used cached `node_modules`
+- CI failed on the PR with a peer dependency conflict the verifier missed
+- Day 4: loop opened 3 patch PRs in one run — reviewer fatigue
+
+## Metrics
+
+| Metric | Week 1 |
+|--------|--------|
+| Patch PRs opened | 11 |
+| Human merges | 7 |
+| Verifier false APPROVE | 1 |
+| Token estimate | ~800k |
+
+## Lesson
+
+Patch-only is not "risk-free." Verifier must run the **same install path as CI** (`npm ci`, not `npm test` alone). Cap auto-PRs per day (we added max 5 to LOOP.md). One false APPROVE cost more human time than a week of manual patches would have.
\ No newline at end of file
diff --git a/stories/l1-to-l2-graduation.md b/stories/l1-to-l2-graduation.md
new file mode 100644
index 0000000..dc02406
--- /dev/null
+++ b/stories/l1-to-l2-graduation.md
@@ -0,0 +1,37 @@
+# L1 → L2 Graduation — When We Turned On Auto-Fix
+
+## Setup
+
+- Pattern: Daily Triage
+- Week 1–2: L1 report-only, `/loop 1d`
+- Week 3: L2 assisted small fixes with verifier
+
+## What Worked
+
+- L1 taught us which items were **actually** high priority vs noise
+- Triage accuracy improved from ~60% to ~85% before we enabled fixes
+- First L2 win: broken internal doc link fixed overnight, zero human minutes
+
+## What Broke
+
+- Week 2 false positive: triage marked a flaky E2E as high priority three days running
+- We almost enabled L2 while still misclassifying flakes — would have produced junk PRs
+- L2 day 2: loop "fixed" a typo in a generated file that should not be edited
+
+## Metrics
+
+| Phase | Runs | Auto-fixes | Human escalations |
+|-------|------|------------|-------------------|
+| L1 (2 weeks) | 14 | 0 | 3 |
+| L2 (week 3) | 7 | 4 | 2 |
+
+## Lesson
+
+Graduation criteria we now use:
+
+1. Two weeks of L1 with <20% noise in High Priority
+2. Verifier + worktree proven on **manual** fix attempts first
+3. Denylist and `AGENTS.md` test commands documented
+4. `loop-audit` score ≥ 58 before L2
+
+Do not skip L1 because L2 feels more impressive. The report-only phase is the calibration phase.
\ No newline at end of file
diff --git a/stories/multi-loop-collision.md b/stories/multi-loop-collision.md
new file mode 100644
index 0000000..284469d
--- /dev/null
+++ b/stories/multi-loop-collision.md
@@ -0,0 +1,31 @@
+# Multi-Loop Collision — CI Sweeper vs PR Babysitter on PR #318
+
+## Setup
+
+- CI Sweeper: `/loop 15m`, max 3 attempts
+- PR Babysitter: `/loop 10m`, same repo
+- Shared branch: `fix/auth-token-refresh` on PR #318
+
+## What Worked
+
+- Both loops correctly identified the failing `auth` test
+- State files showed the overlap when we audited Tuesday morning
+
+## What Broke
+
+- CI Sweeper spawned a worktree fix at 14:02
+- PR Babysitter spawned a **different** minimal fix on the same PR at 14:07
+- Two commits, conflicting approaches, reviewer confused
+- Combined token spend for that PR: ~400k (normally ~80k)
+
+## Metrics
+
+| Metric | Value |
+|--------|-------|
+| Duplicate fix attempts | 2 |
+| Human minutes to untangle | 45 |
+| Root cause | No `acting_on` collision check |
+
+## Lesson
+
+Action loops need a **branch lock** in state. We added collision detection to [multi-loop.md](../docs/multi-loop.md): read all pattern state files before spawning a worktree. CI Sweeper now owns red CI; PR Babysitter skips if `ci-sweeper-state.md` shows `acting_on` for that PR.
\ No newline at end of file
diff --git a/templates/loop-budget.md.template b/templates/loop-budget.md.template
new file mode 100644
index 0000000..f3275c4
--- /dev/null
+++ b/templates/loop-budget.md.template
@@ -0,0 +1,22 @@
+# Loop Budget — YOUR_PROJECT
+
+## Daily limits
+
+| Loop | Max runs/day | Max tokens/day | Max sub-agent spawns/run |
+|------|--------------|----------------|--------------------------|
+| Daily Triage | 2 | 100k | 0 (L1) / 2 (L2) |
+| PR Babysitter | 288 | 2M | 3 |
+| CI Sweeper | 96 | 1M | 3 |
+| Dependency Sweeper | 4 | 500k | 3 |
+| Post-Merge Cleanup | 1 | 200k | 2 |
+
+## On budget exceed
+
+1. Pause all schedulers (`scheduler_delete` or disable automations)
+2. Append event to `loop-run-log.md`
+3. Notify human (Slack / issue / STATE.md High Priority)
+
+## Kill switch
+
+- Command or issue label: `loop-pause-all`
+- Resume only after human clears the flag in STATE.md
\ No newline at end of file
diff --git a/templates/loop-run-log.md.template b/templates/loop-run-log.md.template
new file mode 100644
index 0000000..b35f8d5
--- /dev/null
+++ b/templates/loop-run-log.md.template
@@ -0,0 +1,22 @@
+# Loop Run Log — YOUR_PROJECT
+
+Append one entry per run. Prune entries older than 30 days.
+
+## Format
+
+```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": "report-only | fix-proposed | escalated | no-op"
+}
+```
+
+## Recent Runs
+
+<!-- Loop appends below this line -->
\ No newline at end of file
diff --git a/tools/loop-audit/CHANGELOG.md b/tools/loop-audit/CHANGELOG.md
new file mode 100644
index 0000000..9f121a7
--- /dev/null
+++ b/tools/loop-audit/CHANGELOG.md
@@ -0,0 +1,32 @@
+# Changelog
+
+All notable changes to `@cobusgreyling/loop-audit` are documented here.
+
+## [1.3.0] - 2026-06-09
+
+### Added
+- Unit tests for scoring logic (`test/auditor.test.ts`)
+- `--suggest` now mentions `loop-init` scaffold CLI
+- Registry and starter coverage in audit recommendations
+
+### Changed
+- CI gates on test suite before publish
+
+## [1.2.0] - 2026-06-09
+
+### Added
+- `--suggest` copy-from-template commands for Grok, Claude Code, and Codex
+- Expanded signals: MCP, worktree evidence, `patterns/registry.yaml`
+- L3 scoring threshold with verifier + state requirements
+
+## [1.1.0] - 2026-06-08
+
+### Added
+- `--md` markdown report format
+- Safety doc and GitHub workflow detection
+
+## [1.0.0] - 2026-06-07
+
+### Added
+- Initial Loop Readiness Score CLI (L0–L3)
+- `--json` output for CI integration
\ No newline at end of file
diff --git a/tools/loop-audit/dist/auditor.js b/tools/loop-audit/dist/auditor.js
index 6c291a6..5bb0bfd 100644
--- a/tools/loop-audit/dist/auditor.js
+++ b/tools/loop-audit/dist/auditor.js
@@ -14,6 +14,8 @@ const LOOP_SKILL_NAMES = [
'ci-triage',
'post-merge-scan',
'dependency-triage',
+ 'post-merge-scan',
+ 'rebase-and-clean',
];
const SAFETY_FILES = ['safety.md', 'docs/safety.md', 'SECURITY.md'];
const MCP_FILES = ['.mcp.json', 'mcp.json', '.mcp/config.json'];
@@ -127,7 +129,11 @@ export async function auditProject(target) {
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');
+ const triage = skillNames.includes('loop-triage') ||
+ skillNames.includes('pr-review-triage') ||
+ skillNames.includes('ci-triage') ||
+ skillNames.includes('dependency-triage') ||
+ skillNames.includes('post-merge-scan');
let loopMdContent = '';
if (loopMd) {
loopMdContent = await readFile(path.join(root, 'LOOP.md'), 'utf8');
diff --git a/tools/loop-audit/dist/cli.js b/tools/loop-audit/dist/cli.js
index 2db2f5a..462d404 100644
--- a/tools/loop-audit/dist/cli.js
+++ b/tools/loop-audit/dist/cli.js
@@ -67,6 +67,9 @@ try {
console.log(' # For PR babysitter / CI sweeper patterns, copy the corresponding starter');
console.log(' # Then run: loop-audit . --suggest (again after changes)');
console.log('');
+ console.log(' # Or scaffold automatically:');
+ console.log(' npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok');
+ console.log('');
console.log('See docs/loop-design-checklist.md and patterns/ for full guidance.');
}
if (result.score < 40)
diff --git a/tools/loop-audit/package.json b/tools/loop-audit/package.json
index be74bce..1a8e98a 100644
--- a/tools/loop-audit/package.json
+++ b/tools/loop-audit/package.json
@@ -1,6 +1,6 @@
{
"name": "@cobusgreyling/loop-audit",
- "version": "1.2.0",
+ "version": "1.3.0",
"description": "Loop Readiness Score — audit a project for loop engineering readiness (L0-L3). Supports --suggest for copy commands.",
"type": "module",
"bin": {
@@ -12,7 +12,8 @@
],
"scripts": {
"build": "tsc",
- "prepublishOnly": "npm run build",
+ "test": "npm run build && node --test test/auditor.test.mjs",
+ "prepublishOnly": "npm test",
"start": "node dist/cli.js",
"audit": "npm run build && node dist/cli.js",
"audit:suggest": "npm run build && node dist/cli.js . --suggest",
diff --git a/tools/loop-audit/src/auditor.ts b/tools/loop-audit/src/auditor.ts
index 203fe8d..1807611 100644
--- a/tools/loop-audit/src/auditor.ts
+++ b/tools/loop-audit/src/auditor.ts
@@ -47,6 +47,8 @@ const LOOP_SKILL_NAMES = [
'ci-triage',
'post-merge-scan',
'dependency-triage',
+ 'post-merge-scan',
+ 'rebase-and-clean',
];
const SAFETY_FILES = ['safety.md', 'docs/safety.md', 'SECURITY.md'];
@@ -152,7 +154,11 @@ export async function auditProject(target: string): Promise<AuditResult> {
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');
+ const triage = skillNames.includes('loop-triage') ||
+ skillNames.includes('pr-review-triage') ||
+ skillNames.includes('ci-triage') ||
+ skillNames.includes('dependency-triage') ||
+ skillNames.includes('post-merge-scan');
let loopMdContent = '';
if (loopMd) {
diff --git a/tools/loop-audit/src/cli.ts b/tools/loop-audit/src/cli.ts
index bfd89f2..d66181e 100644
--- a/tools/loop-audit/src/cli.ts
+++ b/tools/loop-audit/src/cli.ts
@@ -68,6 +68,9 @@ try {
console.log(' # For PR babysitter / CI sweeper patterns, copy the corresponding starter');
console.log(' # Then run: loop-audit . --suggest (again after changes)');
console.log('');
+ console.log(' # Or scaffold automatically:');
+ console.log(' npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok');
+ console.log('');
console.log('See docs/loop-design-checklist.md and patterns/ for full guidance.');
}
diff --git a/tools/loop-audit/test/auditor.test.mjs b/tools/loop-audit/test/auditor.test.mjs
new file mode 100644
index 0000000..804b030
--- /dev/null
+++ b/tools/loop-audit/test/auditor.test.mjs
@@ -0,0 +1,117 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { auditProject, computeScore } from '../dist/auditor.js';
+
+function emptySignals() {
+ return {
+ stateFile: { present: false, paths: [] },
+ loopConfig: { present: false },
+ skills: { count: 0, loopSkills: [] },
+ verifier: { present: false },
+ triage: { present: false },
+ agentsMd: { present: false },
+ patterns: { documented: false },
+ safety: { loopMdMentionsSafety: false, safetyDocPresent: false },
+ starters: { used: false },
+ github: { present: false, workflows: false },
+ mcp: { present: false },
+ worktreeEvidence: { present: false },
+ registry: { present: false },
+ };
+}
+
+test('computeScore: empty project is L0', () => {
+ const { score, level } = computeScore(emptySignals());
+ assert.equal(level, 'L0');
+ assert.ok(score < 38);
+});
+
+test('computeScore: state + triage reaches L1', () => {
+ const s = emptySignals();
+ s.stateFile = { present: true, paths: ['STATE.md'] };
+ s.triage = { present: true };
+ const { level, score } = computeScore(s);
+ assert.equal(level, 'L1');
+ assert.ok(score >= 38);
+});
+
+test('computeScore: full L2 signals', () => {
+ const s = emptySignals();
+ s.stateFile = { present: true, paths: ['STATE.md'] };
+ s.triage = { present: true };
+ s.skills = { count: 2, loopSkills: ['loop-triage', 'loop-verifier'] };
+ s.verifier = { present: true };
+ const { level, score } = computeScore(s);
+ assert.equal(level, 'L2');
+ assert.ok(score >= 58 && score < 78);
+});
+
+test('computeScore: L3 requires verifier and high score', () => {
+ const s = emptySignals();
+ s.stateFile = { present: true, paths: ['STATE.md'] };
+ s.triage = { present: true };
+ s.loopConfig = { present: true, path: 'LOOP.md' };
+ s.agentsMd = { present: true };
+ s.skills = { count: 3, loopSkills: ['loop-triage', 'minimal-fix', 'loop-verifier'] };
+ s.verifier = { present: true };
+ s.safety = { loopMdMentionsSafety: true, safetyDocPresent: true };
+ s.github = { present: true, workflows: true };
+ s.mcp = { present: true };
+ s.worktreeEvidence = { present: true };
+ s.registry = { present: true };
+ const { level, score } = computeScore(s);
+ assert.equal(level, 'L3');
+ assert.ok(score >= 78);
+});
+
+test('auditProject: empty directory scores low', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'loop-audit-empty-'));
+ try {
+ const result = await auditProject(dir);
+ assert.equal(result.level, 'L0');
+ assert.ok(result.score < 40);
+ assert.ok(result.findings.some((f) => f.level === 'fail'));
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test('auditProject: minimal L1 layout', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'loop-audit-l1-'));
+ try {
+ await writeFile(path.join(dir, 'STATE.md'), '# State\n');
+ await mkdir(path.join(dir, '.grok', 'skills', 'loop-triage'), { recursive: true });
+ await writeFile(
+ path.join(dir, '.grok', 'skills', 'loop-triage', 'SKILL.md'),
+ '---\nname: loop-triage\ndescription: triage\n---\n# Triage\n',
+ );
+ const result = await auditProject(dir);
+ assert.equal(result.level, 'L1');
+ assert.ok(result.signals.triage.present);
+ assert.ok(result.signals.stateFile.present);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test('auditProject: L2 with verifier skill', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'loop-audit-l2-'));
+ try {
+ await writeFile(path.join(dir, 'STATE.md'), '# State\n');
+ for (const skill of ['loop-triage', 'loop-verifier']) {
+ await mkdir(path.join(dir, '.grok', 'skills', skill), { recursive: true });
+ await writeFile(
+ path.join(dir, '.grok', 'skills', skill, 'SKILL.md'),
+ `---\nname: ${skill}\ndescription: test\n---\n# ${skill}\n`,
+ );
+ }
+ const result = await auditProject(dir);
+ assert.equal(result.level, 'L2');
+ assert.ok(result.signals.verifier.present);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
\ No newline at end of file
diff --git a/tools/loop-init/README.md b/tools/loop-init/README.md
new file mode 100644
index 0000000..1c40442
--- /dev/null
+++ b/tools/loop-init/README.md
@@ -0,0 +1,42 @@
+# loop-init
+
+Scaffold loop engineering starters into your project by pattern and tool.
+
+## Install & Run
+
+```bash
+npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok
+npx @cobusgreyling/loop-init . -p pr-babysitter -t claude
+npx @cobusgreyling/loop-init . -p dependency-sweeper --dry-run
+```
+
+## Patterns
+
+| Pattern | Default state file |
+|---------|-------------------|
+| `daily-triage` | `STATE.md` |
+| `pr-babysitter` | `pr-babysitter-state.md` |
+| `ci-sweeper` | `ci-sweeper-state.md` |
+| `dependency-sweeper` | `dependency-sweeper-state.md` |
+| `post-merge-cleanup` | `post-merge-state.md` |
+
+## Tools
+
+- `grok` (default)
+- `claude`
+- `codex`
+
+Falls back to Grok starter paths when a per-tool variant is not yet available.
+
+## From this repo
+
+```bash
+cd tools/loop-init && npm install && npm run build
+node dist/cli.js /path/to/project --pattern daily-triage --tool grok
+```
+
+Pair with `loop-audit` after scaffolding:
+
+```bash
+npx @cobusgreyling/loop-audit . --suggest
+```
\ No newline at end of file
diff --git a/tools/loop-init/dist/cli.d.ts b/tools/loop-init/dist/cli.d.ts
new file mode 100644
index 0000000..b798801
--- /dev/null
+++ b/tools/loop-init/dist/cli.d.ts
@@ -0,0 +1,2 @@
+#!/usr/bin/env node
+export {};
diff --git a/tools/loop-init/dist/cli.js b/tools/loop-init/dist/cli.js
new file mode 100644
index 0000000..a157526
--- /dev/null
+++ b/tools/loop-init/dist/cli.js
@@ -0,0 +1,226 @@
+#!/usr/bin/env node
+import { cp, mkdir, writeFile, access } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(__dirname, '../../..');
+const PATTERN_STARTERS = {
+ 'daily-triage': 'minimal-loop',
+ 'pr-babysitter': 'pr-babysitter',
+ 'ci-sweeper': 'ci-sweeper',
+ 'dependency-sweeper': 'dependency-sweeper',
+ 'post-merge-cleanup': 'post-merge-cleanup',
+};
+const TOOL_SUFFIX = {
+ grok: '',
+ claude: '-claude',
+ codex: '-codex',
+};
+const STATE_FILES = {
+ 'daily-triage': 'STATE.md',
+ 'pr-babysitter': 'pr-babysitter-state.md',
+ 'ci-sweeper': 'ci-sweeper-state.md',
+ 'dependency-sweeper': 'dependency-sweeper-state.md',
+ 'post-merge-cleanup': 'post-merge-state.md',
+};
+function parseArgs(argv) {
+ let pattern = 'daily-triage';
+ let tool = 'grok';
+ let target = '.';
+ let dryRun = false;
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--pattern' || a === '-p')
+ pattern = argv[++i];
+ else if (a === '--tool' || a === '-t')
+ tool = argv[++i];
+ else if (a === '--dry-run')
+ dryRun = true;
+ else if (a === '--help' || a === '-h')
+ return { help: true, pattern, tool, target, dryRun };
+ else if (!a.startsWith('-'))
+ target = a;
+ }
+ return { help: false, pattern, tool, target, dryRun };
+}
+async function exists(p) {
+ try {
+ await access(p);
+ return true;
+ }
+ catch {
+ return false;
+ }
+}
+async function copyDir(src, dest, dryRun) {
+ if (!(await exists(src)))
+ return false;
+ if (dryRun) {
+ console.log(` would copy: ${src} → ${dest}`);
+ return true;
+ }
+ await mkdir(path.dirname(dest), { recursive: true });
+ await cp(src, dest, { recursive: true });
+ console.log(` copied: ${src} → ${dest}`);
+ return true;
+}
+async function copyFile(src, dest, dryRun) {
+ if (!(await exists(src)))
+ return false;
+ if (dryRun) {
+ console.log(` would copy: ${src} → ${dest}`);
+ return true;
+ }
+ await mkdir(path.dirname(dest), { recursive: true });
+ await cp(src, dest);
+ console.log(` copied: ${src} → ${dest}`);
+ return true;
+}
+function firstLoopCommand(pattern, tool) {
+ const cmds = {
+ 'daily-triage': {
+ grok: '/loop 1d Run loop-triage. Update STATE.md. No auto-fix in week one.',
+ claude: '/loop 1d $loop-triage — update STATE.md. Report-only week one.',
+ codex: 'Automation daily: $loop-triage → update STATE.md. Report-only.',
+ },
+ 'pr-babysitter': {
+ grok: '/loop 10m Run pr-review-triage. Update pr-babysitter-state.md. Worktree + minimal-fix + verifier for allowlisted PRs only. Escalate after 3 attempts.',
+ claude: '/loop 10m $pr-review-triage — update pr-babysitter-state.md. No auto-merge.',
+ codex: 'Automation 10m: pr-review-triage → pr-babysitter-state.md. No auto-merge.',
+ },
+ 'ci-sweeper': {
+ grok: '/loop 15m Run ci-triage on failing CI. Update ci-sweeper-state.md. Fix only regressions in worktree. Max 3 attempts.',
+ claude: '/loop 15m $ci-triage — update ci-sweeper-state.md. Max 3 fix attempts.',
+ codex: 'Automation 15m: ci-triage on CI failures. Max 3 attempts.',
+ },
+ 'dependency-sweeper': {
+ grok: '/loop 6h Run dependency-triage. Patch-only auto-fix in worktree + verifier. Escalate majors and denylist.',
+ claude: '/loop 6h $dependency-triage — patch-only with verifier. Escalate risky bumps.',
+ codex: 'Automation 6h: dependency-triage. Patch-only with verifier.',
+ },
+ 'post-merge-cleanup': {
+ grok: '/loop 1d Run post-merge-scan on recent merges. Update post-merge-state.md. Small fixes only in worktree.',
+ claude: '/loop 1d $post-merge-scan — update post-merge-state.md. Small fixes only.',
+ codex: 'Automation daily: post-merge-scan → post-merge-state.md.',
+ },
+ };
+ return cmds[pattern][tool];
+}
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+ if (args.help) {
+ console.log(`loop-init — scaffold loop engineering starters
+
+Usage:
+ loop-init [target-dir] --pattern <name> --tool <grok|claude|codex>
+
+Patterns:
+ daily-triage (default)
+ pr-babysitter
+ ci-sweeper
+ dependency-sweeper
+ post-merge-cleanup
+
+Options:
+ -p, --pattern Pattern to scaffold
+ -t, --tool Tool target (default: grok)
+ --dry-run Print actions without copying
+ -h, --help This help
+
+Examples:
+ npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok
+ npx @cobusgreyling/loop-init . -p pr-babysitter -t claude
+`);
+ process.exit(0);
+ }
+ const { pattern, tool, target, dryRun } = args;
+ const targetDir = path.resolve(target);
+ const baseStarter = PATTERN_STARTERS[pattern];
+ const suffix = TOOL_SUFFIX[tool];
+ const starterName = pattern === 'daily-triage' ? `minimal-loop${suffix}` : baseStarter;
+ const starterRoot = path.join(REPO_ROOT, 'starters', starterName);
+ if (!(await exists(starterRoot))) {
+ // Fall back to grok starter for patterns without per-tool variants
+ const fallback = path.join(REPO_ROOT, 'starters', baseStarter);
+ if (!(await exists(fallback))) {
+ console.error(`Starter not found: ${starterRoot}`);
+ process.exit(1);
+ }
+ console.log(`Note: no ${tool} variant for ${pattern} — using ${baseStarter} (Grok paths)`);
+ }
+ const effectiveStarter = (await exists(starterRoot))
+ ? starterRoot
+ : path.join(REPO_ROOT, 'starters', baseStarter);
+ console.log(`\nloop-init: ${pattern} → ${targetDir} (${tool})${dryRun ? ' [dry-run]' : ''}\n`);
+ const skillRoots = [
+ path.join(effectiveStarter, '.grok', 'skills'),
+ path.join(effectiveStarter, '.claude', 'skills'),
+ path.join(effectiveStarter, '.codex', 'skills'),
+ ];
+ for (const skillsDir of skillRoots) {
+ if (!(await exists(skillsDir)))
+ continue;
+ const toolPrefix = skillsDir.includes('.grok')
+ ? '.grok/skills'
+ : skillsDir.includes('.claude')
+ ? '.claude/skills'
+ : '.codex/skills';
+ const entries = await readDirNames(skillsDir);
+ for (const entry of entries) {
+ await copyDir(path.join(skillsDir, entry), path.join(targetDir, toolPrefix, entry), dryRun);
+ }
+ }
+ const agentFiles = [
+ { src: path.join(effectiveStarter, '.claude', 'agents'), dest: path.join(targetDir, '.claude', 'agents') },
+ { src: path.join(effectiveStarter, '.codex', 'agents'), dest: path.join(targetDir, '.codex', 'agents') },
+ ];
+ for (const { src, dest } of agentFiles) {
+ if (await exists(src)) {
+ const entries = await readDirNames(src);
+ for (const entry of entries) {
+ await copyFile(path.join(src, entry), path.join(dest, entry), dryRun);
+ }
+ }
+ }
+ const stateFile = STATE_FILES[pattern];
+ const stateExample = path.join(effectiveStarter, `${stateFile}.example`);
+ if (await exists(stateExample)) {
+ await copyFile(stateExample, path.join(targetDir, stateFile), dryRun);
+ }
+ else {
+ const alt = path.join(effectiveStarter, 'STATE.md.example');
+ if (await exists(alt)) {
+ await copyFile(alt, path.join(targetDir, stateFile), dryRun);
+ }
+ }
+ const loopMd = path.join(effectiveStarter, 'LOOP.md');
+ if (await exists(loopMd)) {
+ await copyFile(loopMd, path.join(targetDir, 'LOOP.md'), dryRun);
+ }
+ if (!dryRun && !(await exists(path.join(targetDir, 'AGENTS.md')))) {
+ const agentsTemplate = `# AGENTS.md
+
+## Test commands
+npm test
+npm run lint
+
+## Loop conventions
+- Report-only week one (L1) before enabling auto-fix (L2)
+- See LOOP.md for cadence and human gates
+`;
+ await writeFile(path.join(targetDir, 'AGENTS.md'), agentsTemplate);
+ console.log(' created: AGENTS.md (template)');
+ }
+ console.log('\n=== Next steps ===');
+ console.log(` npx @cobusgreyling/loop-audit ${target === '.' ? '.' : target} --suggest`);
+ console.log(` First loop command (${tool}):\n ${firstLoopCommand(pattern, tool)}\n`);
+}
+async function readDirNames(dir) {
+ const { readdir } = await import('node:fs/promises');
+ const entries = await readdir(dir, { withFileTypes: true });
+ return entries.filter((e) => e.isDirectory() || e.isFile()).map((e) => e.name);
+}
+main().catch((err) => {
+ console.error('loop-init failed:', err instanceof Error ? err.message : err);
+ process.exit(1);
+});
diff --git a/tools/loop-init/package-lock.json b/tools/loop-init/package-lock.json
new file mode 100644
index 0000000..990fd3f
--- /dev/null
+++ b/tools/loop-init/package-lock.json
@@ -0,0 +1,54 @@
+{
+ "name": "@cobusgreyling/loop-init",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@cobusgreyling/loop-init",
+ "version": "1.0.0",
+ "license": "MIT",
+ "bin": {
+ "loop-init": "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-init/package.json b/tools/loop-init/package.json
new file mode 100644
index 0000000..45557ae
--- /dev/null
+++ b/tools/loop-init/package.json
@@ -0,0 +1,41 @@
+{
+ "name": "@cobusgreyling/loop-init",
+ "version": "1.0.0",
+ "description": "Scaffold loop engineering starters into your project by pattern and tool.",
+ "type": "module",
+ "bin": {
+ "loop-init": "./dist/cli.js"
+ },
+ "files": [
+ "dist",
+ "README.md"
+ ],
+ "scripts": {
+ "build": "tsc",
+ "prepublishOnly": "npm run build",
+ "start": "node dist/cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "keywords": [
+ "loop-engineering",
+ "ai-agents",
+ "scaffold",
+ "starter"
+ ],
+ "author": "Cobus Greyling",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/cobusgreyling/loop-engineering.git",
+ "directory": "tools/loop-init"
+ },
+ "publishConfig": {
+ "access": "public"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.0.0"
+ }
+}
\ No newline at end of file
diff --git a/tools/loop-init/src/cli.ts b/tools/loop-init/src/cli.ts
new file mode 100644
index 0000000..c94f562
--- /dev/null
+++ b/tools/loop-init/src/cli.ts
@@ -0,0 +1,255 @@
+#!/usr/bin/env node
+import { cp, mkdir, readFile, writeFile, access } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(__dirname, '../../..');
+
+type Pattern =
+ | 'daily-triage'
+ | 'pr-babysitter'
+ | 'ci-sweeper'
+ | 'dependency-sweeper'
+ | 'post-merge-cleanup';
+
+type Tool = 'grok' | 'claude' | 'codex';
+
+const PATTERN_STARTERS: Record<Pattern, string> = {
+ 'daily-triage': 'minimal-loop',
+ 'pr-babysitter': 'pr-babysitter',
+ 'ci-sweeper': 'ci-sweeper',
+ 'dependency-sweeper': 'dependency-sweeper',
+ 'post-merge-cleanup': 'post-merge-cleanup',
+};
+
+const TOOL_SUFFIX: Record<Tool, string> = {
+ grok: '',
+ claude: '-claude',
+ codex: '-codex',
+};
+
+const STATE_FILES: Record<Pattern, string> = {
+ 'daily-triage': 'STATE.md',
+ 'pr-babysitter': 'pr-babysitter-state.md',
+ 'ci-sweeper': 'ci-sweeper-state.md',
+ 'dependency-sweeper': 'dependency-sweeper-state.md',
+ 'post-merge-cleanup': 'post-merge-state.md',
+};
+
+function parseArgs(argv: string[]) {
+ let pattern: Pattern = 'daily-triage';
+ let tool: Tool = 'grok';
+ let target = '.';
+ let dryRun = false;
+
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--pattern' || a === '-p') pattern = argv[++i] as Pattern;
+ else if (a === '--tool' || a === '-t') tool = argv[++i] as Tool;
+ else if (a === '--dry-run') dryRun = true;
+ else if (a === '--help' || a === '-h') return { help: true as const, pattern, tool, target, dryRun };
+ else if (!a.startsWith('-')) target = a;
+ }
+
+ return { help: false as const, pattern, tool, target, dryRun };
+}
+
+async function exists(p: string): Promise<boolean> {
+ try {
+ await access(p);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function copyDir(src: string, dest: string, dryRun: boolean) {
+ if (!(await exists(src))) return false;
+ if (dryRun) {
+ console.log(` would copy: ${src} → ${dest}`);
+ return true;
+ }
+ await mkdir(path.dirname(dest), { recursive: true });
+ await cp(src, dest, { recursive: true });
+ console.log(` copied: ${src} → ${dest}`);
+ return true;
+}
+
+async function copyFile(src: string, dest: string, dryRun: boolean) {
+ if (!(await exists(src))) return false;
+ if (dryRun) {
+ console.log(` would copy: ${src} → ${dest}`);
+ return true;
+ }
+ await mkdir(path.dirname(dest), { recursive: true });
+ await cp(src, dest);
+ console.log(` copied: ${src} → ${dest}`);
+ return true;
+}
+
+function firstLoopCommand(pattern: Pattern, tool: Tool): string {
+ const cmds: Record<Pattern, Record<Tool, string>> = {
+ 'daily-triage': {
+ grok: '/loop 1d Run loop-triage. Update STATE.md. No auto-fix in week one.',
+ claude: '/loop 1d $loop-triage — update STATE.md. Report-only week one.',
+ codex: 'Automation daily: $loop-triage → update STATE.md. Report-only.',
+ },
+ 'pr-babysitter': {
+ grok: '/loop 10m Run pr-review-triage. Update pr-babysitter-state.md. Worktree + minimal-fix + verifier for allowlisted PRs only. Escalate after 3 attempts.',
+ claude: '/loop 10m $pr-review-triage — update pr-babysitter-state.md. No auto-merge.',
+ codex: 'Automation 10m: pr-review-triage → pr-babysitter-state.md. No auto-merge.',
+ },
+ 'ci-sweeper': {
+ grok: '/loop 15m Run ci-triage on failing CI. Update ci-sweeper-state.md. Fix only regressions in worktree. Max 3 attempts.',
+ claude: '/loop 15m $ci-triage — update ci-sweeper-state.md. Max 3 fix attempts.',
+ codex: 'Automation 15m: ci-triage on CI failures. Max 3 attempts.',
+ },
+ 'dependency-sweeper': {
+ grok: '/loop 6h Run dependency-triage. Patch-only auto-fix in worktree + verifier. Escalate majors and denylist.',
+ claude: '/loop 6h $dependency-triage — patch-only with verifier. Escalate risky bumps.',
+ codex: 'Automation 6h: dependency-triage. Patch-only with verifier.',
+ },
+ 'post-merge-cleanup': {
+ grok: '/loop 1d Run post-merge-scan on recent merges. Update post-merge-state.md. Small fixes only in worktree.',
+ claude: '/loop 1d $post-merge-scan — update post-merge-state.md. Small fixes only.',
+ codex: 'Automation daily: post-merge-scan → post-merge-state.md.',
+ },
+ };
+ return cmds[pattern][tool];
+}
+
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+
+ if (args.help) {
+ console.log(`loop-init — scaffold loop engineering starters
+
+Usage:
+ loop-init [target-dir] --pattern <name> --tool <grok|claude|codex>
+
+Patterns:
+ daily-triage (default)
+ pr-babysitter
+ ci-sweeper
+ dependency-sweeper
+ post-merge-cleanup
+
+Options:
+ -p, --pattern Pattern to scaffold
+ -t, --tool Tool target (default: grok)
+ --dry-run Print actions without copying
+ -h, --help This help
+
+Examples:
+ npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok
+ npx @cobusgreyling/loop-init . -p pr-babysitter -t claude
+`);
+ process.exit(0);
+ }
+
+ const { pattern, tool, target, dryRun } = args;
+ const targetDir = path.resolve(target);
+ const baseStarter = PATTERN_STARTERS[pattern];
+ const suffix = TOOL_SUFFIX[tool];
+ const starterName = pattern === 'daily-triage' ? `minimal-loop${suffix}` : baseStarter;
+ const starterRoot = path.join(REPO_ROOT, 'starters', starterName);
+
+ if (!(await exists(starterRoot))) {
+ // Fall back to grok starter for patterns without per-tool variants
+ const fallback = path.join(REPO_ROOT, 'starters', baseStarter);
+ if (!(await exists(fallback))) {
+ console.error(`Starter not found: ${starterRoot}`);
+ process.exit(1);
+ }
+ console.log(`Note: no ${tool} variant for ${pattern} — using ${baseStarter} (Grok paths)`);
+ }
+
+ const effectiveStarter = (await exists(starterRoot))
+ ? starterRoot
+ : path.join(REPO_ROOT, 'starters', baseStarter);
+
+ console.log(`\nloop-init: ${pattern} → ${targetDir} (${tool})${dryRun ? ' [dry-run]' : ''}\n`);
+
+ const skillRoots = [
+ path.join(effectiveStarter, '.grok', 'skills'),
+ path.join(effectiveStarter, '.claude', 'skills'),
+ path.join(effectiveStarter, '.codex', 'skills'),
+ ];
+
+ for (const skillsDir of skillRoots) {
+ if (!(await exists(skillsDir))) continue;
+ const toolPrefix = skillsDir.includes('.grok')
+ ? '.grok/skills'
+ : skillsDir.includes('.claude')
+ ? '.claude/skills'
+ : '.codex/skills';
+ const entries = await readDirNames(skillsDir);
+ for (const entry of entries) {
+ await copyDir(
+ path.join(skillsDir, entry),
+ path.join(targetDir, toolPrefix, entry),
+ dryRun,
+ );
+ }
+ }
+
+ const agentFiles = [
+ { src: path.join(effectiveStarter, '.claude', 'agents'), dest: path.join(targetDir, '.claude', 'agents') },
+ { src: path.join(effectiveStarter, '.codex', 'agents'), dest: path.join(targetDir, '.codex', 'agents') },
+ ];
+ for (const { src, dest } of agentFiles) {
+ if (await exists(src)) {
+ const entries = await readDirNames(src);
+ for (const entry of entries) {
+ await copyFile(path.join(src, entry), path.join(dest, entry), dryRun);
+ }
+ }
+ }
+
+ const stateFile = STATE_FILES[pattern];
+ const stateExample = path.join(effectiveStarter, `${stateFile}.example`);
+ if (await exists(stateExample)) {
+ await copyFile(stateExample, path.join(targetDir, stateFile), dryRun);
+ } else {
+ const alt = path.join(effectiveStarter, 'STATE.md.example');
+ if (await exists(alt)) {
+ await copyFile(alt, path.join(targetDir, stateFile), dryRun);
+ }
+ }
+
+ const loopMd = path.join(effectiveStarter, 'LOOP.md');
+ if (await exists(loopMd)) {
+ await copyFile(loopMd, path.join(targetDir, 'LOOP.md'), dryRun);
+ }
+
+ if (!dryRun && !(await exists(path.join(targetDir, 'AGENTS.md')))) {
+ const agentsTemplate = `# AGENTS.md
+
+## Test commands
+npm test
+npm run lint
+
+## Loop conventions
+- Report-only week one (L1) before enabling auto-fix (L2)
+- See LOOP.md for cadence and human gates
+`;
+ await writeFile(path.join(targetDir, 'AGENTS.md'), agentsTemplate);
+ console.log(' created: AGENTS.md (template)');
+ }
+
+ console.log('\n=== Next steps ===');
+ console.log(` npx @cobusgreyling/loop-audit ${target === '.' ? '.' : target} --suggest`);
+ console.log(` First loop command (${tool}):\n ${firstLoopCommand(pattern, tool)}\n`);
+}
+
+async function readDirNames(dir: string): Promise<string[]> {
+ const { readdir } = await import('node:fs/promises');
+ const entries = await readdir(dir, { withFileTypes: true });
+ return entries.filter((e) => e.isDirectory() || e.isFile()).map((e) => e.name);
+}
+
+main().catch((err) => {
+ console.error('loop-init failed:', err instanceof Error ? err.message : err);
+ process.exit(1);
+});
\ No newline at end of file
diff --git a/tools/loop-init/tsconfig.json b/tools/loop-init/tsconfig.json
new file mode 100644
index 0000000..1e66d55
--- /dev/null
+++ b/tools/loop-init/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "outDir": "dist",
+ "rootDir": "src",
+ "strict": true,
+ "declaration": true,
+ "skipLibCheck": true
+ },
+ "include": ["src/**/*"]
+}
\ No newline at end of file