jig-plan 0.0.0-stage → 2.0.1
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.
- package/.claude-plugin/marketplace.json +18 -0
- package/.claude-plugin/plugin.json +11 -0
- package/LICENSE +21 -0
- package/README.md +210 -2
- package/agents/jig-reviewer.md +52 -0
- package/bin/jig +2 -0
- package/cli/jig.mjs +138 -0
- package/cli/lib/checks.mjs +56 -0
- package/cli/lib/doctor.mjs +182 -0
- package/cli/lib/git.mjs +48 -0
- package/cli/lib/hooks.mjs +204 -0
- package/cli/lib/lint.mjs +196 -0
- package/cli/lib/plan.mjs +96 -0
- package/cli/lib/scaffold.mjs +66 -0
- package/cli/lib/status.mjs +76 -0
- package/cli/lib/verify.mjs +70 -0
- package/hooks/hooks.json +15 -0
- package/package.json +34 -4
- package/references/failure-modes.md +18 -0
- package/references/fundamentals.md +58 -0
- package/references/mechanisms.md +22 -0
- package/references/plan-format.md +146 -0
- package/references/safe-change.md +26 -0
- package/references/security.md +34 -0
- package/references/sizing.md +43 -0
- package/references/team.md +22 -0
- package/skills/build/SKILL.md +69 -0
- package/skills/guard/SKILL.md +61 -0
- package/skills/plan/SKILL.md +104 -0
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// jig doctor: report harness gaps in a repo. Reads only; never changes files.
|
|
2
|
+
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join, resolve, sep } from 'node:path';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { mkdirSync, realpathSync } from 'node:fs';
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { git } from './git.mjs';
|
|
8
|
+
import { pathMatches } from './hooks.mjs';
|
|
9
|
+
|
|
10
|
+
const read = (p) => { try { return readFileSync(p, 'utf8'); } catch { return null; } };
|
|
11
|
+
const json = (p) => { try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; } };
|
|
12
|
+
|
|
13
|
+
function walk(root, depth, pred, out = [], rel = '') {
|
|
14
|
+
if (depth < 0) return out;
|
|
15
|
+
let names = [];
|
|
16
|
+
try { names = readdirSync(join(root, rel)); } catch { return out; }
|
|
17
|
+
for (const n of names) {
|
|
18
|
+
if (['node_modules', '.git', 'dist', 'build', '.venv', 'venv', 'target', 'vendor', '.next'].includes(n)) continue;
|
|
19
|
+
const r = rel ? `${rel}/${n}` : n;
|
|
20
|
+
let st; try { st = statSync(join(root, r)); } catch { continue; }
|
|
21
|
+
if (st.isDirectory()) walk(root, depth - 1, pred, out, r);
|
|
22
|
+
else if (pred(n, r)) out.push(r);
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Hash of every repo file that can run code or redirect traffic for an agent:
|
|
28
|
+
// everything under .claude/ (no depth limit), .mcp.json, and any repo file the
|
|
29
|
+
// settings or MCP config name in a command (plus package.json or Makefile when
|
|
30
|
+
// a command runs npm-style scripts or make). Full content, no size shortcut.
|
|
31
|
+
export function configDigest(root) {
|
|
32
|
+
const files = new Set(['.mcp.json'].filter((f) => existsSync(join(root, f))));
|
|
33
|
+
const all = (rel) => {
|
|
34
|
+
let names = [];
|
|
35
|
+
try { names = readdirSync(join(root, rel)); } catch { return; }
|
|
36
|
+
for (const n of names) {
|
|
37
|
+
const r = `${rel}/${n}`;
|
|
38
|
+
let st; try { st = statSync(join(root, r)); } catch { continue; }
|
|
39
|
+
if (st.isDirectory()) all(r); else files.add(r);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
if (existsSync(join(root, '.claude'))) all('.claude');
|
|
43
|
+
const text = ['.claude/settings.json', '.claude/settings.local.json', '.mcp.json'].map((f) => read(join(root, f)) ?? '').join('\n');
|
|
44
|
+
const absRoot = resolve(root);
|
|
45
|
+
// Any path-like token in a command may name a script, whatever its extension.
|
|
46
|
+
for (const tok of text.match(/[\w@.\/${}-]*\/[\w@.\/${}-]+|[\w@.-]+\.[\w]+/g) ?? []) {
|
|
47
|
+
const p = resolve(root, tok.replace(/^\$\{?CLAUDE_PROJECT_DIR\}?\//, '').replace(/^\.\//, ''));
|
|
48
|
+
if (p.startsWith(absRoot + sep) && existsSync(p) && statSync(p).isFile()) files.add(p.slice(absRoot.length + 1));
|
|
49
|
+
}
|
|
50
|
+
// Commands that run package scripts or make targets run code those files define.
|
|
51
|
+
if (/\b(npm|pnpm|yarn|bun|npx)\b/.test(text) && existsSync(join(root, 'package.json'))) files.add('package.json');
|
|
52
|
+
if (/\bmake\b/.test(text) && existsSync(join(root, 'Makefile'))) files.add('Makefile');
|
|
53
|
+
const h = createHash('sha256');
|
|
54
|
+
for (const f of [...files].sort()) h.update(`${f}\0`).update(readFileSync(join(root, f))).update('\0');
|
|
55
|
+
return h.digest('hex');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Acks live in the user's home, never in the repo: a repo could ship a
|
|
59
|
+
// pre-written ack to silence D4.
|
|
60
|
+
function ackPath(root, { create = false } = {}) {
|
|
61
|
+
const dir = join(process.env.JIG_HOME ?? join(homedir(), '.config', 'jig'), 'acks');
|
|
62
|
+
if (create) mkdirSync(dir, { recursive: true });
|
|
63
|
+
return join(dir, createHash('sha256').update(realpathSync(root)).digest('hex').slice(0, 32) + '.json');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function diagnose(root) {
|
|
67
|
+
const F = [];
|
|
68
|
+
const add = (id, level, msg, fix = null) => F.push({ id, level, msg, fix });
|
|
69
|
+
const pkg = json(join(root, 'package.json'));
|
|
70
|
+
const has = (p) => existsSync(join(root, p));
|
|
71
|
+
const isJs = Boolean(pkg);
|
|
72
|
+
const isPy = has('pyproject.toml') || has('setup.py') || has('requirements.txt');
|
|
73
|
+
|
|
74
|
+
// D1: one-command verify, named with the repo's own package manager
|
|
75
|
+
const pm = has('pnpm-lock.yaml') ? 'pnpm' : has('yarn.lock') ? 'yarn' : has('bun.lockb') || has('bun.lock') ? 'bun' : 'npm';
|
|
76
|
+
const run = (script) => (pm === 'npm' && script !== 'test' ? `npm run ${script}` : `${pm} ${script}`);
|
|
77
|
+
const verify = [];
|
|
78
|
+
for (const sc of ['verify', 'check']) if (pkg?.scripts?.[sc]) verify.push(run(sc));
|
|
79
|
+
if (pkg?.scripts?.test && !/no test specified/.test(pkg.scripts.test)) verify.push(run('test'));
|
|
80
|
+
if (/^test:/m.test(read(join(root, 'Makefile')) ?? '')) verify.push('make test');
|
|
81
|
+
if (has('Cargo.toml')) verify.push('cargo test');
|
|
82
|
+
if (has('go.mod')) verify.push('go test ./...');
|
|
83
|
+
if (isPy && /pytest/.test((read(join(root, 'pyproject.toml')) ?? '') + (read(join(root, 'requirements-dev.txt')) ?? '') + (read(join(root, 'requirements.txt')) ?? ''))) verify.push('pytest');
|
|
84
|
+
if (verify.length) add('D1', 'ok', `verify command found: ${verify.join(', ')}`);
|
|
85
|
+
else add('D1', 'gap', 'no one-command verify (test script, make test, cargo test, go test, pytest)', 'Add one before agent work. Every slice\'s checks build on it, and agents do measurably better with fast feedback.');
|
|
86
|
+
if (pkg && !pkg.scripts?.typecheck && !pkg.scripts?.lint && has('tsconfig.json')) add('D1', 'info', 'TypeScript repo with no typecheck or lint script', 'Add "typecheck": "tsc --noEmit" so a check can run it.');
|
|
87
|
+
|
|
88
|
+
// D2: empty-catch lint (heuristic)
|
|
89
|
+
if (isJs) {
|
|
90
|
+
const cfgs = walk(root, 1, (n) => /^(\.eslintrc(\..+)?|eslint\.config\.(js|mjs|cjs|ts)|biome\.jsonc?)$/.test(n));
|
|
91
|
+
const text = cfgs.map((c) => read(join(root, c)) ?? '').join('\n') + JSON.stringify(pkg.eslintConfig ?? '');
|
|
92
|
+
if (!cfgs.length && !pkg.eslintConfig) add('D2', 'gap', 'no ESLint or Biome config, so nothing flags empty catch blocks', 'Enable ESLint\'s no-empty (in "recommended") or Biome\'s recommended rules.');
|
|
93
|
+
else if (/no-empty|recommended/.test(text)) add('D2', 'ok', `lint config present (${cfgs.join(', ') || 'package.json'}) with no-empty or a recommended preset`);
|
|
94
|
+
else if (/from ['"](@nx\/eslint-plugin|typescript-eslint|@typescript-eslint|@eslint\/js|eslint-config-[\w-]+|@[\w-]+\/eslint-config[\w-]*)['"]|require\(['"](eslint-config-|@[\w-]+\/eslint-config)/.test(text)) {
|
|
95
|
+
add('D2', 'info', `lint config (${cfgs.join(', ')}) imports presets whose rules doctor can't see (it never runs repo code)`, 'Check: npx eslint --print-config <a source file> | grep no-empty');
|
|
96
|
+
}
|
|
97
|
+
else add('D2', 'info', `lint config present (${cfgs.join(', ')}) but no-empty not found`, 'Turn on no-empty; error-masking constructs rose 47% in AI-era code (GitClear 2026).');
|
|
98
|
+
}
|
|
99
|
+
if (isPy) {
|
|
100
|
+
const t = (read(join(root, 'pyproject.toml')) ?? '') + (read(join(root, 'ruff.toml')) ?? '') + (read(join(root, '.flake8')) ?? '');
|
|
101
|
+
if (/BLE|E722|S110|flake8-blind-except/.test(t)) add('D2', 'ok', 'Python lint flags bare or blind except');
|
|
102
|
+
else add('D2', 'gap', 'no lint rule against bare or blind except (ruff E722, BLE001, S110)', 'Add them to ruff\'s select list.');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// D3: secrets readable without a deny rule
|
|
106
|
+
const secrets = walk(root, 4, (n) => (/^\.env(\..+)?$/.test(n) && !/example|sample|template/.test(n)) || /\.env$/.test(n) && n !== '.env' && !/example/.test(n) || /\.(pem|key|p12)$/.test(n) || /^id_(rsa|ed25519)$/.test(n) || n === 'credentials.json');
|
|
107
|
+
const settings = [json(join(root, '.claude/settings.json')), json(join(root, '.claude/settings.local.json'))].filter(Boolean);
|
|
108
|
+
const deny = settings.flatMap((s) => s.permissions?.deny ?? []).map((d) => d.match(/^Read\((.*)\)$/)?.[1]).filter(Boolean).map((p) => p.replace(/^\.\//, ''));
|
|
109
|
+
const covered = (f) => deny.some((p) => pathMatches(f, p) || (p.startsWith('**/') && (pathMatches(f, p.slice(3)) || pathMatches(f.split('/').pop(), p.slice(3)))));
|
|
110
|
+
const unguarded = secrets.filter((f) => !covered(f));
|
|
111
|
+
if (unguarded.length) add('D3', 'gap', `secret-looking files the agent can read: ${unguarded.slice(0, 6).join(', ')}${unguarded.length > 6 ? ' ...' : ''}`, 'Suggested deny rules for .claude/settings.json (review before adding): {"permissions":{"deny":["Read(./.env)","Read(./.env.*)","Read(./**/*.pem)","Read(~/.ssh/**)","Read(~/.aws/**)"]}}');
|
|
112
|
+
else if (secrets.length) add('D3', 'ok', 'secret-looking files are covered by Read deny rules');
|
|
113
|
+
|
|
114
|
+
// D4: repo agent config is an execution vector
|
|
115
|
+
const risky = [];
|
|
116
|
+
for (const [name, s] of [['.claude/settings.json', settings[0]], ['.claude/settings.local.json', settings[1]]]) {
|
|
117
|
+
if (!s) continue;
|
|
118
|
+
if (s.hooks) risky.push(`${name} defines hooks (${Object.keys(s.hooks).join(', ')}), which run commands`);
|
|
119
|
+
if (s.env?.ANTHROPIC_BASE_URL) risky.push(`${name} sets ANTHROPIC_BASE_URL=${s.env.ANTHROPIC_BASE_URL} (API traffic redirection; see CVE-2026-21852)`);
|
|
120
|
+
if (s.permissions?.defaultMode === 'bypassPermissions') risky.push(`${name} sets permissions.defaultMode to bypassPermissions (see CVE-2026-33068)`);
|
|
121
|
+
if (s.enableAllProjectMcpServers) risky.push(`${name} auto-enables every project MCP server (see CVE-2025-59536)`);
|
|
122
|
+
if (s.apiKeyHelper) risky.push(`${name} sets apiKeyHelper, which runs a command`);
|
|
123
|
+
}
|
|
124
|
+
const mcp = json(join(root, '.mcp.json'));
|
|
125
|
+
if (mcp?.mcpServers) risky.push(`.mcp.json declares MCP servers: ${Object.keys(mcp.mcpServers).join(', ')}`);
|
|
126
|
+
if (has('.claude/hooks')) risky.push('.claude/hooks/ contains hook scripts');
|
|
127
|
+
const acked = json(ackPath(root))?.digest === configDigest(root);
|
|
128
|
+
if (risky.length && acked) add('D4', 'ok', 'repo-level agent config (everything under .claude/, .mcp.json, files their commands name, and package.json or Makefile when commands run them) is unchanged since you ran jig doctor --ack. Code a hook reaches indirectly (imports, PATH lookups) is not tracked');
|
|
129
|
+
else if (risky.length) add('D4', 'review', 'repo-level agent config that can run code or redirect traffic:\n - ' + risky.join('\n - '), 'Read these before trusting the repo, and keep Claude Code updated. jig never edits them. Once read, `jig doctor --ack` stops this note until they change.');
|
|
130
|
+
else add('D4', 'ok', 'no repo-level hooks, MCP servers or risky settings');
|
|
131
|
+
|
|
132
|
+
// D5: CI, secret scanning, SAST
|
|
133
|
+
const wf = walk(root, 2, (n, r) => r.startsWith('.github/workflows/') && /\.ya?ml$/.test(n));
|
|
134
|
+
const ci = wf.map((w) => read(join(root, w)) ?? '').join('\n') + (read(join(root, '.gitlab-ci.yml')) ?? '');
|
|
135
|
+
const hookFiles = [...walk(root, 1, (n, r) => r.startsWith('.githooks/')), ...walk(root, 1, (n, r) => r.startsWith('.husky/')), ...['lefthook.yml', '.pre-commit-config.yaml'].filter(has)];
|
|
136
|
+
const local = hookFiles.map((f) => read(join(root, f)) ?? '').join('\n');
|
|
137
|
+
if (has('.githooks') && !(git(root, ['config', '--local', '--get', 'core.hooksPath']) ?? '').trim()) add('D5', 'gap', '.githooks/ exists but core.hooksPath is not set here, so those hooks never run on this machine', 'git config core.hooksPath .githooks');
|
|
138
|
+
if (!ci.trim() && !local.trim()) add('D5', 'gap', 'no CI configuration or git hooks found', 'Run the verify command in CI so a green result doesn\'t depend on the agent saying so.');
|
|
139
|
+
else {
|
|
140
|
+
const where = ci.trim() ? 'CI config' : 'git hooks';
|
|
141
|
+
if (/gitleaks|trufflehog|detect-secrets|ggshield/.test(ci + local)) add('D5', 'ok', `a secret scanner is configured (${where}); doctor can't tell whether CI actually runs`);
|
|
142
|
+
else add('D5', 'gap', `no secret scanner in the CI config or git hooks (doctor reads the config; it can't tell whether CI runs)`, 'Add gitleaks or trufflehog to CI and to the pre-push hook.');
|
|
143
|
+
if (/codeql|semgrep|snyk|bandit|gosec/.test(ci + local)) add('D5', 'ok', 'static security analysis is configured');
|
|
144
|
+
else add('D5', 'info', 'no SAST configured', 'Consider CodeQL or Semgrep; security prompting reduces issues but doesn\'t remove them.');
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// D6: lockfile drift
|
|
148
|
+
if (pkg) {
|
|
149
|
+
const locks = ['package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb', 'bun.lock'].filter(has);
|
|
150
|
+
const deps = Object.keys({ ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) });
|
|
151
|
+
if (!locks.length && deps.length) add('D6', 'gap', 'package.json has dependencies but no lockfile', 'Commit a lockfile and install with npm ci in CI.');
|
|
152
|
+
else if (locks.includes('package-lock.json')) {
|
|
153
|
+
const lock = json(join(root, 'package-lock.json'));
|
|
154
|
+
const locked = lock?.packages?.['']?.dependencies || lock?.packages?.[''] ? { ...(lock.packages[''].dependencies ?? {}), ...(lock.packages[''].devDependencies ?? {}) } : null;
|
|
155
|
+
const missing = locked ? deps.filter((d) => !(d in locked)) : [];
|
|
156
|
+
if (missing.length) add('D6', 'gap', `package-lock.json is missing: ${missing.join(', ')}`, 'Run npm install and review the lockfile diff.');
|
|
157
|
+
else add('D6', 'ok', 'lockfile matches package.json');
|
|
158
|
+
} else if (locks.length) add('D6', 'ok', `lockfile present (${locks.join(', ')})`);
|
|
159
|
+
}
|
|
160
|
+
return F;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const ICON = { ok: 'ok ', gap: 'GAP ', review: 'REVIEW', info: 'note ' };
|
|
164
|
+
|
|
165
|
+
export function doctor(root, { json: asJson = false, ack = false } = {}) {
|
|
166
|
+
if (ack) {
|
|
167
|
+
const d = configDigest(root);
|
|
168
|
+
writeFileSync(ackPath(root, { create: true }), JSON.stringify({ root: realpathSync(root), digest: d, at: new Date().toISOString() }));
|
|
169
|
+
console.log('Marked the repo-level agent config as reviewed. jig doctor will flag it again if any of those files change.');
|
|
170
|
+
}
|
|
171
|
+
const F = diagnose(root);
|
|
172
|
+
if (asJson) console.log(JSON.stringify(F, null, 2));
|
|
173
|
+
else {
|
|
174
|
+
for (const f of F) {
|
|
175
|
+
console.log(`${ICON[f.level]} ${f.id} ${f.msg}`);
|
|
176
|
+
if (f.fix && f.level !== 'ok') console.log(` ${f.fix}`);
|
|
177
|
+
}
|
|
178
|
+
const gaps = F.filter((f) => f.level === 'gap' || f.level === 'review').length;
|
|
179
|
+
console.log(gaps ? `\n${gaps} item(s) to look at. jig doctor changed nothing.` : '\nNo gaps found. jig doctor changed nothing.');
|
|
180
|
+
}
|
|
181
|
+
return 0;
|
|
182
|
+
}
|
package/cli/lib/git.mjs
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, mkdirSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
// Hardened git: hooks scripts run outside the Bash sandbox, so don't let a
|
|
6
|
+
// checkout's config start programs (fsmonitor, hooks).
|
|
7
|
+
const HARDEN = ['-c', 'core.fsmonitor=', '-c', 'core.hooksPath=/dev/null'];
|
|
8
|
+
|
|
9
|
+
export function git(cwd, args, { allowFail = true } = {}) {
|
|
10
|
+
try {
|
|
11
|
+
return execFileSync('git', [...HARDEN, ...args], {
|
|
12
|
+
cwd,
|
|
13
|
+
encoding: 'utf8',
|
|
14
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
15
|
+
env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' },
|
|
16
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
17
|
+
});
|
|
18
|
+
} catch (e) {
|
|
19
|
+
if (allowFail) return null;
|
|
20
|
+
throw e;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function repoRoot(cwd) {
|
|
25
|
+
const out = git(cwd, ['rev-parse', '--show-toplevel']);
|
|
26
|
+
return out ? out.trim() : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function headSha(cwd) {
|
|
30
|
+
const out = git(cwd, ['rev-parse', '--short', 'HEAD']);
|
|
31
|
+
return out ? out.trim() : null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function isCommit(cwd, sha) {
|
|
35
|
+
return git(cwd, ['cat-file', '-e', `${sha}^{commit}`]) !== null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function showHead(cwd, relPath) {
|
|
39
|
+
return git(cwd, ['show', `HEAD:${relPath}`]);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Per-repo state that must not be committed: inside .git when there is one.
|
|
43
|
+
export function stateDir(root) {
|
|
44
|
+
const gitDir = git(root, ['rev-parse', '--absolute-git-dir']);
|
|
45
|
+
const dir = gitDir ? join(gitDir.trim(), 'jig') : join(root, '.jig-state');
|
|
46
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
47
|
+
return dir;
|
|
48
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// Hook entry points. Each reads the hook JSON on stdin and prints a hook
|
|
2
|
+
// response (or nothing). Rules, with reasons in docs/research/m0-spikes.md:
|
|
3
|
+
// - never return permissionDecision "allow": that would skip the user's prompts
|
|
4
|
+
// - never run repo-defined commands: checks.json is untrusted input
|
|
5
|
+
// - append short context, and don't repeat it
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { join, relative, isAbsolute } from 'node:path';
|
|
8
|
+
import { repoRoot, stateDir } from './git.mjs';
|
|
9
|
+
import { activePlans, doingSlice, sliceTouch, statusSummary, plansDir } from './status.mjs';
|
|
10
|
+
import { loadChecks, validateChecks } from './checks.mjs';
|
|
11
|
+
import { lastEvidence } from './verify.mjs';
|
|
12
|
+
|
|
13
|
+
const off = (name) => {
|
|
14
|
+
const v = (process.env.JIG_HOOKS_OFF ?? '').split(',').map((s) => s.trim());
|
|
15
|
+
return v.includes('all') || v.includes(name);
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function readStdin() {
|
|
19
|
+
try { return JSON.parse(readFileSync(0, 'utf8') || '{}'); } catch { return {}; }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const emit = (obj) => process.stdout.write(JSON.stringify(obj));
|
|
23
|
+
const sid = (input) => String(input.session_id ?? 'nosession').replace(/[^\w.-]/g, '_');
|
|
24
|
+
|
|
25
|
+
function rootOf(input) {
|
|
26
|
+
const cwd = input.cwd ?? process.env.CLAUDE_PROJECT_DIR ?? process.cwd();
|
|
27
|
+
return repoRoot(cwd) ?? cwd;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function sessionState(root, input) {
|
|
31
|
+
const dir = join(stateDir(root), 'sessions');
|
|
32
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
33
|
+
const file = join(dir, `${sid(input)}.json`);
|
|
34
|
+
let data = { editedAt: 0, warned: [] };
|
|
35
|
+
if (existsSync(file)) {
|
|
36
|
+
try { data = { ...data, ...JSON.parse(readFileSync(file, 'utf8')) }; }
|
|
37
|
+
catch { process.stderr.write(`jig: ignoring unreadable session state ${file}\n`); }
|
|
38
|
+
}
|
|
39
|
+
return { data, save: () => writeFileSync(file, JSON.stringify(data)) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// `a/b/` covers everything below a/b; `*` and `**` are simple wildcards.
|
|
43
|
+
export function pathMatches(rel, pattern) {
|
|
44
|
+
if (pattern.endsWith('/')) return rel.startsWith(pattern);
|
|
45
|
+
if (!/[*?]/.test(pattern)) return rel === pattern;
|
|
46
|
+
const re = new RegExp('^' + pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*\*/g, '\u0000').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]').replace(/\u0000/g, '.*') + '$');
|
|
47
|
+
return re.test(rel);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const NUDGE = 'jig: for any request to change code in this repo, invoke the jig:plan skill first, before reading or editing files. For a one-line fix it is a four-line plan in chat and adds little; for anything ambiguous or risky it catches what a direct start misses. Skip it only for questions, explanations, reviews, and debugging an error whose cause is unknown.';
|
|
51
|
+
|
|
52
|
+
export function sessionStart(input) {
|
|
53
|
+
const root = rootOf(input);
|
|
54
|
+
const parts = [];
|
|
55
|
+
if (process.env.JIG_NUDGE !== 'off') parts.push(NUDGE);
|
|
56
|
+
const status = statusSummary(root, { max: 2 });
|
|
57
|
+
if (status.length) parts.push('Active jig plans (read the plan before continuing; use the jig:build skill to work the next slice):\n' + status.join('\n'));
|
|
58
|
+
if (!parts.length) return null;
|
|
59
|
+
return { hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: parts.join('\n\n') } };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function preEdit(input) {
|
|
63
|
+
const file = input.tool_input?.file_path ?? input.tool_input?.notebook_path;
|
|
64
|
+
if (!file) return null;
|
|
65
|
+
const root = rootOf(input);
|
|
66
|
+
const rel = relative(root, isAbsolute(file) ? file : join(root, file));
|
|
67
|
+
if (rel.startsWith('..')) return null;
|
|
68
|
+
const st = sessionState(root, input);
|
|
69
|
+
st.data.editedAt = Date.now();
|
|
70
|
+
st.save();
|
|
71
|
+
|
|
72
|
+
const plans = activePlans(root);
|
|
73
|
+
if (!plans.length) return null;
|
|
74
|
+
for (const { path } of plans) {
|
|
75
|
+
const checks = loadChecks(path);
|
|
76
|
+
// Fail closed on the one guard that protects files: if checks.json can't
|
|
77
|
+
// be read or validated, we can't tell whether this file is protected.
|
|
78
|
+
const problems = checks.exists ? (checks.error ? [checks.error] : validateChecks(checks.data)) : [];
|
|
79
|
+
if (problems.length) {
|
|
80
|
+
return {
|
|
81
|
+
hookSpecificOutput: {
|
|
82
|
+
hookEventName: 'PreToolUse',
|
|
83
|
+
permissionDecision: 'ask',
|
|
84
|
+
permissionDecisionReason: `jig: ${relative(root, checks.path)} is invalid (${problems[0]}), so jig can't tell whether ${rel} is a protected acceptance test. Fix checks.json with \`jig lint\`.`,
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
for (const c of checks.data?.checks ?? []) {
|
|
89
|
+
if ((c.protects ?? []).some((p) => pathMatches(rel, p))) {
|
|
90
|
+
return {
|
|
91
|
+
hookSpecificOutput: {
|
|
92
|
+
hookEventName: 'PreToolUse',
|
|
93
|
+
permissionDecision: 'ask',
|
|
94
|
+
permissionDecisionReason: `jig: ${rel} is protected by check ${c.id} in ${relative(root, path)}. Acceptance tests come from the spec; edit one only when the spec changed, and log the decision in the plan.`,
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (rel.startsWith(`${plansDir(root)}/`) || rel.startsWith('docs/plans/')) return null;
|
|
101
|
+
const doing = plans.map(({ path, plan }) => ({ path, slice: doingSlice(plan) })).find((x) => x.slice);
|
|
102
|
+
if (!doing) return null;
|
|
103
|
+
const touch = sliceTouch(doing.slice);
|
|
104
|
+
if (!touch.length || touch.some((p) => pathMatches(rel, p))) return null;
|
|
105
|
+
if (st.data.warned.includes(rel)) return null;
|
|
106
|
+
st.data.warned.push(rel);
|
|
107
|
+
st.save();
|
|
108
|
+
return {
|
|
109
|
+
hookSpecificOutput: {
|
|
110
|
+
hookEventName: 'PreToolUse',
|
|
111
|
+
additionalContext: `jig: ${rel} is outside ${doing.slice.id}'s Touch list (${touch.join(', ')}). If the slice needs it, add it to Touch with a Log line; otherwise leave it for its own slice.`,
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const INSTALLERS = [
|
|
117
|
+
{ re: /\b(npm|pnpm|yarn|bun)\s+(?:i|install|add)\b(.*)/, eco: 'npm' },
|
|
118
|
+
{ re: /\b(?:pip3?|python3?\s+-m\s+pip|uv\s+pip)\s+install\b(.*)/, eco: 'pypi' },
|
|
119
|
+
{ re: /\b(?:uv|poetry)\s+add\b(.*)/, eco: 'pypi' },
|
|
120
|
+
{ re: /\bcargo\s+(?:add|install)\b(.*)/, eco: 'crates' },
|
|
121
|
+
{ re: /\bgo\s+(?:get|install)\b(.*)/, eco: 'go' },
|
|
122
|
+
{ re: /\bgem\s+install\b(.*)/, eco: 'rubygems' },
|
|
123
|
+
{ re: /\bcomposer\s+require\b(.*)/, eco: 'packagist' },
|
|
124
|
+
];
|
|
125
|
+
|
|
126
|
+
// Package names an install command would add. Lockfile installs (`npm ci`,
|
|
127
|
+
// bare `npm install`, `pip install -r req.txt`, `pip install -e .`) add none.
|
|
128
|
+
export function installedPackages(command) {
|
|
129
|
+
const found = [];
|
|
130
|
+
for (const seg of command.split(/&&|\|\||;|\|/)) {
|
|
131
|
+
for (const { re, eco } of INSTALLERS) {
|
|
132
|
+
const m = seg.match(re);
|
|
133
|
+
if (!m) continue;
|
|
134
|
+
const rest = m[m.length - 1] ?? '';
|
|
135
|
+
const toks = rest.trim().split(/\s+/).filter(Boolean);
|
|
136
|
+
for (let i = 0; i < toks.length; i++) {
|
|
137
|
+
const t = toks[i];
|
|
138
|
+
if (['-r', '--requirement', '-c', '--constraint', '-e', '--editable', '--prefix', '--registry', '-i', '--index-url'].includes(t)) { i++; continue; }
|
|
139
|
+
if (t.startsWith('-') || t === '.' || t.startsWith('./') || t.startsWith('/') || t.startsWith('$')) continue;
|
|
140
|
+
found.push({ eco, name: t.replace(/^['"]|['"]$/g, '') });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return found;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function preBash(input) {
|
|
148
|
+
const cmd = input.tool_input?.command ?? '';
|
|
149
|
+
const pkgs = installedPackages(cmd);
|
|
150
|
+
if (!pkgs.length) return null;
|
|
151
|
+
const names = pkgs.map((p) => `${p.name} (${p.eco})`).join(', ');
|
|
152
|
+
return {
|
|
153
|
+
hookSpecificOutput: {
|
|
154
|
+
hookEventName: 'PreToolUse',
|
|
155
|
+
permissionDecision: 'ask',
|
|
156
|
+
permissionDecisionReason: `jig: this adds ${names}. A new dependency is a one-way door: check that the name is the real package (hallucinated names get registered by attackers), its age and downloads, and record it in the plan's Decisions.`,
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function stop(input) {
|
|
162
|
+
if (input.stop_hook_active) return null;
|
|
163
|
+
if ((input.background_tasks ?? []).length) return null;
|
|
164
|
+
const root = rootOf(input);
|
|
165
|
+
const st = sessionState(root, input);
|
|
166
|
+
if (!st.data.editedAt) return null;
|
|
167
|
+
const plans = activePlans(root).filter(({ plan }) => doingSlice(plan));
|
|
168
|
+
if (!plans.length) return null;
|
|
169
|
+
// Only when a checks.json exists; brief plans state checks as commands.
|
|
170
|
+
const withChecks = plans.map(({ path, plan }) => ({ path, slice: doingSlice(plan), checks: loadChecks(path) })).filter((x) => x.checks.exists && Array.isArray(x.checks.data?.checks));
|
|
171
|
+
if (!withChecks.length) return null;
|
|
172
|
+
const sliceChecks = withChecks.flatMap((x) => x.checks.data.checks.filter((c) => c.slice === x.slice.id));
|
|
173
|
+
const cmd = sliceChecks.some((c) => c.fast === true) ? 'jig verify --fast --record' : 'jig verify --record';
|
|
174
|
+
const ev = lastEvidence(root);
|
|
175
|
+
// Evidence that ran no checks proves nothing.
|
|
176
|
+
if (!ev || ev.t < st.data.editedAt || !(ev.results ?? []).length) {
|
|
177
|
+
return { decision: 'block', reason: `jig: files changed since the last \`jig verify\` that ran a check. Run \`${cmd}\` for the slice in progress and report its result before finishing. If a check cannot run here, say which one and why.` };
|
|
178
|
+
}
|
|
179
|
+
const failed = (ev.results ?? []).filter((r) => !r.pass).map((r) => r.id);
|
|
180
|
+
if (failed.length && !st.data.reportedFailure) {
|
|
181
|
+
st.data.reportedFailure = ev.t;
|
|
182
|
+
st.save();
|
|
183
|
+
return { decision: 'block', reason: `jig: the last \`jig verify\` had failing checks (${failed.join(', ')}). Fix them, or tell the user plainly they are failing; don't describe the slice as done.` };
|
|
184
|
+
}
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const HANDLERS = { 'session-start': sessionStart, 'pre-edit': preEdit, 'pre-bash': preBash, stop };
|
|
189
|
+
|
|
190
|
+
export function runHook(name) {
|
|
191
|
+
const fn = HANDLERS[name];
|
|
192
|
+
if (!fn) { console.error(`jig hook: unknown hook "${name}" (${Object.keys(HANDLERS).join(', ')})`); return 2; }
|
|
193
|
+
if (off(name)) return 0;
|
|
194
|
+
try {
|
|
195
|
+
const out = fn(readStdin());
|
|
196
|
+
if (out) emit(out);
|
|
197
|
+
} catch (e) {
|
|
198
|
+
// Guardrails, not a security boundary (Bash can edit files without Edit):
|
|
199
|
+
// an unexpected error must not block all work. The protected-file check
|
|
200
|
+
// above fails closed on its own known failure mode (invalid checks.json).
|
|
201
|
+
process.stderr.write(`jig hook ${name}: ${e.message}\n`);
|
|
202
|
+
}
|
|
203
|
+
return 0;
|
|
204
|
+
}
|
package/cli/lib/lint.mjs
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { isAbsolute, join, relative } from 'node:path';
|
|
3
|
+
import { parsePlan, section, humanLayer, touchPaths, checkIds, logEntries, STATUSES, TIERS, SLICE_STATES, SECTIONS } from './plan.mjs';
|
|
4
|
+
import { loadChecks, validateChecks } from './checks.mjs';
|
|
5
|
+
import { repoRoot, showHead, isCommit } from './git.mjs';
|
|
6
|
+
|
|
7
|
+
const BUDGET = { brief: 40, full: 80, program: 80 };
|
|
8
|
+
const FILE_BUDGET = 400;
|
|
9
|
+
|
|
10
|
+
// Estimates, not durations in requirements ("keep logs 30 days" is fine).
|
|
11
|
+
const ESTIMATE_RES = [
|
|
12
|
+
/\(\s*~\s*\d+(\.\d+)?\s*(h|d|w|hrs?|days?|weeks?)\s*\)/i,
|
|
13
|
+
/\b(estimated effort|estimate[sd]?|eta|will take|takes about|should take)\b[^.\n]{0,40}?\b\d+(\.\d+)?\s*(-\s*\d+\s*)?(hours?|hrs?|days?|weeks?|sprints?|months?)\b/i,
|
|
14
|
+
/\b\d+(\.\d+)?\s*(person|engineer|dev)[- ](hours?|days?|weeks?)\b/i,
|
|
15
|
+
];
|
|
16
|
+
const VAGUE = ['soon', 'eventually', 'as needed', 'tbd', 'etc.', 'and so on', 'if possible', 'robust', 'seamless', 'various'];
|
|
17
|
+
const RISK_MATRIX = /\b(likelihood|impact)\b.*\b(score|low|med|high)\b/i;
|
|
18
|
+
const DATE_ENTRY = /^-\s+\d{4}-\d{2}-\d{2}( \d{2}:\d{2})?:\s+\S/;
|
|
19
|
+
|
|
20
|
+
export function lintFile(planPath, { cwd = process.cwd(), paths = true } = {}) {
|
|
21
|
+
const abs = isAbsolute(planPath) ? planPath : join(cwd, planPath);
|
|
22
|
+
if (!existsSync(abs)) return { path: planPath, problems: [{ rule: 'J00', level: 'error', line: 0, msg: 'file not found' }] };
|
|
23
|
+
const text = readFileSync(abs, 'utf8');
|
|
24
|
+
const root = repoRoot(cwd) ?? cwd;
|
|
25
|
+
const rel = relative(realpathSync(root), realpathSync(abs));
|
|
26
|
+
return { path: planPath, problems: lintText(text, { root, rel, checks: loadChecks(abs), paths }) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function lintText(text, { root = null, rel = null, checks = null, paths = true } = {}) {
|
|
30
|
+
const plan = parsePlan(text);
|
|
31
|
+
const P = [];
|
|
32
|
+
const err = (rule, line, msg) => P.push({ rule, level: 'error', line: line + 1, msg });
|
|
33
|
+
const warn = (rule, line, msg) => P.push({ rule, level: 'warning', line: line + 1, msg });
|
|
34
|
+
|
|
35
|
+
// J01-J03 header
|
|
36
|
+
if (!plan.title) err('J01', 0, 'missing "# <title>" on the first line');
|
|
37
|
+
const h = plan.header;
|
|
38
|
+
const tier = h?.tier?.toLowerCase();
|
|
39
|
+
const status = h?.status?.toLowerCase();
|
|
40
|
+
if (!h) err('J02', 0, 'missing "Status: <status> · Tier: <tier> · Baseline: <sha> · Updated: <date>" line under the title');
|
|
41
|
+
else {
|
|
42
|
+
if (!STATUSES.includes(status)) err('J02', plan.headerLine, `Status must be one of ${STATUSES.join(', ')}`);
|
|
43
|
+
if (!TIERS.includes(tier)) err('J02', plan.headerLine, `Tier must be one of ${TIERS.join(', ')} (tier 0 plans stay in chat)`);
|
|
44
|
+
if (!h.baseline) err('J02', plan.headerLine, 'Baseline commit is missing');
|
|
45
|
+
else if (root && /^[0-9a-f]{7,40}$/.test(h.baseline) && !isCommit(root, h.baseline)) warn('J20', plan.headerLine, `Baseline ${h.baseline} is not a commit in this repo`);
|
|
46
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(h.updated ?? '')) err('J02', plan.headerLine, 'Updated must be a YYYY-MM-DD date');
|
|
47
|
+
}
|
|
48
|
+
if (plan.nowLine === -1) err('J03', 0, 'missing "Now:" line saying where the plan stands');
|
|
49
|
+
|
|
50
|
+
// J04 sections in order
|
|
51
|
+
const names = plan.sections.map((s) => s.name.toLowerCase());
|
|
52
|
+
let last = -1;
|
|
53
|
+
for (const want of SECTIONS) {
|
|
54
|
+
const idx = names.indexOf(want.toLowerCase());
|
|
55
|
+
if (idx === -1) err('J04', 0, `missing section "## ${want}"`);
|
|
56
|
+
else if (idx < last) err('J04', plan.sections[idx].start, `section "## ${want}" is out of order (expected ${SECTIONS.join(', ')})`);
|
|
57
|
+
else last = idx;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// J05 outcome done-when
|
|
61
|
+
const outcome = section(plan, 'Outcome');
|
|
62
|
+
if (outcome) {
|
|
63
|
+
const dwIdx = outcome.body.findIndex((l) => /^done when:?/i.test(l.trim()));
|
|
64
|
+
const items = dwIdx === -1 ? [] : outcome.body.slice(dwIdx + 1).filter((l) => /^\s*-\s/.test(l));
|
|
65
|
+
if (dwIdx === -1) err('J05', outcome.start, 'Outcome needs a "Done when:" list');
|
|
66
|
+
else if (!items.length) err('J05', outcome.start + dwIdx + 1, '"Done when:" has no items');
|
|
67
|
+
else items.forEach((l) => {
|
|
68
|
+
if (!/`[^`]+`/.test(l) && !/\b[A-Z][\w.-]*\d\b/.test(l)) {
|
|
69
|
+
err('J05', plan.lines.indexOf(l), 'each "Done when" item names a command in backticks or a check ID');
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// J06/J07 budgets
|
|
75
|
+
const human = humanLayer(plan);
|
|
76
|
+
const budget = BUDGET[tier];
|
|
77
|
+
if (budget && human.length > budget) err('J06', 0, `human layer is ${human.length} lines; the ${tier} budget is ${budget}`);
|
|
78
|
+
if (plan.lines.length > FILE_BUDGET) err('J07', 0, `plan is ${plan.lines.length} lines; the budget is ${FILE_BUDGET}. Collapse finished slices into the Log or split into child plans`);
|
|
79
|
+
|
|
80
|
+
// J14 decisions
|
|
81
|
+
const decisions = section(plan, 'Decisions');
|
|
82
|
+
if (decisions) {
|
|
83
|
+
decisions.body.forEach((l, k) => {
|
|
84
|
+
if (!/^\s*-\s/.test(l) || /^\s*-\s*none\.?\s*$/i.test(l)) return;
|
|
85
|
+
const ln = decisions.start + 1 + k;
|
|
86
|
+
if (!/\bReason:/.test(l)) err('J14', ln, 'decision has no "Reason:"');
|
|
87
|
+
if (/\[one-way\]/i.test(l) && status && status !== 'draft' && !/\bDecided:\s*\S+/.test(l)) {
|
|
88
|
+
err('J14', ln, 'one-way decision has no "Decided: <who> <date>" but the plan is past draft');
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Slices: J08-J11, J15, J19
|
|
94
|
+
let checksData = null;
|
|
95
|
+
if (checks?.exists) {
|
|
96
|
+
if (checks.error) err('J17', 0, `checks.json: ${checks.error}`);
|
|
97
|
+
else {
|
|
98
|
+
checksData = checks.data;
|
|
99
|
+
for (const e of validateChecks(checks.data, plan.slices.map((s) => s.id).filter(Boolean))) err('J17', 0, `checks.json: ${e}`);
|
|
100
|
+
}
|
|
101
|
+
} else if (checks && (tier === 'full')) {
|
|
102
|
+
err('J10', 0, 'full-tier plans need a checks.json beside PLAN.md');
|
|
103
|
+
}
|
|
104
|
+
const knownIds = new Set((checksData?.checks ?? []).map((c) => c.id));
|
|
105
|
+
// J21: an acceptance check that runs a whole suite with no filter passes
|
|
106
|
+
// before the new behaviour exists, so it can't show the slice is done.
|
|
107
|
+
const FILTER = /(--grep|--testPathPattern|--testNamePattern|--test-name-pattern|\s-t\s|\s-k\s|::|--filter|--project|\.(spec|test)\.[cm]?[jt]sx?\b|test_[\w]+\.py|_test\.go\b)/;
|
|
108
|
+
for (const c of checksData?.checks ?? []) {
|
|
109
|
+
if (c.kind !== 'acceptance' || typeof c.cmd !== 'string') continue;
|
|
110
|
+
const names = (c.protects ?? []).map((p) => p.split('/').pop().replace(/\.[^.]+$/, '').replace(/\.(spec|test)$/, ''));
|
|
111
|
+
const RUNNER = /\b((npm|pnpm|yarn|bun)( run)? test\b|nx (run [\w@/.-]+:test|test|run-many -t test|affected -t test)\b|vitest\b|jest\b|mocha\b|pytest\b|go test\b|cargo test\b|node --test\s*$)/;
|
|
112
|
+
if (RUNNER.test(c.cmd) && !FILTER.test(` ${c.cmd} `) && !names.some((n) => n && c.cmd.includes(n))) {
|
|
113
|
+
warn('J21', 0, `acceptance check ${c.id} runs \`${c.cmd}\` with no filter for its own tests, so it can pass before the behaviour exists; point it at the new test file or name`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const slicesSec = section(plan, 'Slices');
|
|
117
|
+
if (slicesSec && !plan.slices.length) err('J08', slicesSec.start, 'Slices section has no "### S<n>: <title> [state]" headings');
|
|
118
|
+
const doing = [];
|
|
119
|
+
for (const s of plan.slices) {
|
|
120
|
+
if (!s.id) { err('J08', s.line, 'slice heading must look like "### S1: <title> [todo]"'); continue; }
|
|
121
|
+
if (!SLICE_STATES.includes(s.state)) err('J08', s.line, `slice ${s.id} state must be one of ${SLICE_STATES.map((x) => `[${x}]`).join(' ')}`);
|
|
122
|
+
if (s.state === 'doing') doing.push(s);
|
|
123
|
+
const isProgramChild = tier === 'program' && s.fields.plan;
|
|
124
|
+
if (isProgramChild) {
|
|
125
|
+
const child = s.fields.plan.value.replace(/`/g, '').trim();
|
|
126
|
+
if (root && !existsSync(join(root, child))) warn('J11', s.fields.plan.line, `child plan ${child} does not exist yet`);
|
|
127
|
+
} else {
|
|
128
|
+
if (!s.fields.touch) err('J09', s.line, `slice ${s.id} has no "Touch:" line`);
|
|
129
|
+
if (!s.fields.checks) err('J09', s.line, `slice ${s.id} has no "Checks:" line`);
|
|
130
|
+
}
|
|
131
|
+
if (s.fields.touch && root && paths) {
|
|
132
|
+
for (const t of touchPaths(s.fields.touch.value)) {
|
|
133
|
+
if (!t.isNew && !/[*?]/.test(t.path) && !existsSync(join(root, t.path))) {
|
|
134
|
+
err('J11', s.fields.touch.line, `${t.path} does not exist; mark it "(new)" if the slice creates it`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (!touchPaths(s.fields.touch.value).length) err('J09', s.fields.touch.line, `slice ${s.id} Touch: lists no paths in backticks`);
|
|
138
|
+
}
|
|
139
|
+
if (s.fields.checks) {
|
|
140
|
+
const ids = checkIds(s.fields.checks.value);
|
|
141
|
+
const hasCmd = /`[^`]+`/.test(s.fields.checks.value);
|
|
142
|
+
if (!ids.length && !hasCmd) err('J09', s.fields.checks.line, `slice ${s.id} Checks: names no check IDs or commands`);
|
|
143
|
+
if (checksData) {
|
|
144
|
+
for (const id of ids) if (!knownIds.has(id)) err('J10', s.fields.checks.line, `check ${id} is not in checks.json`);
|
|
145
|
+
} else if (ids.length && checks) {
|
|
146
|
+
err('J10', s.fields.checks.line, `slice ${s.id} names check IDs but there is no checks.json (a brief plan may give commands in backticks instead)`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
for (const r of s.risks) {
|
|
150
|
+
if (!/\bDetect:/.test(r.text) || !/\bFallback:/.test(r.text)) err('J15', r.line, 'risk needs "Detect:" and "Fallback:"');
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (doing.length > 1) err('J19', doing[1].line, `more than one slice is [doing]: ${doing.map((s) => s.id).join(', ')}`);
|
|
154
|
+
|
|
155
|
+
// J18 Now references
|
|
156
|
+
if (plan.now) {
|
|
157
|
+
const ids = new Set(plan.slices.map((s) => s.id));
|
|
158
|
+
for (const m of plan.now.matchAll(/\bS\d+\b/g)) if (!ids.has(m[0])) err('J18', plan.nowLine, `"Now:" names ${m[0]}, which is not a slice`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// J12 estimates, J13 vague words, J15 matrix (whole file except Log)
|
|
162
|
+
const logSec = section(plan, 'Log');
|
|
163
|
+
const scanEnd = logSec ? logSec.start : plan.lines.length;
|
|
164
|
+
let inFence = false;
|
|
165
|
+
for (let i = 0; i < scanEnd; i++) {
|
|
166
|
+
const l = plan.lines[i];
|
|
167
|
+
if (/^```/.test(l.trim())) { inFence = !inFence; continue; }
|
|
168
|
+
if (inFence) continue;
|
|
169
|
+
const prose = l.replace(/`[^`]*`/g, '');
|
|
170
|
+
if (ESTIMATE_RES.some((re) => re.test(prose))) err('J12', i, 'time or effort estimate; report scope (slices, files, checks) instead');
|
|
171
|
+
const low = ` ${prose.toLowerCase()} `;
|
|
172
|
+
for (const w of VAGUE) {
|
|
173
|
+
const re = new RegExp(`(^|[^a-z])${w.replace('.', '\\.')}([^a-z]|$)`);
|
|
174
|
+
if (re.test(low)) warn('J13', i, `"${w}" defers a decision; state it or move it to Questions`);
|
|
175
|
+
}
|
|
176
|
+
if (RISK_MATRIX.test(prose)) warn('J15', i, 'risk scoring grid; give each risk Detect: and Fallback: instead');
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// J16 log
|
|
180
|
+
if (logSec) {
|
|
181
|
+
logSec.body.forEach((l, k) => {
|
|
182
|
+
if (/^\s*-\s/.test(l) && !DATE_ENTRY.test(l.trim())) err('J16', logSec.start + 1 + k, 'log entry must start "- YYYY-MM-DD: "');
|
|
183
|
+
});
|
|
184
|
+
if (root && rel) {
|
|
185
|
+
const old = showHead(root, rel);
|
|
186
|
+
if (old) {
|
|
187
|
+
const before = logEntries(parsePlan(old));
|
|
188
|
+
const now = logEntries(plan);
|
|
189
|
+
const broken = before.findIndex((e, k) => now[k] !== e);
|
|
190
|
+
if (broken !== -1) err('J16', logSec.start, `log is append-only: committed entry ${broken + 1} was changed or removed ("${before[broken].slice(0, 60)}")`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return P.sort((a, b) => a.line - b.line || a.rule.localeCompare(b.rule));
|
|
196
|
+
}
|