jig-plan 2.1.0 → 2.4.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.
package/cli/lib/hooks.mjs CHANGED
@@ -3,13 +3,13 @@
3
3
  // - never return permissionDecision "allow": that would skip the user's prompts
4
4
  // - never run repo-defined commands: checks.json is untrusted input
5
5
  // - append short context, and don't repeat it
6
- import { existsSync, mkdirSync, readFileSync, writeFileSync, statSync, appendFileSync } from 'node:fs';
7
- import { join, relative, isAbsolute } from 'node:path';
6
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, statSync, lstatSync, readlinkSync, appendFileSync, realpathSync } from 'node:fs';
7
+ import { join, relative, isAbsolute, dirname, basename } from 'node:path';
8
8
  import { repoRoot, stateDir } from './git.mjs';
9
9
  import { activePlans, doingSlice, sliceTouch, statusSummary, plansDir } from './status.mjs';
10
10
  import { loadChecks, validateChecks, snapshot, loosened, applyEdit } from './checks.mjs';
11
- import { evidence, workTree } from './verify.mjs';
12
- import { parsePlan } from './plan.mjs';
11
+ import { evidence, workTree, readJsonl } from './verify.mjs';
12
+ import { parsePlan, logEntries } from './plan.mjs';
13
13
 
14
14
  const off = (name) => {
15
15
  const v = (process.env.JIG_HOOKS_OFF ?? '').split(',').map((s) => s.trim());
@@ -62,6 +62,12 @@ export const NUDGE = 'jig: for any request to change code in this repo, invoke t
62
62
 
63
63
  export function sessionStart(input) {
64
64
  const root = rootOf(input);
65
+ // The transcript path, kept so a review can read the builder's tool calls
66
+ // locally (docs/evidence-schema.md). Only the path is stored, never content.
67
+ if (typeof input.transcript_path === 'string' && repoRoot(root)) {
68
+ const st = sessionState(root, input);
69
+ if (st.data.transcript !== input.transcript_path) { st.data.transcript = input.transcript_path; st.save(); }
70
+ }
65
71
  if (activePlans(root).length) keepStartTree(root, sessionState(root, input));
66
72
  const parts = [];
67
73
  if (process.env.JIG_NUDGE !== 'off') parts.push(NUDGE);
@@ -101,9 +107,11 @@ function sameFile(a, b) {
101
107
  // code-review post treats them, and CI workflows, as paths a person reads.
102
108
  // Claude Code also reads CLAUDE.md and .claude/ below the root. Compared in
103
109
  // lower case: on macOS and Windows `.CLAUDE/` is the same directory.
110
+ const pathParts = (rel) => rel.toLowerCase().split(/[\\/]/);
111
+ const isWorkflow = (rel) => pathParts(rel).slice(0, 2).join('/') === '.github/workflows';
104
112
  const isRuleFile = (rel) => {
105
- const parts = rel.toLowerCase().split(/[\\/]/);
106
- return ['claude.md', 'review.md'].includes(parts[parts.length - 1]) || parts.slice(0, -1).includes('.claude') || parts.slice(0, 2).join('/') === '.github/workflows';
113
+ const parts = pathParts(rel);
114
+ return ['claude.md', 'review.md'].includes(parts[parts.length - 1]) || parts.slice(0, -1).includes('.claude') || isWorkflow(rel);
107
115
  };
108
116
  // Any case (Windows env names ignore it), or JIG followed by an escape.
109
117
  const SWITCHES = /\bjig_(gates|hooks_off)\b|\bjig\\[xuU_]/i;
@@ -115,10 +123,62 @@ function switchesIn(text) {
115
123
  return s.match(SWITCHES)?.[0] ?? null;
116
124
  }
117
125
 
126
+ // The path as git sees it. The directory part is resolved (nearest existing
127
+ // ancestor), so a file reached through a symlink of the repo (macOS /tmp and
128
+ // /private/tmp) maps to the same repo-relative path. The file name is kept as
129
+ // the edit spelled it: a symlink named CLAUDE.md is still a rule file.
130
+ function underRealDir(abs) {
131
+ let dir = dirname(abs); const rest = [basename(abs)];
132
+ while (!existsSync(dir) && dirname(dir) !== dir) { rest.unshift(basename(dir)); dir = dirname(dir); }
133
+ try { return join(realpathSync(dir), ...rest); } catch { return abs; }
134
+ }
135
+
136
+ // A symlinked file is judged twice, by its own name and by its target, and
137
+ // the first ask wins: an edit through it changes the target.
118
138
  export function preEdit(input) {
119
- const file = input.tool_input?.file_path ?? input.tool_input?.notebook_path;
139
+ const key = input.tool_input?.file_path !== undefined ? 'file_path' : 'notebook_path';
140
+ const raw = input.tool_input?.[key];
141
+ if (!raw) return guardPath(input);
120
142
  const root = rootOf(input);
121
- const abs = file ? (isAbsolute(file) ? file : join(root, file)) : null;
143
+ const given = isAbsolute(raw) ? raw : join(root, raw);
144
+ const named = underRealDir(given);
145
+ const hops = linkTargets(named);
146
+ if (hops === null) return ask(undefined, `jig: ${relative(root, named)} is a symlink jig can't resolve (a loop or an unreadable link), so it can't tell what this edit would change.`);
147
+ // Spellings to judge: resolved directories with the edit's file name, the
148
+ // path exactly as given (keeps an in-repo directory link's name, such as a
149
+ // linked .github/), and every hop of a symlink chain, including a target
150
+ // that doesn't exist yet (a Write through a dangling link creates it).
151
+ const paths = [...new Set([named, given, ...hops])];
152
+ const at = (p) => ({ ...input, tool_input: { ...input.tool_input, [key]: p } });
153
+ const asks = (o) => Boolean(o?.decision || o?.hookSpecificOutput?.permissionDecision);
154
+ const outs = paths.map((p) => guardPath(at(p)));
155
+ // An ask observe mode can't silence beats an enforced one, which beats an
156
+ // observed one: whichever is returned is what runHook acts on.
157
+ return outs.find((o) => asks(o) && !o.gate) ?? outs.find((o) => asks(o) && !observed(o.gate)) ?? outs.find(asks) ?? outs[0];
158
+ }
159
+
160
+ // The paths a symlink chain passes through, each under a real directory.
161
+ // [] when the path isn't a link; null when the chain can't be followed.
162
+ function linkTargets(p) {
163
+ const out = [];
164
+ let cur = p;
165
+ for (let i = 0; i < 40; i++) {
166
+ let st;
167
+ try { st = lstatSync(cur); } catch { return out; } // missing: the chain ends here
168
+ if (!st.isSymbolicLink()) return out;
169
+ let to;
170
+ try { to = readlinkSync(cur); } catch { return null; }
171
+ cur = underRealDir(isAbsolute(to) ? to : join(dirname(cur), to));
172
+ out.push(cur);
173
+ }
174
+ return null;
175
+ }
176
+
177
+ function guardPath(input) {
178
+ const key = input.tool_input?.file_path !== undefined ? 'file_path' : 'notebook_path';
179
+ const raw = input.tool_input?.[key];
180
+ const root = rootOf(input);
181
+ const abs = raw ? (isAbsolute(raw) ? raw : join(root, raw)) : null;
122
182
  const rel = abs ? relative(root, abs) : null;
123
183
  // Turning jig's gates off from a rule file always asks, and has no gate
124
184
  // name, so observe mode can't silence it. Judged on the whole file after
@@ -135,9 +195,21 @@ export function preEdit(input) {
135
195
  }
136
196
  }
137
197
  const out = guardEdit(input);
138
- if (out?.gate || !rel || !isRuleFile(rel)) return out;
139
- // Observe-only until the owner decides from the log, so log here and keep
140
- // any scope warning.
198
+ // A workflow edit keeps its own ask even when another gate on the same edit
199
+ // (protects, freeze) is only being observed: log that one, ask for rules.
200
+ if (rel && isWorkflow(rel) && out?.gate && observed(out.gate)) {
201
+ observe(input, 'pre-edit', out.gate, out);
202
+ } else if (out?.gate || !rel || !isRuleFile(rel)) return out;
203
+ // CI workflows run with the repo's secrets and are rarely part of normal
204
+ // work, so an edit asks (JIG_GATES=observe:rules turns it into a log entry).
205
+ // CLAUDE.md, REVIEW.md and .claude/ are only logged: CLAUDE.md edits are
206
+ // usually legitimate, and Claude Code already prompts for .claude/ writes.
207
+ if (isWorkflow(rel)) {
208
+ const a = ask('rules', `jig: ${rel} is a CI workflow. It runs in CI with the repo's secrets, so a person should read this change.`);
209
+ const ctx = out?.gate ? null : out?.hookSpecificOutput?.additionalContext;
210
+ if (ctx) a.hookSpecificOutput.additionalContext = ctx;
211
+ return a;
212
+ }
141
213
  observe(input, 'pre-edit', 'rules', ask('rules', `jig: ${rel} is a rule file (it tells agents or reviewers what to do). A person should read changes to it.`));
142
214
  return out;
143
215
  }
@@ -233,22 +305,150 @@ export function installedPackages(command) {
233
305
  return found;
234
306
  }
235
307
 
308
+ // A command split at unquoted ;, &&, ||, | and newlines. A heredoc body
309
+ // stays with the segment that opened it, so its lines aren't commands.
310
+ export function shellSegments(cmd) {
311
+ const out = [];
312
+ let cur = ''; let q = null;
313
+ for (let i = 0; i < cmd.length; i++) {
314
+ const c = cmd[i];
315
+ if (q) { cur += c; if (c === '\\' && q === '"' && i + 1 < cmd.length) cur += cmd[++i]; else if (c === q) q = null; continue; }
316
+ if (c === "'" || c === '"') { q = c; cur += c; continue; }
317
+ if (c === '\\' && i + 1 < cmd.length) { cur += c + cmd[++i]; continue; }
318
+ const two = cmd.slice(i, i + 2);
319
+ if (c === '\n') {
320
+ const h = cur.match(/<<-?\s*(['"]?)([\w.-]+)\1/);
321
+ if (h) {
322
+ const rest = cmd.slice(i + 1);
323
+ const end = rest.search(new RegExp(`^\\s*${h[2].replace(/[.-]/g, '\\$&')}\\s*$`, 'm'));
324
+ const body = end === -1 ? rest : rest.slice(0, end);
325
+ cur += `\n${body}`;
326
+ i += body.length + (end === -1 ? 0 : (rest.slice(end).match(/^.*$/m)?.[0].length ?? 0));
327
+ }
328
+ out.push(cur); cur = ''; continue;
329
+ }
330
+ if (c === ';' || two === '&&' || two === '||' || c === '|') { if (two === '&&' || two === '||') i++; out.push(cur); cur = ''; continue; }
331
+ cur += c;
332
+ }
333
+ out.push(cur);
334
+ return out.map((s) => s.trim()).filter(Boolean);
335
+ }
336
+
337
+ // A real `git commit` segment: allowing a subshell, sudo/env/command/time/
338
+ // nice/exec, env assignments, a path to git, and git's own options before the
339
+ // subcommand; `sh -c "..."` is looked into. A dry run isn't a commit.
340
+ // Misses: aliases, functions, scripts and `eval`.
341
+ const PREFIX = String.raw`(?:[({]\s*)*(?:(?:sudo|env|command|time|nice|exec)\s+(?:-\S+\s+)*|\w+=\S*\s+)*`;
342
+ const GITOPT = String.raw`(?:-[cC]\s+(?:"[^"]*"|'[^']*'|\S+)|--(?:git-dir|work-tree|namespace)(?:=\S+|\s+\S+)|--[\w-]+(?:=\S+)?)`;
343
+ const COMMIT = new RegExp(String.raw`^${PREFIX}(?:\S*/)?\\?git(?:\s+${GITOPT})*\s+commit(?=\s|$|[)}])`);
344
+ export function commitSegment(cmd) {
345
+ for (const seg of shellSegments(cmd)) {
346
+ const inner = seg.match(/^(?:\S*\/)?(?:ba|z|da)?sh\s+-c\s+(['"])([\s\S]*)\1\s*$/);
347
+ if (inner) { const s = commitSegment(inner[2]); if (s) return s; continue; }
348
+ if (COMMIT.test(seg) && !/\s--dry-run\b/.test(seg)) return seg;
349
+ }
350
+ return null;
351
+ }
352
+ export const isGitCommit = (cmd) => commitSegment(cmd) !== null;
353
+ const VERIFIED_NONE = /Verified: none \([^)\s][^)]*\)/;
354
+
355
+ // What the commit's own message says, read from its segment (-m, a heredoc)
356
+ // or a -F file. null when there's no message flag (an editor will open, or
357
+ // --no-edit reuses a message jig can't see).
358
+ function commitMessage(seg, cwd) {
359
+ if (VERIFIED_NONE.test(seg)) return { none: true };
360
+ const f = seg.match(/(?:^|\s)(?:-[a-zA-Z]*F\s*|--file(?:=|\s+))(?:"([^"]+)"|'([^']+)'|([^\s'"]+))/);
361
+ const file = f ? (f[1] ?? f[2] ?? f[3]) : null;
362
+ if (file && file !== '-') {
363
+ const p = isAbsolute(file) ? file : join(cwd, file);
364
+ try {
365
+ const st = lstatSync(p);
366
+ if (st.isFile() && st.size <= 65536) return { none: VERIFIED_NONE.test(readFileSync(p, 'utf8')) };
367
+ } catch { /* unreadable: judged as a message without the line */ }
368
+ return { none: false };
369
+ }
370
+ if (file || /(?:^|\s)(?:-[a-zA-Z]*m|--message)(?=[\s=]|$|["'])/.test(seg)) return { none: false };
371
+ return null;
372
+ }
373
+
374
+ // The commit gate, observed by default (JIG_GATES=enforce:commit to ask).
375
+ // It only looks at repos where jig is in use: an active plan with
376
+ // checks.json, or a review record. It compares the working-tree fingerprint,
377
+ // not the index, so a commit that leaves verified changes unstaged can pass.
378
+ function commitGate(input, root, seg) {
379
+ const plans = activePlans(root);
380
+ const reviewRecs = readJsonl(root, 'reviews.jsonl');
381
+ const used = plans.some(({ path }) => loadChecks(path).exists) || reviewRecs.length > 0;
382
+ // A Blocked slice may commit its work in progress, but only when every
383
+ // plan being built is blocked: one blocked plan doesn't excuse another.
384
+ const building = plans.filter(({ path, plan }) => doingSlice(plan) && loadChecks(path).exists);
385
+ if (!used || (building.length && building.every(({ plan }) => blockedReason(plan)))) return null;
386
+ const msg = commitMessage(seg, input.cwd ?? root);
387
+ if (msg?.none) return null;
388
+ const tree = workTree(root);
389
+ if (!tree) return null;
390
+ const passed = (r) => (r.results ?? []).length > 0 && r.results.every((x) => x.pass);
391
+ // Only a passing record is cover: a fix-first review at this tree is not.
392
+ if (evidence(root).some((r) => r.tree === tree && passed(r)) || reviewRecs.some((r) => !r.kind && r.tree === tree && r.verdict === 'ready')) return null;
393
+ const why = `jig: this commit's tree (${tree.slice(0, 7)}) has no current passing evidence or review record`;
394
+ const fix = 'Run `jig verify --record` or jig:review first, or say in the message why nothing was verified.';
395
+ // No message flag: the message can't be read, so this is only logged.
396
+ if (!msg) { observe(input, 'pre-bash', 'commit', ask('commit', `${why}, and it has no message flag (message unknown: an editor will open or a message is reused). Logged only.`)); return null; }
397
+ // A gate that keeps firing gets switched off: when it enforces, two per
398
+ // session, then it lets go. Observed, every fire is logged, so the count
399
+ // the owner decides from is complete.
400
+ if (!observed('commit')) {
401
+ const st = sessionState(root, input);
402
+ const fired = st.data.commitFired ?? 0;
403
+ if (fired >= 2) return null;
404
+ st.data.commitFired = fired + 1;
405
+ st.save();
406
+ }
407
+ return ask('commit', `${why}, and its message has no "Verified: none (<reason>)" line. ${fix}`);
408
+ }
409
+
236
410
  export function preBash(input) {
237
411
  const cmd = input.tool_input?.command ?? '';
238
412
  const root = rootOf(input);
239
413
  if (activePlans(root).length) keepStartTree(root, sessionState(root, input));
240
414
  const pkgs = installedPackages(cmd);
241
- if (!pkgs.length) return null;
415
+ if (!pkgs.length) {
416
+ const seg = commitSegment(cmd);
417
+ return seg ? commitGate(input, root, seg) : null;
418
+ }
242
419
  const names = pkgs.map((p) => `${p.name} (${p.eco})`).join(', ');
243
420
  return ask('install', `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.`);
244
421
  }
245
422
 
423
+ // The reason when a plan's last Log entry is `Blocked: <reason>`: the
424
+ // builder stopped on purpose (a spec conflict, a check that can't pass here,
425
+ // a missing service) and the owner decides. A later verify line, or any other
426
+ // entry after it, ends the block.
427
+ export function blockedReason(plan) {
428
+ const last = logEntries(plan).pop() ?? '';
429
+ return last.match(/^-\s*\d{4}-\d{2}-\d{2}(?: \d{2}:\d{2})?:\s*Blocked:\s*(\S.*)$/)?.[1] ?? null;
430
+ }
431
+
246
432
  export function stop(input) {
247
433
  if (input.stop_hook_active) return null;
248
434
  if ((input.background_tasks ?? []).length) return null;
249
435
  const root = rootOf(input);
250
436
  const st = sessionState(root, input);
251
- const plans = activePlans(root).filter(({ plan }) => doingSlice(plan));
437
+ const doing = activePlans(root).filter(({ plan }) => doingSlice(plan));
438
+ // Blocked plans are an accepted end state: no tree or rounds checks. The
439
+ // owner hears about each once per session.
440
+ const blocked = doing.map(({ path, plan }) => ({ rel: relative(root, path), why: blockedReason(plan) })).filter((b) => b.why);
441
+ const told = new Set(st.data.blockedTold ?? []);
442
+ const news = blocked.filter((b) => !told.has(`${b.rel}\0${b.why}`));
443
+ const out = stopChecks(root, st, doing.filter(({ path }) => !blocked.some((b) => b.rel === relative(root, path))));
444
+ if (!news.length) return out;
445
+ st.data.blockedTold = [...told, ...news.map((b) => `${b.rel}\0${b.why}`)].slice(-20);
446
+ st.save();
447
+ const systemMessage = news.map((b) => `jig: ${b.rel} is blocked: ${b.why}. The agent stopped on purpose; this needs your decision.`).join(' ');
448
+ return out ? { ...out, systemMessage } : { systemMessage };
449
+ }
450
+
451
+ function stopChecks(root, st, plans) {
252
452
  if (!plans.length) return null;
253
453
  // Only when a checks.json exists; brief plans state checks as commands.
254
454
  const withChecks = plans.map(({ path, plan }) => ({ path, slice: doingSlice(plan), checks: loadChecks(path) })).filter((x) => x.checks.exists && Array.isArray(x.checks.data?.checks));
@@ -323,19 +523,25 @@ const HANDLERS = { 'session-start': sessionStart, 'pre-edit': preEdit, 'pre-bash
323
523
  // JIG_GATES=observe logs every ask and block to .git/jig/observe.jsonl and
324
524
  // prints nothing; observe:<gate>,<gate> does that for the named gates only.
325
525
  // Use it to count false positives before a gate enforces. Gates: protects,
326
- // freeze, install, tree, rounds, and rules (observe-only for now).
526
+ // freeze, install, tree, rounds, rules (asks for CI workflows, logs the
527
+ // other rule files), and commit (observed unless JIG_GATES=enforce:commit).
528
+ // Gates that ship observed until the owner decides from observe.jsonl.
529
+ // JIG_GATES=enforce:<gate>,... makes one ask.
530
+ const OBSERVED_BY_DEFAULT = ['commit'];
327
531
  function observed(gate) {
328
532
  const v = (process.env.JIG_GATES ?? '').trim();
329
533
  if (v === 'observe') return true;
330
- const m = v.match(/^observe:(.*)$/);
331
- return Boolean(m && m[1].split(',').map((s) => s.trim()).includes(gate));
534
+ const m = v.match(/^(observe|enforce):(.*)$/);
535
+ const named = m ? m[2].split(',').map((s) => s.trim()).includes(gate) : false;
536
+ if (m?.[1] === 'observe' && named) return true;
537
+ return OBSERVED_BY_DEFAULT.includes(gate) && !(m?.[1] === 'enforce' && named);
332
538
  }
333
539
 
334
540
  function observe(input, hook, gate, out) {
335
541
  const root = rootOf(input);
336
542
  const file = input.tool_input?.file_path;
337
543
  const entry = {
338
- t: Date.now(), hook, gate, session: sid(input),
544
+ v: 1, t: Date.now(), hook, gate, session: sid(input),
339
545
  decision: out.decision ?? out.hookSpecificOutput?.permissionDecision,
340
546
  reason: out.reason ?? out.hookSpecificOutput?.permissionDecisionReason,
341
547
  ...(file ? { file: relative(root, isAbsolute(file) ? file : join(root, file)) } : {}),
@@ -353,8 +559,11 @@ export function runHook(name) {
353
559
  const out = fn(input);
354
560
  if (out) {
355
561
  const { gate, ...rest } = out;
356
- if (gate && observed(gate)) observe(input, name, gate, rest);
357
- else emit(rest);
562
+ if (gate && observed(gate)) {
563
+ observe(input, name, gate, rest);
564
+ // A message for the owner is never observed away with the gate.
565
+ if (rest.systemMessage) emit({ systemMessage: rest.systemMessage });
566
+ } else emit(rest);
358
567
  }
359
568
  } catch (e) {
360
569
  // Guardrails, not a security boundary (Bash can edit files without Edit):
package/cli/lib/lint.mjs CHANGED
@@ -158,7 +158,8 @@ export function lintText(text, { root = null, rel = null, checks = null, paths =
158
158
  for (const id of ids) if (!knownIds.has(id)) err('J10', s.fields.checks.line, `check ${id} is not in checks.json`);
159
159
  // jig verify runs a slice's checks by their `slice` field, so a check
160
160
  // listed here but owned by another slice never runs for this one.
161
- for (const id of ids) if (knownIds.has(id) && checkSlice.get(id) !== s.id) warn('J24', s.fields.checks.line, `check ${id} belongs to ${checkSlice.get(id)}, so \`jig verify\` won't run it for ${s.id}; give ${s.id} its own check`);
161
+ // A [done] slice never runs its checks again, so J24 looks ahead only.
162
+ if (s.state !== 'done') for (const id of ids) if (knownIds.has(id) && checkSlice.get(id) !== s.id) warn('J24', s.fields.checks.line, `check ${id} belongs to ${checkSlice.get(id)}, so \`jig verify\` won't run it for ${s.id}; give ${s.id} its own check`);
162
163
  } else if (ids.length && checks) {
163
164
  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)`);
164
165
  }