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.
TypeScript agentic-aiai-agentsai-codinganthropicautomationclaudeclaude-codecodexcoding-agentsdevops-automationdevtoolsgithub-actionsgrokllmloop-engineeringmcpprompt-engineering
feat: add @cobusgreyling/loop unified CLI front door
Cobus Greyling6e06f92311fe
diff --git a/.github/workflows/release-loop.yml b/.github/workflows/release-loop.ymlnew file mode 100644index 0000000..f3b3fe1--- /dev/null+++ b/.github/workflows/release-loop.yml@@ -0,0 +1,54 @@+name: Release loop (umbrella CLI)++on:+ push:+ tags:+ - 'loop-v*'+ workflow_dispatch:+ inputs:+ tag:+ description: 'Tag to publish (e.g. loop-v0.1.0)'+ required: true+ type: string++permissions:+ contents: read+ id-token: write++jobs:+ test-and-publish:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7+ with:+ ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/tags/{0}', github.event.inputs.tag) || github.ref }}++ - uses: actions/setup-node@v7+ with:+ node-version: '22'+ registry-url: 'https://registry.npmjs.org'+ cache: 'npm'+ cache-dependency-path: tools/loop/package-lock.json++ - name: Ensure npm supports trusted publishing (OIDC)+ run: |+ npm install -g npm@latest+ npm install -g sigstore++ - name: Build sibling tools + umbrella+ run: |+ (cd tools/readiness-core && npm ci && npm run build)+ (cd tools/loop-audit && npm ci && npm run build)+ (cd tools/loop-sync && npm ci && npm run build)+ (cd tools/loop-init && npm ci && npm run build)+ (cd tools/loop-cost && npm ci && npm run build)+ cd tools/loop+ npm ci+ npm run build+ npm test++ - name: Publish to npm+ working-directory: tools/loop+ run: npm publish --access public --provenance+ env:+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}diff --git a/AGENTS.md b/AGENTS.mdindex f86e5a3..45cabc0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -5,7 +5,12 @@ Conventions for humans and loops maintaining this repository.## Build & verify```bash-# Loop readiness audit CLI+# Unified front door (prefer for new workflows)+cd tools/loop && npm ci && npm test+node dist/cli.js doctor ../..+node dist/cli.js status ../..++# Loop readiness audit CLI (still canonical scorer)cd tools/loop-audit && npm ci && npm run buildnode dist/cli.js ../.. # audit repo rootnode dist/cli.js ../.. --suggest # show copy commands for gaps@@ -14,6 +19,8 @@ node dist/cli.js ../.. --suggest # show copy commands for gapsbash scripts/before-after-demo.sh```+Front door map: [docs/cli-front-door.md](docs/cli-front-door.md). Agent install skill: [skills/install-loop/SKILL.md](skills/install-loop/SKILL.md).+CI runs `validate-patterns` and `audit` on every push/PR (see `.github/workflows/`).## Review norms@@ -34,6 +41,7 @@ CI runs `validate-patterns` and `audit` on every push/PR (see `.github/workflowsThis repo has no application test suite. Quality gates:```bash+cd tools/loop && npm test && node dist/cli.js doctor ../..cd tools/loop-audit && npm run build && node dist/cli.js ../../bash scripts/before-after-demo.sh```\ No newline at end of filediff --git a/LOOP.md b/LOOP.mdindex bc7170e..8be21ea 100644--- a/LOOP.md+++ b/LOOP.md@@ -68,8 +68,12 @@ See [docs/multi-loop.md](docs/multi-loop.md). Priority: CI Sweeper → PR Babysi## How to run locally```bash+# Front door (after build or npm publish)+node tools/loop/dist/cli.js doctor .+node tools/loop/dist/cli.js status .node tools/loop-audit/dist/cli.js . --suggest-npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok # after npm publish+npx @cobusgreyling/loop init . --pattern daily-triage --tool grok # after npm publish+# same as: npx @cobusgreyling/loop-init . --pattern daily-triage --tool grokbash scripts/before-after-demo.sh```diff --git a/README.md b/README.mdindex 75b39fe..cf4012b 100644--- a/README.md+++ b/README.md@@ -10,6 +10,7 @@<p align="center"><a href="https://github.com/cobusgreyling/loop-engineering/stargazers"><img src="https://img.shields.io/github/stars/cobusgreyling/loop-engineering?style=social" alt="GitHub stars"></a><a href="https://github.com/cobusgreyling/loop-engineering/actions/workflows/audit.yml"><img src="https://img.shields.io/github/actions/workflow/status/cobusgreyling/loop-engineering/audit.yml?label=loop-audit%20dogfood" alt="loop-audit dogfood"></a>+ <a href="https://www.npmjs.com/package/@cobusgreyling/loop"><img src="https://img.shields.io/npm/v/@cobusgreyling/loop?label=loop" alt="loop npm"></a><a href="https://www.npmjs.com/package/@cobusgreyling/loop-audit"><img src="https://img.shields.io/npm/v/@cobusgreyling/loop-audit?label=loop-audit" alt="loop-audit npm"></a><a href="https://www.npmjs.com/package/@cobusgreyling/loop-init"><img src="https://img.shields.io/npm/v/@cobusgreyling/loop-init?label=loop-init" alt="loop-init npm"></a><a href="https://www.npmjs.com/package/@cobusgreyling/loop-cost"><img src="https://img.shields.io/npm/v/@cobusgreyling/loop-cost?label=loop-cost" alt="loop-cost npm"></a>@@ -35,12 +36,17 @@</p>```bash+# Front door (recommended) — one binary for init + doctor + status+npx @cobusgreyling/loop init . --pattern daily-triage --tool grok+npx @cobusgreyling/loop doctor .++# Same as before (still fully supported — forks need not change)npx @cobusgreyling/loop-init .# Optional: also scaffold a versioned harness (harness-foundry)-npx @cobusgreyling/loop-init . --with-foundry+npx @cobusgreyling/loop init . --with-foundry```-`loop-init` scaffolds skills, state, and budget files, then prints your **Loop Ready** score and first loop command. Swap `--tool` for `claude`, `codex`, or `opencode`. Use `--with-foundry` when you want the loop as a composable runtime stack.+`loop init` (or `loop-init`) scaffolds skills, state, and budget files, then prints your **Loop Ready** score and first loop command. `loop doctor` combines audit + sync + file checks into top-3 next actions. Swap `--tool` for `claude`, `codex`, or `opencode`. Use `--with-foundry` when you want the loop as a composable runtime stack. See [docs/cli-front-door.md](docs/cli-front-door.md).<p align="center"><a href="docs/QUICKSTART.md">@@ -81,7 +87,8 @@ For developers using Grok, Claude Code, Codex, Cursor, and other AI coding agent| Start here | Description ||------------|-------------|-| [Quickstart (5 min)](docs/QUICKSTART.md) | Scaffold → cost check → audit → first loop — **start here if you just landed** |+| [Quickstart (5 min)](docs/QUICKSTART.md) | `loop init` → `loop doctor` → first loop — **start here if you just landed** |+| [CLI front door](docs/cli-front-door.md) | Unified `@cobusgreyling/loop` — old packages stay open || [Loop Engineering essay](https://cobusgreyling.substack.com/p/loop-engineering) | The concept, primitives, and Grok mapping — read for the why || [Pattern Picker](docs/pattern-picker.md) | Which loop to run first — **start here if unsure** || [Primitives Matrix](docs/primitives-matrix.md) | Cross-tool loop primitive mapping — bookmark this |@@ -89,8 +96,9 @@ For developers using Grok, Claude Code, Codex, Cursor, and other AI coding agent| [Patterns](patterns/README.md) | 7 production patterns + [interactive picker](https://cobusgreyling.github.io/loop-engineering/#interactive) || [Starters](starters/) | Clone-and-run kits (Grok, Claude Code, Codex, Opencode) || [Opencode examples](examples/opencode/) | CLI-first loops: cron/systemd + `opencode run`, skills, worktrees |-| [loop-audit](tools/loop-audit/) | Loop Readiness Score CLI (v1.7 — constraints + governance + **Harness Runtime**) — `npx @cobusgreyling/loop-audit . --suggest` · `--badge` for README |-| [loop-init](tools/loop-init/) | Scaffold starters + budget/run-log + constraints (v1.5) — `npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok` · **`--with-foundry`** for harness stack |+| [**loop** (front door)](tools/loop/) | **Unified CLI** — `npx @cobusgreyling/loop init \| doctor \| status \| audit \| cost` · [cli-front-door](docs/cli-front-door.md) |+| [loop-audit](tools/loop-audit/) | Loop Readiness Score CLI (v1.7 — constraints + governance + **Harness Runtime**) — `npx @cobusgreyling/loop audit . --suggest` · also `loop-audit` |+| [loop-init](tools/loop-init/) | Scaffold starters + budget/run-log + constraints (v1.5) — `npx @cobusgreyling/loop init . --pattern daily-triage --tool grok` · also `loop-init` || [harness-foundry](https://github.com/cobusgreyling/harness-foundry) | **Companion runtime:** versioned stacks, sessions, traces — `npx @cobusgreyling/harness-foundry init --from loop-engineering:daily-triage` || [outerloop](https://github.com/cobusgreyling/outerloop) | **Companion governance:** evidence → verdict → answerability || [loop-cost](tools/loop-cost/) | Token spend estimator — `npx @cobusgreyling/loop-cost` |@@ -114,8 +122,8 @@ memory-engineering → loop-engineering → harness-foundry → outerloop → fl| Layer | You get | Start ||-------|---------|--------|| **Memory** | Tiers, recall budget, Memory Ready score | [memory-engineering](https://github.com/cobusgreyling/memory-engineering) |-| **Design** (this repo) | Patterns, starters, Loop Ready score | `npx @cobusgreyling/loop-init .` |-| **Runtime** | Versioned harness, traces, evolve | `npx @cobusgreyling/loop-init . --with-foundry` or [Foundry showcase](https://github.com/cobusgreyling/harness-foundry/blob/main/docs/showcase.md) |+| **Design** (this repo) | Patterns, starters, Loop Ready score | `npx @cobusgreyling/loop init .` then `loop doctor .` |+| **Runtime** | Versioned harness, traces, evolve | `npx @cobusgreyling/loop init . --with-foundry` or [Foundry showcase](https://github.com/cobusgreyling/harness-foundry/blob/main/docs/showcase.md) || **Govern** | Evidence, verdict, answerability | [outerloop](https://github.com/cobusgreyling/outerloop) || **Fleet** | Registry, inbox, budgets, kill switch | `npx @cobusgreyling/fleet-init .` · [Fleet Ready](https://github.com/cobusgreyling/fleet-engineering/blob/main/docs/fleet-ready-score.md) |@@ -216,17 +224,16 @@ Machine-readable index: [patterns/registry.yaml](patterns/registry.yaml) (7 patt## Getting Started (5 minutes)```bash-# 1. Scaffold + get your Loop Ready score (printed automatically)-npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok--# 2. Estimate token spend for your cadence-npx @cobusgreyling/loop-cost --pattern daily-triage --level L1+# 1. Scaffold + Loop Ready score (printed automatically)+npx @cobusgreyling/loop init . --pattern daily-triage --tool grok-# 3. Re-audit after improvements-npx @cobusgreyling/loop-audit . --suggest+# 2. One health check (audit + sync + files → top 3 actions)+npx @cobusgreyling/loop doctor .-# Optional: paste Loop Ready badge into your README-npx @cobusgreyling/loop-audit . --badge+# 3. Optional: cost estimate / badge / day-2 dashboard+npx @cobusgreyling/loop cost --pattern daily-triage --level L1+npx @cobusgreyling/loop badge .+npx @cobusgreyling/loop status .# 4. See scores climb: empty → L1 → L2bash scripts/before-after-demo.sh@@ -235,11 +242,14 @@ bash scripts/before-after-demo.sh/loop 1d Run loop-triage. Update STATE.md. No auto-fix in week one.```+**Same as before:** `npx @cobusgreyling/loop-init` and `loop-audit` still work — [CLI front door](docs/cli-front-door.md).+All npm CLIs publish from tagged releases — see [docs/RELEASE.md](docs/RELEASE.md). No clone required.**Develop from source** (monorepo contributors):```bash+cd tools/loop && npm ci && npm test && node dist/cli.js doctor ../..cd tools/loop-init && npm ci && npm test && node dist/cli.js /path/to/project --pattern daily-triage --tool grokcd tools/loop-audit && npm ci && npm test && node dist/cli.js /path/to/project --suggestcd tools/loop-cost && npm ci && npm test && node dist/cli.js --pattern ci-sweeper --cadence 15mdiff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.mdindex 0e1a7ca..4b6ccde 100644--- a/docs/QUICKSTART.md+++ b/docs/QUICKSTART.md@@ -8,6 +8,8 @@ Landed from [X](https://x.com), the [showcase](https://cobusgreyling.github.io/l**Week one rule:** report only. No auto-fix, no auto-merge. Read what the loop writes before you let it act.+**Front door:** prefer the unified CLI (`@cobusgreyling/loop`). Dedicated packages (`loop-init`, `loop-audit`, …) stay fully supported — see [cli-front-door.md](./cli-front-door.md).+## 1. Pick your pain (30 seconds)Not sure which loop? Use the [interactive pattern picker](https://cobusgreyling.github.io/loop-engineering/#interactive) on the showcase — it recommends a pattern, scaffold command, first `/loop` line, and a token estimate.@@ -19,15 +21,23 @@ Or start with **Daily Triage** if you just want to learn loop discipline with loRun this in the root of any git project (no clone required):```bash-npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok+npx @cobusgreyling/loop init . --pattern daily-triage --tool grok+# One health check (audit + sync + top 3 actions):+npx @cobusgreyling/loop doctor .# Optional one-command funnel into harness-foundry:-npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok --with-foundry+npx @cobusgreyling/loop init . --pattern daily-triage --tool grok --with-foundry+```++Equivalent (old door, still supported):++```bash+npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok```Swap `--pattern` for any pattern from [patterns/registry.yaml](../patterns/registry.yaml). List all patterns:```bash-npx @cobusgreyling/loop-init --help+npx @cobusgreyling/loop init --help```### Which `--tool` values work?@@ -47,7 +57,8 @@ npx @cobusgreyling/loop-init --help## 3. Check cost before you schedule (30 seconds)```bash-npx @cobusgreyling/loop-cost --pattern daily-triage --level L1 --cadence 1d+npx @cobusgreyling/loop cost --pattern daily-triage --level L1 --cadence 1d+# same as: npx @cobusgreyling/loop-cost --pattern daily-triage --level L1 --cadence 1d```Adjust `--pattern`, `--level` (L1 → L2 → L3), and `--cadence` to match what you plan to run. High-frequency loops (CI Sweeper at 5m) can burn tokens fast — slow the cadence or require early-exit triage first.@@ -57,7 +68,8 @@ Adjust `--pattern`, `--level` (L1 → L2 → L3), and `--cadence` to match whatWhen a loop starts fixing code unattended, wire a **circuit breaker** so it escalates instead of retrying the same failure forever. `loop-init` scaffolds `loop-ledger.json` and a `loop-guard` skill for fix-capable patterns; check the ledger before each retry:```bash-npx @cobusgreyling/loop-context --check --ledger loop-ledger.json+npx @cobusgreyling/loop context --check --ledger loop-ledger.json+# same as: npx @cobusgreyling/loop-context --check --ledger loop-ledger.json```Exit `0` = continue · `2` = escalate to a human. The breaker trips on max iterations, the same error repeating N× in a row, too many consecutive failures, or a token budget cap. Full API: [tools/loop-context/README.md](../tools/loop-context/README.md).@@ -65,29 +77,33 @@ Exit `0` = continue · `2` = escalate to a human. The breaker trips on max itera## 4. Audit readiness (30 seconds)```bash-npx @cobusgreyling/loop-audit . --suggest+# Prefer doctor for day-to-day (includes audit + sync)+npx @cobusgreyling/loop doctor .+# Or audit alone:+npx @cobusgreyling/loop audit . --suggest```Scores 0–100 with concrete next steps. Re-run after each improvement. Paste a badge when you're proud of the score:```bash-npx @cobusgreyling/loop-audit . --badge+npx @cobusgreyling/loop badge .```-When the score is **≥ 80**, audit (and `loop-init`) nudge you to version the loop as a [harness-foundry](https://github.com/cobusgreyling/harness-foundry) stack — declarative runtime, traces, outerloop emit:+When the score is **≥ 80**, audit (and `loop init`) nudge you to version the loop as a [harness-foundry](https://github.com/cobusgreyling/harness-foundry) stack — declarative runtime, traces, outerloop emit:```bash-npx @cobusgreyling/loop-init . --with-foundry+npx @cobusgreyling/loop init . --with-foundrynpx @cobusgreyling/harness-foundry validatenpx @cobusgreyling/harness-foundry run --goal "Verify harness wiring"```-### Catch drift before you schedule (`loop-sync`)+### Catch drift before you schedule (`loop sync`)-`loop-audit` scores readiness; `loop-sync` checks that your `STATE.md` and `LOOP.md` still agree. When they drift — you edit `LOOP.md` to add a loop but never wire it into `STATE.md`, or a starter update leaves one file behind — a scheduled loop can run against stale instructions.+`loop audit` scores readiness; `loop sync` checks that your `STATE.md` and `LOOP.md` still agree. When they drift — you edit `LOOP.md` to add a loop but never wire it into `STATE.md`, or a starter update leaves one file behind — a scheduled loop can run against stale instructions. `loop doctor` runs this for you.```bash-npx @cobusgreyling/loop-sync .+npx @cobusgreyling/loop sync .+# same as: npx @cobusgreyling/loop-sync .```Sample output on a fresh daily-triage scaffold:diff --git a/docs/RELEASE.md b/docs/RELEASE.mdindex df4fa24..6650d26 100644--- a/docs/RELEASE.md+++ b/docs/RELEASE.md@@ -1,9 +1,10 @@# Release playbook — npm packages-This repo ships eleven public npm packages from `tools/`:+This repo ships public npm packages from `tools/`. **Front door for users:** `@cobusgreyling/loop` ([cli-front-door.md](./cli-front-door.md)). Sibling packages stay published and supported.| Package | Directory | Release tag ||---------|-----------|-------------|+| `@cobusgreyling/loop` | `tools/loop` | `loop-v*` || `@cobusgreyling/readiness-core` | `tools/readiness-core` | `readiness-core-v*` || `@cobusgreyling/loop-audit` | `tools/loop-audit` | `loop-audit-v*` || `@cobusgreyling/loop-init` | `tools/loop-init` | `loop-init-v*` |@@ -22,6 +23,7 @@ Link npm to GitHub, then for **each package** on [npmjs.com](https://www.npmjs.c| Package | Repository | Workflow filename ||---------|--------------|-------------------|+| `@cobusgreyling/loop` | `cobusgreyling/loop-engineering` | `release-loop.yml` || `@cobusgreyling/readiness-core` | `cobusgreyling/loop-engineering` | `release-readiness-core.yml` || `@cobusgreyling/loop-audit` | `cobusgreyling/loop-engineering` | `release-loop-audit.yml` || `@cobusgreyling/loop-init` | `cobusgreyling/loop-engineering` | `release-loop-init.yml` |@@ -55,6 +57,10 @@ Tag pushes trigger the release workflows:git tag readiness-core-v1.0.0git push origin readiness-core-v1.0.0+# loop (unified front door — pass-through + doctor/status)+git tag loop-v0.1.0+git push origin loop-v0.1.0+# loop-audit (runs tests before publish)git tag loop-audit-v1.6.0git push origin loop-audit-v1.6.0@@ -96,7 +102,7 @@ git tag goal-init-v1.0.0git push origin goal-init-v1.0.0```-Workflows: `.github/workflows/release-readiness-core.yml`, `.github/workflows/release-loop-audit.yml`, `.github/workflows/release-loop-init.yml`, `.github/workflows/release-loop-cost.yml`, `.github/workflows/release-loop-sync.yml`, `.github/workflows/release-loop-context.yml`, `.github/workflows/release-loop-mcp-server.yml`, `.github/workflows/release-loop-worktree.yml`, `.github/workflows/release-loop-gate.yml`, `.github/workflows/release-goal-audit.yml`, `.github/workflows/release-goal-init.yml`.+Workflows: `.github/workflows/release-loop.yml`, `.github/workflows/release-readiness-core.yml`, `.github/workflows/release-loop-audit.yml`, `.github/workflows/release-loop-init.yml`, `.github/workflows/release-loop-cost.yml`, `.github/workflows/release-loop-sync.yml`, `.github/workflows/release-loop-context.yml`, `.github/workflows/release-loop-mcp-server.yml`, `.github/workflows/release-loop-worktree.yml`, `.github/workflows/release-loop-gate.yml`, `.github/workflows/release-goal-audit.yml`, `.github/workflows/release-goal-init.yml`.## Verify after publishdiff --git a/docs/cli-front-door.md b/docs/cli-front-door.mdnew file mode 100644index 0000000..c153da8--- /dev/null+++ b/docs/cli-front-door.md@@ -0,0 +1,70 @@+# CLI front door — `@cobusgreyling/loop`++> **Additive.** Old packages stay fully supported. This is the recommended entry for new users, forks, and agents.++## Why++Loop Engineering ships several focused CLIs (`loop-init`, `loop-audit`, `loop-cost`, …). That is great for maintainers; it is hard for first-time adopters to remember.++`@cobusgreyling/loop` is a **thin umbrella**:++1. One binary people can remember+2. **Pass-through** to existing tools (same flags)+3. **doctor** / **status** for activation and day-2 habit++```text+npx @cobusgreyling/loop init . -p daily-triage -t grok+npx @cobusgreyling/loop doctor .+```++## Map (new → same as before)++| Front door | Existing package / command |+|------------|----------------------------|+| `loop init …` | `npx @cobusgreyling/loop-init …` |+| `loop audit …` | `npx @cobusgreyling/loop-audit …` |+| `loop cost …` | `npx @cobusgreyling/loop-cost …` |+| `loop sync …` | `npx @cobusgreyling/loop-sync …` |+| `loop context …` | `npx @cobusgreyling/loop-context …` |+| `loop worktree …` | `npx @cobusgreyling/loop-worktree …` |+| `loop gate …` | `npx @cobusgreyling/loop-gate …` |+| `loop mcp …` | `npx @cobusgreyling/loop-mcp-server …` |+| `loop badge .` | `loop-audit . --badge` |+| `loop doctor .` | **new** (audit + sync + files) |+| `loop status .` | **new** (run-log dashboard) |++## Doctor exit codes++| Code | Meaning | CI use |+|------|---------|--------|+| 0 | Healthy | green |+| 1 | Warnings | soft-fail or comment |+| 2 | Blocked | hard-fail if you require scaffold |++```bash+npx @cobusgreyling/loop doctor . --json+```++## Forks & contributors++- **Forks that already call `loop-init` / `loop-audit`:** change nothing.+- **New docs / skills / Actions:** prefer `loop`.+- **Contributors adding tools:** keep a dedicated package; add a one-line pass-through in `tools/loop` if it should be discoverable.++## Agent skill++[`skills/install-loop/SKILL.md`](../skills/install-loop/SKILL.md) — copy into `.grok/skills`, `.claude/skills`, etc., or point agents at this path.++## Publish++```bash+git tag loop-v0.1.0+git push origin loop-v0.1.0+```++Workflow: [`.github/workflows/release-loop.yml`](../.github/workflows/release-loop.yml). See [RELEASE.md](./RELEASE.md).++## Version policy++- `0.x` while the umbrella settles; pass-through tracks whatever sibling versions are installed via monorepo dist or npx.+- No deprecation of sibling packages in this phase.diff --git a/docs/index.html b/docs/index.htmlindex a19c09b..be564d1 100644--- a/docs/index.html+++ b/docs/index.html@@ -78,7 +78,7 @@ title: Loop Engineering — Showcase<div class="badge">Open source · Tool-agnostic · Production-ready · L3 dogfood · 7 patterns · Interactive tools</div><h1>Stop prompting.<br>Design the loop.<br>Get a score.</h1><p class="lead">- Run one command in any repo. <code>loop-init</code> scaffolds your loop and prints your <strong>Loop Ready</strong> score plus the first run line.+ Run one command in any repo. <code>@cobusgreyling/loop</code> is the front door (<code>init</code> + <code>doctor</code>). <code>loop-init</code> still works. Prints your <strong>Loop Ready</strong> score plus the first run line.</p><div class="code-block" style="max-width:720px;margin:0 auto 24px;"><div class="code-header">@@ -86,7 +86,8 @@ title: Loop Engineering — Showcase<span>terminal — try now</span><button onclick="copyNpxInit()" class="copy-btn">Copy</button></div>- <pre>npx @cobusgreyling/loop-init .</pre>+ <pre>npx @cobusgreyling/loop init .+npx @cobusgreyling/loop doctor .</pre></div><div class="hero-cta"><a href="#start" class="btn btn-primary">Try in 60 seconds →</a>@@ -313,7 +314,7 @@ flowchart TBendsubgraph Tooling["CLIs + connectors"]- Init[loop-init: scaffold]+ Init[loop init: scaffold]Audit[loop-audit: readiness score]MCP[MCP server: read-only policy + tools]end@@ -462,7 +463,7 @@ flowchart TB<span>terminal — minimal loop</span></div><pre><span class="comment"># Scaffold starter (or copy manually)</span>-npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok+npx @cobusgreyling/loop init . --pattern daily-triage --tool grok<span class="comment"># Score loop readiness (PRs get audit comments in CI)</span>npx @cobusgreyling/loop-audit . --suggest@@ -705,7 +706,7 @@ npx @cobusgreyling/loop-audit . --suggest<script>// Copy helpers for herofunction copyNpxInit() {- const txt = 'npx @cobusgreyling/loop-init .';+ const txt = 'npx @cobusgreyling/loop init .';navigator.clipboard.writeText(txt).then(() => {const b = event.currentTarget; // best effort});@@ -818,7 +819,7 @@ const PATTERNS = {patternId: 'ci-sweeper',costLevel: 'L2',costCadence: '15m',- npx: 'npx @cobusgreyling/loop-init . --pattern ci-sweeper --tool grok',+ npx: 'npx @cobusgreyling/loop init . --pattern ci-sweeper --tool grok',loop: '/loop 15m Run ci-triage on failing CI. Update ci-sweeper-state.md. Fix only regressions in worktree. Max 3 attempts.',patternHref: 'https://github.com/cobusgreyling/loop-engineering/blob/main/patterns/ci-sweeper.md',starterHref: 'https://github.com/cobusgreyling/loop-engineering/tree/main/starters/ci-sweeper'@@ -829,7 +830,7 @@ const PATTERNS = {patternId: 'pr-babysitter',costLevel: 'L1',costCadence: '10m',- npx: 'npx @cobusgreyling/loop-init . --pattern pr-babysitter --tool grok',+ npx: 'npx @cobusgreyling/loop init . --pattern pr-babysitter --tool grok',loop: '/loop 10m Run pr-review-triage. Update pr-babysitter-state.md. Worktree + verifier. No auto-merge by default.',patternHref: 'https://github.com/cobusgreyling/loop-engineering/blob/main/patterns/pr-babysitter.md',starterHref: 'https://github.com/cobusgreyling/loop-engineering/tree/main/starters/pr-babysitter'@@ -840,7 +841,7 @@ const PATTERNS = {patternId: 'daily-triage',costLevel: 'L1',costCadence: '1d',- npx: 'npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok',+ npx: 'npx @cobusgreyling/loop init . --pattern daily-triage --tool grok',loop: '/loop 1d Run loop-triage. Update STATE.md. No auto-fix in week one.',patternHref: 'https://github.com/cobusgreyling/loop-engineering/blob/main/patterns/daily-triage.md',starterHref: 'https://github.com/cobusgreyling/loop-engineering/tree/main/starters/minimal-loop'@@ -851,7 +852,7 @@ const PATTERNS = {patternId: 'dependency-sweeper',costLevel: 'L2',costCadence: '6h',- npx: 'npx @cobusgreyling/loop-init . --pattern dependency-sweeper --tool grok',+ npx: 'npx @cobusgreyling/loop init . --pattern dependency-sweeper --tool grok',loop: '/loop 6h Run dependency-triage. Patch-only auto-fix in worktree + verifier. Escalate majors.',patternHref: 'https://github.com/cobusgreyling/loop-engineering/blob/main/patterns/dependency-sweeper.md',starterHref: 'https://github.com/cobusgreyling/loop-engineering/tree/main/starters/dependency-sweeper'@@ -862,7 +863,7 @@ const PATTERNS = {patternId: 'post-merge-cleanup',costLevel: 'L1',costCadence: '1d',- npx: 'npx @cobusgreyling/loop-init . --pattern post-merge-cleanup --tool grok',+ npx: 'npx @cobusgreyling/loop init . --pattern post-merge-cleanup --tool grok',loop: '/loop 1d Run post-merge-scan on recent merges. Update post-merge-state.md. Small fixes only.',patternHref: 'https://github.com/cobusgreyling/loop-engineering/blob/main/patterns/post-merge-cleanup.md',starterHref: 'https://github.com/cobusgreyling/loop-engineering/tree/main/starters/post-merge-cleanup'@@ -873,7 +874,7 @@ const PATTERNS = {patternId: 'changelog-drafter',costLevel: 'L1',costCadence: '1d',- npx: 'npx @cobusgreyling/loop-init . --pattern changelog-drafter --tool grok',+ npx: 'npx @cobusgreyling/loop init . --pattern changelog-drafter --tool grok',loop: '/loop 1d Run changelog-scan + draft-release-notes. Write RELEASE_NOTES_DRAFT.md. Human review only.',patternHref: 'https://github.com/cobusgreyling/loop-engineering/blob/main/patterns/changelog-drafter.md',starterHref: 'https://github.com/cobusgreyling/loop-engineering/tree/main/starters/changelog-drafter'@@ -884,7 +885,7 @@ const PATTERNS = {patternId: 'issue-triage',costLevel: 'L1',costCadence: '1d',- npx: 'npx @cobusgreyling/loop-init . --pattern issue-triage --tool grok',+ npx: 'npx @cobusgreyling/loop init . --pattern issue-triage --tool grok',loop: '/loop 1d Run issue-triage. Update issue-triage-state.md. Propose labels and priorities only — no auto-close.',patternHref: 'https://github.com/cobusgreyling/loop-engineering/blob/main/patterns/issue-triage.md',starterHref: 'https://github.com/cobusgreyling/loop-engineering/tree/main/starters/issue-triage'@@ -991,7 +992,7 @@ function setupSimulator() {} else if (score >= 78 && hasVerifier && hasState && !costReady) {level = 'L2';assess = 'Strong signals but missing cost observability — add budget + run log before L3.';- reco = 'npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok (scaffolds loop-budget.md + loop-run-log.md)';+ reco = 'npx @cobusgreyling/loop init . --pattern daily-triage --tool grok (scaffolds loop-budget.md + loop-run-log.md)';} else if (score >= 78 && hasVerifier && hasState && costReady && !hasActivity) {level = 'L2';assess = 'Strong structure but no proven loop runs yet.';@@ -1007,7 +1008,7 @@ function setupSimulator() {} else {level = 'L0';assess = 'Not loop-ready — start with a starter from this repo (minimal-loop or pr-babysitter).';- reco = 'npx @cobusgreyling/loop-init . --pattern daily-triage --tool grok';+ reco = 'npx @cobusgreyling/loop init . --pattern daily-triage --tool grok';}scoreEl.textContent = score;diff --git a/package.json b/package.jsonindex 6250038..442c0db 100644--- a/package.json+++ b/package.json@@ -14,11 +14,12 @@"test:mcp-server": "cd tools/mcp-server && npm test","test:loop-worktree": "cd tools/loop-worktree && npm test","test:loop-sandbox": "cd tools/loop-sandbox && npm test",+ "test:loop": "cd tools/loop && npm test","test:goal-init": "cd tools/goal-init && npm test","test:readiness-core": "cd tools/readiness-core && npm test","test:goal-audit": "cd tools/goal-audit && npm test",- "test:tools": "npm run test:readiness-core && npm run test:loop-audit && npm run test:loop-init && npm run test:loop-cost && npm run test:loop-sync && npm run test:loop-context && npm run test:loop-gate && npm run test:mcp-server && npm run test:loop-worktree && npm run test:loop-sandbox && npm run test:goal-audit && npm run test:goal-init",- "build:tools": "cd tools/readiness-core && npm run build && cd ../loop-audit && npm run build && cd ../loop-init && npm run build && cd ../loop-cost && npm run build && cd ../loop-sync && npm run build && cd ../loop-context && npm run build && cd ../loop-gate && npm run build && cd ../mcp-server && npm run build && cd ../loop-worktree && npm run build && cd ../loop-sandbox && npm run build && cd ../goal-audit && npm run build && cd ../goal-init && npm run build",+ "test:tools": "npm run test:readiness-core && npm run test:loop-audit && npm run test:loop-init && npm run test:loop-cost && npm run test:loop-sync && npm run test:loop-context && npm run test:loop-gate && npm run test:mcp-server && npm run test:loop-worktree && npm run test:loop-sandbox && npm run test:loop && npm run test:goal-audit && npm run test:goal-init",+ "build:tools": "cd tools/readiness-core && npm run build && cd ../loop-audit && npm run build && cd ../loop-init && npm run build && cd ../loop-cost && npm run build && cd ../loop-sync && npm run build && cd ../loop-context && npm run build && cd ../loop-gate && npm run build && cd ../mcp-server && npm run build && cd ../loop-worktree && npm run build && cd ../loop-sandbox && npm run build && cd ../loop && npm run build && cd ../goal-audit && npm run build && cd ../goal-init && npm run build","contributors:generate": "node scripts/generate-contributors.mjs","contributors:check": "node scripts/generate-contributors.mjs --check"},diff --git a/scripts/ci-audit-gates.sh b/scripts/ci-audit-gates.shindex 226a5e0..0c0d583 100755--- a/scripts/ci-audit-gates.sh+++ b/scripts/ci-audit-gates.sh@@ -19,6 +19,33 @@ npm cinpm testecho "=== Audit of repo root ==="node dist/cli.js "$REPO_ROOT" --json > "$ROOT_AUDIT_FILE"+echo ""++# Umbrella CLI dogfood (additive — does not replace loop-audit gates)+echo "=== loop doctor (umbrella front door) ==="+(+ cd "$REPO_ROOT/tools/loop-sync"+ npm ci+ npm run build+)+(+ cd "$REPO_ROOT/tools/loop"+ npm ci+ npm test+ # Reference repo should not be blocked (exit 2). Warnings (exit 1) are OK.+ set +e+ node dist/cli.js doctor "$REPO_ROOT" --json > "$AUDIT_TMP_DIR/doctor.json"+ DOCTOR_CODE=$?+ set -e+ if [ "$DOCTOR_CODE" -ge 2 ]; then+ echo "loop doctor blocked (exit $DOCTOR_CODE) on reference repo"+ cat "$AUDIT_TMP_DIR/doctor.json" || true+ exit 2+ fi+ echo "loop doctor exit=$DOCTOR_CODE (0=healthy, 1=warning OK for dogfood)"+ node dist/cli.js status "$REPO_ROOT" --json > /dev/null+)+echo ""echo "=== Audit of starters (L1 gate) ==="FAILED=0diff --git a/skills/install-loop/SKILL.md b/skills/install-loop/SKILL.mdnew file mode 100644index 0000000..16653b5--- /dev/null+++ b/skills/install-loop/SKILL.md@@ -0,0 +1,80 @@+---+name: install-loop+description: >+ Install Loop Engineering into a project via the unified CLI front door+ (@cobusgreyling/loop). Prefer this over invoking loop-init / loop-audit+ separately. Week-one is report-only; never enable auto-merge or unattended+ fixes unless the human explicitly asks and doctor is healthy.+---++# Install Loop Engineering++## Goal++Leave the repo with a scaffolded **report-only** loop, a **Loop Ready** score, and clear next actions — using the **single** CLI:++```bash+npx @cobusgreyling/loop+```++Do **not** deprecate or remove existing `loop-init` / `loop-audit` usages you find; both doors stay valid. Prefer `loop` for new work.++## Steps++1. **Detect context**+ - If `LOOP.md` or `STATE.md` already exists, run doctor only (skip init unless human asks to re-scaffold):+ ```bash+ npx @cobusgreyling/loop doctor . --json+ npx @cobusgreyling/loop status .+ ```+ - Otherwise continue.++2. **Pick pattern** (default: `daily-triage`)+ | Pain | Pattern |+ |------|---------|+ | Morning chaos / unclear priorities | `daily-triage` |+ | PRs stalling | `pr-babysitter` |+ | CI red / flakes | `ci-sweeper` |+ | CVE / Dependabot noise | `dependency-sweeper` |+ | Post-merge TODOs | `post-merge-cleanup` |+ | Stale release notes | `changelog-drafter` |+ | Noisy issues | `issue-triage` |++3. **Pick tool** — `grok` | `claude` | `codex` | `opencode` (default `grok`).++4. **Scaffold**+ ```bash+ npx @cobusgreyling/loop init . --pattern <pattern> --tool <tool>+ ```+ Optional harness (only if human wants Foundry): add `--with-foundry`.++5. **Doctor**+ ```bash+ npx @cobusgreyling/loop doctor .+ ```+ - Exit `0` = healthy · `1` = warnings · `2` = blocked+ - Follow the **top 3** printed actions; do not invent extra architecture.++6. **Cost check** before high-cadence schedules:+ ```bash+ npx @cobusgreyling/loop cost -p <pattern> -l L1 -c 1d+ ```++7. **Week-one rule**+ - Report only. No auto-fix, no auto-merge.+ - Tell the human the first `/loop` or scheduler command from init output.+ - Suggest badge only when score is strong: `npx @cobusgreyling/loop badge .`++## Compatibility++These remain fully supported (do not rewrite existing docs/scripts unless asked):++```bash+npx @cobusgreyling/loop-init .+npx @cobusgreyling/loop-audit . --suggest+```++## Stop conditions++- Stop after doctor + first-run instructions unless the human asks for L2+.+- Never expand into fleet/memory/foundry unless score ≥ 80 **and** human opts in.diff --git a/tools/loop/CHANGELOG.md b/tools/loop/CHANGELOG.mdnew file mode 100644index 0000000..689d615--- /dev/null+++ b/tools/loop/CHANGELOG.md@@ -0,0 +1,9 @@+# Changelog++## 0.1.0++- Initial unified CLI front door: `init`, `audit`, `cost`, `sync`, `context`, `worktree`, `gate`, `mcp`, `sandbox` pass-through+- `doctor` — audit + sync + structural checks, top 3 actions, exit 0/1/2, `--json`+- `status` — day-2 dashboard from STATE / LOOP / run-log / ledger+- `badge` — alias for `loop-audit --badge`+- `wizard` / bare help — week-one path without removing old packagesdiff --git a/tools/loop/README.md b/tools/loop/README.mdnew file mode 100644index 0000000..8243f8d--- /dev/null+++ b/tools/loop/README.md@@ -0,0 +1,91 @@+# @cobusgreyling/loop++**Unified front door** for [Loop Engineering](https://github.com/cobusgreyling/loop-engineering) CLIs.++```bash+npx @cobusgreyling/loop init . --pattern daily-triage --tool grok+npx @cobusgreyling/loop doctor .+```++This package does **not** replace `loop-init`, `loop-audit`, or the other tools. It wraps them and adds **doctor** + **status** so week-one activation is one mental model.++| Command | Delegates to | Notes |+|---------|--------------|--------|+| `loop init` | `@cobusgreyling/loop-init` | Scaffold pattern + tool |+| `loop audit` | `@cobusgreyling/loop-audit` | Loop Ready score |+| `loop cost` | `@cobusgreyling/loop-cost` | Token estimates |+| `loop sync` | `@cobusgreyling/loop-sync` | STATE ↔ LOOP drift |+| `loop doctor` | audit + sync + files | **New** — top 3 actions, exit codes |+| `loop status` | files + audit | **New** — run-log dashboard |+| `loop badge` | `loop-audit --badge` | README badge |+| `loop context` | `@cobusgreyling/loop-context` | Circuit breaker / memory |+| `loop worktree` | `@cobusgreyling/loop-worktree` | Isolated fix attempts |+| `loop gate` | `@cobusgreyling/loop-gate` | Path denylist |+| `loop mcp` | `@cobusgreyling/loop-mcp-server` | MCP server |+| `loop sandbox` | `@cobusgreyling/loop-sandbox` | Sandbox helper (if present) |++## Week-one path++```bash+# 1. Scaffold (report-only)+npx @cobusgreyling/loop init . --pattern daily-triage --tool grok++# 2. One health check+npx @cobusgreyling/loop doctor .++# 3. Optional cost estimate+npx @cobusgreyling/loop cost -p daily-triage -l L1 -c 1d++# 4. Day-2 dashboard+npx @cobusgreyling/loop status .+```++### Doctor exit codes++| Code | Meaning |+|------|---------|+| `0` | Healthy |+| `1` | Warnings (gaps, mild drift, incomplete budget/run-log) |+| `2` | Blocked (score < 40, critical drift, or not scaffolded) |++```bash+npx @cobusgreyling/loop doctor . --json+npx @cobusgreyling/loop status . --json+```++## Compatibility (old doors stay open)++These continue to work forever (or until a future major with long deprecation):++```bash+npx @cobusgreyling/loop-init .+npx @cobusgreyling/loop-audit . --suggest+npx @cobusgreyling/loop-cost --pattern daily-triage+npx @cobusgreyling/loop-sync .+```++`loop <cmd>` is the same binary behavior for pass-through commands.++## Monorepo develop++```bash+# Build sibling tools first (audit + sync used by doctor)+(cd ../readiness-core && npm ci && npm run build)+(cd ../loop-audit && npm ci && npm run build)+(cd ../loop-sync && npm ci && npm run build)+(cd ../loop-init && npm ci && npm run build)++cd ../loop+npm ci+npm test+node dist/cli.js doctor ../..+node dist/cli.js status ../..+```++## Agent skill++See [`skills/install-loop`](../../skills/install-loop/) in the monorepo — a short skill agents can follow to install and doctor a project.++## License++MITdiff --git a/tools/loop/dist/cli.d.ts b/tools/loop/dist/cli.d.tsnew file mode 100644index 0000000..b798801--- /dev/null+++ b/tools/loop/dist/cli.d.ts@@ -0,0 +1,2 @@+#!/usr/bin/env node+export {};diff --git a/tools/loop/dist/cli.js b/tools/loop/dist/cli.jsnew file mode 100755index 0000000..a918728--- /dev/null+++ b/tools/loop/dist/cli.js@@ -0,0 +1,175 @@+#!/usr/bin/env node+/**+ * @cobusgreyling/loop — unified front door for Loop Engineering CLIs.+ * Additive: loop-init, loop-audit, and siblings stay fully supported.+ */+import { runTool } from './pass-through.js';+import { runDoctor, formatDoctorHuman } from './doctor.js';+import { runStatus, formatStatusHuman } from './status.js';+import { defaultPlan, executePlan, printNonInteractiveHelp, resolvePattern, resolveTool, runInteractiveWizard, } from './wizard.js';+const VERSION = '0.1.0';+const PASS_THROUGH = new Set([+ 'init',+ 'audit',+ 'cost',+ 'sync',+ 'context',+ 'worktree',+ 'gate',+ 'mcp',+ 'sandbox',+]);+function printHelp() {+ console.log(`loop — Loop Engineering unified CLI v${VERSION}++Usage:+ loop Week-one help (or wizard if TTY + --interactive)+ loop init [args…] → loop-init (scaffold)+ loop audit [args…] → loop-audit (Loop Ready score)+ loop cost [args…] → loop-cost+ loop sync [args…] → loop-sync+ loop doctor [path] [--json] Audit + sync + files → top 3 actions+ loop status [path] [--json] Day-2 dashboard from STATE / run-log+ loop badge [path] README badge (→ loop-audit --badge)+ loop wizard [--yes] Guided scaffold + doctor+ loop context|worktree|gate|mcp|sandbox [args…]++Week-one (recommended):+ npx @cobusgreyling/loop init . --pattern daily-triage --tool grok+ npx @cobusgreyling/loop doctor .++Doctor exit codes:+ 0 healthy+ 1 warnings (score/sync/budget gaps)+ 2 blocked (score < 40, critical drift, or unscaffolded)++Compatibility (old doors stay open):+ npx @cobusgreyling/loop-init .+ npx @cobusgreyling/loop-audit . --suggest++Docs: https://github.com/cobusgreyling/loop-engineering/blob/main/docs/QUICKSTART.md+Showcase: https://cobusgreyling.github.io/loop-engineering/+`);+}+async function cmdDoctor(args) {+ const json = args.includes('--json');+ const target = args.find((a) => !a.startsWith('-')) || '.';+ if (args.includes('--help') || args.includes('-h')) {+ console.log(`loop doctor [path] [--json]++Combines loop-audit + loop-sync + structural file checks.+Prints severity and the top 3 next actions.++Exit: 0 healthy · 1 warning · 2 blocked+`);+ return 0;+ }+ const report = await runDoctor(target);+ if (json)+ console.log(JSON.stringify(report, null, 2));+ else+ console.log(formatDoctorHuman(report));+ return report.exitCode;+}+async function cmdStatus(args) {+ const json = args.includes('--json');+ const target = args.find((a) => !a.startsWith('-')) || '.';+ if (args.includes('--help') || args.includes('-h')) {+ console.log(`loop status [path] [--json]++Shows pattern, Loop Ready score, last runs from loop-run-log.md, ledger, budget.+`);+ return 0;+ }+ const report = await runStatus(target);+ if (json)+ console.log(JSON.stringify(report, null, 2));+ else+ console.log(formatStatusHuman(report));+ return 0;+}+async function cmdBadge(args) {+ const target = args.find((a) => !a.startsWith('-')) || '.';+ return runTool('audit', [target, '--badge']);+}+async function cmdWizard(args) {+ const yes = args.includes('--yes') || args.includes('-y');+ const interactive = args.includes('--interactive') || args.includes('-i');+ // Allow: loop wizard -p daily-triage -t claude .+ let plan = defaultPlan();+ for (let i = 0; i < args.length; i++) {+ const a = args[i];+ if (a === '--pattern' || a === '-p')+ plan.pattern = resolvePattern(args[++i] ?? '');+ else if (a === '--tool' || a === '-t')+ plan.tool = resolveTool(args[++i] ?? '');+ else if (a === '--with-foundry')+ plan.withFoundry = true;+ else if (a === '--yes' || a === '-y' || a === '--interactive' || a === '-i')+ continue;+ else if (!a.startsWith('-'))+ plan.target = a;+ }+ if (interactive && process.stdin.isTTY) {+ plan = await runInteractiveWizard();+ return executePlan(plan);+ }+ if (yes || args.some((a) => a === '--pattern' || a === '-p')) {+ return executePlan(plan);+ }+ printNonInteractiveHelp();+ return 0;+}+async function main() {+ const argv = process.argv.slice(2);+ if (argv.length === 0) {+ if (process.stdin.isTTY && argv.includes('--interactive')) {+ // unreachable when length 0 — handled below+ }+ printNonInteractiveHelp();+ return;+ }+ const [cmd, ...rest] = argv;+ if (cmd === '--help' || cmd === '-h' || cmd === 'help') {+ printHelp();+ return;+ }+ if (cmd === '--version' || cmd === '-V' || cmd === 'version') {+ console.log(VERSION);+ return;+ }+ if (cmd === '--interactive' || cmd === '-i') {+ const plan = await runInteractiveWizard();+ process.exitCode = await executePlan(plan);+ return;+ }+ if (PASS_THROUGH.has(cmd)) {+ const code = await runTool(cmd, rest);+ process.exitCode = code;+ return;+ }+ if (cmd === 'doctor') {+ process.exitCode = await cmdDoctor(rest);+ return;+ }+ if (cmd === 'status') {+ process.exitCode = await cmdStatus(rest);+ return;+ }+ if (cmd === 'badge') {+ process.exitCode = await cmdBadge(rest);+ return;+ }+ if (cmd === 'wizard') {+ process.exitCode = await cmdWizard(rest);+ return;+ }+ // Unknown: if it looks like a path or init flags, hint; else help+ console.error(`Unknown command: ${cmd}\n`);+ printHelp();+ process.exitCode = 1;+}+main().catch((err) => {+ console.error('loop failed:', err instanceof Error ? err.message : err);+ process.exit(1);+});diff --git a/tools/loop/dist/doctor.d.ts b/tools/loop/dist/doctor.d.tsnew file mode 100644index 0000000..230f5ac--- /dev/null+++ b/tools/loop/dist/doctor.d.ts@@ -0,0 +1,34 @@+export type DoctorSeverity = 'healthy' | 'warning' | 'blocked';+export interface DoctorAction {+ priority: number;+ text: string;+ command?: string;+}+export interface DoctorReport {+ target: string;+ severity: DoctorSeverity;+ exitCode: number;+ ready: {+ score: number | null;+ level: string | null;+ assessment: string | null;+ };+ sync: {+ score: number | null;+ level: string | null;+ issueCount: number;+ };+ files: {+ state: string | null;+ loopMd: boolean;+ budget: boolean;+ runLog: boolean;+ constraints: boolean;+ gate: boolean;+ agentsMd: boolean;+ };+ actions: DoctorAction[];+ notes: string[];+}+export declare function runDoctor(target: string): Promise<DoctorReport>;+export declare function formatDoctorHuman(r: DoctorReport): string;diff --git a/tools/loop/dist/doctor.js b/tools/loop/dist/doctor.jsnew file mode 100644index 0000000..e26ca13--- /dev/null+++ b/tools/loop/dist/doctor.js@@ -0,0 +1,244 @@+/**+ * loop doctor — single activation check: audit + sync + budget/gate presence.+ * Exit: 0 healthy · 1 warnings · 2 blocked+ */+import path from 'node:path';+import { runToolCapture } from './pass-through.js';+import { budgetPresent, fileExists, findStateFile, readText, } from './files.js';+function parseJsonLoose(stdout) {+ const t = stdout.trim();+ if (!t)+ return null;+ try {+ return JSON.parse(t);+ }+ catch {+ /* Some CLIs may print a banner before JSON — take first object/array */+ const startObj = t.indexOf('{');+ const startArr = t.indexOf('[');+ const candidates = [startObj, startArr].filter((i) => i >= 0);+ if (!candidates.length)+ return null;+ const start = Math.min(...candidates);+ try {+ return JSON.parse(t.slice(start));+ }+ catch {+ return null;+ }+ }+}+export async function runDoctor(target) {+ const root = path.resolve(target);+ const notes = [];+ const actions = [];+ const stateName = await findStateFile(root);+ const loopMd = await fileExists(path.join(root, 'LOOP.md'));+ const budgetPath = path.join(root, 'loop-budget.md');+ const budgetRaw = await readText(budgetPath);+ const runLog = await fileExists(path.join(root, 'loop-run-log.md'));+ const constraints = await fileExists(path.join(root, 'loop-constraints.md'));+ const gate = await fileExists(path.join(root, 'gate.yaml'));+ const agentsMd = await fileExists(path.join(root, 'AGENTS.md'));+ let readyScore = null;+ let readyLevel = null;+ let assessment = null;+ let auditRecs = [];+ const auditRun = await runToolCapture('audit', [root, '--json']);+ if (auditRun.code !== 0 && !auditRun.stdout.trim()) {+ notes.push(`loop-audit failed: ${auditRun.stderr.trim() || `exit ${auditRun.code}`}`);+ }+ else {+ const j = parseJsonLoose(auditRun.stdout);+ if (j && typeof j.score === 'number') {+ readyScore = j.score;+ readyLevel = j.level ?? null;+ assessment = j.assessment ?? null;+ auditRecs = Array.isArray(j.recommendations) ? j.recommendations : [];+ }+ else {+ notes.push('Could not parse loop-audit JSON output');+ }+ }+ let syncScore = null;+ let syncLevel = null;+ let issueCount = 0;+ const syncRun = await runToolCapture('sync', [root, '--json']);+ if (syncRun.code !== 0 && !syncRun.stdout.trim()) {+ notes.push(`loop-sync failed: ${syncRun.stderr.trim() || `exit ${syncRun.code}`}`);+ }+ else {+ const j = parseJsonLoose(syncRun.stdout);+ if (j && typeof j.score === 'number') {+ syncScore = j.score;+ syncLevel = j.level ?? null;+ issueCount = Array.isArray(j.issues) ? j.issues.length : 0;+ if (Array.isArray(j.suggestions)) {+ for (const s of j.suggestions.slice(0, 2)) {+ actions.push({ priority: 40, text: s });+ }+ }+ }+ else {+ notes.push('Could not parse loop-sync JSON output');+ }+ }+ // Structural actions (highest priority for empty repos)+ if (!stateName && !loopMd) {+ actions.push({+ priority: 1,+ text: 'Scaffold a first loop (report-only week one)',+ command: 'npx @cobusgreyling/loop init . --pattern daily-triage --tool grok',+ });+ }+ else if (!stateName) {+ actions.push({+ priority: 2,+ text: 'Add a state file (STATE.md or pattern state)',+ command: 'npx @cobusgreyling/loop init . --pattern daily-triage --tool grok',+ });+ }+ if (!loopMd) {+ actions.push({+ priority: 3,+ text: 'Add LOOP.md documenting cadence, gates, and kill switch',+ });+ }+ if (!budgetPresent(budgetRaw)) {+ actions.push({+ priority: 10,+ text: 'Add loop-budget.md with daily token caps and kill switch',+ command: 'npx @cobusgreyling/loop init . --pattern daily-triage --tool grok',+ });+ }+ if (!runLog) {+ actions.push({+ priority: 11,+ text: 'Add loop-run-log.md so runs are observable',+ });+ }+ if (readyScore !== null && readyScore < 40) {+ actions.push({+ priority: 5,+ text: 'Raise Loop Ready above 40 before scheduling unattended work',+ command: `npx @cobusgreyling/loop audit ${target} --suggest`,+ });+ }+ if (syncLevel === 'critical') {+ actions.push({+ priority: 4,+ text: 'Fix STATE ↔ LOOP drift before the next scheduled run',+ command: `npx @cobusgreyling/loop sync ${target}`,+ });+ }+ for (const rec of auditRecs.slice(0, 3)) {+ actions.push({ priority: 50, text: rec });+ }+ if (readyScore !== null && readyScore >= 80) {+ actions.push({+ priority: 90,+ text: 'Optional next: version the loop as a harness (Foundry)',+ command: 'npx @cobusgreyling/loop init . --with-foundry',+ });+ actions.push({+ priority: 91,+ text: 'Share your score',+ command: `npx @cobusgreyling/loop badge ${target}`,+ });+ }+ // Dedupe by text, keep best priority+ const byText = new Map();+ for (const a of actions) {+ const prev = byText.get(a.text);+ if (!prev || a.priority < prev.priority)+ byText.set(a.text, a);+ }+ const topActions = [...byText.values()].sort((a, b) => a.priority - b.priority).slice(0, 3);+ // Severity / exit code+ let severity = 'healthy';+ let exitCode = 0;+ const blocked = (readyScore !== null && readyScore < 40) ||+ syncLevel === 'critical' ||+ (!stateName && !loopMd);+ const warning = (readyScore !== null && readyScore < 58) ||+ syncLevel === 'warning' ||+ issueCount > 0 ||+ !budgetPresent(budgetRaw) ||+ !runLog;+ if (blocked) {+ severity = 'blocked';+ exitCode = 2;+ }+ else if (warning) {+ severity = 'warning';+ exitCode = 1;+ }+ return {+ target: root,+ severity,+ exitCode,+ ready: {+ score: readyScore,+ level: readyLevel,+ assessment,+ },+ sync: {+ score: syncScore,+ level: syncLevel,+ issueCount,+ },+ files: {+ state: stateName,+ loopMd,+ budget: budgetPresent(budgetRaw),+ runLog,+ constraints,+ gate,+ agentsMd,+ },+ actions: topActions,+ notes,+ };+}+export function formatDoctorHuman(r) {+ const lines = [];+ lines.push('');+ lines.push(`Loop doctor — ${r.target}`);+ lines.push('═'.repeat(50));+ const score = r.ready.score !== null ? `${r.ready.score}/100 ${r.ready.level ?? ''}`.trim() : 'n/a';+ lines.push(`Ready: ${score}`);+ if (r.ready.assessment)+ lines.push(` ${r.ready.assessment}`);+ const sync = r.sync.score !== null+ ? `${r.sync.score}/100 (${r.sync.level ?? '?'}) · ${r.sync.issueCount} issue(s)`+ : 'n/a';+ lines.push(`Sync: ${sync}`);+ lines.push(`Files: state=${r.files.state ?? 'missing'} LOOP.md=${yn(r.files.loopMd)} budget=${yn(r.files.budget)} run-log=${yn(r.files.runLog)} gate=${yn(r.files.gate)}`);+ lines.push(`Status: ${r.severity.toUpperCase()} (exit ${r.exitCode})`);+ lines.push('');+ if (r.actions.length) {+ lines.push('Top next actions:');+ r.actions.forEach((a, i) => {+ lines.push(` ${i + 1}. ${a.text}`);+ if (a.command)+ lines.push(` $ ${a.command}`);+ });+ }+ else {+ lines.push('No blockers — schedule a report-only run and append loop-run-log.md.');+ }+ if (r.notes.length) {+ lines.push('');+ lines.push('Notes:');+ for (const n of r.notes)+ lines.push(` · ${n}`);+ }+ lines.push('');+ lines.push('Week one: report only. Old packages still work: loop-init, loop-audit, …');+ lines.push('Docs: https://github.com/cobusgreyling/loop-engineering/blob/main/docs/QUICKSTART.md');+ lines.push('');+ return lines.join('\n');+}+function yn(b) {+ return b ? 'yes' : 'no';+}diff --git a/tools/loop/dist/files.d.ts b/tools/loop/dist/files.d.tsnew file mode 100644index 0000000..45f6e5c--- /dev/null+++ b/tools/loop/dist/files.d.ts@@ -0,0 +1,27 @@+export declare function fileExists(p: string): Promise<boolean>;+export declare function readText(p: string): Promise<string | null>;+export declare function findStateFile(root: string): Promise<string | null>;+export interface RunLogEntry {+ run_id?: string;+ pattern?: string;+ outcome?: string;+ tokens_estimate?: number;+ readiness_score?: number;+ escalations?: number;+ items_found?: number;+ duration_s?: number;+ [key: string]: unknown;+}+/** Parse JSONL-ish entries from loop-run-log.md (lines that look like JSON objects). */+export declare function parseRunLog(content: string, limit?: number): RunLogEntry[];+export declare function extractLastRun(stateContent: string | null): string | null;+export declare function extractPatternsFromLoop(loopContent: string | null): string[];+export declare function budgetPresent(content: string | null): boolean;+export interface LedgerSummary {+ present: boolean;+ pattern?: string;+ level?: string;+ attempts?: number;+ open?: boolean;+}+export declare function parseLedger(raw: string | null): LedgerSummary;diff --git a/tools/loop/dist/files.js b/tools/loop/dist/files.jsnew file mode 100644index 0000000..ece3a51--- /dev/null+++ b/tools/loop/dist/files.js@@ -0,0 +1,110 @@+import { access, readFile } from 'node:fs/promises';+import path from 'node:path';+export async function fileExists(p) {+ try {+ await access(p);+ return true;+ }+ catch {+ return false;+ }+}+export async function readText(p) {+ try {+ return await readFile(p, 'utf8');+ }+ catch {+ return null;+ }+}+const STATE_CANDIDATES = [+ 'STATE.md',+ 'pr-babysitter-state.md',+ 'ci-sweeper-state.md',+ 'post-merge-state.md',+ 'dependency-sweeper-state.md',+ 'changelog-drafter-state.md',+ 'issue-triage-state.md',+];+export async function findStateFile(root) {+ for (const name of STATE_CANDIDATES) {+ const p = path.join(root, name);+ if (await fileExists(p))+ return name;+ }+ return null;+}+/** Parse JSONL-ish entries from loop-run-log.md (lines that look like JSON objects). */+export function parseRunLog(content, limit = 5) {+ const entries = [];+ for (const line of content.split('\n')) {+ const t = line.trim();+ if (!t.startsWith('{') || !t.endsWith('}'))+ continue;+ try {+ entries.push(JSON.parse(t));+ }+ catch {+ /* skip malformed */+ }+ }+ return entries.slice(-limit).reverse();+}+export function extractLastRun(stateContent) {+ if (!stateContent)+ return null;+ const m = stateContent.match(/Last run:\s*(.+)/i);+ return m ? m[1].trim() : null;+}+export function extractPatternsFromLoop(loopContent) {+ if (!loopContent)+ return [];+ const patterns = new Set();+ const known = [+ 'daily-triage',+ 'pr-babysitter',+ 'ci-sweeper',+ 'dependency-sweeper',+ 'post-merge-cleanup',+ 'changelog-drafter',+ 'issue-triage',+ ];+ for (const p of known) {+ if (loopContent.toLowerCase().includes(p.replace(/-/g, ' ')) || loopContent.includes(p)) {+ patterns.add(p);+ }+ }+ // ### Daily Triage headers+ const headerRe = /^###\s+([A-Za-z][A-Za-z0-9 /&-]+)/gm;+ let m;+ while ((m = headerRe.exec(loopContent)) !== null) {+ const slug = m[1]+ .toLowerCase()+ .replace(/\(.*\)/g, '')+ .trim()+ .replace(/\s+/g, '-');+ if (known.includes(slug))+ patterns.add(slug);+ }+ return [...patterns];+}+export function budgetPresent(content) {+ return Boolean(content && /max tokens|daily limits|kill switch/i.test(content));+}+export function parseLedger(raw) {+ if (!raw)+ return { present: false };+ try {+ const j = JSON.parse(raw);+ return {+ present: true,+ pattern: j.pattern,+ level: j.level,+ attempts: Array.isArray(j.attempts) ? j.attempts.length : undefined,+ open: typeof j.open === 'boolean' ? j.open : j.status === 'open',+ };+ }+ catch {+ return { present: true };+ }+}diff --git a/tools/loop/dist/pass-through.d.ts b/tools/loop/dist/pass-through.d.tsnew file mode 100644index 0000000..1f143f6--- /dev/null+++ b/tools/loop/dist/pass-through.d.ts@@ -0,0 +1,14 @@+export type ToolId = 'init' | 'audit' | 'cost' | 'sync' | 'context' | 'worktree' | 'gate' | 'mcp' | 'sandbox';+/** Resolve absolute path to a tool CLI script, or null if only npx remains. */+export declare function resolveToolScript(id: ToolId): Promise<string | null>;+export interface SpawnResult {+ code: number;+ stdout: string;+ stderr: string;+}+/** Run a sibling tool; inherit stdio for interactive pass-through. */+export declare function runTool(id: ToolId, args: string[]): Promise<number>;+/** Run a sibling tool and capture stdout (for doctor/status). */+export declare function runToolCapture(id: ToolId, args: string[]): Promise<SpawnResult>;+export declare function toolPackageName(id: ToolId): string;+export declare function listToolIds(): ToolId[];diff --git a/tools/loop/dist/pass-through.js b/tools/loop/dist/pass-through.jsnew file mode 100644index 0000000..ec7ab13--- /dev/null+++ b/tools/loop/dist/pass-through.js@@ -0,0 +1,161 @@+/**+ * Resolve and run sibling loop-* CLIs without deprecating them.+ * Prefer monorepo dist/, then node_modules package bin, then npx.+ */+import { access } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { spawn } from 'node:child_process';+const __dirname = path.dirname(fileURLToPath(import.meta.url));+/** tools/loop/dist → tools/loop → tools */+const TOOLS_ROOT = path.resolve(__dirname, '../..');+const PACKAGE_ROOT = path.resolve(__dirname, '..');+const TOOLS = {+ init: {+ pkg: '@cobusgreyling/loop-init',+ dir: 'loop-init',+ bin: 'dist/cli.js',+ command: 'loop-init',+ },+ audit: {+ pkg: '@cobusgreyling/loop-audit',+ dir: 'loop-audit',+ bin: 'dist/cli.js',+ command: 'loop-audit',+ },+ cost: {+ pkg: '@cobusgreyling/loop-cost',+ dir: 'loop-cost',+ bin: 'dist/cli.js',+ command: 'loop-cost',+ },+ sync: {+ pkg: '@cobusgreyling/loop-sync',+ dir: 'loop-sync',+ bin: 'dist/cli.js',+ command: 'loop-sync',+ },+ context: {+ pkg: '@cobusgreyling/loop-context',+ dir: 'loop-context',+ bin: 'dist/cli.js',+ command: 'loop-context',+ },+ worktree: {+ pkg: '@cobusgreyling/loop-worktree',+ dir: 'loop-worktree',+ bin: 'dist/cli.js',+ command: 'loop-worktree',+ },+ gate: {+ pkg: '@cobusgreyling/loop-gate',+ dir: 'loop-gate',+ bin: 'dist/cli.js',+ command: 'loop-gate',+ },+ mcp: {+ pkg: '@cobusgreyling/loop-mcp-server',+ dir: 'mcp-server',+ bin: 'dist/index.js',+ command: 'loop-mcp-server',+ },+ sandbox: {+ pkg: '@cobusgreyling/loop-sandbox',+ dir: 'loop-sandbox',+ bin: 'dist/cli.js',+ command: 'loop-sandbox',+ },+};+async function exists(p) {+ try {+ await access(p);+ return true;+ }+ catch {+ return false;+ }+}+/** Resolve absolute path to a tool CLI script, or null if only npx remains. */+export async function resolveToolScript(id) {+ const spec = TOOLS[id];+ const monorepo = path.join(TOOLS_ROOT, spec.dir, spec.bin);+ if (await exists(monorepo))+ return monorepo;+ // nested under this package's node_modules (if ever installed as dep)+ const nested = path.join(PACKAGE_ROOT, 'node_modules', spec.pkg, spec.bin);+ if (await exists(nested))+ return nested;+ // hoisted from repo root+ const hoisted = path.join(TOOLS_ROOT, '..', 'node_modules', spec.pkg, spec.bin);+ if (await exists(hoisted))+ return hoisted;+ return null;+}+function spawnNode(script, args, capture) {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [script, ...args], {+ stdio: capture ? ['ignore', 'pipe', 'pipe'] : 'inherit',+ env: process.env,+ });+ let stdout = '';+ let stderr = '';+ if (capture) {+ child.stdout?.on('data', (d) => {+ stdout += d.toString();+ });+ child.stderr?.on('data', (d) => {+ stderr += d.toString();+ });+ }+ child.on('error', reject);+ child.on('close', (code) => {+ resolve({ code: code ?? 1, stdout, stderr });+ });+ });+}+function spawnNpx(pkg, args, capture) {+ return new Promise((resolve, reject) => {+ const child = spawn('npx', ['--yes', pkg, ...args], {+ stdio: capture ? ['ignore', 'pipe', 'pipe'] : 'inherit',+ env: process.env,+ shell: process.platform === 'win32',+ });+ let stdout = '';+ let stderr = '';+ if (capture) {+ child.stdout?.on('data', (d) => {+ stdout += d.toString();+ });+ child.stderr?.on('data', (d) => {+ stderr += d.toString();+ });+ }+ child.on('error', reject);+ child.on('close', (code) => {+ resolve({ code: code ?? 1, stdout, stderr });+ });+ });+}+/** Run a sibling tool; inherit stdio for interactive pass-through. */+export async function runTool(id, args) {+ const script = await resolveToolScript(id);+ if (script) {+ const r = await spawnNode(script, args, false);+ return r.code;+ }+ const r = await spawnNpx(TOOLS[id].pkg, args, false);+ return r.code;+}+/** Run a sibling tool and capture stdout (for doctor/status). */+export async function runToolCapture(id, args) {+ const script = await resolveToolScript(id);+ if (script)+ return spawnNode(script, args, true);+ return spawnNpx(TOOLS[id].pkg, args, true);+}+export function toolPackageName(id) {+ return TOOLS[id].pkg;+}+export function listToolIds() {+ return Object.keys(TOOLS);+}diff --git a/tools/loop/dist/status.d.ts b/tools/loop/dist/status.d.tsnew file mode 100644index 0000000..869ef19--- /dev/null+++ b/tools/loop/dist/status.d.ts@@ -0,0 +1,26 @@+import { type RunLogEntry, type LedgerSummary } from './files.js';+export interface StatusReport {+ target: string;+ patterns: string[];+ stateFile: string | null;+ lastRunFromState: string | null;+ ready: {+ score: number | null;+ level: string | null;+ };+ recentRuns: RunLogEntry[];+ ledger: LedgerSummary;+ budget: {+ present: boolean;+ path: string;+ };+ gate: {+ present: boolean;+ };+ constraints: {+ present: boolean;+ };+ nextHint: string;+}+export declare function runStatus(target: string): Promise<StatusReport>;+export declare function formatStatusHuman(r: StatusReport): string;diff --git a/tools/loop/dist/status.js b/tools/loop/dist/status.jsnew file mode 100644index 0000000..12aab47--- /dev/null+++ b/tools/loop/dist/status.js@@ -0,0 +1,110 @@+/**+ * loop status — day-2 dashboard over existing markdown artifacts.+ */+import path from 'node:path';+import { runToolCapture } from './pass-through.js';+import { extractLastRun, extractPatternsFromLoop, fileExists, findStateFile, parseLedger, parseRunLog, readText, } from './files.js';+function parseJsonLoose(stdout) {+ const t = stdout.trim();+ if (!t)+ return null;+ try {+ return JSON.parse(t);+ }+ catch {+ const start = t.indexOf('{');+ if (start < 0)+ return null;+ try {+ return JSON.parse(t.slice(start));+ }+ catch {+ return null;+ }+ }+}+export async function runStatus(target) {+ const root = path.resolve(target);+ const stateName = await findStateFile(root);+ const stateRaw = stateName ? await readText(path.join(root, stateName)) : null;+ const loopRaw = await readText(path.join(root, 'LOOP.md'));+ const runLogRaw = await readText(path.join(root, 'loop-run-log.md'));+ const ledgerRaw = await readText(path.join(root, 'loop-ledger.json'));+ const budgetPresent = await fileExists(path.join(root, 'loop-budget.md'));+ const gatePresent = await fileExists(path.join(root, 'gate.yaml'));+ const constraintsPresent = await fileExists(path.join(root, 'loop-constraints.md'));+ let readyScore = null;+ let readyLevel = null;+ try {+ const auditRun = await runToolCapture('audit', [root, '--json']);+ const j = parseJsonLoose(auditRun.stdout);+ if (j && typeof j.score === 'number') {+ readyScore = j.score;+ readyLevel = j.level ?? null;+ }+ }+ catch {+ /* status still useful without audit */+ }+ const recentRuns = runLogRaw ? parseRunLog(runLogRaw, 5) : [];+ const patterns = extractPatternsFromLoop(loopRaw);+ if (recentRuns[0]?.pattern && !patterns.includes(recentRuns[0].pattern)) {+ patterns.unshift(recentRuns[0].pattern);+ }+ let nextHint = 'Run: npx @cobusgreyling/loop doctor .';+ if (!stateName && !loopRaw) {+ nextHint = 'Scaffold: npx @cobusgreyling/loop init . --pattern daily-triage --tool grok';+ }+ else if (recentRuns.length === 0) {+ nextHint = 'Schedule a report-only first run and append loop-run-log.md';+ }+ else if (readyScore !== null && readyScore >= 80) {+ nextHint = 'Optional: npx @cobusgreyling/loop badge . · harness: loop init . --with-foundry';+ }+ return {+ target: root,+ patterns,+ stateFile: stateName,+ lastRunFromState: extractLastRun(stateRaw),+ ready: { score: readyScore, level: readyLevel },+ recentRuns,+ ledger: parseLedger(ledgerRaw),+ budget: { present: budgetPresent, path: 'loop-budget.md' },+ gate: { present: gatePresent },+ constraints: { present: constraintsPresent },+ nextHint,+ };+}+export function formatStatusHuman(r) {+ const lines = [];+ lines.push('');+ lines.push(`Loop status · ${r.target}`);+ lines.push('═'.repeat(50));+ lines.push(` Pattern: ${r.patterns.length ? r.patterns.join(', ') : '(none detected — check LOOP.md)'}`);+ lines.push(` Ready: ${r.ready.score !== null ? `${r.ready.score}/100 ${r.ready.level ?? ''}` : 'n/a'}`.trimEnd());+ lines.push(` State: ${r.stateFile ?? 'missing'}${r.lastRunFromState ? ` · ${r.lastRunFromState}` : ''}`);+ lines.push(` Budget: ${r.budget.present ? 'loop-budget.md' : 'missing'} · gate=${r.gate.present ? 'yes' : 'no'} · constraints=${r.constraints.present ? 'yes' : 'no'}`);+ if (r.ledger.present) {+ lines.push(` Ledger: present${r.ledger.pattern ? ` · ${r.ledger.pattern}` : ''}${r.ledger.attempts != null ? ` · ${r.ledger.attempts} attempt(s)` : ''}`);+ }+ lines.push('');+ lines.push(' Recent runs:');+ if (!r.recentRuns.length) {+ lines.push(' (none in loop-run-log.md)');+ }+ else {+ for (const e of r.recentRuns) {+ const bits = [+ e.run_id ?? '?',+ e.pattern ?? '?',+ e.outcome ?? '?',+ e.tokens_estimate != null ? `~${e.tokens_estimate} tok` : null,+ ].filter(Boolean);+ lines.push(` · ${bits.join(' · ')}`);+ }+ }+ lines.push('');+ lines.push(` Next: ${r.nextHint}`);+ lines.push('');+ return lines.join('\n');+}diff --git a/tools/loop/dist/wizard.d.ts b/tools/loop/dist/wizard.d.tsnew file mode 100644index 0000000..af67340--- /dev/null+++ b/tools/loop/dist/wizard.d.ts@@ -0,0 +1,23 @@+export interface PainOption {+ id: string;+ label: string;+ pattern: string;+}+export declare const PAIN_OPTIONS: PainOption[];+export declare const TOOLS: readonly ["grok", "claude", "codex", "opencode"];+export type WizardTool = (typeof TOOLS)[number];+export interface WizardPlan {+ pattern: string;+ tool: WizardTool;+ target: string;+ withFoundry: boolean;+}+export declare function defaultPlan(): WizardPlan;+export declare function formatWizardBanner(): string;+export declare function formatPainMenu(): string;+export declare function resolvePattern(answer: string): string;+export declare function resolveTool(answer: string): WizardTool;+export declare function runInteractiveWizard(): Promise<WizardPlan>;+export declare function printNonInteractiveHelp(): void;+/** Run init with plan, then doctor. */+export declare function executePlan(plan: WizardPlan): Promise<number>;diff --git a/tools/loop/dist/wizard.js b/tools/loop/dist/wizard.jsnew file mode 100644index 0000000..b31c503--- /dev/null+++ b/tools/loop/dist/wizard.js@@ -0,0 +1,124 @@+/**+ * Non-interactive week-one wizard when `loop` is run with no args+ * (or `loop wizard`). Interactive prompts only when TTY + --interactive.+ */+import * as readline from 'node:readline/promises';+import { stdin as input, stdout as output } from 'node:process';+import { runTool } from './pass-through.js';+import { runDoctor, formatDoctorHuman } from './doctor.js';+export const PAIN_OPTIONS = [+ { id: '1', label: 'Morning chaos — what should I do?', pattern: 'daily-triage' },+ { id: '2', label: 'PRs stalling on review/CI', pattern: 'pr-babysitter' },+ { id: '3', label: 'CI red / flaky checks', pattern: 'ci-sweeper' },+ { id: '4', label: 'Dependabot / CVE noise', pattern: 'dependency-sweeper' },+ { id: '5', label: 'Merge debt / TODOs piling up', pattern: 'post-merge-cleanup' },+ { id: '6', label: 'Stale release notes / changelogs', pattern: 'changelog-drafter' },+ { id: '7', label: 'Noisy issue backlog / duplicates', pattern: 'issue-triage' },+];+export const TOOLS = ['grok', 'claude', 'codex', 'opencode'];+export function defaultPlan() {+ return {+ pattern: 'daily-triage',+ tool: 'grok',+ target: '.',+ withFoundry: false,+ };+}+export function formatWizardBanner() {+ return `+Loop Engineering — week-one wizard+══════════════════════════════════════════════════+Front door for init · audit · cost · doctor · status+Existing packages (loop-init, loop-audit, …) stay supported.++Not sure which loop? Start with daily-triage (report-only).+Interactive picker: https://cobusgreyling.github.io/loop-engineering/#interactive+`;+}+export function formatPainMenu() {+ const lines = ['What is hurting right now?', ''];+ for (const p of PAIN_OPTIONS) {+ lines.push(` ${p.id}) ${p.label} → ${p.pattern}`);+ }+ lines.push('');+ lines.push(' Enter 1-7, or pattern id (default: daily-triage)');+ return lines.join('\n');+}+export function resolvePattern(answer) {+ const t = answer.trim().toLowerCase();+ if (!t)+ return 'daily-triage';+ const byId = PAIN_OPTIONS.find((p) => p.id === t);+ if (byId)+ return byId.pattern;+ const byPattern = PAIN_OPTIONS.find((p) => p.pattern === t);+ if (byPattern)+ return byPattern.pattern;+ // free-form pattern id+ if (/^[a-z0-9-]+$/.test(t))+ return t;+ return 'daily-triage';+}+export function resolveTool(answer) {+ const t = answer.trim().toLowerCase();+ if (TOOLS.includes(t))+ return t;+ return 'grok';+}+export async function runInteractiveWizard() {+ const rl = readline.createInterface({ input, output });+ try {+ console.log(formatWizardBanner());+ console.log(formatPainMenu());+ const pain = await rl.question('> ');+ const pattern = resolvePattern(pain);+ console.log(`\nCoding agent tool? (${TOOLS.join(' / ')}) [grok]`);+ const toolAns = await rl.question('> ');+ const tool = resolveTool(toolAns);+ console.log('\nTarget directory? [.]');+ const targetAns = await rl.question('> ');+ const target = targetAns.trim() || '.';+ return { pattern, tool, target, withFoundry: false };+ }+ finally {+ rl.close();+ }+}+export function printNonInteractiveHelp() {+ console.log(formatWizardBanner());+ console.log(`Week-one path (copy/paste):++ npx @cobusgreyling/loop init . --pattern daily-triage --tool grok+ npx @cobusgreyling/loop doctor .++Or pick a pain point, then scaffold:++${PAIN_OPTIONS.map((p) => ` ${p.id}. ${p.label}\n npx @cobusgreyling/loop init . -p ${p.pattern} -t grok`).join('\n\n')}++Commands:+ loop init|audit|cost|sync|doctor|status|badge|wizard+ loop context|worktree|gate|mcp|sandbox (pass-through)++ loop doctor . --json+ loop status .+ loop --help++Same as before (still fully supported):+ npx @cobusgreyling/loop-init .+ npx @cobusgreyling/loop-audit . --suggest+`);+}+/** Run init with plan, then doctor. */+export async function executePlan(plan) {+ const initArgs = [plan.target, '--pattern', plan.pattern, '--tool', plan.tool];+ if (plan.withFoundry)+ initArgs.push('--with-foundry');+ console.log(`\n→ loop init ${initArgs.join(' ')}\n`);+ const code = await runTool('init', initArgs);+ if (code !== 0)+ return code;+ console.log('\n→ loop doctor\n');+ const report = await runDoctor(plan.target);+ console.log(formatDoctorHuman(report));+ return report.exitCode;+}diff --git a/tools/loop/package-lock.json b/tools/loop/package-lock.jsonnew file mode 100644index 0000000..5a31c8c--- /dev/null+++ b/tools/loop/package-lock.json@@ -0,0 +1,54 @@+{+ "name": "@cobusgreyling/loop",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@cobusgreyling/loop",+ "version": "0.1.0",+ "license": "MIT",+ "bin": {+ "loop": "dist/cli.js"+ },+ "devDependencies": {+ "@types/node": "^22.0.0",+ "typescript": "^5.9.3"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@types/node": {+ "version": "22.20.1",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz",+ "integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==",+ "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/package.json b/tools/loop/package.jsonnew file mode 100644index 0000000..88b8988--- /dev/null+++ b/tools/loop/package.json@@ -0,0 +1,52 @@+{+ "name": "@cobusgreyling/loop",+ "version": "0.1.0",+ "description": "Unified Loop Engineering CLI — one front door for init, audit, cost, sync, doctor, and status. Existing packages stay supported. npx @cobusgreyling/loop doctor .",+ "type": "module",+ "bin": {+ "loop": "./dist/cli.js"+ },+ "files": [+ "dist",+ "README.md"+ ],+ "scripts": {+ "build": "tsc",+ "test": "npm run build && node --test test/*.test.mjs",+ "prepublishOnly": "npm test",+ "start": "node dist/cli.js"+ },+ "engines": {+ "node": ">=18"+ },+ "keywords": [+ "loop-engineering",+ "ai-agents",+ "coding-agents",+ "claude-code",+ "codex",+ "grok",+ "opencode",+ "cli",+ "doctor",+ "readiness"+ ],+ "author": "Cobus Greyling",+ "license": "MIT",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/cobusgreyling/loop-engineering.git",+ "directory": "tools/loop"+ },+ "homepage": "https://cobusgreyling.github.io/loop-engineering/",+ "bugs": {+ "url": "https://github.com/cobusgreyling/loop-engineering/issues"+ },+ "publishConfig": {+ "access": "public"+ },+ "devDependencies": {+ "@types/node": "^22.0.0",+ "typescript": "^5.9.3"+ }+}diff --git a/tools/loop/src/cli.ts b/tools/loop/src/cli.tsnew file mode 100644index 0000000..ca3ccf2--- /dev/null+++ b/tools/loop/src/cli.ts@@ -0,0 +1,193 @@+#!/usr/bin/env node+/**+ * @cobusgreyling/loop — unified front door for Loop Engineering CLIs.+ * Additive: loop-init, loop-audit, and siblings stay fully supported.+ */+import { runTool } from './pass-through.js';+import { runDoctor, formatDoctorHuman } from './doctor.js';+import { runStatus, formatStatusHuman } from './status.js';+import {+ defaultPlan,+ executePlan,+ printNonInteractiveHelp,+ resolvePattern,+ resolveTool,+ runInteractiveWizard,+ type WizardPlan,+} from './wizard.js';++const VERSION = '0.1.0';++const PASS_THROUGH = new Set([+ 'init',+ 'audit',+ 'cost',+ 'sync',+ 'context',+ 'worktree',+ 'gate',+ 'mcp',+ 'sandbox',+]);++function printHelp(): void {+ console.log(`loop — Loop Engineering unified CLI v${VERSION}++Usage:+ loop Week-one help (or wizard if TTY + --interactive)+ loop init [args…] → loop-init (scaffold)+ loop audit [args…] → loop-audit (Loop Ready score)+ loop cost [args…] → loop-cost+ loop sync [args…] → loop-sync+ loop doctor [path] [--json] Audit + sync + files → top 3 actions+ loop status [path] [--json] Day-2 dashboard from STATE / run-log+ loop badge [path] README badge (→ loop-audit --badge)+ loop wizard [--yes] Guided scaffold + doctor+ loop context|worktree|gate|mcp|sandbox [args…]++Week-one (recommended):+ npx @cobusgreyling/loop init . --pattern daily-triage --tool grok+ npx @cobusgreyling/loop doctor .++Doctor exit codes:+ 0 healthy+ 1 warnings (score/sync/budget gaps)+ 2 blocked (score < 40, critical drift, or unscaffolded)++Compatibility (old doors stay open):+ npx @cobusgreyling/loop-init .+ npx @cobusgreyling/loop-audit . --suggest++Docs: https://github.com/cobusgreyling/loop-engineering/blob/main/docs/QUICKSTART.md+Showcase: https://cobusgreyling.github.io/loop-engineering/+`);+}++async function cmdDoctor(args: string[]): Promise<number> {+ const json = args.includes('--json');+ const target = args.find((a) => !a.startsWith('-')) || '.';+ if (args.includes('--help') || args.includes('-h')) {+ console.log(`loop doctor [path] [--json]++Combines loop-audit + loop-sync + structural file checks.+Prints severity and the top 3 next actions.++Exit: 0 healthy · 1 warning · 2 blocked+`);+ return 0;+ }+ const report = await runDoctor(target);+ if (json) console.log(JSON.stringify(report, null, 2));+ else console.log(formatDoctorHuman(report));+ return report.exitCode;+}++async function cmdStatus(args: string[]): Promise<number> {+ const json = args.includes('--json');+ const target = args.find((a) => !a.startsWith('-')) || '.';+ if (args.includes('--help') || args.includes('-h')) {+ console.log(`loop status [path] [--json]++Shows pattern, Loop Ready score, last runs from loop-run-log.md, ledger, budget.+`);+ return 0;+ }+ const report = await runStatus(target);+ if (json) console.log(JSON.stringify(report, null, 2));+ else console.log(formatStatusHuman(report));+ return 0;+}++async function cmdBadge(args: string[]): Promise<number> {+ const target = args.find((a) => !a.startsWith('-')) || '.';+ return runTool('audit', [target, '--badge']);+}++async function cmdWizard(args: string[]): Promise<number> {+ const yes = args.includes('--yes') || args.includes('-y');+ const interactive = args.includes('--interactive') || args.includes('-i');++ // Allow: loop wizard -p daily-triage -t claude .+ let plan: WizardPlan = defaultPlan();+ for (let i = 0; i < args.length; i++) {+ const a = args[i];+ if (a === '--pattern' || a === '-p') plan.pattern = resolvePattern(args[++i] ?? '');+ else if (a === '--tool' || a === '-t') plan.tool = resolveTool(args[++i] ?? '');+ else if (a === '--with-foundry') plan.withFoundry = true;+ else if (a === '--yes' || a === '-y' || a === '--interactive' || a === '-i') continue;+ else if (!a.startsWith('-')) plan.target = a;+ }++ if (interactive && process.stdin.isTTY) {+ plan = await runInteractiveWizard();+ return executePlan(plan);+ }++ if (yes || args.some((a) => a === '--pattern' || a === '-p')) {+ return executePlan(plan);+ }++ printNonInteractiveHelp();+ return 0;+}++async function main(): Promise<void> {+ const argv = process.argv.slice(2);++ if (argv.length === 0) {+ if (process.stdin.isTTY && argv.includes('--interactive')) {+ // unreachable when length 0 — handled below+ }+ printNonInteractiveHelp();+ return;+ }++ const [cmd, ...rest] = argv;++ if (cmd === '--help' || cmd === '-h' || cmd === 'help') {+ printHelp();+ return;+ }+ if (cmd === '--version' || cmd === '-V' || cmd === 'version') {+ console.log(VERSION);+ return;+ }+ if (cmd === '--interactive' || cmd === '-i') {+ const plan = await runInteractiveWizard();+ process.exitCode = await executePlan(plan);+ return;+ }++ if (PASS_THROUGH.has(cmd)) {+ const code = await runTool(cmd as 'init', rest);+ process.exitCode = code;+ return;+ }++ if (cmd === 'doctor') {+ process.exitCode = await cmdDoctor(rest);+ return;+ }+ if (cmd === 'status') {+ process.exitCode = await cmdStatus(rest);+ return;+ }+ if (cmd === 'badge') {+ process.exitCode = await cmdBadge(rest);+ return;+ }+ if (cmd === 'wizard') {+ process.exitCode = await cmdWizard(rest);+ return;+ }++ // Unknown: if it looks like a path or init flags, hint; else help+ console.error(`Unknown command: ${cmd}\n`);+ printHelp();+ process.exitCode = 1;+}++main().catch((err) => {+ console.error('loop failed:', err instanceof Error ? err.message : err);+ process.exit(1);+});diff --git a/tools/loop/src/doctor.ts b/tools/loop/src/doctor.tsnew file mode 100644index 0000000..eb2e276--- /dev/null+++ b/tools/loop/src/doctor.ts@@ -0,0 +1,301 @@+/**+ * loop doctor — single activation check: audit + sync + budget/gate presence.+ * Exit: 0 healthy · 1 warnings · 2 blocked+ */+import path from 'node:path';+import { runToolCapture } from './pass-through.js';+import {+ budgetPresent,+ fileExists,+ findStateFile,+ readText,+} from './files.js';++export type DoctorSeverity = 'healthy' | 'warning' | 'blocked';++export interface DoctorAction {+ priority: number;+ text: string;+ command?: string;+}++export interface DoctorReport {+ target: string;+ severity: DoctorSeverity;+ exitCode: number;+ ready: {+ score: number | null;+ level: string | null;+ assessment: string | null;+ };+ sync: {+ score: number | null;+ level: string | null;+ issueCount: number;+ };+ files: {+ state: string | null;+ loopMd: boolean;+ budget: boolean;+ runLog: boolean;+ constraints: boolean;+ gate: boolean;+ agentsMd: boolean;+ };+ actions: DoctorAction[];+ notes: string[];+}++function parseJsonLoose(stdout: string): unknown | null {+ const t = stdout.trim();+ if (!t) return null;+ try {+ return JSON.parse(t);+ } catch {+ /* Some CLIs may print a banner before JSON — take first object/array */+ const startObj = t.indexOf('{');+ const startArr = t.indexOf('[');+ const candidates = [startObj, startArr].filter((i) => i >= 0);+ if (!candidates.length) return null;+ const start = Math.min(...candidates);+ try {+ return JSON.parse(t.slice(start));+ } catch {+ return null;+ }+ }+}++export async function runDoctor(target: string): Promise<DoctorReport> {+ const root = path.resolve(target);+ const notes: string[] = [];+ const actions: DoctorAction[] = [];++ const stateName = await findStateFile(root);+ const loopMd = await fileExists(path.join(root, 'LOOP.md'));+ const budgetPath = path.join(root, 'loop-budget.md');+ const budgetRaw = await readText(budgetPath);+ const runLog = await fileExists(path.join(root, 'loop-run-log.md'));+ const constraints = await fileExists(path.join(root, 'loop-constraints.md'));+ const gate = await fileExists(path.join(root, 'gate.yaml'));+ const agentsMd = await fileExists(path.join(root, 'AGENTS.md'));++ let readyScore: number | null = null;+ let readyLevel: string | null = null;+ let assessment: string | null = null;+ let auditRecs: string[] = [];++ const auditRun = await runToolCapture('audit', [root, '--json']);+ if (auditRun.code !== 0 && !auditRun.stdout.trim()) {+ notes.push(`loop-audit failed: ${auditRun.stderr.trim() || `exit ${auditRun.code}`}`);+ } else {+ const j = parseJsonLoose(auditRun.stdout) as {+ score?: number;+ level?: string;+ assessment?: string;+ recommendations?: string[];+ } | null;+ if (j && typeof j.score === 'number') {+ readyScore = j.score;+ readyLevel = j.level ?? null;+ assessment = j.assessment ?? null;+ auditRecs = Array.isArray(j.recommendations) ? j.recommendations : [];+ } else {+ notes.push('Could not parse loop-audit JSON output');+ }+ }++ let syncScore: number | null = null;+ let syncLevel: string | null = null;+ let issueCount = 0;++ const syncRun = await runToolCapture('sync', [root, '--json']);+ if (syncRun.code !== 0 && !syncRun.stdout.trim()) {+ notes.push(`loop-sync failed: ${syncRun.stderr.trim() || `exit ${syncRun.code}`}`);+ } else {+ const j = parseJsonLoose(syncRun.stdout) as {+ score?: number;+ level?: string;+ issues?: unknown[];+ suggestions?: string[];+ } | null;+ if (j && typeof j.score === 'number') {+ syncScore = j.score;+ syncLevel = j.level ?? null;+ issueCount = Array.isArray(j.issues) ? j.issues.length : 0;+ if (Array.isArray(j.suggestions)) {+ for (const s of j.suggestions.slice(0, 2)) {+ actions.push({ priority: 40, text: s });+ }+ }+ } else {+ notes.push('Could not parse loop-sync JSON output');+ }+ }++ // Structural actions (highest priority for empty repos)+ if (!stateName && !loopMd) {+ actions.push({+ priority: 1,+ text: 'Scaffold a first loop (report-only week one)',+ command: 'npx @cobusgreyling/loop init . --pattern daily-triage --tool grok',+ });+ } else if (!stateName) {+ actions.push({+ priority: 2,+ text: 'Add a state file (STATE.md or pattern state)',+ command: 'npx @cobusgreyling/loop init . --pattern daily-triage --tool grok',+ });+ }+ if (!loopMd) {+ actions.push({+ priority: 3,+ text: 'Add LOOP.md documenting cadence, gates, and kill switch',+ });+ }+ if (!budgetPresent(budgetRaw)) {+ actions.push({+ priority: 10,+ text: 'Add loop-budget.md with daily token caps and kill switch',+ command: 'npx @cobusgreyling/loop init . --pattern daily-triage --tool grok',+ });+ }+ if (!runLog) {+ actions.push({+ priority: 11,+ text: 'Add loop-run-log.md so runs are observable',+ });+ }+ if (readyScore !== null && readyScore < 40) {+ actions.push({+ priority: 5,+ text: 'Raise Loop Ready above 40 before scheduling unattended work',+ command: `npx @cobusgreyling/loop audit ${target} --suggest`,+ });+ }+ if (syncLevel === 'critical') {+ actions.push({+ priority: 4,+ text: 'Fix STATE ↔ LOOP drift before the next scheduled run',+ command: `npx @cobusgreyling/loop sync ${target}`,+ });+ }+ for (const rec of auditRecs.slice(0, 3)) {+ actions.push({ priority: 50, text: rec });+ }+ if (readyScore !== null && readyScore >= 80) {+ actions.push({+ priority: 90,+ text: 'Optional next: version the loop as a harness (Foundry)',+ command: 'npx @cobusgreyling/loop init . --with-foundry',+ });+ actions.push({+ priority: 91,+ text: 'Share your score',+ command: `npx @cobusgreyling/loop badge ${target}`,+ });+ }++ // Dedupe by text, keep best priority+ const byText = new Map<string, DoctorAction>();+ for (const a of actions) {+ const prev = byText.get(a.text);+ if (!prev || a.priority < prev.priority) byText.set(a.text, a);+ }+ const topActions = [...byText.values()].sort((a, b) => a.priority - b.priority).slice(0, 3);++ // Severity / exit code+ let severity: DoctorSeverity = 'healthy';+ let exitCode = 0;++ const blocked =+ (readyScore !== null && readyScore < 40) ||+ syncLevel === 'critical' ||+ (!stateName && !loopMd);++ const warning =+ (readyScore !== null && readyScore < 58) ||+ syncLevel === 'warning' ||+ issueCount > 0 ||+ !budgetPresent(budgetRaw) ||+ !runLog;++ if (blocked) {+ severity = 'blocked';+ exitCode = 2;+ } else if (warning) {+ severity = 'warning';+ exitCode = 1;+ }++ return {+ target: root,+ severity,+ exitCode,+ ready: {+ score: readyScore,+ level: readyLevel,+ assessment,+ },+ sync: {+ score: syncScore,+ level: syncLevel,+ issueCount,+ },+ files: {+ state: stateName,+ loopMd,+ budget: budgetPresent(budgetRaw),+ runLog,+ constraints,+ gate,+ agentsMd,+ },+ actions: topActions,+ notes,+ };+}++export function formatDoctorHuman(r: DoctorReport): string {+ const lines: string[] = [];+ lines.push('');+ lines.push(`Loop doctor — ${r.target}`);+ lines.push('═'.repeat(50));+ const score =+ r.ready.score !== null ? `${r.ready.score}/100 ${r.ready.level ?? ''}`.trim() : 'n/a';+ lines.push(`Ready: ${score}`);+ if (r.ready.assessment) lines.push(` ${r.ready.assessment}`);+ const sync =+ r.sync.score !== null+ ? `${r.sync.score}/100 (${r.sync.level ?? '?'}) · ${r.sync.issueCount} issue(s)`+ : 'n/a';+ lines.push(`Sync: ${sync}`);+ lines.push(+ `Files: state=${r.files.state ?? 'missing'} LOOP.md=${yn(r.files.loopMd)} budget=${yn(r.files.budget)} run-log=${yn(r.files.runLog)} gate=${yn(r.files.gate)}`,+ );+ lines.push(`Status: ${r.severity.toUpperCase()} (exit ${r.exitCode})`);+ lines.push('');+ if (r.actions.length) {+ lines.push('Top next actions:');+ r.actions.forEach((a, i) => {+ lines.push(` ${i + 1}. ${a.text}`);+ if (a.command) lines.push(` $ ${a.command}`);+ });+ } else {+ lines.push('No blockers — schedule a report-only run and append loop-run-log.md.');+ }+ if (r.notes.length) {+ lines.push('');+ lines.push('Notes:');+ for (const n of r.notes) lines.push(` · ${n}`);+ }+ lines.push('');+ lines.push('Week one: report only. Old packages still work: loop-init, loop-audit, …');+ lines.push('Docs: https://github.com/cobusgreyling/loop-engineering/blob/main/docs/QUICKSTART.md');+ lines.push('');+ return lines.join('\n');+}++function yn(b: boolean): string {+ return b ? 'yes' : 'no';+}diff --git a/tools/loop/src/files.ts b/tools/loop/src/files.tsnew file mode 100644index 0000000..0332e65--- /dev/null+++ b/tools/loop/src/files.ts@@ -0,0 +1,135 @@+import { access, readFile } from 'node:fs/promises';+import path from 'node:path';++export async function fileExists(p: string): Promise<boolean> {+ try {+ await access(p);+ return true;+ } catch {+ return false;+ }+}++export async function readText(p: string): Promise<string | null> {+ try {+ return await readFile(p, 'utf8');+ } catch {+ return null;+ }+}++const STATE_CANDIDATES = [+ 'STATE.md',+ 'pr-babysitter-state.md',+ 'ci-sweeper-state.md',+ 'post-merge-state.md',+ 'dependency-sweeper-state.md',+ 'changelog-drafter-state.md',+ 'issue-triage-state.md',+];++export async function findStateFile(root: string): Promise<string | null> {+ for (const name of STATE_CANDIDATES) {+ const p = path.join(root, name);+ if (await fileExists(p)) return name;+ }+ return null;+}++export interface RunLogEntry {+ run_id?: string;+ pattern?: string;+ outcome?: string;+ tokens_estimate?: number;+ readiness_score?: number;+ escalations?: number;+ items_found?: number;+ duration_s?: number;+ [key: string]: unknown;+}++/** Parse JSONL-ish entries from loop-run-log.md (lines that look like JSON objects). */+export function parseRunLog(content: string, limit = 5): RunLogEntry[] {+ const entries: RunLogEntry[] = [];+ for (const line of content.split('\n')) {+ const t = line.trim();+ if (!t.startsWith('{') || !t.endsWith('}')) continue;+ try {+ entries.push(JSON.parse(t) as RunLogEntry);+ } catch {+ /* skip malformed */+ }+ }+ return entries.slice(-limit).reverse();+}++export function extractLastRun(stateContent: string | null): string | null {+ if (!stateContent) return null;+ const m = stateContent.match(/Last run:\s*(.+)/i);+ return m ? m[1].trim() : null;+}++export function extractPatternsFromLoop(loopContent: string | null): string[] {+ if (!loopContent) return [];+ const patterns = new Set<string>();+ const known = [+ 'daily-triage',+ 'pr-babysitter',+ 'ci-sweeper',+ 'dependency-sweeper',+ 'post-merge-cleanup',+ 'changelog-drafter',+ 'issue-triage',+ ];+ for (const p of known) {+ if (loopContent.toLowerCase().includes(p.replace(/-/g, ' ')) || loopContent.includes(p)) {+ patterns.add(p);+ }+ }+ // ### Daily Triage headers+ const headerRe = /^###\s+([A-Za-z][A-Za-z0-9 /&-]+)/gm;+ let m: RegExpExecArray | null;+ while ((m = headerRe.exec(loopContent)) !== null) {+ const slug = m[1]+ .toLowerCase()+ .replace(/\(.*\)/g, '')+ .trim()+ .replace(/\s+/g, '-');+ if (known.includes(slug)) patterns.add(slug);+ }+ return [...patterns];+}++export function budgetPresent(content: string | null): boolean {+ return Boolean(content && /max tokens|daily limits|kill switch/i.test(content));+}++export interface LedgerSummary {+ present: boolean;+ pattern?: string;+ level?: string;+ attempts?: number;+ open?: boolean;+}++export function parseLedger(raw: string | null): LedgerSummary {+ if (!raw) return { present: false };+ try {+ const j = JSON.parse(raw) as {+ pattern?: string;+ level?: string;+ attempts?: unknown[];+ status?: string;+ open?: boolean;+ };+ return {+ present: true,+ pattern: j.pattern,+ level: j.level,+ attempts: Array.isArray(j.attempts) ? j.attempts.length : undefined,+ open: typeof j.open === 'boolean' ? j.open : j.status === 'open',+ };+ } catch {+ return { present: true };+ }+}diff --git a/tools/loop/src/pass-through.ts b/tools/loop/src/pass-through.tsnew file mode 100644index 0000000..aa16998--- /dev/null+++ b/tools/loop/src/pass-through.ts@@ -0,0 +1,198 @@+/**+ * Resolve and run sibling loop-* CLIs without deprecating them.+ * Prefer monorepo dist/, then node_modules package bin, then npx.+ */+import { access } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { spawn } from 'node:child_process';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+/** tools/loop/dist → tools/loop → tools */+const TOOLS_ROOT = path.resolve(__dirname, '../..');+const PACKAGE_ROOT = path.resolve(__dirname, '..');++export type ToolId =+ | 'init'+ | 'audit'+ | 'cost'+ | 'sync'+ | 'context'+ | 'worktree'+ | 'gate'+ | 'mcp'+ | 'sandbox';++interface ToolSpec {+ /** npm package name */+ pkg: string;+ /** monorepo directory under tools/ */+ dir: string;+ /** relative path to CLI entry inside package */+ bin: string;+ /** binary name when installed globally */+ command: string;+}++const TOOLS: Record<ToolId, ToolSpec> = {+ init: {+ pkg: '@cobusgreyling/loop-init',+ dir: 'loop-init',+ bin: 'dist/cli.js',+ command: 'loop-init',+ },+ audit: {+ pkg: '@cobusgreyling/loop-audit',+ dir: 'loop-audit',+ bin: 'dist/cli.js',+ command: 'loop-audit',+ },+ cost: {+ pkg: '@cobusgreyling/loop-cost',+ dir: 'loop-cost',+ bin: 'dist/cli.js',+ command: 'loop-cost',+ },+ sync: {+ pkg: '@cobusgreyling/loop-sync',+ dir: 'loop-sync',+ bin: 'dist/cli.js',+ command: 'loop-sync',+ },+ context: {+ pkg: '@cobusgreyling/loop-context',+ dir: 'loop-context',+ bin: 'dist/cli.js',+ command: 'loop-context',+ },+ worktree: {+ pkg: '@cobusgreyling/loop-worktree',+ dir: 'loop-worktree',+ bin: 'dist/cli.js',+ command: 'loop-worktree',+ },+ gate: {+ pkg: '@cobusgreyling/loop-gate',+ dir: 'loop-gate',+ bin: 'dist/cli.js',+ command: 'loop-gate',+ },+ mcp: {+ pkg: '@cobusgreyling/loop-mcp-server',+ dir: 'mcp-server',+ bin: 'dist/index.js',+ command: 'loop-mcp-server',+ },+ sandbox: {+ pkg: '@cobusgreyling/loop-sandbox',+ dir: 'loop-sandbox',+ bin: 'dist/cli.js',+ command: 'loop-sandbox',+ },+};++async function exists(p: string): Promise<boolean> {+ try {+ await access(p);+ return true;+ } catch {+ return false;+ }+}++/** Resolve absolute path to a tool CLI script, or null if only npx remains. */+export async function resolveToolScript(id: ToolId): Promise<string | null> {+ const spec = TOOLS[id];++ const monorepo = path.join(TOOLS_ROOT, spec.dir, spec.bin);+ if (await exists(monorepo)) return monorepo;++ // nested under this package's node_modules (if ever installed as dep)+ const nested = path.join(PACKAGE_ROOT, 'node_modules', spec.pkg, spec.bin);+ if (await exists(nested)) return nested;++ // hoisted from repo root+ const hoisted = path.join(TOOLS_ROOT, '..', 'node_modules', spec.pkg, spec.bin);+ if (await exists(hoisted)) return hoisted;++ return null;+}++export interface SpawnResult {+ code: number;+ stdout: string;+ stderr: string;+}++function spawnNode(script: string, args: string[], capture: boolean): Promise<SpawnResult> {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [script, ...args], {+ stdio: capture ? ['ignore', 'pipe', 'pipe'] : 'inherit',+ env: process.env,+ });+ let stdout = '';+ let stderr = '';+ if (capture) {+ child.stdout?.on('data', (d: Buffer) => {+ stdout += d.toString();+ });+ child.stderr?.on('data', (d: Buffer) => {+ stderr += d.toString();+ });+ }+ child.on('error', reject);+ child.on('close', (code) => {+ resolve({ code: code ?? 1, stdout, stderr });+ });+ });+}++function spawnNpx(pkg: string, args: string[], capture: boolean): Promise<SpawnResult> {+ return new Promise((resolve, reject) => {+ const child = spawn('npx', ['--yes', pkg, ...args], {+ stdio: capture ? ['ignore', 'pipe', 'pipe'] : 'inherit',+ env: process.env,+ shell: process.platform === 'win32',+ });+ let stdout = '';+ let stderr = '';+ if (capture) {+ child.stdout?.on('data', (d: Buffer) => {+ stdout += d.toString();+ });+ child.stderr?.on('data', (d: Buffer) => {+ stderr += d.toString();+ });+ }+ child.on('error', reject);+ child.on('close', (code) => {+ resolve({ code: code ?? 1, stdout, stderr });+ });+ });+}++/** Run a sibling tool; inherit stdio for interactive pass-through. */+export async function runTool(id: ToolId, args: string[]): Promise<number> {+ const script = await resolveToolScript(id);+ if (script) {+ const r = await spawnNode(script, args, false);+ return r.code;+ }+ const r = await spawnNpx(TOOLS[id].pkg, args, false);+ return r.code;+}++/** Run a sibling tool and capture stdout (for doctor/status). */+export async function runToolCapture(id: ToolId, args: string[]): Promise<SpawnResult> {+ const script = await resolveToolScript(id);+ if (script) return spawnNode(script, args, true);+ return spawnNpx(TOOLS[id].pkg, args, true);+}++export function toolPackageName(id: ToolId): string {+ return TOOLS[id].pkg;+}++export function listToolIds(): ToolId[] {+ return Object.keys(TOOLS) as ToolId[];+}diff --git a/tools/loop/src/status.ts b/tools/loop/src/status.tsnew file mode 100644index 0000000..3228228--- /dev/null+++ b/tools/loop/src/status.ts@@ -0,0 +1,141 @@+/**+ * loop status — day-2 dashboard over existing markdown artifacts.+ */+import path from 'node:path';+import { runToolCapture } from './pass-through.js';+import {+ extractLastRun,+ extractPatternsFromLoop,+ fileExists,+ findStateFile,+ parseLedger,+ parseRunLog,+ readText,+ type RunLogEntry,+ type LedgerSummary,+} from './files.js';++export interface StatusReport {+ target: string;+ patterns: string[];+ stateFile: string | null;+ lastRunFromState: string | null;+ ready: { score: number | null; level: string | null };+ recentRuns: RunLogEntry[];+ ledger: LedgerSummary;+ budget: { present: boolean; path: string };+ gate: { present: boolean };+ constraints: { present: boolean };+ nextHint: string;+}++function parseJsonLoose(stdout: string): unknown | null {+ const t = stdout.trim();+ if (!t) return null;+ try {+ return JSON.parse(t);+ } catch {+ const start = t.indexOf('{');+ if (start < 0) return null;+ try {+ return JSON.parse(t.slice(start));+ } catch {+ return null;+ }+ }+}++export async function runStatus(target: string): Promise<StatusReport> {+ const root = path.resolve(target);+ const stateName = await findStateFile(root);+ const stateRaw = stateName ? await readText(path.join(root, stateName)) : null;+ const loopRaw = await readText(path.join(root, 'LOOP.md'));+ const runLogRaw = await readText(path.join(root, 'loop-run-log.md'));+ const ledgerRaw = await readText(path.join(root, 'loop-ledger.json'));+ const budgetPresent = await fileExists(path.join(root, 'loop-budget.md'));+ const gatePresent = await fileExists(path.join(root, 'gate.yaml'));+ const constraintsPresent = await fileExists(path.join(root, 'loop-constraints.md'));++ let readyScore: number | null = null;+ let readyLevel: string | null = null;+ try {+ const auditRun = await runToolCapture('audit', [root, '--json']);+ const j = parseJsonLoose(auditRun.stdout) as { score?: number; level?: string } | null;+ if (j && typeof j.score === 'number') {+ readyScore = j.score;+ readyLevel = j.level ?? null;+ }+ } catch {+ /* status still useful without audit */+ }++ const recentRuns = runLogRaw ? parseRunLog(runLogRaw, 5) : [];+ const patterns = extractPatternsFromLoop(loopRaw);+ if (recentRuns[0]?.pattern && !patterns.includes(recentRuns[0].pattern)) {+ patterns.unshift(recentRuns[0].pattern);+ }++ let nextHint = 'Run: npx @cobusgreyling/loop doctor .';+ if (!stateName && !loopRaw) {+ nextHint = 'Scaffold: npx @cobusgreyling/loop init . --pattern daily-triage --tool grok';+ } else if (recentRuns.length === 0) {+ nextHint = 'Schedule a report-only first run and append loop-run-log.md';+ } else if (readyScore !== null && readyScore >= 80) {+ nextHint = 'Optional: npx @cobusgreyling/loop badge . · harness: loop init . --with-foundry';+ }++ return {+ target: root,+ patterns,+ stateFile: stateName,+ lastRunFromState: extractLastRun(stateRaw),+ ready: { score: readyScore, level: readyLevel },+ recentRuns,+ ledger: parseLedger(ledgerRaw),+ budget: { present: budgetPresent, path: 'loop-budget.md' },+ gate: { present: gatePresent },+ constraints: { present: constraintsPresent },+ nextHint,+ };+}++export function formatStatusHuman(r: StatusReport): string {+ const lines: string[] = [];+ lines.push('');+ lines.push(`Loop status · ${r.target}`);+ lines.push('═'.repeat(50));+ lines.push(+ ` Pattern: ${r.patterns.length ? r.patterns.join(', ') : '(none detected — check LOOP.md)'}`,+ );+ lines.push(+ ` Ready: ${r.ready.score !== null ? `${r.ready.score}/100 ${r.ready.level ?? ''}` : 'n/a'}`.trimEnd(),+ );+ lines.push(` State: ${r.stateFile ?? 'missing'}${r.lastRunFromState ? ` · ${r.lastRunFromState}` : ''}`);+ lines.push(+ ` Budget: ${r.budget.present ? 'loop-budget.md' : 'missing'} · gate=${r.gate.present ? 'yes' : 'no'} · constraints=${r.constraints.present ? 'yes' : 'no'}`,+ );+ if (r.ledger.present) {+ lines.push(+ ` Ledger: present${r.ledger.pattern ? ` · ${r.ledger.pattern}` : ''}${r.ledger.attempts != null ? ` · ${r.ledger.attempts} attempt(s)` : ''}`,+ );+ }+ lines.push('');+ lines.push(' Recent runs:');+ if (!r.recentRuns.length) {+ lines.push(' (none in loop-run-log.md)');+ } else {+ for (const e of r.recentRuns) {+ const bits = [+ e.run_id ?? '?',+ e.pattern ?? '?',+ e.outcome ?? '?',+ e.tokens_estimate != null ? `~${e.tokens_estimate} tok` : null,+ ].filter(Boolean);+ lines.push(` · ${bits.join(' · ')}`);+ }+ }+ lines.push('');+ lines.push(` Next: ${r.nextHint}`);+ lines.push('');+ return lines.join('\n');+}diff --git a/tools/loop/src/wizard.ts b/tools/loop/src/wizard.tsnew file mode 100644index 0000000..d23eb0e--- /dev/null+++ b/tools/loop/src/wizard.ts@@ -0,0 +1,145 @@+/**+ * Non-interactive week-one wizard when `loop` is run with no args+ * (or `loop wizard`). Interactive prompts only when TTY + --interactive.+ */+import * as readline from 'node:readline/promises';+import { stdin as input, stdout as output } from 'node:process';+import { runTool } from './pass-through.js';+import { runDoctor, formatDoctorHuman } from './doctor.js';++export interface PainOption {+ id: string;+ label: string;+ pattern: string;+}++export const PAIN_OPTIONS: PainOption[] = [+ { id: '1', label: 'Morning chaos — what should I do?', pattern: 'daily-triage' },+ { id: '2', label: 'PRs stalling on review/CI', pattern: 'pr-babysitter' },+ { id: '3', label: 'CI red / flaky checks', pattern: 'ci-sweeper' },+ { id: '4', label: 'Dependabot / CVE noise', pattern: 'dependency-sweeper' },+ { id: '5', label: 'Merge debt / TODOs piling up', pattern: 'post-merge-cleanup' },+ { id: '6', label: 'Stale release notes / changelogs', pattern: 'changelog-drafter' },+ { id: '7', label: 'Noisy issue backlog / duplicates', pattern: 'issue-triage' },+];++export const TOOLS = ['grok', 'claude', 'codex', 'opencode'] as const;+export type WizardTool = (typeof TOOLS)[number];++export interface WizardPlan {+ pattern: string;+ tool: WizardTool;+ target: string;+ withFoundry: boolean;+}++export function defaultPlan(): WizardPlan {+ return {+ pattern: 'daily-triage',+ tool: 'grok',+ target: '.',+ withFoundry: false,+ };+}++export function formatWizardBanner(): string {+ return `+Loop Engineering — week-one wizard+══════════════════════════════════════════════════+Front door for init · audit · cost · doctor · status+Existing packages (loop-init, loop-audit, …) stay supported.++Not sure which loop? Start with daily-triage (report-only).+Interactive picker: https://cobusgreyling.github.io/loop-engineering/#interactive+`;+}++export function formatPainMenu(): string {+ const lines = ['What is hurting right now?', ''];+ for (const p of PAIN_OPTIONS) {+ lines.push(` ${p.id}) ${p.label} → ${p.pattern}`);+ }+ lines.push('');+ lines.push(' Enter 1-7, or pattern id (default: daily-triage)');+ return lines.join('\n');+}++export function resolvePattern(answer: string): string {+ const t = answer.trim().toLowerCase();+ if (!t) return 'daily-triage';+ const byId = PAIN_OPTIONS.find((p) => p.id === t);+ if (byId) return byId.pattern;+ const byPattern = PAIN_OPTIONS.find((p) => p.pattern === t);+ if (byPattern) return byPattern.pattern;+ // free-form pattern id+ if (/^[a-z0-9-]+$/.test(t)) return t;+ return 'daily-triage';+}++export function resolveTool(answer: string): WizardTool {+ const t = answer.trim().toLowerCase();+ if ((TOOLS as readonly string[]).includes(t)) return t as WizardTool;+ return 'grok';+}++export async function runInteractiveWizard(): Promise<WizardPlan> {+ const rl = readline.createInterface({ input, output });+ try {+ console.log(formatWizardBanner());+ console.log(formatPainMenu());+ const pain = await rl.question('> ');+ const pattern = resolvePattern(pain);++ console.log(`\nCoding agent tool? (${TOOLS.join(' / ')}) [grok]`);+ const toolAns = await rl.question('> ');+ const tool = resolveTool(toolAns);++ console.log('\nTarget directory? [.]');+ const targetAns = await rl.question('> ');+ const target = targetAns.trim() || '.';++ return { pattern, tool, target, withFoundry: false };+ } finally {+ rl.close();+ }+}++export function printNonInteractiveHelp(): void {+ console.log(formatWizardBanner());+ console.log(`Week-one path (copy/paste):++ npx @cobusgreyling/loop init . --pattern daily-triage --tool grok+ npx @cobusgreyling/loop doctor .++Or pick a pain point, then scaffold:++${PAIN_OPTIONS.map((p) => ` ${p.id}. ${p.label}\n npx @cobusgreyling/loop init . -p ${p.pattern} -t grok`).join('\n\n')}++Commands:+ loop init|audit|cost|sync|doctor|status|badge|wizard+ loop context|worktree|gate|mcp|sandbox (pass-through)++ loop doctor . --json+ loop status .+ loop --help++Same as before (still fully supported):+ npx @cobusgreyling/loop-init .+ npx @cobusgreyling/loop-audit . --suggest+`);+}++/** Run init with plan, then doctor. */+export async function executePlan(plan: WizardPlan): Promise<number> {+ const initArgs = [plan.target, '--pattern', plan.pattern, '--tool', plan.tool];+ if (plan.withFoundry) initArgs.push('--with-foundry');++ console.log(`\n→ loop init ${initArgs.join(' ')}\n`);+ const code = await runTool('init', initArgs);+ if (code !== 0) return code;++ console.log('\n→ loop doctor\n');+ const report = await runDoctor(plan.target);+ console.log(formatDoctorHuman(report));+ return report.exitCode;+}diff --git a/tools/loop/test/cli.test.mjs b/tools/loop/test/cli.test.mjsnew file mode 100644index 0000000..0b4f523--- /dev/null+++ b/tools/loop/test/cli.test.mjs@@ -0,0 +1,91 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { access } from 'node:fs/promises';++const exec = promisify(execFile);+const __dirname = path.dirname(fileURLToPath(import.meta.url));+const CLI = path.resolve(__dirname, '../dist/cli.js');+const REPO_ROOT = path.resolve(__dirname, '../../..');++async function run(args, opts = {}) {+ try {+ const r = await exec(process.execPath, [CLI, ...args], {+ cwd: opts.cwd || REPO_ROOT,+ maxBuffer: 10 * 1024 * 1024,+ env: { ...process.env, ...opts.env },+ });+ return { ...r, code: 0 };+ } catch (e) {+ if (opts.allowNonZero && e.stdout != null) {+ return { stdout: e.stdout, stderr: e.stderr || '', code: e.code ?? 1 };+ }+ throw e;+ }+}++test('loop --help exits 0 and documents doctor', async () => {+ const { stdout } = await run(['--help']);+ assert.match(stdout, /loop doctor/);+ assert.match(stdout, /loop-init/);+ assert.match(stdout, /Week-one/);+});++test('loop --version prints semver', async () => {+ const { stdout } = await run(['--version']);+ assert.match(stdout.trim(), /^\d+\.\d+\.\d+/);+});++test('loop with no args prints week-one path', async () => {+ const { stdout } = await run([]);+ assert.match(stdout, /loop init/);+ assert.match(stdout, /loop doctor/);+ assert.match(stdout, /loop-init/);+});++test('loop audit --help pass-through works when monorepo dist exists', async () => {+ await access(path.join(REPO_ROOT, 'tools/loop-audit/dist/cli.js'));+ const { stdout } = await run(['audit', '--help']);+ assert.match(stdout, /loop-audit|Loop Readiness/i);+});++test('loop doctor --json on repo root returns ready score', async () => {+ await access(path.join(REPO_ROOT, 'tools/loop-audit/dist/cli.js'));+ await access(path.join(REPO_ROOT, 'tools/loop-sync/dist/cli.js'));+ // doctor may exit 1 (warnings) on drift; still emits JSON+ const { stdout, code } = await run(['doctor', REPO_ROOT, '--json'], { allowNonZero: true });+ const report = JSON.parse(stdout);+ assert.equal(typeof report.ready.score, 'number');+ assert.ok(report.ready.score >= 40, `expected dogfood score >= 40, got ${report.ready.score}`);+ assert.ok(['healthy', 'warning', 'blocked'].includes(report.severity));+ assert.ok(Array.isArray(report.actions));+ assert.ok(report.actions.length <= 3);+ assert.ok(code < 2, `reference repo must not be blocked, exit ${code}`);+});++test('loop status --json includes recentRuns array', async () => {+ await access(path.join(REPO_ROOT, 'tools/loop-audit/dist/cli.js'));+ const { stdout } = await run(['status', REPO_ROOT, '--json']);+ const report = JSON.parse(stdout);+ assert.ok(Array.isArray(report.recentRuns));+ assert.ok(report.stateFile === 'STATE.md' || report.stateFile === null);+ assert.equal(typeof report.nextHint, 'string');+});++test('loop doctor on empty temp dir is blocked', async () => {+ const { mkdtemp, rm } = await import('node:fs/promises');+ const { tmpdir } = await import('node:os');+ const dir = await mkdtemp(path.join(tmpdir(), 'loop-doctor-empty-'));+ try {+ const { stdout, code } = await run(['doctor', dir, '--json'], { allowNonZero: true });+ const report = JSON.parse(stdout);+ assert.equal(report.severity, 'blocked');+ assert.equal(report.exitCode, 2);+ assert.equal(code, 2);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});diff --git a/tools/loop/test/files.test.mjs b/tools/loop/test/files.test.mjsnew file mode 100644index 0000000..49086ba--- /dev/null+++ b/tools/loop/test/files.test.mjs@@ -0,0 +1,42 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const files = await import(path.resolve(__dirname, '../dist/files.js'));++test('parseRunLog extracts trailing JSON lines newest first', () => {+ const content = `+# Log+{"run_id":"a","pattern":"daily-triage","outcome":"report-only"}+not json+{"run_id":"b","pattern":"ci-sweeper","outcome":"fix-proposed"}+`;+ const entries = files.parseRunLog(content, 5);+ assert.equal(entries.length, 2);+ assert.equal(entries[0].run_id, 'b');+ assert.equal(entries[1].run_id, 'a');+});++test('extractPatternsFromLoop finds known pattern names', () => {+ const loop = `+### Daily Triage (L1)+### PR Babysitter+Something about changelog-drafter in prose+`;+ const p = files.extractPatternsFromLoop(loop);+ assert.ok(p.includes('daily-triage'));+ assert.ok(p.includes('pr-babysitter'));+ assert.ok(p.includes('changelog-drafter'));+});++test('parseLedger handles missing and valid', () => {+ assert.equal(files.parseLedger(null).present, false);+ const L = files.parseLedger(+ JSON.stringify({ pattern: 'ci-sweeper', level: 'L2', attempts: [{}, {}] }),+ );+ assert.equal(L.present, true);+ assert.equal(L.pattern, 'ci-sweeper');+ assert.equal(L.attempts, 2);+});diff --git a/tools/loop/tsconfig.json b/tools/loop/tsconfig.jsonnew file mode 100644index 0000000..2fd12bc--- /dev/null+++ b/tools/loop/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "outDir": "dist",+ "rootDir": "src",+ "strict": true,+ "skipLibCheck": true,+ "declaration": true,+ "types": ["node"]+ },+ "include": ["src/**/*"]+}