jig-plan 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,96 @@
1
+ // Parse a jig PLAN.md into a plain object. No dependencies.
2
+
3
+ export const STATUSES = ['draft', 'approved', 'building', 'shipped', 'abandoned'];
4
+ export const TIERS = ['brief', 'full', 'program'];
5
+ export const SLICE_STATES = ['todo', 'doing', 'done', 'dropped'];
6
+ export const SECTIONS = ['Outcome', 'Decisions', 'Out of scope', 'Questions', 'Assumptions', 'Slices', 'Log'];
7
+
8
+ const SLICE_RE = /^###\s+(S\d+):\s*(.*?)\s*(?:\[([a-z]+)\])?\s*$/;
9
+
10
+ export function parsePlan(text) {
11
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
12
+ const plan = { lines, title: null, header: null, headerLine: -1, now: null, nowLine: -1, sections: [], slices: [] };
13
+
14
+ const titleIdx = lines.findIndex((l) => /^#\s+\S/.test(l));
15
+ if (titleIdx !== -1) plan.title = lines[titleIdx].replace(/^#\s+/, '').trim();
16
+
17
+ for (let i = 0; i < Math.min(lines.length, (titleIdx === -1 ? 0 : titleIdx) + 6); i++) {
18
+ if (plan.headerLine === -1 && /^Status:/.test(lines[i])) {
19
+ plan.headerLine = i;
20
+ plan.header = {};
21
+ for (const part of lines[i].split(/\s+·\s+/)) {
22
+ const m = part.match(/^([A-Za-z]+):\s*(.*)$/);
23
+ if (m) plan.header[m[1].toLowerCase()] = m[2].trim();
24
+ }
25
+ }
26
+ if (plan.nowLine === -1 && /^Now:/.test(lines[i])) {
27
+ plan.nowLine = i;
28
+ plan.now = lines[i].replace(/^Now:\s*/, '').trim();
29
+ }
30
+ }
31
+
32
+ lines.forEach((l, i) => {
33
+ const m = l.match(/^##\s+(.+?)\s*$/);
34
+ if (m && !l.startsWith('###')) plan.sections.push({ name: m[1], start: i });
35
+ });
36
+ plan.sections.forEach((s, k) => {
37
+ s.end = k + 1 < plan.sections.length ? plan.sections[k + 1].start : lines.length;
38
+ s.body = lines.slice(s.start + 1, s.end);
39
+ });
40
+
41
+ const slicesSec = section(plan, 'Slices');
42
+ if (slicesSec) {
43
+ let cur = null;
44
+ for (let i = slicesSec.start + 1; i < slicesSec.end; i++) {
45
+ const l = lines[i];
46
+ if (l.startsWith('###')) {
47
+ const m = l.match(SLICE_RE);
48
+ cur = { line: i, raw: l, id: m?.[1] ?? null, title: m?.[2] ?? '', state: m?.[3] ?? null, fields: {}, risks: [] };
49
+ plan.slices.push(cur);
50
+ continue;
51
+ }
52
+ if (!cur) continue;
53
+ const f = l.match(/^(Goal|Touch|Checks|Plan):\s*(.*)$/);
54
+ if (f) cur.fields[f[1].toLowerCase()] = { value: f[2].trim(), line: i };
55
+ const r = l.match(/^\s*-\s*Risk:\s*(.*)$/);
56
+ if (r) cur.risks.push({ text: r[1], line: i });
57
+ }
58
+ }
59
+ return plan;
60
+ }
61
+
62
+ export function section(plan, name) {
63
+ return plan.sections.find((s) => s.name.toLowerCase() === name.toLowerCase()) ?? null;
64
+ }
65
+
66
+ // Lines from the title to just before "## Slices": the part the owner approves.
67
+ export function humanLayer(plan) {
68
+ const s = section(plan, 'Slices');
69
+ return plan.lines.slice(0, s ? s.start : plan.lines.length);
70
+ }
71
+
72
+ // Paths in backticks, e.g. `src/a.ts (new)` or `src/a.ts` (new).
73
+ export function touchPaths(value) {
74
+ const out = [];
75
+ const re = /`([^`]+)`(\s*\(new\))?/g;
76
+ let m;
77
+ while ((m = re.exec(value))) {
78
+ let p = m[1].trim();
79
+ let isNew = Boolean(m[2]);
80
+ const inner = p.match(/^(.*?)\s*\(new\)$/);
81
+ if (inner) { p = inner[1]; isNew = true; }
82
+ out.push({ path: p, isNew });
83
+ }
84
+ return out;
85
+ }
86
+
87
+ export function checkIds(value) {
88
+ const stripped = value.replace(/`[^`]*`/g, '');
89
+ return stripped.split(/[,\s]+/).map((s) => s.trim()).filter((s) => /^[A-Za-z][\w.-]*$/.test(s));
90
+ }
91
+
92
+ export function logEntries(plan) {
93
+ const s = section(plan, 'Log');
94
+ if (!s) return [];
95
+ return s.body.filter((l) => /^\s*-\s/.test(l)).map((l) => l.trim());
96
+ }
@@ -0,0 +1,66 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { headSha } from './git.mjs';
4
+ import { TIERS } from './plan.mjs';
5
+
6
+ export function today() {
7
+ const d = new Date();
8
+ const p = (n) => String(n).padStart(2, '0');
9
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
10
+ }
11
+
12
+ export function planTemplate({ title, tier, baseline, date }) {
13
+ const sliceBody = tier === 'program'
14
+ ? 'Goal: <what this phase makes true>\nPlan: `docs/plans/<child>/PLAN.md`\n'
15
+ : 'Goal: <what is true when this slice is done>\nTouch: `<path>`, `<new path> (new)`\nChecks: ' + (tier === 'brief' ? '`<command>`' : 'C1') + '\n- Risk: <what could go wrong>. Detect: <how you would notice>. Fallback: <what you do then>.\n';
16
+ return `# ${title}
17
+
18
+ Status: draft · Tier: ${tier} · Baseline: ${baseline} · Updated: ${date}
19
+ Now: drafting.
20
+
21
+ ## Outcome
22
+ <One to three sentences: what is true for the user when this is done.>
23
+ Done when:
24
+ - \`<command>\` <expected result>
25
+
26
+ ## Decisions
27
+ - <Decision>. Reason: <why>.
28
+
29
+ ## Out of scope
30
+ - <Only what a reader would otherwise assume is included.>
31
+
32
+ ## Questions
33
+ - None.
34
+
35
+ ## Assumptions
36
+ - <What you decided without asking.>
37
+
38
+ ## Slices
39
+
40
+ ### S1: <title> [todo]
41
+ ${sliceBody}
42
+ ## Log
43
+ - ${date}: Plan started at ${baseline}.
44
+ `;
45
+ }
46
+
47
+ export function checksTemplate() {
48
+ return JSON.stringify({ version: 1, checks: [{ id: 'C1', slice: 'S1', kind: 'acceptance', cmd: '<command>', expect: { exit: 0 }, timeout_s: 60, fast: true, protects: [] }] }, null, 2) + '\n';
49
+ }
50
+
51
+ export function newPlan(root, slug, { tier = 'brief', title, dir = 'docs/plans' } = {}) {
52
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) throw new Error('slug must be lowercase kebab-case');
53
+ if (!TIERS.includes(tier)) throw new Error(`tier must be one of ${TIERS.join(', ')}`);
54
+ const planDir = join(root, dir, slug);
55
+ const planPath = join(planDir, 'PLAN.md');
56
+ if (existsSync(planPath)) throw new Error(`${join(dir, slug, 'PLAN.md')} already exists`);
57
+ mkdirSync(planDir, { recursive: true });
58
+ const baseline = headSha(root) ?? 'none';
59
+ writeFileSync(planPath, planTemplate({ title: title ?? slug, tier, baseline, date: today() }));
60
+ const written = [planPath];
61
+ if (tier === 'full') {
62
+ writeFileSync(join(planDir, 'checks.json'), checksTemplate());
63
+ written.push(join(planDir, 'checks.json'));
64
+ }
65
+ return written;
66
+ }
@@ -0,0 +1,76 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { join, relative, normalize, isAbsolute } from 'node:path';
3
+ import { parsePlan, touchPaths } from './plan.mjs';
4
+
5
+ const ACTIVE = ['approved', 'building'];
6
+
7
+ // Where this repo keeps plans. `.jig.json` {"plansDir": "..."} wins; else an
8
+ // existing docs/plans/ or docs/plan/ (the repo's convention); else docs/plans/.
9
+ export function plansDir(root) {
10
+ try {
11
+ const cfg = JSON.parse(readFileSync(join(root, '.jig.json'), 'utf8'));
12
+ if (typeof cfg.plansDir === 'string' && cfg.plansDir.trim()) {
13
+ // .jig.json comes from the repo, so it may not point outside it or at a
14
+ // source tree: the edit hook exempts this directory from scope checks.
15
+ const d = normalize(cfg.plansDir.trim()).replace(/\/+$/, '');
16
+ if (!isAbsolute(d) && !d.split('/').includes('..') && d !== '.' && /plan/i.test(d.split('/').pop())) return d;
17
+ process.stderr.write(`jig: ignoring .jig.json plansDir "${cfg.plansDir}" (must be a relative folder inside the repo whose name contains "plan")\n`);
18
+ }
19
+ } catch (e) {
20
+ if (e.code !== 'ENOENT') process.stderr.write(`jig: ignoring unreadable .jig.json (${e.message})\n`);
21
+ }
22
+ for (const d of ['docs/plans', 'docs/plan']) if (existsSync(join(root, d)) && statSync(join(root, d)).isDirectory()) return d;
23
+ return 'docs/plans';
24
+ }
25
+
26
+ // PLAN.md files one level under the plans directory, plus docs/PLAN.md (the
27
+ // convention in older repos). Bounded: no recursive walk.
28
+ export function findPlans(root) {
29
+ const found = [];
30
+ const seen = new Set();
31
+ const add = (p) => { if (!seen.has(p) && existsSync(p) && statSync(p).isFile()) { seen.add(p); found.push(p); } };
32
+ for (const d of new Set([plansDir(root), 'docs/plans', 'docs/plan'])) {
33
+ const base = join(root, d);
34
+ if (!existsSync(base) || !statSync(base).isDirectory()) continue;
35
+ for (const n of readdirSync(base)) add(join(base, n, 'PLAN.md'));
36
+ }
37
+ add(join(root, 'docs', 'PLAN.md'));
38
+ return found;
39
+ }
40
+
41
+ export function readPlan(path) {
42
+ return parsePlan(readFileSync(path, 'utf8'));
43
+ }
44
+
45
+ export function activePlans(root) {
46
+ return findPlans(root)
47
+ .map((path) => ({ path, plan: readPlan(path) }))
48
+ .filter(({ plan }) => ACTIVE.includes(plan.header?.status?.toLowerCase()));
49
+ }
50
+
51
+ export function doingSlice(plan) {
52
+ return plan.slices.find((s) => s.state === 'doing') ?? null;
53
+ }
54
+
55
+ export function sliceTouch(slice) {
56
+ return slice?.fields.touch ? touchPaths(slice.fields.touch.value).map((t) => t.path) : [];
57
+ }
58
+
59
+ // A few lines per active plan; used by `jig status` and the SessionStart hook.
60
+ export function statusSummary(root, { max = 3 } = {}) {
61
+ const plans = activePlans(root).slice(0, max);
62
+ return plans.map(({ path, plan }) => {
63
+ const rel = relative(root, path);
64
+ const counts = { todo: 0, doing: 0, done: 0, dropped: 0 };
65
+ for (const s of plan.slices) if (s.state in counts) counts[s.state]++;
66
+ const cur = doingSlice(plan);
67
+ const next = plan.slices.find((s) => s.state === 'todo');
68
+ const lines = [
69
+ `${plan.title ?? rel} (${rel}) · ${plan.header.status} · ${counts.done}/${plan.slices.length - counts.dropped} slices done`,
70
+ ` Now: ${plan.now ?? '(no Now line)'}`,
71
+ ];
72
+ if (cur) lines.push(` Doing: ${cur.id} ${cur.title}${sliceTouch(cur).length ? ` · touch: ${sliceTouch(cur).join(', ')}` : ''}`);
73
+ else if (next) lines.push(` Next: ${next.id} ${next.title}`);
74
+ return lines.join('\n');
75
+ });
76
+ }
@@ -0,0 +1,70 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { appendFileSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
3
+ import { join, relative } from 'node:path';
4
+ import { loadChecks } from './checks.mjs';
5
+ import { parsePlan, section } from './plan.mjs';
6
+ import { stateDir } from './git.mjs';
7
+ import { today } from './scaffold.mjs';
8
+
9
+ function lastLine(s) {
10
+ const lines = (s ?? '').split('\n').map((l) => l.trim()).filter(Boolean);
11
+ return lines.length ? lines[lines.length - 1].slice(0, 200) : '';
12
+ }
13
+
14
+ export function runCheck(root, c) {
15
+ const t0 = Date.now();
16
+ const r = spawnSync(c.cmd, { cwd: root, shell: true, encoding: 'utf8', timeout: (c.timeout_s ?? 60) * 1000, maxBuffer: 32 * 1024 * 1024 });
17
+ const ms = Date.now() - t0;
18
+ const want = c.expect?.exit ?? 0;
19
+ const out = `${r.stdout ?? ''}\n${r.stderr ?? ''}`;
20
+ let pass = !r.error && r.status === want;
21
+ let why = '';
22
+ if (r.error?.code === 'ETIMEDOUT' || r.signal === 'SIGTERM') { pass = false; why = `timed out after ${c.timeout_s}s`; }
23
+ else if (r.error) { pass = false; why = r.error.message; }
24
+ else if (r.status !== want) why = `exit ${r.status} (expected ${want}): ${lastLine(r.stderr) || lastLine(r.stdout)}`;
25
+ if (pass && c.expect?.stdout && !new RegExp(c.expect.stdout, 'm').test(out)) { pass = false; why = `output did not match /${c.expect.stdout}/`; }
26
+ return { id: c.id, slice: c.slice, cmd: c.cmd, pass, exit: r.status, ms, why, evidence: pass ? lastLine(r.stdout) : why };
27
+ }
28
+
29
+ export function selectChecks(checks, { slice = null, fast = false, ids = null } = {}) {
30
+ return checks.filter((c) => (!slice || c.slice === slice) && (!fast || c.fast === true) && (!ids || ids.includes(c.id)));
31
+ }
32
+
33
+ export function verifyPlan(root, planPath, opts = {}) {
34
+ const loaded = loadChecks(planPath);
35
+ if (!loaded.exists) return { error: `no checks.json beside ${relative(root, planPath)}` };
36
+ if (loaded.error) return { error: `checks.json: ${loaded.error}` };
37
+ const chosen = selectChecks(loaded.data.checks ?? [], opts);
38
+ const results = chosen.map((c) => runCheck(root, c));
39
+ const record = { t: Date.now(), plan: relative(root, planPath), slice: opts.slice ?? null, fast: Boolean(opts.fast), results: results.map(({ id, pass, exit, ms }) => ({ id, pass, exit, ms })) };
40
+ appendFileSync(join(stateDir(root), 'evidence.jsonl'), JSON.stringify(record) + '\n');
41
+ if (opts.record && results.length) appendLog(planPath, logLine(results, opts.slice));
42
+ return { results };
43
+ }
44
+
45
+ export function logLine(results, slice) {
46
+ const now = new Date();
47
+ const hm = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
48
+ const parts = results.map((r) => (r.pass ? `${r.id} pass` : `${r.id} FAIL (${r.why})`));
49
+ return `- ${today()} ${hm}: jig verify${slice ? ` ${slice}` : ''}: ${parts.join('; ')}`;
50
+ }
51
+
52
+ // Append under ## Log (which is the last section by the format rules).
53
+ export function appendLog(planPath, line) {
54
+ const text = readFileSync(planPath, 'utf8');
55
+ const plan = parsePlan(text);
56
+ const log = section(plan, 'Log');
57
+ if (!log) { writeFileSync(planPath, text.replace(/\s*$/, '\n\n## Log\n' + line + '\n')); return; }
58
+ const lines = plan.lines;
59
+ let end = log.end;
60
+ while (end > log.start + 1 && lines[end - 1].trim() === '') end--;
61
+ lines.splice(end, 0, line);
62
+ writeFileSync(planPath, lines.join('\n').replace(/\n*$/, '\n'));
63
+ }
64
+
65
+ export function lastEvidence(root) {
66
+ const p = join(stateDir(root), 'evidence.jsonl');
67
+ if (!existsSync(p)) return null;
68
+ const lines = readFileSync(p, 'utf8').trim().split('\n').filter(Boolean);
69
+ try { return lines.length ? JSON.parse(lines[lines.length - 1]) : null; } catch { return null; }
70
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "description": "jig guardrails: plan nudge and status at session start, protected acceptance tests and out-of-scope edits, package installs, and verification before stopping.",
3
+ "hooks": {
4
+ "SessionStart": [
5
+ { "matcher": "startup|resume|clear|compact", "hooks": [ { "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/cli/jig.mjs\" hook session-start", "timeout": 10 } ] }
6
+ ],
7
+ "PreToolUse": [
8
+ { "matcher": "Edit|Write|MultiEdit|NotebookEdit", "hooks": [ { "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/cli/jig.mjs\" hook pre-edit", "timeout": 10 } ] },
9
+ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/cli/jig.mjs\" hook pre-bash", "timeout": 10 } ] }
10
+ ],
11
+ "Stop": [
12
+ { "hooks": [ { "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/cli/jig.mjs\" hook stop", "timeout": 10 } ] }
13
+ ]
14
+ }
15
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "jig-plan",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.0",
4
+ "description": "Plan, verify and guard work done by coding agents: short reviewable plans, executable acceptance checks, and hooks that stop false completion claims.",
5
+ "type": "module",
6
+ "bin": {
7
+ "jig": "cli/jig.mjs"
8
+ },
9
+ "files": [
10
+ "cli",
11
+ "references",
12
+ "skills",
13
+ "agents",
14
+ "hooks",
15
+ "bin",
16
+ ".claude-plugin",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "engines": {
21
+ "node": ">=20"
22
+ },
23
+ "scripts": {
24
+ "test": "node --test test/*.test.mjs"
25
+ },
26
+ "license": "MIT",
27
+ "author": "Ashwin Sathian (https://ashwinsathian.com/)",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/AshwinSathian/jig.git"
31
+ },
32
+ "homepage": "https://github.com/AshwinSathian/jig#readme",
33
+ "bugs": {
34
+ "url": "https://github.com/AshwinSathian/jig/issues"
35
+ }
36
+ }
@@ -0,0 +1,18 @@
1
+ # How AI-written code fails, and the plan field that catches it
2
+
3
+ Use this list when choosing checks for a slice. Pick only the rows that apply, and don't add a check for a failure the slice can't have. Figures were checked against their sources on 2026-11-25; see `docs/research/2026-11-adversarial-review.md`.
4
+
5
+ | Failure | What it looks like | What to put in the plan |
6
+ |---|---|---|
7
+ | Tests that mirror the code | A green suite that asserts what the code does, not what it should do | Write acceptance checks from the spec **before** the code and list their files under `protects`. At the full tier, add a `mutation` check on core logic (Stryker for JS/TS, mutmut for Python, cargo-mutants for Rust) |
8
+ | Test tampering | The agent edits or deletes a test to make it pass. Prompting barely stops this (METR 2025; ImpossibleBench) | `protects` in checks.json; the edit hook asks first. The build skill stops and reports when a test conflicts with the spec |
9
+ | Swallowed errors | Empty or broad `catch`, fallbacks that hide failure. GitClear 2026: error-masking constructs up 47% | Name the error paths in the slice Goal. A lint rule against empty catch (doctor reports a missing one). The diff reviewer reads every catch block |
10
+ | Duplication over reuse | A new helper where one already exists. GitClear 2026: duplicated blocks up 81% | Survey first. Decisions name what is reused. The reviewer greps for near-duplicates of each new function |
11
+ | Invented packages and APIs | Imports of packages or methods that don't exist. 43% of hallucinated package names recur in every re-run (Spracklen et al., USENIX Security 2025), so attackers register them | A new dependency is a one-way door. Name it, its registry URL, age and maintainer in Decisions. The Bash hook asks on installs. Type-check and run the code |
12
+ | Plausible wrong logic | Reads correctly but mishandles a domain rule. CodeRabbit 2025: logic issues 75% more common in AI PRs | Worked examples from the spec as acceptance checks. A `property` check (fast-check, Hypothesis, proptest) where the rule has an invariant |
13
+ | Insecure defaults | XSS, weak password handling, missing authorization on a new route | Read `security.md` when a slice touches auth, input, secrets or dependencies. Add a `security` check (a test that the route rejects an unauthenticated call). Flag auth paths for a human to read |
14
+ | Performance blind spots | Queries in loops, excessive I/O (CodeRabbit: about 8x more common in AI PRs), quadratic scans | Agents don't measure unless a check makes them. Add a `perf` check with a threshold when a slice touches a hot path or a list that grows |
15
+ | Scope creep | Extra abstractions, edits to unrelated files | `Touch:` per slice. Each slice stays reviewable in one sitting |
16
+ | False completion claims | "Tests pass" without running them. Replit's agent told its user rollback was impossible; it wasn't | Completion is the `jig verify --record` line in the Log, not a sentence. The Stop hook asks for evidence when files changed after the last verify |
17
+ | Context rot | Quality drops late in long sessions | One slice per session. The plan's `Now:` line and Log are the memory, and subagents do investigation |
18
+ | Destructive action in the wrong environment | Replit deleted a production database during a freeze it had been told about | Production and data changes are one-way doors. A freeze is enforced by permissions and credentials; the plan never claims a prompt enforces it |
@@ -0,0 +1,58 @@
1
+ # Engineering fundamentals, by what the change touches
2
+
3
+ Read only the sections for areas the slice touches. Each question either has an answer you can write into the plan (a decision, a check, or a risk with Detect and Fallback), or it doesn't apply. Don't paste these questions into the plan.
4
+
5
+ ## Algorithms and data structures
6
+ - What is n today, and what is it in a year? Is any loop over n inside another loop over n?
7
+ - Is the structure right for the access pattern: a map for lookups, a set for membership, a heap for top-k?
8
+ - Where are the boundaries: empty input, one element, the maximum, off-by-one at page or window edges?
9
+
10
+ ## Concurrency and async
11
+ - What happens if this runs twice at once? If it runs twice in a row (idempotency)?
12
+ - Is concurrency bounded: pool sizes, `Promise.all` over user-sized lists, goroutines per request?
13
+ - What shared state is there, and what guards it? Is every await or lock released on the error path?
14
+ - Can a retry or a timeout leave work half-done?
15
+
16
+ ## Databases
17
+ - Which queries does the change add, and which index serves each one? Run `EXPLAIN` on anything new against realistic data.
18
+ - Is there a query inside a loop? Batch it or join.
19
+ - Key design for NoSQL stores (Mongo, Dynamo): what is the partition key, does traffic spread across it, and can a hot tenant create a hot partition? This is a one-way door.
20
+ - Migrations: is it reversible, does it lock a large table, and can old and new code run against it at the same time (expand and contract)? See `safe-change.md`.
21
+
22
+ ## Networking and the OS
23
+ - Does every outbound call have a timeout, and is the retry bounded and backed off with jitter?
24
+ - Are connections pooled and released? What about file descriptors under load?
25
+ - TLS verification, DNS caching, proxy settings: does the change assume any of them?
26
+
27
+ ## Performance
28
+ - Which path is hot? Measure before and after with a command that goes in checks.json as a `perf` check with a threshold.
29
+ - What does the change allocate per request? What grows without bound (caches, queues, logs)?
30
+
31
+ ## Distributed systems
32
+ - What happens on partial failure: the write succeeds and the ack is lost, or one of two services is down?
33
+ - Is there an "exactly once" assumption? The usual answer is at-least-once delivery plus idempotent handling.
34
+ - Can a retry storm happen: clients retrying in lockstep, or retries multiplying through layers?
35
+ - Is ordering assumed anywhere it isn't guaranteed?
36
+
37
+ ## Software design
38
+ - Does the change deepen an existing module or add a shallow one: a wrapper that passes calls through, or an interface with one implementation?
39
+ - Agents optimize locally. Does the change respect the boundaries and invariants the repo already has? Look for ADRs and module owners.
40
+ - Could this be done by deleting or changing something that exists instead of adding?
41
+
42
+ ## LLM and agent features
43
+ - What does each step actually need in context? Name what gets dropped, cleared or moved into a subagent, and at what point.
44
+ - Is the prompt ordered static first, dynamic last (tools, then system, then messages)? Caching is a prefix match, so a change at any position invalidates everything after it.
45
+ - Silent cache invalidators:
46
+ - a timestamp, user name or request ID in the system prompt
47
+ - unsorted JSON in tool definitions
48
+ - tools added or removed mid-session
49
+ - a model switch
50
+ - a change to thinking or effort settings
51
+
52
+ Add a check that reads `usage.cache_read_input_tokens` across two identical-prefix requests and fails at zero.
53
+ - Do history edits conflict with caching? Pruning or rewriting earlier turns invalidates the cache from that point, and on current Claude models it drops later thinking blocks. Clear in large batches at a threshold, or start a fresh context at a natural boundary.
54
+ - What is the cost and latency per **completed task**, not per request? Add a `perf` check with a threshold on a fixed task set, and re-run it before changing model, effort or prompt.
55
+ - Untrusted text reaches the model (user input, documents, web pages, tool output). Read `security.md`, starting with the lethal trifecta.
56
+
57
+ ## Security
58
+ Read `security.md`.
@@ -0,0 +1,22 @@
1
+ # Match the need to the mechanism
2
+
3
+ Prose instructions are advisory, and models follow them less as they pile up (IFScale, arXiv 2507.11538). Claude Code's own guidance is that a rule that can't bend should be a hook. Use this table when a plan has a requirement that must keep holding after the plan is done, and in the guard skill when a correction repeats.
4
+
5
+ | Need | Mechanism | Why |
6
+ |---|---|---|
7
+ | A rule that must always hold ("never edit migrations", "no prod credentials") | Permission deny rule, or a PreToolUse hook | Deterministic: it runs whether or not the model remembers it |
8
+ | A behaviour that must be true of the code | A test, type or lint rule, run in CI | Fails the build instead of relying on review |
9
+ | A convention or non-obvious fact (build command, a trap in this repo) | One line in CLAUDE.md or AGENTS.md | Advisory and cheap. Only write what isn't already in the repo; generated context files raised cost 20–23% with no significant gain (Gloaguen et al., arXiv 2602.11988) |
10
+ | A procedure used now and then | A skill | Loaded only when needed, so it costs nothing the rest of the time |
11
+ | Investigation, or parallel work | A subagent, or one agent per git worktree split along module boundaries | Keeps searches and logs out of the main context and avoids merge conflicts |
12
+ | Access to an outside system | An MCP server, pinned, with a read-only token where possible | Each server widens what an injected instruction can reach |
13
+
14
+ ## The second-time rule
15
+
16
+ The first time the agent makes a mistake, fix it. The second time it makes the same mistake, add a mechanism from the top three rows, and note it in the plan Log. The guard skill does this.
17
+
18
+ ## Choosing between rows
19
+
20
+ - If a check can decide it, use a test, lint rule or type. Prose is the last resort.
21
+ - If it must hold during the agent's work, not only in CI, use a hook.
22
+ - If the cost of being wrong is high and the rule has exceptions, use a hook that asks (`permissionDecision: ask`) rather than one that denies, so a person decides each case.
@@ -0,0 +1,146 @@
1
+ # jig plan format
2
+
3
+ `jig lint` enforces everything on this page. Rule IDs are in brackets.
4
+
5
+ ## Where plans live
6
+
7
+ `<plans dir>/<slug>/PLAN.md`, with `checks.json` beside it at the full and program tiers. The plans directory is `plansDir` from `.jig.json` if set, otherwise an existing `docs/plans/` or `docs/plan/`, otherwise `docs/plans/`. `jig status` prints which one it uses. Start a plan with `jig new <slug> --tier brief|full|program --title "..."`, which picks that directory and fills in the baseline commit and date.
8
+
9
+ ## Layout
10
+
11
+ ```markdown
12
+ # CSV export for reports
13
+
14
+ Status: draft · Tier: full · Baseline: 3f2a91c · Updated: 2026-11-25
15
+ Now: drafting. Next: owner review.
16
+
17
+ ## Outcome
18
+ Users download the filtered report as CSV, streamed, for reports up to 100k rows.
19
+ Done when:
20
+ - `npm test -- export` passes (C1, C2)
21
+ - `node scripts/export-load.mjs 100000` finishes under 30 s (C3)
22
+
23
+ ## Decisions
24
+ - [one-way] Stream from the server, not build in the browser. Reason: 100k rows don't fit in browser memory. Decided: owner 2026-11-25
25
+ - Use the existing `csvStringify` in `src/lib/csv.ts`. Reason: it already handles escaping.
26
+
27
+ ## Out of scope
28
+ - Excel output. A reader could assume "export" includes it.
29
+
30
+ ## Questions
31
+ - None.
32
+
33
+ ## Assumptions
34
+ - 100k rows is the ceiling (from the ticket).
35
+
36
+ ## Slices
37
+
38
+ ### S1: Export endpoint streams CSV [todo]
39
+ Goal: POST /api/reports/export returns text/csv for the current filters.
40
+ Touch: `src/api/reports/export.ts (new)`, `src/db/queries/reports.ts`
41
+ Checks: C1, C2
42
+ - Risk: the cursor query skips rows at page boundaries. Detect: C2 compares row counts with the report query. Fallback: switch to keyset pagination on `id`.
43
+
44
+ ## Log
45
+ - 2026-11-25: Plan drafted from ticket #212.
46
+ ```
47
+
48
+ ## Header
49
+
50
+ - Line 1 is `# <title>` [J01].
51
+ - The Status line comes within the next few lines, with fields separated by ` · ` [J02]:
52
+ - `Status`: one of `draft`, `approved`, `building`, `shipped` or `abandoned`.
53
+ - `Tier`: one of `brief`, `full` or `program`. Tier 0 plans live only in chat and never get a file.
54
+ - `Baseline`: the commit the plan was written against.
55
+ - `Updated`: a date.
56
+ - The `Now:` line says where things stand in one line. A resuming session reads this first [J03]. A slice ID it names must exist [J18].
57
+
58
+ ## Sections
59
+
60
+ The sections are, in this order [J04]: Outcome, Decisions, Out of scope, Questions, Assumptions, Slices, Log. Everything before `## Slices` is the **human layer**, the part the owner approves. Slices and Log are the **agent layer**.
61
+
62
+ - **Outcome** needs a `Done when:` list in which each item names a command in backticks or a check ID [J05].
63
+ - **Decisions**: every item gives a `Reason:` [J14]. Mark one-way doors `[one-way]`. Once the status is past `draft`, every one-way item also needs `Decided: <who> <date>` [J14]. One-way doors are:
64
+ - schema and partition-key design
65
+ - public API contracts
66
+ - the auth model
67
+ - data deletion
68
+ - production or infrastructure changes
69
+ - new runtime dependencies
70
+ - scope changes
71
+ - **Out of scope**: list an item only when a reader would otherwise assume it's included. No minimum count.
72
+ - **Questions**: only what the human has to answer. Write `None.` if there are none.
73
+ - **Assumptions**: what you decided without asking, so the owner can overrule it.
74
+
75
+ ## Budgets
76
+
77
+ | Tier | Human layer | Whole file |
78
+ |---|---|---|
79
+ | brief | 40 lines | 400 lines |
80
+ | full | 80 lines | 400 lines |
81
+ | program | 80 lines | 400 lines |
82
+
83
+ Going over the human-layer budget [J06] means the plan says things the owner won't read. Going over the file budget [J07] means it's time to collapse finished slices into one Log line each, or to split a program plan into child plans.
84
+
85
+ ## Slices
86
+
87
+ ```markdown
88
+ ### S2: Export button in the toolbar [doing]
89
+ Goal: ...
90
+ Touch: `src/components/ExportButton.tsx (new)`, `src/pages/Reports.tsx`
91
+ Checks: C4
92
+ - Risk: ... Detect: ... Fallback: ...
93
+ ```
94
+
95
+ - The heading is `### S<n>: <title> [todo|doing|done|dropped]` [J08], and at most one slice is `doing` [J19].
96
+ - `Touch:` lists the files the slice may change. Each path must exist or be marked `(new)` [J09, J11]. The edit hook warns when the agent edits a file outside the `doing` slice's list.
97
+ - `Checks:` names check IDs from `checks.json` [J09, J10]. A brief plan without `checks.json` may give commands in backticks instead.
98
+ - A program-tier slice can give `Plan: docs/plans/<child>/PLAN.md` instead of Touch and Checks.
99
+ - Every `Risk:` line has a `Detect:` and a `Fallback:` [J15]. Don't score risks; likelihood × impact grids rank risks badly (Cox 2008).
100
+
101
+ ## Log
102
+
103
+ The Log is append-only and dated: `- 2026-11-25: ...` or `- 2026-11-25 14:02: ...` [J16]. `jig lint` compares it with the committed version and fails if an earlier entry changed or disappeared. Log entries record:
104
+
105
+ - decisions changed after approval, with the reason
106
+ - check evidence, which `jig verify --record` writes: command, exit code, the line that decides it
107
+ - each finished slice, with two or three lines on what changed and why
108
+
109
+ ## Wording
110
+
111
+ - No time or effort estimates such as `(~3d)`, "estimated effort" or "will take 2 weeks" [J12]. Report scope instead: slices, files, checks. Agents and planners both estimate badly, and estimates turn into deadlines.
112
+ - Avoid words that defer a decision: soon, eventually, as needed, TBD, etc. [J13, warning]. Write the decision, or put it under Questions.
113
+
114
+ ## checks.json
115
+
116
+ ```json
117
+ {
118
+ "version": 1,
119
+ "checks": [
120
+ {
121
+ "id": "C1",
122
+ "slice": "S1",
123
+ "kind": "acceptance",
124
+ "cmd": "npm test -- export.accept",
125
+ "expect": { "exit": 0 },
126
+ "timeout_s": 60,
127
+ "fast": true,
128
+ "protects": ["test/export.accept.test.ts"]
129
+ }
130
+ ]
131
+ }
132
+ ```
133
+
134
+ | Field | Meaning |
135
+ |---|---|
136
+ | `id` | Letters, digits, `.`, `-` or `_`, starting with a letter. Unique |
137
+ | `slice` | A slice ID from the plan |
138
+ | `kind` | `acceptance`, `regression`, `property`, `mutation`, `perf` or `security` |
139
+ | `cmd` | Shell command, run from the repo root |
140
+ | `expect.exit` | Expected exit code (default 0) |
141
+ | `expect.stdout` | Optional JavaScript regex the output must match |
142
+ | `timeout_s` | 1 to 600 |
143
+ | `fast` | True for checks that finish within 120 s. The build skill runs these before every stop |
144
+ | `protects` | Paths the agent may not edit without a logged decision. The edit hook asks first |
145
+
146
+ Write acceptance checks from the spec, before the code they check. They state what the code should do, not what it already does. Point each one at its own tests (a file path, `--grep`, `--testPathPattern`, `-t`): a whole-suite command passes before the behaviour exists, and `jig lint` warns about it [J21]. Lint errors here are [J17].
@@ -0,0 +1,26 @@
1
+ # Changing something people already use
2
+
3
+ Read this when a slice changes behaviour in a running product: a migration, a changed API, new infrastructure, or a feature reaching users. Skip it for new code nobody runs yet.
4
+
5
+ ## Rollout and rollback
6
+ - **How does this ship?** Behind a feature flag, as a canary, or all at once? All at once is fine for a reversible change with a fast rollback, and a decision with a reason otherwise.
7
+ - **How is it undone?** Write the rollback as a command or a flag flip in the slice, and test it when you can. "Revert the commit" is no rollback once data has changed.
8
+ - **Mark the one-way doors.** Destructive migrations, partition keys, public API removals and auth model changes can't be rolled back by a deploy. They get `[one-way]` in Decisions and a human decision.
9
+
10
+ ## Migrations: expand and contract
11
+ Run old and new code against the same data at every step:
12
+ 1. **Expand:** add new columns, tables or fields without removing anything. Old code ignores them.
13
+ 2. **Dual write**, or backfill, and verify with a check that compares counts or checksums.
14
+ 3. **Switch reads** to the new shape, behind a flag.
15
+ 4. **Contract:** remove the old shape in a later slice, after the switch has run cleanly for a stated period.
16
+
17
+ Each step is its own slice with its own check. Step 4 is a one-way door.
18
+
19
+ ## Observability
20
+ You can't debug what you can't see, and neither can an agent.
21
+ - **What tells you it works in production?** A metric, a log line or a trace span (OpenTelemetry), named in the slice.
22
+ - **What tells you it broke?** An alert or SLO that would fire, or a stated reason you don't need one.
23
+ - **Use structured logs** with the request or job ID, and no secrets or personal data.
24
+
25
+ ## Incidents
26
+ After an incident caused by a planned change, write a blameless postmortem and record whether AI wrote the code involved. Turn each cause into a test, hook or gate with the guard skill. Then add a Log line to the plan that caused it.