Agent skill
Plan and build
Plan a multi-file change from real research, with a stage diagram and a check for every step, have it reviewed, then build it in parallel stages with one green commit each.
Use this skill
Install it into a project with the Skills CLI, or read the files below and adapt them to your own agent.
npx skills add shan8851/agent-skills --skill plan-and-buildSKILL.md
View this file on GitHub---
name: plan-and-build
description: Plan a multi-file change to an existing codebase, then build it in stages with parallel agents. Researches the code with read-only explore agents, writes a committed plan (plans/<name>.md) with a PR-ready motivation and benefits, a stage graph diagram, a machine-checkable stage index and checklists where every item says how it's verified, has a separate strongest-tier agent review the plan adversarially, then executes the stages in waves of isolated agents with one green commit per stage and the plan's checkboxes as resume state. Use when the user says "plan and build this", "plan this refactor", "break this into stages", "make an implementation plan and do it", "resume the plan", or describes a feature, refactor or migration that spans several files and concerns. Not for one-file fixes.
---
# Plan and build
Big changes go wrong in two ways: the agent starts coding before it understands the code, or it does everything in one long pass that nobody can review or resume. This skill separates the two jobs. First a plan you can read, check and commit. Then execution in small, verified, committed stages, in parallel where it's provably safe.
The plan file is the contract. It's what the user approves, what each agent is briefed from, what a lint script checks, and (through its checkboxes) where a later session resumes.
## When to use
- A feature, refactor or migration that touches several files across several concerns (types, logic, persistence, tests).
- "Plan and build this", "plan this refactor", "break this into stages", "make an implementation plan", "execute / resume plans/<name>.md".
- A milestone from a `product-planning-doc-pack` PRD that's ready to build (use it as the input; this skill doesn't need it).
Do not use when:
- it's a one-file change, a rename or a small fix. Just do it;
- the product itself is still unclear. Plan the product first (`product-planning-doc-pack`) or challenge the idea;
- the user wants a plan only. Do phases 1–4 and stop.
## Rules that matter most
1. **Research, plan, review, then code.** No implementation until the plan has been reviewed and the user approves it.
2. **Every checklist item is verifiable.** Each has Action, Files and Verify. Verify is either `` `command` → expected result `` or explicitly `Verify (manual): …`. "Cannot verify" stops the stage; it never becomes a note.
3. **Parallel only when provably safe.** Two stages may run in parallel only if their file sets are disjoint **and** neither imports anything the other creates. When unsure, sequential.
4. **The stage graph is mandatory.** Mermaid `flowchart TD` by default; an ASCII diagram where Mermaid won't render. It must show the same edges as the Stage Index.
5. **Agents never touch git** (one exception: the setup step in rule 6). The lead checks, merges, verifies and commits.
6. **Isolated agents start from the execution branch.** Worktree isolation usually branches from the default branch, not your branch. Each brief's first step is `git checkout --detach origin/<execution-branch>` and checking the tip matches the expected commit; on mismatch the agent reports blocked. This needs a remote you can push the branch to before each wave. **Without a remote, run the stages one at a time in the single checkout** instead.
7. **One green commit per stage**, with that stage's checkboxes ticked in the same commit. Never `--no-verify`, never commit a failing stage.
8. **Pin a model tier per stage** in the Stage Index, by tier name, never a dated model ID.
## Process
### 1. Confirm scope (one line)
"Planning <goal> in <repo/package> → `plans/<kebab-name>.md`; proceeding." If the request is ambiguous or could mean two jobs, ask one question first. If `plans/<name>.md` already exists, read it and ask: execute it, update it, or replace it?
### 2. Research (fan out)
Launch 5 **read-only** explore agents in parallel, each with one brief and asked for paths and line numbers, not prose:
1. **Structure:** affected directories, entry points, exports, generated files.
2. **Types and contracts:** types, interfaces, schemas the change touches; type escape hatches (`any`, casts).
3. **Tests:** what covers the affected code, helpers and fixtures, how tests are run, and the gaps.
4. **Dependencies, config and conventions:** who imports the affected modules and what they import; env vars, config values, external services, magic numbers; the repo's `CLAUDE.md` / `AGENTS.md` / `CONTRIBUTING`, lint rules, commit style, and the install, build and test commands.
5. **Observable behaviour:** anything outside the code depends on: error class names, log fields and messages, metrics and analytics events, public API and response shapes, CLI output. Who depends on each (dashboards, alerts, clients) if the repo says.
**An empty category is a finding** ("no tests cover the writer", "no signals found"), not a reason to pad the plan. If research shows the job is materially bigger, smaller or different from what was confirmed, check back with the user before writing the plan.
### 3. Write the plan
Write `plans/<kebab-name>.md` following `references/plan-format.md`: Motivation (written to paste into the PR), Benefits, Stage graph, Stage Index, Stage definitions, Execution notes. Name real files and types from the research, never "the relevant types". Put tests in their own stage after implementation unless a stage needs its tests to be green. If research found observable signals, end with a stage that verifies each one still holds.
### 4. Assign parallelism and models, then lint
For each pair of stages, apply rule 3. Pin each stage's model tier: the cheapest you're confident will get it right; raise it for subtle cross-cutting work and say why in the stage. Then run `node <skill-dir>/scripts/plan-lint.mjs plans/<name>.md` and fix every error.
### 5. Adversarial review
Hand the plan and the research findings to a **separate reviewer agent on the strongest tier** with the brief in `references/plan-review.md`. It looks for wrong parallelism, missing stages, unverifiable checks, hidden risks and simpler alternatives. It's told to be pragmatic, that accepted risks are listed, and that "a simpler plan" is a valid answer. If a second-opinion model is available (for example Codex), ask it too. Fold the findings you accept into the plan; list the ones you reject, each with a reason, in the plan's `## Review` section. Lint again.
Then report in the plan output format, showing what the review changed (the revised Stage Index or graph if it changed). If the user asks to approve a plan that hasn't been reviewed yet, run the review first and come back with the revised plan, not a description of the review you'd run. **Stop and wait for approval.** Nothing is committed or branched before then.
On approval, create the execution branch off the base and commit the plan as its first commit (`docs(plans): add <name>`). Approval is also the go-ahead for the per-stage commits; it isn't permission to push anywhere except the execution branch, and never to open a PR.
### 6. Check the branch, then execute in waves
Before the first stage: `git fetch origin`, confirm you're on the execution branch, and run `git log --oneline origin/<base>..HEAD`. If it shows nothing ahead (not even the plan commit), stop and ask: the branch may already be merged, or you're on the wrong one.
Before the first wave with two or more parallel agents, **probe once**: dispatch one tiny agent with only the setup step from `references/agent-brief.md` and ask it to report `pwd` and `git log --oneline -1`. If the tip is wrong, fix that before spending a wave.
A wave is every stage whose dependencies are committed. For each wave:
1. **Push the execution branch** (if using worktrees) so `origin/<branch>` has the latest stage commits. Note the expected tip commit.
2. **Dispatch** one implementation agent per stage, all in one message so they run in parallel, each with worktree isolation and its pinned model. A one-stage wave is a single agent, or just do it yourself. Brief each agent with `references/agent-brief.md`. Agents may only edit their declared files.
3. **Check each report** (`completed`, `filesChanged`, `verifyResults`, `deviations`, `blocked`). Compare `filesChanged` to the declared files; anything outside the set is rejected or explicitly accepted with a note. Read the diff. An agent's "verified" is not proof.
4. **Merge** each worktree's changes into the execution branch (in the main session, never delegated), resolve conflicts, then **re-run every verify command yourself**.
5. **Commit each stage** once its verifies pass: code plus the plan with that stage's boxes ticked (`- [x]`) and any deviations written in. Conventional message, e.g. `feat(sync): S1B batch inserts`.
6. **Blocked or failed stage:** don't commit or tick it. Re-brief, pull the smallest piece of a later stage forward, or amend the plan and tell the user.
### 7. Resume
To resume, read the plan: ticked stages are done. Spot-check that their files exist and that `git log` has their commits (`plan-lint.mjs --check-resume .` helps), report any drift, then continue from the first unticked wave.
### 8. Finish
Report stages done, verify results and the overall diff stat. Suggest **`clean-comments`** next (agents over-comment), then **`tidy-commits`** to turn the stage commits into release-shaped ones (it'll offer to keep or drop the plan file). Then offer a draft PR description built from Motivation and Benefits. Open a draft PR only if the user says yes; never on your own.
## Output format
After planning and review (step 5):
```markdown
**Plan:** plans/batched-sync.md (lint: 0 errors; committed on feat/batched-sync once you approve)
**Review:** 4 findings, 3 accepted (S1B made sequential: shares index.ts), 1 rejected (see ## Review)
**Stages:** 5 (2 parallel, 3 sequential). First wave: S0.
**Execution:** worktree agents from origin/feat/batched-sync | sequential in this checkout (no remote)
**Biggest risk:** [one line, from research]
Approve to start building, or tell me what to change.
```
After each wave: one line per stage, `S1A ✓ committed a1b2c3d (3/3 verifies)` or `S1B ✗ blocked: <reason>`.
## Adapting to your setup
- **Claude Code:** explore agents are the `Explore` subagent; implementation agents are general-purpose `Agent` calls with `isolation: "worktree"` and a `model` per stage, all sent in one message for a parallel wave. Worktrees branch from the default branch, hence rule 6. Long runs: plan on the strongest model, execute in a fresh session from the committed plan. For a second opinion in review, `codex exec` (if installed) can read the plan file read-only.
- **Codex:** use its subagents or parallel tasks if available; otherwise run stages sequentially in one checkout. The plan format and lint don't change. A Claude model makes a good second-opinion reviewer here, and the other way round.
- **OpenClaw and similar:** if there are no subagents, do the research yourself in the same categories and execute stages sequentially. The value is still the plan, the verify gates and the per-stage commits.
- **No remote / local-only repo:** sequential execution in one checkout, same gates and commits. Don't create a remote just for this.
- **Mermaid doesn't render** (some terminals, plain-text viewers): use the ASCII graph form in `references/plan-format.md`.
## Common failure modes
- **Planning from vibes:** stages that name no files because research was skipped or skimmed.
- **Unverifiable items:** "Verify: works correctly". Lint catches the form; you have to catch the substance.
- **Optimistic parallelism:** two stages editing the same barrel file or lockfile, or one importing what the other creates.
- **Agents on a stale tree:** a worktree based on `main` without earlier stages, and an agent "recreating" the missing files from memory.
- **Trusting the report:** committing because the agent said tests passed, without re-running them after the merge.
- **Unticked commits:** a stage committed without ticking its boxes, which breaks resume.
- **Red commits:** "break it here, fix it two stages later". Draw stage boundaries so every commit is green.
- **Scope drift:** research found a bigger job, or the review suggested extras, and the plan quietly grows without asking. Review findings that add scope go to the user as options, not straight into the plan.
- **Review theatre:** asking the reviewer to "find everything wrong", then accepting all forty nitpicks. Frame it pragmatically and reject findings with a reason.
- **Breaking what others watch:** renaming an error class or log field that an alert keys on. That's what the observable-behaviour research and final stage are for.
## References
- `references/plan-format.md`: the plan structure, Stage Index schema, checklist and verify forms, ASCII fallback.
- `references/plan-review.md`: the reviewer brief, what it checks, and how to record accepted and rejected findings.
- `references/agent-brief.md`: the implementation-agent brief template and report shape.
- `references/worked-example.md`: a complete small plan, and how its first two waves ran.
- `references/edge-cases.md`: no remote, no tests, monorepos, lockfile changes, blocked agents, plan/diff drift.
- `scripts/plan-lint.mjs`: dependency-free Node check for the plan format. `scripts/fixtures/` has one good and several bad plans.
references/agent-brief.md
View this file on GitHub# Implementation agent brief
Fill this in per stage. Quote the stage's checklist and verify commands from the plan verbatim; don't paraphrase them.
```markdown
You are implementing one stage of a committed plan. Work only inside the box below.
## Setup (do this first)
1. [worktree mode] Run exactly: `git checkout --detach origin/<execution-branch>`
Then run `git log --oneline -1`. The tip must be `<expected short sha> <expected subject>`.
If it isn't, stop and report `blocked: "worktree tip is <what you saw>, expected <sha>"`.
Do not try to recreate missing files.
2. Install dependencies: `<install command, e.g. pnpm install --frozen-lockfile>`
## Your stage
Read `plans/<name>.md`, section "## Stage <id>: <name>". Your checklist:
<paste the stage's checklist items verbatim>
## Rules
- Edit only these files: <the stage's files list>. If the work needs another file, stop and report blocked, saying which file and why.
- No git commands after setup: no add, commit, stash, checkout, merge, rebase, push or reset.
- Don't weaken, skip or delete tests to make a verify pass.
- How you get each verify to pass is up to you, inside those limits.
- Follow the repo's conventions: <one or two from research, e.g. "named exports only", "errors extend AppError">.
## Before you finish
Run every verify command for your stage:
<paste the verify commands verbatim>
## Your final message
Return only this JSON:
{ "stage": "<id>", "completed": [...], "filesChanged": [...], "verifyResults": [{ "cmd": "...", "pass": true, "output": "<tail, on failure only>" }], "deviations": [...], "blocked": null }
```
## Notes for the lead
- In sequential mode (no remote, or a single checkout), drop setup step 1. The agent works in your checkout, one stage at a time.
- If your platform supports a structured-output schema on agent calls, use the report shape as the schema so a malformed report is rejected at the tool layer.
- Set the agent's model from the stage's `model` field. Don't leave it to the default.
- An agent that returns prose instead of the report hasn't finished. Ask once for the report; if it still can't, treat the stage as blocked.
references/edge-cases.md
View this file on GitHub# Edge cases
## No remote, or can't push
- Worktree agents won't see your branch (rule 6). Run every stage sequentially in your own checkout, same briefs minus the setup step, same verify gates and per-stage commits. Say so in the plan's Execution notes and in the approval message.
## Worktree isolation unavailable
- Same as no remote: sequential in one checkout. Never let two editing agents share a checkout, even with disjoint files: installs, build caches and the git index are shared state.
## The worktree tip is wrong
- The agent reports blocked. Usually the branch wasn't pushed after the last wave. Push, re-dispatch. Never let an agent recreate missing files from memory.
## No tests exist
- That's a research finding. Either add a test stage early (so later stages have something to verify against) or use typecheck/build plus manual verifies, and say clearly in the plan that behaviour isn't machine-verified.
## No verify command can express the check
- Use `Verify (manual)` with a concrete pass condition. The lead does manual verifies, not the agent that wrote the code.
## Lockfile or dependency changes
- Give exactly one stage ownership of `package.json` and the lockfile, and make it sequential. Parallel installs in different worktrees produce conflicting lockfiles.
## Shared barrel or index files
- Two stages both adding exports to `index.ts` share a file, so they can't be parallel. Either move the barrel edits to one stage or make them sequential.
## Monorepos
- Scope research to the affected packages. Verify commands should be package-scoped (`pnpm --filter <pkg> test`) for speed, with one full-repo check in the final stage.
## A stage can't be made green on its own
- A pre-commit hook or typecheck fails because the fix lives in a later stage. Pull the smallest needed slice forward into this stage and amend the plan. Never `--no-verify`, never commit red.
## An agent edits outside its files
- Read the extra change. Reject it (drop it and re-verify) or accept it (add the file to the stage in the plan and note the deviation). If accepting it creates overlap with a stage running in parallel, re-run that stage's verify after merging both.
## The plan and the code drift during execution
- An agent's deviation changes what a later stage needs: update the later stage in the plan before dispatching it, in the same commit as the current stage.
## Resuming in a new session
- Read the plan, run `plan-lint.mjs plans/<name>.md --check-resume .`, check the ticked stages' files exist, then continue from the first unticked wave. If ticks and commits disagree, ask before continuing.
## The user only wants the plan
- Stop after step 4. The plan stands alone; another session (or person) can execute it later.
## Input from a product-planning-doc-pack
- Take one milestone from `planning-docs/PRD.md` as the scope, with `ARCHITECTURE.md` as context. Its outcome and verification seed the stages; research still happens, because the doc pack was written before the code existed.
## Scope turns out much bigger
- Stop after research. Present the new picture and suggest splitting into several plans, each shippable alone.
references/plan-format.md
View this file on GitHub# Plan format
The plan lives at `plans/<kebab-name>.md` in the target repo and is committed. `scripts/plan-lint.mjs` checks everything marked **(lint)**.
## Sections, in order
1. `# <Title>`
2. `## Motivation` **(lint)**: 2–4 short paragraphs written to paste straight into the PR description. What's wrong now (concrete failure modes, not "cleaner code"), why it matters, what the change achieves.
3. `## Benefits` **(lint)**: a short list of concrete improvements, quantified where research allows ("removes 3 `as` casts", "one request per 250 rows instead of per row", "error now names the failing batch"). No "improves maintainability".
4. `## Stage graph` **(lint)**: a fenced diagram. Mermaid `flowchart TD` by default; a `text` block (ASCII) where Mermaid won't render. For Mermaid, the edges must match the Stage Index `dependsOn` exactly **(lint)**.
5. `## Stage Index` **(lint)**: the machine-readable block below.
6. One `## Stage <id>: <name>` per stage **(lint: 1:1 with the index)**, each with a one-line goal and its checklist. If research found observable signals, the last stage verifies them (see below).
7. `## Execution notes` **(lint)**: everything a later session needs so it doesn't work it out again:
- **Prerequisites:** base branch, execution branch, remote or not, isolation mode (worktrees or sequential).
- **Commands:** install, and the repo's full check (lint, typecheck, test, build).
- **Commit policy:** one green commit per stage with its boxes ticked; Conventional Commit format; no `--no-verify`; changesets or other release files ride with the stage that needs them.
- **Accepted risks:** known risks the plan deliberately doesn't address, one line each with why. The reviewer won't re-raise these.
- Anything else every agent must know (conventions from research).
8. `## Review` (lint warns if missing): what the adversarial review found, what was accepted and what was rejected with reasons. See `plan-review.md`.
Keep it as short as the change allows. A five-stage plan is usually 100–180 lines.
## Observable-behaviour stage
Include only when research found signals something outside the code depends on: error class names, log fields or messages, metrics or analytics events, public API or response shapes, CLI output. One checklist item per signal, each saying what depends on it and how it's checked:
```markdown
## Stage S4: Observable behaviour
Confirm nothing that dashboards, alerts or clients rely on changed by accident.
- [ ] **Action**: Confirm `SyncBatchError` is still the class name thrown on exhausted retries (the on-call alert matches on it).
- **Files**: src/sync/writer.ts
- **Verify**: `grep -n "class SyncBatchError" src/sync/writer.ts` → one match
- [ ] **Action**: Confirm the `sync.batch.written` log line still carries `batchIndex` and `rows`.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts -t "log fields"` → passes
```
If a signal changes on purpose, the item says so and names who needs telling. With no signals, omit the stage and note "no observable signals found" once in Execution notes.
## Stage graph
Mermaid, node ids equal to stage ids. Parallel stages branch from a common parent and join at a common child:
````markdown
```mermaid
flowchart TD
S0[S0: Types and helper] --> S1A[S1A: Batched writer]
S0 --> S1B[S1B: Config and env]
S1A --> S2[S2: Tests]
S1B --> S2
S2 --> S3[S3: Retry on failure]
```
````
ASCII fallback (same edges, not edge-checked by lint):
````markdown
```text
S0 Types and helper
├─► S1A Batched writer ─┐
└─► S1B Config and env ─┴─► S2 Tests ─► S3 Retry on failure
```
````
## Stage Index
A fenced block with the info string `json stage-index`, directly after the graph:
````markdown
```json stage-index
{
"stages": [
{ "id": "S0", "name": "Types and helper", "dependsOn": [], "parallelism": "sequential", "files": ["src/util/chunk.ts", "src/util/index.ts"], "model": "sonnet" },
{ "id": "S1A", "name": "Batched writer", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/writer.ts"], "model": "sonnet" },
{ "id": "S1B", "name": "Config and env", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/config.ts", ".env.example"], "model": "haiku" }
]
}
```
````
| Field | Meaning | Lint |
|---|---|---|
| `id` | Short id (`S0`, `S1A`). Matches the `## Stage <id>:` heading. | unique, 1:1 with headings |
| `name` | Human name. | present |
| `dependsOn` | Ids of stages that must be committed first. | known ids, no cycles, matches Mermaid edges |
| `parallelism` | `"parallel"` may run alongside other ready stages; `"sequential"` runs alone. | one of the two |
| `files` | Every path the stage creates, modifies or deletes. | equals the union of its checklist items' Files; two `parallel` stages that could run at the same time (neither depends on the other, directly or indirectly) must share no file |
| `model` | Tier name for the stage's agent (`haiku`, `sonnet`, `opus`, or your platform's equivalent). | present; not a dated model ID |
The lint can't see imports. Rule 3 also says neither parallel stage may import a file the other creates. Check that yourself when assigning `parallel`, and prefer `sequential` when unsure.
## Checklist items
```markdown
- [ ] **Action**: Replace the per-row insert loop with chunked `insertMany` calls.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all tests pass
```
- **Action**: one imperative sentence.
- **Files**: comma-separated paths from the repo root (backticks optional). Must be inside the stage's `files`.
- **Verify**, exactly one of two forms **(lint)**:
- Command: `` **Verify**: `<command>` → <expected result> ``. Runnable from the repo root; quoted verbatim into agent briefs and re-run by the lead.
- Manual: `**Verify (manual)**: <what to read or check, and what counts as a pass>`. Only when no command can express it.
- Checkbox: `- [ ]` until the stage is committed, then `- [x]` in that same commit. This is the resume state.
## Stage report (what agents return)
```json
{
"stage": "S1A",
"completed": ["Replace the per-row insert loop with chunked insertMany calls."],
"filesChanged": ["src/sync/writer.ts"],
"verifyResults": [{ "cmd": "pnpm vitest run src/sync/writer.test.ts", "pass": true, "output": "" }],
"deviations": [],
"blocked": null
}
```
`output` is the tail of the command output, on failure only. `deviations` lists anything done differently from the checklist and why. `blocked` is `null` or a sentence saying what stopped the agent: it reports blocked rather than editing outside its files or weakening a test.
references/plan-review.md
View this file on GitHub# Adversarial plan review
A plan's author is the worst-placed party to find its holes. Before the user sees the plan, a separate agent on the strongest tier you have reviews it against the research. Framing matters: "find everything wrong" produces forty nitpicks and buries the two findings that matter. "Be pragmatic" produces fewer, better findings.
## Reviewer brief
```markdown
You're reviewing an implementation plan before anyone builds it. Be pragmatic: the goal is a plan that ships safely, not a perfect one.
Read:
- the plan: plans/<name>.md
- the research findings: <paste them, or the path to them>
- the repo itself, read-only, as needed to check claims (don't edit anything)
Accepted risks are listed in the plan; don't re-raise them unless one is worse than the plan says.
"This could be simpler" is a valid finding, including "drop stages X and Y" or "this doesn't need parallel agents at all".
Look for, in order of importance:
1. Wrong parallelism: two parallel stages that share a file (barrels, index files, lockfiles, config, shared test fixtures), or where one imports something the other creates.
2. Missing work: a stage the change needs that isn't there (migration, config, docs, a caller that also needs updating, observable signals that will change).
3. Unverifiable checks: a Verify that wouldn't fail if the work were wrong, or a manual check that could be a command.
4. Ordering: a stage that can't be green on its own, so its commit would be red.
5. Hidden risks the research shows but the plan ignores.
6. A simpler plan that gets the same result.
Return at most 10 findings, most important first, each as:
{ "id": "R1", "severity": "blocker | should-fix | consider", "stage": "S1B or plan", "finding": "...", "evidence": "file:line or research point", "suggestion": "..." }
If the plan is fine, say so and return an empty list. Don't pad.
```
## Second opinion (optional)
If another model family is available (for example Codex CLI from a Claude session, or a Claude model from Codex), give it the same brief and files. Different models miss different things. Merge both lists, dropping duplicates.
## Folding findings in
- **Accept** what you agree with: change the plan (stages, Stage Index, graph, checks), not just the Review section.
- **Reject** with a one-line reason. "Disagree" isn't a reason; "S1B only appends to index.ts after S1A is merged, so they're sequential already" is.
- Blockers can't be quietly rejected. If you disagree with one, put it in front of the user when you ask for approval.
- Re-run plan-lint after editing.
Record it in the plan, after Execution notes:
```markdown
## Review
Reviewed by a strongest-tier agent (and Codex as a second opinion). 5 findings: 3 accepted, 2 rejected.
- **Accepted R1** (blocker): S1A and S1B both edit `src/reports/index.ts` → S1B is now sequential after S1A.
- **Accepted R2**: S2's verify only ran typecheck → now runs `pnpm test src/reports` with an expected count.
- **Accepted R4**: the export endpoint's response shape is consumed by the mobile app → added S4 observable-behaviour check.
- **Rejected R3**: "use a streaming CSV library" → tables are capped at 5,000 rows (research: `MAX_ROWS` in `config.ts`), so in-memory is fine.
- **Rejected R5**: "split S0 into two stages" → both halves are a few lines; one green commit is simpler.
```
Keep it short. The point is that a reader can see what was challenged and why the plan looks the way it does.
references/worked-example.md
View this file on GitHub# Worked example
**User:** "The nightly sync falls over on big imports, rate limits I think. Plan and build a fix: batch the writes and retry failures."
## 1. Scope
> Planning batched writes with retries for the sync job in `src/sync` → `plans/batched-sync.md`; proceeding.
## 2. Research (five explore agents, in parallel)
Condensed findings:
- **Structure:** `src/sync/writer.ts` (`writeRows`, 38 lines), `src/sync/config.ts`, `src/util/index.ts` barrel. No generated files.
- **Types:** `Row` in `src/sync/types.ts`; `client.insertMany(rows: Row[])` already exists in `src/db.ts:44` and is unused.
- **Tests:** `src/sync/writer.test.ts` has 2 tests, both single-row. **Nothing tests large inputs or failures** (finding).
- **Dependencies, config and conventions:** only `jobs/nightly.ts` calls `writeRows`. No env var for batch size; the provider docs in `docs/provider.md` say 500 rows per request max. `CLAUDE.md`: named exports, errors extend `AppError`, run `pnpm lint && pnpm tsc --noEmit && pnpm vitest run && pnpm build`. Commits are Conventional. Remote `origin` exists.
- **Observable behaviour:** no named error classes or structured log fields in `src/sync` today; the job's only output is a row count logged as plain text. Finding: no observable-behaviour stage needed.
Nothing changes the scope, so no checkpoint needed.
## 3–4. The plan
The full plan is `scripts/fixtures/good.md`. Its shape:
```mermaid
flowchart TD
S0[S0: Chunk helper] --> S1A[S1A: Batched writer]
S0 --> S1B[S1B: Batch size config]
S1A --> S2[S2: Tests]
S1B --> S2
S2 --> S3[S3: Retry failed batches]
```
Parallelism decisions:
- S1A (`writer.ts`) and S1B (`config.ts`, `.env.example`) have disjoint files. Does either import something the other *creates*? S1A imports `BATCH_SIZE` from `config.ts`, but research shows it's already exported today (hard-coded to 100); S1B only changes how its value is read. Nothing new crosses between them: **parallel**. Had S1B been introducing `BATCH_SIZE` for the first time, S1A would depend on it and both would be sequential.
- S3 also edits `writer.ts` but depends on S1A, so it can't run at the same time.
- Models: S0 and S1B are mechanical (`haiku`); S1A, S2, S3 need judgement about the client API and test design (`sonnet`).
`plan-lint.mjs plans/batched-sync.md` → 0 errors, 1 warning (not reviewed yet).
**Review.** A separate agent on the strongest tier gets the plan, the research findings and the reviewer brief. It returns three findings:
- R1 (should-fix): S2's writer test only counts `insertMany` calls; a bug that drops the last partial batch would still pass. Accepted: the test now also asserts every row is written once.
- R2 (should-fix): S1B reads a new env var but `.env.example` isn't in its files. Accepted.
- R3 (consider): make S1A and S1B sequential to be safe. Rejected: the files are disjoint and `BATCH_SIZE` already exists.
The lead edits the plan, writes the `## Review` section and lints again (0 errors, 0 warnings). Nothing is committed yet.
```markdown
**Plan:** plans/batched-sync.md (lint: 0 errors; committed on feat/batched-sync once you approve)
**Stages:** 5 (2 parallel, 3 sequential). First wave: S0.
**Execution:** worktree agents from origin/feat/batched-sync
**Review:** 3 findings, 2 accepted, 1 rejected (see ## Review)
**Biggest risk:** no existing test covers multi-row writes, so S1A's verify only proves nothing broke; S2 is where batching is actually proven.
Approve to start building, or tell me what to change.
```
User: "go". The lead creates `feat/batched-sync` off `main` and commits the plan as `docs(plans): add batched-sync`.
## 5. Execution
**Branch check.** `git fetch origin && git log --oneline origin/main..HEAD` shows the plan commit, so the branch is live and ahead.
**Wave 1 (S0).** One stage, mechanical: the lead does it directly, runs `pnpm tsc --noEmit`, ticks S0's two boxes, commits `refactor(util): S0 chunk helper`, pushes.
**Probe.** Before the first parallel wave, one tiny agent runs only the setup step and reports `pwd` and `git log --oneline -1`. It shows `4d5e6f7 refactor(util): S0 chunk helper`, so worktrees will see S0.
**Wave 2 (S1A ∥ S1B).** Two agents in one message, worktree isolation, models from the index. Each brief starts:
```text
1. Run exactly: git checkout --detach origin/feat/batched-sync
git log --oneline -1 must show: 4d5e6f7 refactor(util): S0 chunk helper
```
Reports:
```json
{ "stage": "S1A", "completed": ["Replace the per-row insert loop…"], "filesChanged": ["src/sync/writer.ts"],
"verifyResults": [{ "cmd": "pnpm vitest run src/sync", "pass": true, "output": "" }], "deviations": [], "blocked": null }
{ "stage": "S1B", "completed": ["Read SYNC_BATCH_SIZE…"], "filesChanged": ["src/sync/config.ts", ".env.example", "src/sync/types.ts"],
"verifyResults": [{ "cmd": "pnpm tsc --noEmit", "pass": true, "output": "" }],
"deviations": ["Added a BatchSize type to types.ts"], "blocked": null }
```
S1B touched `src/sync/types.ts`, outside its declared set. The lead reads it: a one-line type alias nothing needs. Rejected: the lead drops that file from the merge and re-runs S1B's verify (still passes). If it had been needed, the lead would have accepted it and added it to S1B's files in the plan, noting the deviation.
The lead merges both worktrees, re-runs `pnpm vitest run src/sync` and `pnpm tsc --noEmit` (pass), then makes two commits, each ticking its own stage's boxes:
```text
fix(sync): S1A batch inserts
chore(sync): S1B configurable batch size
```
**Waves 3–4** (S2, then S3) run the same way. S3's manual verify is done by the lead reading the error message, not by the agent.
## 7. Finish
```markdown
**Built:** 5/5 stages, 6 commits (plan + 5 stages). Full check passes: lint, typecheck, 11 tests, build.
**Diff:** 6 files, +184 −21.
**Next:** run `clean-comments` (S1A and S3 added several "now batches…" comments), then `tidy-commits` to fold the stage commits into release-shaped ones. Want a draft PR description from the plan's Motivation and Benefits? I'll only open the PR if you say so.
```
scripts/fixtures/bad-cycle.md
View this file on GitHub# Batched sync writes
## Motivation
The nightly sync inserts one row per database call. Imports over about 2,000 rows hit the provider's rate limit and fail part-way, leaving a half-written table that the next run doesn't repair.
This change batches inserts, makes the batch size configurable, and retries a failed batch before giving up, so a large import either completes or fails cleanly with a clear error.
## Benefits
- Imports of any size complete: one request per 250 rows instead of one per row (a 2,000-row import goes from 2,000 calls to 8).
- A failed batch is retried up to 5 times instead of failing the whole run.
- When it does fail, `SyncBatchError` names the batch and row range, so a rerun can be targeted.
## Stage graph
```mermaid
flowchart TD
S0[S0: Chunk helper] --> S1A[S1A: Batched writer]
S0 --> S1B[S1B: Batch size config]
S1A --> S2[S2: Tests]
S1B --> S2
S2 --> S3[S3: Retry failed batches]
S3 --> S0
```
## Stage Index
```json stage-index
{
"stages": [
{ "id": "S0", "name": "Chunk helper", "dependsOn": ["S3"], "parallelism": "sequential", "files": ["src/util/chunk.ts", "src/util/index.ts"], "model": "haiku" },
{ "id": "S1A", "name": "Batched writer", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/writer.ts"], "model": "sonnet" },
{ "id": "S1B", "name": "Batch size config", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/config.ts", ".env.example"], "model": "haiku" },
{ "id": "S2", "name": "Tests", "dependsOn": ["S1A", "S1B"], "parallelism": "sequential", "files": ["src/sync/writer.test.ts", "src/util/chunk.test.ts"], "model": "sonnet" },
{ "id": "S3", "name": "Retry failed batches", "dependsOn": ["S2"], "parallelism": "sequential", "files": ["src/sync/writer.ts", "src/sync/writer.test.ts"], "model": "sonnet" }
]
}
```
## Stage S0: Chunk helper
Add a small pure helper that splits an array into fixed-size chunks.
- [ ] **Action**: Create `chunked(items, size)` returning arrays of at most `size` items; throw on size < 1.
- **Files**: src/util/chunk.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
- [ ] **Action**: Export it from the util barrel.
- **Files**: src/util/index.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S1A: Batched writer
- [ ] **Action**: Replace the per-row insert loop in `writeRows` with `insertMany` over `chunked(rows, BATCH_SIZE)`.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → existing tests pass
## Stage S1B: Batch size config
- [ ] **Action**: Read `SYNC_BATCH_SIZE` (default 250, max 500) and export `BATCH_SIZE`.
- **Files**: src/sync/config.ts, .env.example
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S2: Tests
- [ ] **Action**: Unit-test `chunked` (empty, exact multiple, remainder, size < 1).
- **Files**: src/util/chunk.test.ts
- **Verify**: `pnpm vitest run src/util/chunk.test.ts` → 4 tests pass
- [ ] **Action**: Test that 1,001 rows with batch size 250 make 5 `insertMany` calls.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass
## Stage S3: Retry failed batches
- [ ] **Action**: Retry a failed batch up to 5 times with backoff, then throw `SyncBatchError` naming the batch index.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → all pass
- [ ] **Action**: Test retry-then-succeed and retry-exhausted paths.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass, including 2 new tests
- [ ] **Action**: Read the error message a user sees when retries run out.
- **Files**: src/sync/writer.ts
- **Verify (manual)**: the message names the batch, the row range and the last provider error, and contains no credentials
## Execution notes
- **Prerequisites:** base `main`; execution branch `feat/batched-sync`; remote `origin`, so worktree agents detach onto `origin/feat/batched-sync`.
- **Commands:** install `pnpm install --frozen-lockfile`; full check `pnpm lint && pnpm tsc --noEmit && pnpm vitest run && pnpm build`.
- **Commit policy:** one green commit per stage with its boxes ticked, Conventional Commits, never `--no-verify`.
- **Accepted risks:** a run that dies mid-import still leaves earlier batches written; making the import transactional is out of scope.
- **Conventions:** errors extend `AppError` (src/errors.ts); named exports only.
- No observable signals found beyond `SyncBatchError`, which this change introduces.
## Review
Reviewed by a strongest-tier agent. 3 findings: 2 accepted, 1 rejected.
- **Accepted R1:** S2's writer test originally only checked the call count → now also asserts every row is written once.
- **Accepted R2:** `.env.example` was missing from S1B's files → added.
- **Rejected R3:** "make S1A and S1B sequential to be safe" → files are disjoint and `BATCH_SIZE` already exists, so neither creates what the other imports.
scripts/fixtures/bad-dated-model.md
View this file on GitHub# Batched sync writes
## Motivation
The nightly sync inserts one row per database call. Imports over about 2,000 rows hit the provider's rate limit and fail part-way, leaving a half-written table that the next run doesn't repair.
This change batches inserts, makes the batch size configurable, and retries a failed batch before giving up, so a large import either completes or fails cleanly with a clear error.
## Benefits
- Imports of any size complete: one request per 250 rows instead of one per row (a 2,000-row import goes from 2,000 calls to 8).
- A failed batch is retried up to 5 times instead of failing the whole run.
- When it does fail, `SyncBatchError` names the batch and row range, so a rerun can be targeted.
## Stage graph
```mermaid
flowchart TD
S0[S0: Chunk helper] --> S1A[S1A: Batched writer]
S0 --> S1B[S1B: Batch size config]
S1A --> S2[S2: Tests]
S1B --> S2
S2 --> S3[S3: Retry failed batches]
```
## Stage Index
```json stage-index
{
"stages": [
{ "id": "S0", "name": "Chunk helper", "dependsOn": [], "parallelism": "sequential", "files": ["src/util/chunk.ts", "src/util/index.ts"], "model": "haiku" },
{ "id": "S1A", "name": "Batched writer", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/writer.ts"], "model": "sonnet" },
{ "id": "S1B", "name": "Batch size config", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/config.ts", ".env.example"], "model": "haiku" },
{ "id": "S2", "name": "Tests", "dependsOn": ["S1A", "S1B"], "parallelism": "sequential", "files": ["src/sync/writer.test.ts", "src/util/chunk.test.ts"], "model": "sonnet" },
{ "id": "S3", "name": "Retry failed batches", "dependsOn": ["S2"], "parallelism": "sequential", "files": ["src/sync/writer.ts", "src/sync/writer.test.ts"], "model": "claude-sonnet-20250514" }
]
}
```
## Stage S0: Chunk helper
Add a small pure helper that splits an array into fixed-size chunks.
- [ ] **Action**: Create `chunked(items, size)` returning arrays of at most `size` items; throw on size < 1.
- **Files**: src/util/chunk.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
- [ ] **Action**: Export it from the util barrel.
- **Files**: src/util/index.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S1A: Batched writer
- [ ] **Action**: Replace the per-row insert loop in `writeRows` with `insertMany` over `chunked(rows, BATCH_SIZE)`.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → existing tests pass
## Stage S1B: Batch size config
- [ ] **Action**: Read `SYNC_BATCH_SIZE` (default 250, max 500) and export `BATCH_SIZE`.
- **Files**: src/sync/config.ts, .env.example
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S2: Tests
- [ ] **Action**: Unit-test `chunked` (empty, exact multiple, remainder, size < 1).
- **Files**: src/util/chunk.test.ts
- **Verify**: `pnpm vitest run src/util/chunk.test.ts` → 4 tests pass
- [ ] **Action**: Test that 1,001 rows with batch size 250 make 5 `insertMany` calls.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass
## Stage S3: Retry failed batches
- [ ] **Action**: Retry a failed batch up to 5 times with backoff, then throw `SyncBatchError` naming the batch index.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → all pass
- [ ] **Action**: Test retry-then-succeed and retry-exhausted paths.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass, including 2 new tests
- [ ] **Action**: Read the error message a user sees when retries run out.
- **Files**: src/sync/writer.ts
- **Verify (manual)**: the message names the batch, the row range and the last provider error, and contains no credentials
## Execution notes
- **Prerequisites:** base `main`; execution branch `feat/batched-sync`; remote `origin`, so worktree agents detach onto `origin/feat/batched-sync`.
- **Commands:** install `pnpm install --frozen-lockfile`; full check `pnpm lint && pnpm tsc --noEmit && pnpm vitest run && pnpm build`.
- **Commit policy:** one green commit per stage with its boxes ticked, Conventional Commits, never `--no-verify`.
- **Accepted risks:** a run that dies mid-import still leaves earlier batches written; making the import transactional is out of scope.
- **Conventions:** errors extend `AppError` (src/errors.ts); named exports only.
- No observable signals found beyond `SyncBatchError`, which this change introduces.
## Review
Reviewed by a strongest-tier agent. 3 findings: 2 accepted, 1 rejected.
- **Accepted R1:** S2's writer test originally only checked the call count → now also asserts every row is written once.
- **Accepted R2:** `.env.example` was missing from S1B's files → added.
- **Rejected R3:** "make S1A and S1B sequential to be safe" → files are disjoint and `BATCH_SIZE` already exists, so neither creates what the other imports.
scripts/fixtures/bad-files-mismatch.md
View this file on GitHub# Batched sync writes
## Motivation
The nightly sync inserts one row per database call. Imports over about 2,000 rows hit the provider's rate limit and fail part-way, leaving a half-written table that the next run doesn't repair.
This change batches inserts, makes the batch size configurable, and retries a failed batch before giving up, so a large import either completes or fails cleanly with a clear error.
## Benefits
- Imports of any size complete: one request per 250 rows instead of one per row (a 2,000-row import goes from 2,000 calls to 8).
- A failed batch is retried up to 5 times instead of failing the whole run.
- When it does fail, `SyncBatchError` names the batch and row range, so a rerun can be targeted.
## Stage graph
```mermaid
flowchart TD
S0[S0: Chunk helper] --> S1A[S1A: Batched writer]
S0 --> S1B[S1B: Batch size config]
S1A --> S2[S2: Tests]
S1B --> S2
S2 --> S3[S3: Retry failed batches]
```
## Stage Index
```json stage-index
{
"stages": [
{ "id": "S0", "name": "Chunk helper", "dependsOn": [], "parallelism": "sequential", "files": ["src/util/chunk.ts", "src/util/index.ts"], "model": "haiku" },
{ "id": "S1A", "name": "Batched writer", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/writer.ts"], "model": "sonnet" },
{ "id": "S1B", "name": "Batch size config", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/config.ts", ".env.example"], "model": "haiku" },
{ "id": "S2", "name": "Tests", "dependsOn": ["S1A", "S1B"], "parallelism": "sequential", "files": ["src/sync/writer.test.ts", "src/util/chunk.test.ts"], "model": "sonnet" },
{ "id": "S3", "name": "Retry failed batches", "dependsOn": ["S2"], "parallelism": "sequential", "files": ["src/sync/writer.ts", "src/sync/writer.test.ts"], "model": "sonnet" }
]
}
```
## Stage S0: Chunk helper
Add a small pure helper that splits an array into fixed-size chunks.
- [ ] **Action**: Create `chunked(items, size)` returning arrays of at most `size` items; throw on size < 1.
- **Files**: src/util/chunk.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
- [ ] **Action**: Export it from the util barrel.
- **Files**: src/util/index.ts, src/index.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S1A: Batched writer
- [ ] **Action**: Replace the per-row insert loop in `writeRows` with `insertMany` over `chunked(rows, BATCH_SIZE)`.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → existing tests pass
## Stage S1B: Batch size config
- [ ] **Action**: Read `SYNC_BATCH_SIZE` (default 250, max 500) and export `BATCH_SIZE`.
- **Files**: src/sync/config.ts, .env.example
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S2: Tests
- [ ] **Action**: Unit-test `chunked` (empty, exact multiple, remainder, size < 1).
- **Files**: src/util/chunk.test.ts
- **Verify**: `pnpm vitest run src/util/chunk.test.ts` → 4 tests pass
- [ ] **Action**: Test that 1,001 rows with batch size 250 make 5 `insertMany` calls.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass
## Stage S3: Retry failed batches
- [ ] **Action**: Retry a failed batch up to 5 times with backoff, then throw `SyncBatchError` naming the batch index.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → all pass
- [ ] **Action**: Test retry-then-succeed and retry-exhausted paths.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass, including 2 new tests
- [ ] **Action**: Read the error message a user sees when retries run out.
- **Files**: src/sync/writer.ts
- **Verify (manual)**: the message names the batch, the row range and the last provider error, and contains no credentials
## Execution notes
- **Prerequisites:** base `main`; execution branch `feat/batched-sync`; remote `origin`, so worktree agents detach onto `origin/feat/batched-sync`.
- **Commands:** install `pnpm install --frozen-lockfile`; full check `pnpm lint && pnpm tsc --noEmit && pnpm vitest run && pnpm build`.
- **Commit policy:** one green commit per stage with its boxes ticked, Conventional Commits, never `--no-verify`.
- **Accepted risks:** a run that dies mid-import still leaves earlier batches written; making the import transactional is out of scope.
- **Conventions:** errors extend `AppError` (src/errors.ts); named exports only.
- No observable signals found beyond `SyncBatchError`, which this change introduces.
## Review
Reviewed by a strongest-tier agent. 3 findings: 2 accepted, 1 rejected.
- **Accepted R1:** S2's writer test originally only checked the call count → now also asserts every row is written once.
- **Accepted R2:** `.env.example` was missing from S1B's files → added.
- **Rejected R3:** "make S1A and S1B sequential to be safe" → files are disjoint and `BATCH_SIZE` already exists, so neither creates what the other imports.
scripts/fixtures/bad-graph-mismatch.md
View this file on GitHub# Batched sync writes
## Motivation
The nightly sync inserts one row per database call. Imports over about 2,000 rows hit the provider's rate limit and fail part-way, leaving a half-written table that the next run doesn't repair.
This change batches inserts, makes the batch size configurable, and retries a failed batch before giving up, so a large import either completes or fails cleanly with a clear error.
## Benefits
- Imports of any size complete: one request per 250 rows instead of one per row (a 2,000-row import goes from 2,000 calls to 8).
- A failed batch is retried up to 5 times instead of failing the whole run.
- When it does fail, `SyncBatchError` names the batch and row range, so a rerun can be targeted.
## Stage graph
```mermaid
flowchart TD
S0[S0: Chunk helper] --> S1A[S1A: Batched writer]
S0 --> S1B[S1B: Batch size config]
S1A --> S2[S2: Tests]
S2 --> S3[S3: Retry failed batches]
```
## Stage Index
```json stage-index
{
"stages": [
{ "id": "S0", "name": "Chunk helper", "dependsOn": [], "parallelism": "sequential", "files": ["src/util/chunk.ts", "src/util/index.ts"], "model": "haiku" },
{ "id": "S1A", "name": "Batched writer", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/writer.ts"], "model": "sonnet" },
{ "id": "S1B", "name": "Batch size config", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/config.ts", ".env.example"], "model": "haiku" },
{ "id": "S2", "name": "Tests", "dependsOn": ["S1A", "S1B"], "parallelism": "sequential", "files": ["src/sync/writer.test.ts", "src/util/chunk.test.ts"], "model": "sonnet" },
{ "id": "S3", "name": "Retry failed batches", "dependsOn": ["S2"], "parallelism": "sequential", "files": ["src/sync/writer.ts", "src/sync/writer.test.ts"], "model": "sonnet" }
]
}
```
## Stage S0: Chunk helper
Add a small pure helper that splits an array into fixed-size chunks.
- [ ] **Action**: Create `chunked(items, size)` returning arrays of at most `size` items; throw on size < 1.
- **Files**: src/util/chunk.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
- [ ] **Action**: Export it from the util barrel.
- **Files**: src/util/index.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S1A: Batched writer
- [ ] **Action**: Replace the per-row insert loop in `writeRows` with `insertMany` over `chunked(rows, BATCH_SIZE)`.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → existing tests pass
## Stage S1B: Batch size config
- [ ] **Action**: Read `SYNC_BATCH_SIZE` (default 250, max 500) and export `BATCH_SIZE`.
- **Files**: src/sync/config.ts, .env.example
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S2: Tests
- [ ] **Action**: Unit-test `chunked` (empty, exact multiple, remainder, size < 1).
- **Files**: src/util/chunk.test.ts
- **Verify**: `pnpm vitest run src/util/chunk.test.ts` → 4 tests pass
- [ ] **Action**: Test that 1,001 rows with batch size 250 make 5 `insertMany` calls.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass
## Stage S3: Retry failed batches
- [ ] **Action**: Retry a failed batch up to 5 times with backoff, then throw `SyncBatchError` naming the batch index.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → all pass
- [ ] **Action**: Test retry-then-succeed and retry-exhausted paths.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass, including 2 new tests
- [ ] **Action**: Read the error message a user sees when retries run out.
- **Files**: src/sync/writer.ts
- **Verify (manual)**: the message names the batch, the row range and the last provider error, and contains no credentials
## Execution notes
- **Prerequisites:** base `main`; execution branch `feat/batched-sync`; remote `origin`, so worktree agents detach onto `origin/feat/batched-sync`.
- **Commands:** install `pnpm install --frozen-lockfile`; full check `pnpm lint && pnpm tsc --noEmit && pnpm vitest run && pnpm build`.
- **Commit policy:** one green commit per stage with its boxes ticked, Conventional Commits, never `--no-verify`.
- **Accepted risks:** a run that dies mid-import still leaves earlier batches written; making the import transactional is out of scope.
- **Conventions:** errors extend `AppError` (src/errors.ts); named exports only.
- No observable signals found beyond `SyncBatchError`, which this change introduces.
## Review
Reviewed by a strongest-tier agent. 3 findings: 2 accepted, 1 rejected.
- **Accepted R1:** S2's writer test originally only checked the call count → now also asserts every row is written once.
- **Accepted R2:** `.env.example` was missing from S1B's files → added.
- **Rejected R3:** "make S1A and S1B sequential to be safe" → files are disjoint and `BATCH_SIZE` already exists, so neither creates what the other imports.
scripts/fixtures/bad-missing-benefits.md
View this file on GitHub# Batched sync writes
## Motivation
The nightly sync inserts one row per database call. Imports over about 2,000 rows hit the provider's rate limit and fail part-way, leaving a half-written table that the next run doesn't repair.
This change batches inserts, makes the batch size configurable, and retries a failed batch before giving up, so a large import either completes or fails cleanly with a clear error.
## Stage graph
```mermaid
flowchart TD
S0[S0: Chunk helper] --> S1A[S1A: Batched writer]
S0 --> S1B[S1B: Batch size config]
S1A --> S2[S2: Tests]
S1B --> S2
S2 --> S3[S3: Retry failed batches]
```
## Stage Index
```json stage-index
{
"stages": [
{ "id": "S0", "name": "Chunk helper", "dependsOn": [], "parallelism": "sequential", "files": ["src/util/chunk.ts", "src/util/index.ts"], "model": "haiku" },
{ "id": "S1A", "name": "Batched writer", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/writer.ts"], "model": "sonnet" },
{ "id": "S1B", "name": "Batch size config", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/config.ts", ".env.example"], "model": "haiku" },
{ "id": "S2", "name": "Tests", "dependsOn": ["S1A", "S1B"], "parallelism": "sequential", "files": ["src/sync/writer.test.ts", "src/util/chunk.test.ts"], "model": "sonnet" },
{ "id": "S3", "name": "Retry failed batches", "dependsOn": ["S2"], "parallelism": "sequential", "files": ["src/sync/writer.ts", "src/sync/writer.test.ts"], "model": "sonnet" }
]
}
```
## Stage S0: Chunk helper
Add a small pure helper that splits an array into fixed-size chunks.
- [ ] **Action**: Create `chunked(items, size)` returning arrays of at most `size` items; throw on size < 1.
- **Files**: src/util/chunk.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
- [ ] **Action**: Export it from the util barrel.
- **Files**: src/util/index.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S1A: Batched writer
- [ ] **Action**: Replace the per-row insert loop in `writeRows` with `insertMany` over `chunked(rows, BATCH_SIZE)`.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → existing tests pass
## Stage S1B: Batch size config
- [ ] **Action**: Read `SYNC_BATCH_SIZE` (default 250, max 500) and export `BATCH_SIZE`.
- **Files**: src/sync/config.ts, .env.example
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S2: Tests
- [ ] **Action**: Unit-test `chunked` (empty, exact multiple, remainder, size < 1).
- **Files**: src/util/chunk.test.ts
- **Verify**: `pnpm vitest run src/util/chunk.test.ts` → 4 tests pass
- [ ] **Action**: Test that 1,001 rows with batch size 250 make 5 `insertMany` calls.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass
## Stage S3: Retry failed batches
- [ ] **Action**: Retry a failed batch up to 5 times with backoff, then throw `SyncBatchError` naming the batch index.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → all pass
- [ ] **Action**: Test retry-then-succeed and retry-exhausted paths.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass, including 2 new tests
- [ ] **Action**: Read the error message a user sees when retries run out.
- **Files**: src/sync/writer.ts
- **Verify (manual)**: the message names the batch, the row range and the last provider error, and contains no credentials
## Execution notes
- **Prerequisites:** base `main`; execution branch `feat/batched-sync`; remote `origin`, so worktree agents detach onto `origin/feat/batched-sync`.
- **Commands:** install `pnpm install --frozen-lockfile`; full check `pnpm lint && pnpm tsc --noEmit && pnpm vitest run && pnpm build`.
- **Commit policy:** one green commit per stage with its boxes ticked, Conventional Commits, never `--no-verify`.
- **Accepted risks:** a run that dies mid-import still leaves earlier batches written; making the import transactional is out of scope.
- **Conventions:** errors extend `AppError` (src/errors.ts); named exports only.
- No observable signals found beyond `SyncBatchError`, which this change introduces.
## Review
Reviewed by a strongest-tier agent. 3 findings: 2 accepted, 1 rejected.
- **Accepted R1:** S2's writer test originally only checked the call count → now also asserts every row is written once.
- **Accepted R2:** `.env.example` was missing from S1B's files → added.
- **Rejected R3:** "make S1A and S1B sequential to be safe" → files are disjoint and `BATCH_SIZE` already exists, so neither creates what the other imports.
scripts/fixtures/bad-missing-execution-notes.md
View this file on GitHub# Batched sync writes
## Motivation
The nightly sync inserts one row per database call. Imports over about 2,000 rows hit the provider's rate limit and fail part-way, leaving a half-written table that the next run doesn't repair.
This change batches inserts, makes the batch size configurable, and retries a failed batch before giving up, so a large import either completes or fails cleanly with a clear error.
## Benefits
- Imports of any size complete: one request per 250 rows instead of one per row (a 2,000-row import goes from 2,000 calls to 8).
- A failed batch is retried up to 5 times instead of failing the whole run.
- When it does fail, `SyncBatchError` names the batch and row range, so a rerun can be targeted.
## Stage graph
```mermaid
flowchart TD
S0[S0: Chunk helper] --> S1A[S1A: Batched writer]
S0 --> S1B[S1B: Batch size config]
S1A --> S2[S2: Tests]
S1B --> S2
S2 --> S3[S3: Retry failed batches]
```
## Stage Index
```json stage-index
{
"stages": [
{ "id": "S0", "name": "Chunk helper", "dependsOn": [], "parallelism": "sequential", "files": ["src/util/chunk.ts", "src/util/index.ts"], "model": "haiku" },
{ "id": "S1A", "name": "Batched writer", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/writer.ts"], "model": "sonnet" },
{ "id": "S1B", "name": "Batch size config", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/config.ts", ".env.example"], "model": "haiku" },
{ "id": "S2", "name": "Tests", "dependsOn": ["S1A", "S1B"], "parallelism": "sequential", "files": ["src/sync/writer.test.ts", "src/util/chunk.test.ts"], "model": "sonnet" },
{ "id": "S3", "name": "Retry failed batches", "dependsOn": ["S2"], "parallelism": "sequential", "files": ["src/sync/writer.ts", "src/sync/writer.test.ts"], "model": "sonnet" }
]
}
```
## Stage S0: Chunk helper
Add a small pure helper that splits an array into fixed-size chunks.
- [ ] **Action**: Create `chunked(items, size)` returning arrays of at most `size` items; throw on size < 1.
- **Files**: src/util/chunk.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
- [ ] **Action**: Export it from the util barrel.
- **Files**: src/util/index.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S1A: Batched writer
- [ ] **Action**: Replace the per-row insert loop in `writeRows` with `insertMany` over `chunked(rows, BATCH_SIZE)`.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → existing tests pass
## Stage S1B: Batch size config
- [ ] **Action**: Read `SYNC_BATCH_SIZE` (default 250, max 500) and export `BATCH_SIZE`.
- **Files**: src/sync/config.ts, .env.example
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S2: Tests
- [ ] **Action**: Unit-test `chunked` (empty, exact multiple, remainder, size < 1).
- **Files**: src/util/chunk.test.ts
- **Verify**: `pnpm vitest run src/util/chunk.test.ts` → 4 tests pass
- [ ] **Action**: Test that 1,001 rows with batch size 250 make 5 `insertMany` calls.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass
## Stage S3: Retry failed batches
- [ ] **Action**: Retry a failed batch up to 5 times with backoff, then throw `SyncBatchError` naming the batch index.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → all pass
- [ ] **Action**: Test retry-then-succeed and retry-exhausted paths.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass, including 2 new tests
- [ ] **Action**: Read the error message a user sees when retries run out.
- **Files**: src/sync/writer.ts
- **Verify (manual)**: the message names the batch, the row range and the last provider error, and contains no credentials
## Notes
- **Prerequisites:** base `main`; execution branch `feat/batched-sync`; remote `origin`, so worktree agents detach onto `origin/feat/batched-sync`.
- **Commands:** install `pnpm install --frozen-lockfile`; full check `pnpm lint && pnpm tsc --noEmit && pnpm vitest run && pnpm build`.
- **Commit policy:** one green commit per stage with its boxes ticked, Conventional Commits, never `--no-verify`.
- **Accepted risks:** a run that dies mid-import still leaves earlier batches written; making the import transactional is out of scope.
- **Conventions:** errors extend `AppError` (src/errors.ts); named exports only.
- No observable signals found beyond `SyncBatchError`, which this change introduces.
## Review
Reviewed by a strongest-tier agent. 3 findings: 2 accepted, 1 rejected.
- **Accepted R1:** S2's writer test originally only checked the call count → now also asserts every row is written once.
- **Accepted R2:** `.env.example` was missing from S1B's files → added.
- **Rejected R3:** "make S1A and S1B sequential to be safe" → files are disjoint and `BATCH_SIZE` already exists, so neither creates what the other imports.
scripts/fixtures/bad-missing-model.md
View this file on GitHub# Batched sync writes
## Motivation
The nightly sync inserts one row per database call. Imports over about 2,000 rows hit the provider's rate limit and fail part-way, leaving a half-written table that the next run doesn't repair.
This change batches inserts, makes the batch size configurable, and retries a failed batch before giving up, so a large import either completes or fails cleanly with a clear error.
## Benefits
- Imports of any size complete: one request per 250 rows instead of one per row (a 2,000-row import goes from 2,000 calls to 8).
- A failed batch is retried up to 5 times instead of failing the whole run.
- When it does fail, `SyncBatchError` names the batch and row range, so a rerun can be targeted.
## Stage graph
```mermaid
flowchart TD
S0[S0: Chunk helper] --> S1A[S1A: Batched writer]
S0 --> S1B[S1B: Batch size config]
S1A --> S2[S2: Tests]
S1B --> S2
S2 --> S3[S3: Retry failed batches]
```
## Stage Index
```json stage-index
{
"stages": [
{ "id": "S0", "name": "Chunk helper", "dependsOn": [], "parallelism": "sequential", "files": ["src/util/chunk.ts", "src/util/index.ts"], "model": "" },
{ "id": "S1A", "name": "Batched writer", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/writer.ts"], "model": "sonnet" },
{ "id": "S1B", "name": "Batch size config", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/config.ts", ".env.example"], "model": "" },
{ "id": "S2", "name": "Tests", "dependsOn": ["S1A", "S1B"], "parallelism": "sequential", "files": ["src/sync/writer.test.ts", "src/util/chunk.test.ts"], "model": "sonnet" },
{ "id": "S3", "name": "Retry failed batches", "dependsOn": ["S2"], "parallelism": "sequential", "files": ["src/sync/writer.ts", "src/sync/writer.test.ts"], "model": "sonnet" }
]
}
```
## Stage S0: Chunk helper
Add a small pure helper that splits an array into fixed-size chunks.
- [ ] **Action**: Create `chunked(items, size)` returning arrays of at most `size` items; throw on size < 1.
- **Files**: src/util/chunk.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
- [ ] **Action**: Export it from the util barrel.
- **Files**: src/util/index.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S1A: Batched writer
- [ ] **Action**: Replace the per-row insert loop in `writeRows` with `insertMany` over `chunked(rows, BATCH_SIZE)`.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → existing tests pass
## Stage S1B: Batch size config
- [ ] **Action**: Read `SYNC_BATCH_SIZE` (default 250, max 500) and export `BATCH_SIZE`.
- **Files**: src/sync/config.ts, .env.example
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S2: Tests
- [ ] **Action**: Unit-test `chunked` (empty, exact multiple, remainder, size < 1).
- **Files**: src/util/chunk.test.ts
- **Verify**: `pnpm vitest run src/util/chunk.test.ts` → 4 tests pass
- [ ] **Action**: Test that 1,001 rows with batch size 250 make 5 `insertMany` calls.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass
## Stage S3: Retry failed batches
- [ ] **Action**: Retry a failed batch up to 5 times with backoff, then throw `SyncBatchError` naming the batch index.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → all pass
- [ ] **Action**: Test retry-then-succeed and retry-exhausted paths.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass, including 2 new tests
- [ ] **Action**: Read the error message a user sees when retries run out.
- **Files**: src/sync/writer.ts
- **Verify (manual)**: the message names the batch, the row range and the last provider error, and contains no credentials
## Execution notes
- **Prerequisites:** base `main`; execution branch `feat/batched-sync`; remote `origin`, so worktree agents detach onto `origin/feat/batched-sync`.
- **Commands:** install `pnpm install --frozen-lockfile`; full check `pnpm lint && pnpm tsc --noEmit && pnpm vitest run && pnpm build`.
- **Commit policy:** one green commit per stage with its boxes ticked, Conventional Commits, never `--no-verify`.
- **Accepted risks:** a run that dies mid-import still leaves earlier batches written; making the import transactional is out of scope.
- **Conventions:** errors extend `AppError` (src/errors.ts); named exports only.
- No observable signals found beyond `SyncBatchError`, which this change introduces.
## Review
Reviewed by a strongest-tier agent. 3 findings: 2 accepted, 1 rejected.
- **Accepted R1:** S2's writer test originally only checked the call count → now also asserts every row is written once.
- **Accepted R2:** `.env.example` was missing from S1B's files → added.
- **Rejected R3:** "make S1A and S1B sequential to be safe" → files are disjoint and `BATCH_SIZE` already exists, so neither creates what the other imports.
scripts/fixtures/bad-parallel-overlap.md
View this file on GitHub# Batched sync writes
## Motivation
The nightly sync inserts one row per database call. Imports over about 2,000 rows hit the provider's rate limit and fail part-way, leaving a half-written table that the next run doesn't repair.
This change batches inserts, makes the batch size configurable, and retries a failed batch before giving up, so a large import either completes or fails cleanly with a clear error.
## Benefits
- Imports of any size complete: one request per 250 rows instead of one per row (a 2,000-row import goes from 2,000 calls to 8).
- A failed batch is retried up to 5 times instead of failing the whole run.
- When it does fail, `SyncBatchError` names the batch and row range, so a rerun can be targeted.
## Stage graph
```mermaid
flowchart TD
S0[S0: Chunk helper] --> S1A[S1A: Batched writer]
S0 --> S1B[S1B: Batch size config]
S1A --> S2[S2: Tests]
S1B --> S2
S2 --> S3[S3: Retry failed batches]
```
## Stage Index
```json stage-index
{
"stages": [
{ "id": "S0", "name": "Chunk helper", "dependsOn": [], "parallelism": "sequential", "files": ["src/util/chunk.ts", "src/util/index.ts"], "model": "haiku" },
{ "id": "S1A", "name": "Batched writer", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/writer.ts"], "model": "sonnet" },
{ "id": "S1B", "name": "Batch size config", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/config.ts", ".env.example", "src/sync/writer.ts"], "model": "haiku" },
{ "id": "S2", "name": "Tests", "dependsOn": ["S1A", "S1B"], "parallelism": "sequential", "files": ["src/sync/writer.test.ts", "src/util/chunk.test.ts"], "model": "sonnet" },
{ "id": "S3", "name": "Retry failed batches", "dependsOn": ["S2"], "parallelism": "sequential", "files": ["src/sync/writer.ts", "src/sync/writer.test.ts"], "model": "sonnet" }
]
}
```
## Stage S0: Chunk helper
Add a small pure helper that splits an array into fixed-size chunks.
- [ ] **Action**: Create `chunked(items, size)` returning arrays of at most `size` items; throw on size < 1.
- **Files**: src/util/chunk.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
- [ ] **Action**: Export it from the util barrel.
- **Files**: src/util/index.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S1A: Batched writer
- [ ] **Action**: Replace the per-row insert loop in `writeRows` with `insertMany` over `chunked(rows, BATCH_SIZE)`.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → existing tests pass
## Stage S1B: Batch size config
- [ ] **Action**: Read `SYNC_BATCH_SIZE` (default 250, max 500) and export `BATCH_SIZE`.
- **Files**: src/sync/config.ts, .env.example, src/sync/writer.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S2: Tests
- [ ] **Action**: Unit-test `chunked` (empty, exact multiple, remainder, size < 1).
- **Files**: src/util/chunk.test.ts
- **Verify**: `pnpm vitest run src/util/chunk.test.ts` → 4 tests pass
- [ ] **Action**: Test that 1,001 rows with batch size 250 make 5 `insertMany` calls.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass
## Stage S3: Retry failed batches
- [ ] **Action**: Retry a failed batch up to 5 times with backoff, then throw `SyncBatchError` naming the batch index.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → all pass
- [ ] **Action**: Test retry-then-succeed and retry-exhausted paths.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass, including 2 new tests
- [ ] **Action**: Read the error message a user sees when retries run out.
- **Files**: src/sync/writer.ts
- **Verify (manual)**: the message names the batch, the row range and the last provider error, and contains no credentials
## Execution notes
- **Prerequisites:** base `main`; execution branch `feat/batched-sync`; remote `origin`, so worktree agents detach onto `origin/feat/batched-sync`.
- **Commands:** install `pnpm install --frozen-lockfile`; full check `pnpm lint && pnpm tsc --noEmit && pnpm vitest run && pnpm build`.
- **Commit policy:** one green commit per stage with its boxes ticked, Conventional Commits, never `--no-verify`.
- **Accepted risks:** a run that dies mid-import still leaves earlier batches written; making the import transactional is out of scope.
- **Conventions:** errors extend `AppError` (src/errors.ts); named exports only.
- No observable signals found beyond `SyncBatchError`, which this change introduces.
## Review
Reviewed by a strongest-tier agent. 3 findings: 2 accepted, 1 rejected.
- **Accepted R1:** S2's writer test originally only checked the call count → now also asserts every row is written once.
- **Accepted R2:** `.env.example` was missing from S1B's files → added.
- **Rejected R3:** "make S1A and S1B sequential to be safe" → files are disjoint and `BATCH_SIZE` already exists, so neither creates what the other imports.
scripts/fixtures/bad-verify-form.md
View this file on GitHub# Batched sync writes
## Motivation
The nightly sync inserts one row per database call. Imports over about 2,000 rows hit the provider's rate limit and fail part-way, leaving a half-written table that the next run doesn't repair.
This change batches inserts, makes the batch size configurable, and retries a failed batch before giving up, so a large import either completes or fails cleanly with a clear error.
## Benefits
- Imports of any size complete: one request per 250 rows instead of one per row (a 2,000-row import goes from 2,000 calls to 8).
- A failed batch is retried up to 5 times instead of failing the whole run.
- When it does fail, `SyncBatchError` names the batch and row range, so a rerun can be targeted.
## Stage graph
```mermaid
flowchart TD
S0[S0: Chunk helper] --> S1A[S1A: Batched writer]
S0 --> S1B[S1B: Batch size config]
S1A --> S2[S2: Tests]
S1B --> S2
S2 --> S3[S3: Retry failed batches]
```
## Stage Index
```json stage-index
{
"stages": [
{ "id": "S0", "name": "Chunk helper", "dependsOn": [], "parallelism": "sequential", "files": ["src/util/chunk.ts", "src/util/index.ts"], "model": "haiku" },
{ "id": "S1A", "name": "Batched writer", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/writer.ts"], "model": "sonnet" },
{ "id": "S1B", "name": "Batch size config", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/config.ts", ".env.example"], "model": "haiku" },
{ "id": "S2", "name": "Tests", "dependsOn": ["S1A", "S1B"], "parallelism": "sequential", "files": ["src/sync/writer.test.ts", "src/util/chunk.test.ts"], "model": "sonnet" },
{ "id": "S3", "name": "Retry failed batches", "dependsOn": ["S2"], "parallelism": "sequential", "files": ["src/sync/writer.ts", "src/sync/writer.test.ts"], "model": "sonnet" }
]
}
```
## Stage S0: Chunk helper
Add a small pure helper that splits an array into fixed-size chunks.
- [ ] **Action**: Create `chunked(items, size)` returning arrays of at most `size` items; throw on size < 1.
- **Files**: src/util/chunk.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
- [ ] **Action**: Export it from the util barrel.
- **Files**: src/util/index.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S1A: Batched writer
- [ ] **Action**: Replace the per-row insert loop in `writeRows` with `insertMany` over `chunked(rows, BATCH_SIZE)`.
- **Files**: src/sync/writer.ts
- **Verify**: check it works
## Stage S1B: Batch size config
- [ ] **Action**: Read `SYNC_BATCH_SIZE` (default 250, max 500) and export `BATCH_SIZE`.
- **Files**: src/sync/config.ts, .env.example
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S2: Tests
- [ ] **Action**: Unit-test `chunked` (empty, exact multiple, remainder, size < 1).
- **Files**: src/util/chunk.test.ts
- **Verify**: `pnpm vitest run src/util/chunk.test.ts` → 4 tests pass
- [ ] **Action**: Test that 1,001 rows with batch size 250 make 5 `insertMany` calls.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass
## Stage S3: Retry failed batches
- [ ] **Action**: Retry a failed batch up to 5 times with backoff, then throw `SyncBatchError` naming the batch index.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → all pass
- [ ] **Action**: Test retry-then-succeed and retry-exhausted paths.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass, including 2 new tests
- [ ] **Action**: Read the error message a user sees when retries run out.
- **Files**: src/sync/writer.ts
- **Verify (manual)**: the message names the batch, the row range and the last provider error, and contains no credentials
## Execution notes
- **Prerequisites:** base `main`; execution branch `feat/batched-sync`; remote `origin`, so worktree agents detach onto `origin/feat/batched-sync`.
- **Commands:** install `pnpm install --frozen-lockfile`; full check `pnpm lint && pnpm tsc --noEmit && pnpm vitest run && pnpm build`.
- **Commit policy:** one green commit per stage with its boxes ticked, Conventional Commits, never `--no-verify`.
- **Accepted risks:** a run that dies mid-import still leaves earlier batches written; making the import transactional is out of scope.
- **Conventions:** errors extend `AppError` (src/errors.ts); named exports only.
- No observable signals found beyond `SyncBatchError`, which this change introduces.
## Review
Reviewed by a strongest-tier agent. 3 findings: 2 accepted, 1 rejected.
- **Accepted R1:** S2's writer test originally only checked the call count → now also asserts every row is written once.
- **Accepted R2:** `.env.example` was missing from S1B's files → added.
- **Rejected R3:** "make S1A and S1B sequential to be safe" → files are disjoint and `BATCH_SIZE` already exists, so neither creates what the other imports.
scripts/fixtures/good-ascii.md
View this file on GitHub# Batched sync writes
## Motivation
The nightly sync inserts one row per database call. Imports over about 2,000 rows hit the provider's rate limit and fail part-way, leaving a half-written table that the next run doesn't repair.
This change batches inserts, makes the batch size configurable, and retries a failed batch before giving up, so a large import either completes or fails cleanly with a clear error.
## Benefits
- Imports of any size complete: one request per 250 rows instead of one per row (a 2,000-row import goes from 2,000 calls to 8).
- A failed batch is retried up to 5 times instead of failing the whole run.
- When it does fail, `SyncBatchError` names the batch and row range, so a rerun can be targeted.
## Stage graph
```text
S0 Chunk helper
├─► S1A Batched writer ────┐
└─► S1B Batch size config ─┴─► S2 Tests ─► S3 Retry failed batches
```
## Stage Index
```json stage-index
{
"stages": [
{ "id": "S0", "name": "Chunk helper", "dependsOn": [], "parallelism": "sequential", "files": ["src/util/chunk.ts", "src/util/index.ts"], "model": "haiku" },
{ "id": "S1A", "name": "Batched writer", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/writer.ts"], "model": "sonnet" },
{ "id": "S1B", "name": "Batch size config", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/config.ts", ".env.example"], "model": "haiku" },
{ "id": "S2", "name": "Tests", "dependsOn": ["S1A", "S1B"], "parallelism": "sequential", "files": ["src/sync/writer.test.ts", "src/util/chunk.test.ts"], "model": "sonnet" },
{ "id": "S3", "name": "Retry failed batches", "dependsOn": ["S2"], "parallelism": "sequential", "files": ["src/sync/writer.ts", "src/sync/writer.test.ts"], "model": "sonnet" }
]
}
```
## Stage S0: Chunk helper
Add a small pure helper that splits an array into fixed-size chunks.
- [ ] **Action**: Create `chunked(items, size)` returning arrays of at most `size` items; throw on size < 1.
- **Files**: src/util/chunk.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
- [ ] **Action**: Export it from the util barrel.
- **Files**: src/util/index.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S1A: Batched writer
- [ ] **Action**: Replace the per-row insert loop in `writeRows` with `insertMany` over `chunked(rows, BATCH_SIZE)`.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → existing tests pass
## Stage S1B: Batch size config
- [ ] **Action**: Read `SYNC_BATCH_SIZE` (default 250, max 500) and export `BATCH_SIZE`.
- **Files**: src/sync/config.ts, .env.example
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S2: Tests
- [ ] **Action**: Unit-test `chunked` (empty, exact multiple, remainder, size < 1).
- **Files**: src/util/chunk.test.ts
- **Verify**: `pnpm vitest run src/util/chunk.test.ts` → 4 tests pass
- [ ] **Action**: Test that 1,001 rows with batch size 250 make 5 `insertMany` calls.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass
## Stage S3: Retry failed batches
- [ ] **Action**: Retry a failed batch up to 5 times with backoff, then throw `SyncBatchError` naming the batch index.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → all pass
- [ ] **Action**: Test retry-then-succeed and retry-exhausted paths.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass, including 2 new tests
- [ ] **Action**: Read the error message a user sees when retries run out.
- **Files**: src/sync/writer.ts
- **Verify (manual)**: the message names the batch, the row range and the last provider error, and contains no credentials
## Execution notes
- **Prerequisites:** base `main`; execution branch `feat/batched-sync`; remote `origin`, so worktree agents detach onto `origin/feat/batched-sync`.
- **Commands:** install `pnpm install --frozen-lockfile`; full check `pnpm lint && pnpm tsc --noEmit && pnpm vitest run && pnpm build`.
- **Commit policy:** one green commit per stage with its boxes ticked, Conventional Commits, never `--no-verify`.
- **Accepted risks:** a run that dies mid-import still leaves earlier batches written; making the import transactional is out of scope.
- **Conventions:** errors extend `AppError` (src/errors.ts); named exports only.
- No observable signals found beyond `SyncBatchError`, which this change introduces.
## Review
Reviewed by a strongest-tier agent. 3 findings: 2 accepted, 1 rejected.
- **Accepted R1:** S2's writer test originally only checked the call count → now also asserts every row is written once.
- **Accepted R2:** `.env.example` was missing from S1B's files → added.
- **Rejected R3:** "make S1A and S1B sequential to be safe" → files are disjoint and `BATCH_SIZE` already exists, so neither creates what the other imports.
scripts/fixtures/good.md
View this file on GitHub# Batched sync writes
## Motivation
The nightly sync inserts one row per database call. Imports over about 2,000 rows hit the provider's rate limit and fail part-way, leaving a half-written table that the next run doesn't repair.
This change batches inserts, makes the batch size configurable, and retries a failed batch before giving up, so a large import either completes or fails cleanly with a clear error.
## Benefits
- Imports of any size complete: one request per 250 rows instead of one per row (a 2,000-row import goes from 2,000 calls to 8).
- A failed batch is retried up to 5 times instead of failing the whole run.
- When it does fail, `SyncBatchError` names the batch and row range, so a rerun can be targeted.
## Stage graph
```mermaid
flowchart TD
S0[S0: Chunk helper] --> S1A[S1A: Batched writer]
S0 --> S1B[S1B: Batch size config]
S1A --> S2[S2: Tests]
S1B --> S2
S2 --> S3[S3: Retry failed batches]
```
## Stage Index
```json stage-index
{
"stages": [
{ "id": "S0", "name": "Chunk helper", "dependsOn": [], "parallelism": "sequential", "files": ["src/util/chunk.ts", "src/util/index.ts"], "model": "haiku" },
{ "id": "S1A", "name": "Batched writer", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/writer.ts"], "model": "sonnet" },
{ "id": "S1B", "name": "Batch size config", "dependsOn": ["S0"], "parallelism": "parallel", "files": ["src/sync/config.ts", ".env.example"], "model": "haiku" },
{ "id": "S2", "name": "Tests", "dependsOn": ["S1A", "S1B"], "parallelism": "sequential", "files": ["src/sync/writer.test.ts", "src/util/chunk.test.ts"], "model": "sonnet" },
{ "id": "S3", "name": "Retry failed batches", "dependsOn": ["S2"], "parallelism": "sequential", "files": ["src/sync/writer.ts", "src/sync/writer.test.ts"], "model": "sonnet" }
]
}
```
## Stage S0: Chunk helper
Add a small pure helper that splits an array into fixed-size chunks.
- [ ] **Action**: Create `chunked(items, size)` returning arrays of at most `size` items; throw on size < 1.
- **Files**: src/util/chunk.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
- [ ] **Action**: Export it from the util barrel.
- **Files**: src/util/index.ts
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S1A: Batched writer
- [ ] **Action**: Replace the per-row insert loop in `writeRows` with `insertMany` over `chunked(rows, BATCH_SIZE)`.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → existing tests pass
## Stage S1B: Batch size config
- [ ] **Action**: Read `SYNC_BATCH_SIZE` (default 250, max 500) and export `BATCH_SIZE`.
- **Files**: src/sync/config.ts, .env.example
- **Verify**: `pnpm tsc --noEmit` → exits 0
## Stage S2: Tests
- [ ] **Action**: Unit-test `chunked` (empty, exact multiple, remainder, size < 1).
- **Files**: src/util/chunk.test.ts
- **Verify**: `pnpm vitest run src/util/chunk.test.ts` → 4 tests pass
- [ ] **Action**: Test that 1,001 rows with batch size 250 make 5 `insertMany` calls.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass
## Stage S3: Retry failed batches
- [ ] **Action**: Retry a failed batch up to 5 times with backoff, then throw `SyncBatchError` naming the batch index.
- **Files**: src/sync/writer.ts
- **Verify**: `pnpm vitest run src/sync` → all pass
- [ ] **Action**: Test retry-then-succeed and retry-exhausted paths.
- **Files**: src/sync/writer.test.ts
- **Verify**: `pnpm vitest run src/sync/writer.test.ts` → all pass, including 2 new tests
- [ ] **Action**: Read the error message a user sees when retries run out.
- **Files**: src/sync/writer.ts
- **Verify (manual)**: the message names the batch, the row range and the last provider error, and contains no credentials
## Execution notes
- **Prerequisites:** base `main`; execution branch `feat/batched-sync`; remote `origin`, so worktree agents detach onto `origin/feat/batched-sync`.
- **Commands:** install `pnpm install --frozen-lockfile`; full check `pnpm lint && pnpm tsc --noEmit && pnpm vitest run && pnpm build`.
- **Commit policy:** one green commit per stage with its boxes ticked, Conventional Commits, never `--no-verify`.
- **Accepted risks:** a run that dies mid-import still leaves earlier batches written; making the import transactional is out of scope.
- **Conventions:** errors extend `AppError` (src/errors.ts); named exports only.
- No observable signals found beyond `SyncBatchError`, which this change introduces.
## Review
Reviewed by a strongest-tier agent. 3 findings: 2 accepted, 1 rejected.
- **Accepted R1:** S2's writer test originally only checked the call count → now also asserts every row is written once.
- **Accepted R2:** `.env.example` was missing from S1B's files → added.
- **Rejected R3:** "make S1A and S1B sequential to be safe" → files are disjoint and `BATCH_SIZE` already exists, so neither creates what the other imports.
scripts/plan-lint.mjs
View this file on GitHub#!/usr/bin/env node
// Checks a plan-and-build plan file against references/plan-format.md.
// Node standard library only.
//
// node plan-lint.mjs <plan.md> lint one plan
// node plan-lint.mjs <plan.md> --check-resume <repo> also compare ticked stages with git log
// node plan-lint.mjs --self-test run the fixtures in ./fixtures
//
// Exit code 1 if there are errors, 0 otherwise (warnings don't fail).
import { readFileSync, readdirSync } from 'node:fs'
import { execFileSync } from 'node:child_process'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
export function lintPlan(text, { resumeLog = null } = {}) {
const findings = []
const error = (code, msg) => findings.push({ level: 'error', code, msg })
const warn = (code, msg) => findings.push({ level: 'warning', code, msg })
if (!/^##\s+Motivation\b/m.test(text)) error('missing-motivation', 'no "## Motivation" section')
if (!/^##\s+Benefits\b/m.test(text)) error('missing-benefits', 'no "## Benefits" section')
if (!/^##\s+Execution notes\b/m.test(text)) error('missing-execution-notes', 'no "## Execution notes" section (prerequisites, commands, commit policy)')
if (!/^##\s+Review\b/m.test(text)) warn('not-reviewed', 'no "## Review" section yet: run the adversarial review before asking for approval')
// Stage graph: a heading followed by a fenced block.
const graphSection = text.match(/^##\s+Stage graph\s*\n+```(\w*)[^\n]*\n([\s\S]*?)\n```/m)
if (!graphSection) error('missing-graph', 'no "## Stage graph" section with a fenced diagram under it')
// Stage index.
const indexBlock = text.match(/```json stage-index\n([\s\S]*?)\n```/)
let stages = null
if (!indexBlock) {
error('missing-index', 'no ```json stage-index block')
} else {
try {
const parsed = JSON.parse(indexBlock[1])
stages = Array.isArray(parsed.stages) ? parsed.stages : null
if (!stages) error('index-shape', 'stage index has no "stages" array')
} catch (e) {
error('index-parse', `stage index is not valid JSON: ${e.message}`)
}
}
// Stage sections.
const headingRe = /^##\s+Stage\s+([^\s:]+):\s*(.+)$/gm
const headings = [...text.matchAll(headingRe)].map((m) => ({ id: m[1], start: m.index }))
const nextH2 = (from) => {
const rest = text.slice(from + 1).search(/^##\s/m)
return rest === -1 ? text.length : from + 1 + rest
}
const sections = headings.map((h) => ({ id: h.id, body: text.slice(h.start, nextH2(h.start)) }))
// Checklist items (checked for every stage section, index or not).
const itemFiles = new Map()
for (const s of sections) {
const files = new Set()
const items = s.body.split(/^(?=- \[[ xX]\] \*\*Action\*\*:)/m).slice(1)
if (items.length === 0) warn('stage-no-items', `stage ${s.id} has no checklist items`)
for (const item of items) {
const label = item.split('\n')[0].replace(/^- \[[ xX]\] \*\*Action\*\*:\s*/, '').slice(0, 50)
const filesLine = item.match(/^\s*- \*\*Files\*\*:\s*(.+)$/m)
const verifyLine = item.match(/^\s*- (\*\*Verify(?: \(manual\))?\*\*:.*)$/m)
if (!filesLine) error('item-missing-files', `${s.id} "${label}": no Files line`)
else for (const f of filesLine[1].split(',')) { const p = f.trim().replace(/^`|`$/g, ''); if (p) files.add(p) }
if (!verifyLine) { error('item-missing-verify', `${s.id} "${label}": no Verify line`); continue }
const v = verifyLine[1]
const command = /^\*\*Verify\*\*:\s*`[^`]+`\s*(→|->)\s*\S/.test(v)
const manual = /^\*\*Verify \(manual\)\*\*:\s*\S/.test(v)
if (!command && !manual) error('verify-form', `${s.id} "${label}": Verify must be \`command\` → expected, or "Verify (manual): ..."`)
}
itemFiles.set(s.id, files)
}
if (!stages) return findings
// Ids: unique, 1:1 with headings.
const ids = stages.map((s) => s.id)
const dupes = ids.filter((id, i) => ids.indexOf(id) !== i)
for (const d of new Set(dupes)) error('duplicate-id', `stage id ${d} appears more than once in the index`)
const headingIds = new Set(headings.map((h) => h.id))
for (const id of ids) if (!headingIds.has(id)) error('id-mismatch', `index stage ${id} has no "## Stage ${id}:" section`)
for (const id of headingIds) if (!ids.includes(id)) error('id-mismatch', `section "## Stage ${id}:" is not in the index`)
const byId = new Map(stages.map((s) => [s.id, s]))
// Fields.
for (const s of stages) {
if (!s.name) error('missing-name', `stage ${s.id}: no name`)
if (!Array.isArray(s.dependsOn)) error('missing-depends', `stage ${s.id}: dependsOn must be an array`)
if (s.parallelism !== 'parallel' && s.parallelism !== 'sequential') error('parallelism-value', `stage ${s.id}: parallelism must be "parallel" or "sequential"`)
if (!Array.isArray(s.files) || s.files.length === 0) error('missing-files', `stage ${s.id}: files must be a non-empty array`)
if (typeof s.model !== 'string' || !s.model.trim()) error('missing-model', `stage ${s.id}: no model tier`)
else if (/\d{8}|\d{4}-\d{2}-\d{2}|^claude-/i.test(s.model)) error('dated-model', `stage ${s.id}: model "${s.model}" looks like a dated model ID; use a tier name`)
for (const d of s.dependsOn ?? []) if (!byId.has(d)) error('unknown-dependency', `stage ${s.id} depends on unknown stage ${d}`)
}
// Cycles, and ancestor sets for the overlap check.
const ancestors = new Map()
let cyclic = false
const visiting = new Set()
const ancestorsOf = (id, path = []) => {
if (ancestors.has(id)) return ancestors.get(id)
if (visiting.has(id)) { if (!cyclic) error('cycle', `dependency cycle: ${[...path, id].join(' → ')}`); cyclic = true; return new Set() }
visiting.add(id)
const acc = new Set()
for (const d of byId.get(id)?.dependsOn ?? []) {
if (!byId.has(d)) continue
acc.add(d)
for (const a of ancestorsOf(d, [...path, id])) acc.add(a)
}
visiting.delete(id)
ancestors.set(id, acc)
return acc
}
for (const s of stages) ancestorsOf(s.id)
// Parallel stages that could run together must not share files.
if (!cyclic) {
const par = stages.filter((s) => s.parallelism === 'parallel')
for (let i = 0; i < par.length; i++) {
for (let j = i + 1; j < par.length; j++) {
const a = par[i], b = par[j]
if (ancestors.get(a.id).has(b.id) || ancestors.get(b.id).has(a.id)) continue
const shared = (a.files ?? []).filter((f) => (b.files ?? []).includes(f))
if (shared.length) error('parallel-overlap', `parallel stages ${a.id} and ${b.id} can run together but share: ${shared.join(', ')}`)
}
}
}
// Index files must equal the union of the stage's item files.
for (const s of stages) {
const fromItems = itemFiles.get(s.id)
if (!fromItems) continue
const declared = new Set(s.files ?? [])
const extra = [...fromItems].filter((f) => !declared.has(f))
const unused = [...declared].filter((f) => !fromItems.has(f))
if (extra.length) error('files-mismatch', `stage ${s.id}: checklist touches files not in the index: ${extra.join(', ')}`)
if (unused.length) error('files-mismatch', `stage ${s.id}: index lists files no checklist item touches: ${unused.join(', ')}`)
}
// Mermaid edges must match dependsOn.
if (graphSection && graphSection[1] === 'mermaid') {
const body = graphSection[2]
if (!/^\s*(flowchart|graph)\s+TD\b/m.test(body)) warn('graph-direction', 'Mermaid graph should be "flowchart TD"')
const edges = new Set()
for (const line of body.split('\n')) {
if (!line.includes('-->')) continue
// "A[label] --> B[label] --> C": take the node id at the start of each segment.
const parts = line.split('-->').map((p) => p.trim().replace(/^\|[^|]*\|\s*/, '').match(/^([A-Za-z][\w-]*)/)?.[1])
for (let k = 0; k + 1 < parts.length; k++) {
if (byId.has(parts[k]) && byId.has(parts[k + 1])) edges.add(`${parts[k]}->${parts[k + 1]}`)
}
}
const expected = new Set(stages.flatMap((s) => (s.dependsOn ?? []).map((d) => `${d}->${s.id}`)))
for (const e of expected) if (!edges.has(e)) error('graph-mismatch', `index says ${e.replace('->', ' → ')} but the Mermaid graph has no such edge`)
for (const e of edges) if (!expected.has(e)) error('graph-mismatch', `Mermaid graph has ${e.replace('->', ' → ')} but the index has no such dependency`)
} else if (graphSection) {
warn('graph-not-checked', 'stage graph is not Mermaid, so its edges were not checked against the index')
}
// Resume check: ticked stages should have a commit, committed stages should be ticked.
if (resumeLog !== null) {
for (const s of sections) {
const boxes = [...s.body.matchAll(/^- \[([ xX])\] \*\*Action\*\*/gm)].map((m) => m[1] !== ' ')
if (!boxes.length) continue
const inLog = new RegExp(`\\b${s.id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`).test(resumeLog)
if (boxes.every(Boolean) && !inLog) warn('resume-ticked-uncommitted', `stage ${s.id} is ticked but no commit message mentions ${s.id}`)
if (!boxes.some(Boolean) && inLog) warn('resume-committed-unticked', `a commit mentions ${s.id} but its boxes are unticked`)
if (boxes.some(Boolean) && !boxes.every(Boolean)) warn('resume-partial', `stage ${s.id} is partly ticked; stages are ticked all at once on commit`)
}
}
return findings
}
function report(findings) {
for (const f of findings) console.log(`[${f.level.toUpperCase()}] ${f.code}: ${f.msg}`)
const errors = findings.filter((f) => f.level === 'error').length
console.log(`plan-lint: ${errors} error(s), ${findings.length - errors} warning(s)`)
return errors
}
function selfTest() {
// good*.md must have no errors; bad-<code>.md must report an error with that code.
const dir = join(dirname(fileURLToPath(import.meta.url)), 'fixtures')
let failed = 0
for (const name of readdirSync(dir).filter((n) => n.endsWith('.md')).sort()) {
const findings = lintPlan(readFileSync(join(dir, name), 'utf8'))
const codes = findings.filter((f) => f.level === 'error').map((f) => f.code)
const expected = name.match(/^bad-(.+)\.md$/)?.[1]
const ok = expected ? codes.includes(expected) : codes.length === 0
console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${ok ? '' : ` (errors: ${codes.join(', ') || 'none'})`}`)
if (!ok) failed++
}
console.log(failed ? `${failed} fixture(s) failed` : 'all fixtures passed')
return failed
}
const isMain = process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]
if (isMain) {
const args = process.argv.slice(2)
if (args[0] === '--self-test') process.exit(selfTest() ? 1 : 0)
const planPath = args[0]
if (!planPath) { console.error('usage: plan-lint.mjs <plan.md> [--check-resume <repo>] | --self-test'); process.exit(2) }
let text
try { text = readFileSync(planPath, 'utf8') } catch (e) { console.error(`plan-lint: cannot read ${planPath}: ${e.message}`); process.exit(2) }
const r = args.indexOf('--check-resume')
let resumeLog = null
if (r !== -1) {
try { resumeLog = execFileSync('git', ['-C', args[r + 1] ?? '.', 'log', '--format=%s'], { encoding: 'utf8' }) }
catch (e) { console.error(`plan-lint: git log failed: ${e.message}`); process.exit(2) }
}
process.exit(report(lintPlan(text, { resumeLog })) ? 1 : 0)
}