handoff-check 0.5.0 → 0.7.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/dist/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
- import { open as open2 } from "node:fs/promises";
5
- import { resolve as resolve5 } from "node:path";
4
+ import { open as open3 } from "node:fs/promises";
5
+ import { resolve as resolve6 } from "node:path";
6
6
  import { parseArgs } from "node:util";
7
7
  // package.json
8
8
  var package_default = {
9
9
  name: "handoff-check",
10
- version: "0.5.0",
10
+ version: "0.7.0",
11
11
  description: "A deterministic, local CLI that verifies active constraints before a coding agent resumes work.",
12
12
  type: "module",
13
13
  packageManager: "bun@1.2.10",
@@ -67,6 +67,7 @@ var package_default = {
67
67
  };
68
68
 
69
69
  // src/config.ts
70
+ import { createHash as createHash2 } from "node:crypto";
70
71
  import { readFile } from "node:fs/promises";
71
72
  import { dirname, resolve } from "node:path";
72
73
 
@@ -143,9 +144,9 @@ function timestamp(value, path) {
143
144
  }
144
145
  return millis;
145
146
  }
146
- function version(value, path, retained = false) {
147
- if (value.schemaVersion !== 1 && value.schemaVersion !== 2 && !(retained && value.schemaVersion === 3))
148
- fail(`${path}.schemaVersion: expected ${retained ? "1, 2 or 3" : "1 or 2"}`);
147
+ function version(value, path, max) {
148
+ if (!Number.isInteger(value.schemaVersion) || value.schemaVersion < 1 || value.schemaVersion > max)
149
+ fail(`${path}.schemaVersion: expected 1 through ${max}`);
149
150
  }
150
151
  function revision(value, path) {
151
152
  if (!Number.isSafeInteger(value) || value < 1)
@@ -199,12 +200,17 @@ function parseConstraint(input, path, revisioned) {
199
200
  }
200
201
  function parseManifest(input) {
201
202
  const root = object(input, "manifest");
202
- keys(root, ["schemaVersion", "constraints"], "manifest");
203
- version(root, "manifest");
203
+ keys(root, [
204
+ "schemaVersion",
205
+ "constraints",
206
+ ...root.schemaVersion === 3 ? ["projectId"] : []
207
+ ], "manifest");
208
+ version(root, "manifest", 3);
209
+ const projectId = root.schemaVersion === 3 ? identifier(root.projectId, "manifest.projectId") : undefined;
204
210
  if (!Array.isArray(root.constraints))
205
211
  fail("manifest.constraints: expected an array");
206
212
  const constraints = root.constraints.map((entry, index) => {
207
- return parseConstraint(entry, `manifest.constraints[${index}]`, root.schemaVersion === 2);
213
+ return parseConstraint(entry, `manifest.constraints[${index}]`, root.schemaVersion !== 1);
208
214
  });
209
215
  unique(constraints.map((rule) => rule.id), "manifest.constraints");
210
216
  const byId = new Map(constraints.map((rule) => [rule.id, rule]));
@@ -230,32 +236,36 @@ function parseManifest(input) {
230
236
  for (const id of path)
231
237
  completed.add(id);
232
238
  }
233
- return { schemaVersion: root.schemaVersion, constraints };
239
+ return {
240
+ schemaVersion: root.schemaVersion,
241
+ ...projectId === undefined ? {} : { projectId },
242
+ constraints
243
+ };
234
244
  }
235
245
  function parseHandoff(input) {
236
246
  const root = object(input, "handoff");
237
- version(root, "handoff", true);
247
+ version(root, "handoff", 4);
238
248
  keys(root, [
239
249
  "schemaVersion",
240
250
  "task",
241
251
  "activeConstraints",
242
- ...root.schemaVersion !== 1 ? ["scope", "capturedAt"] : []
252
+ ...root.schemaVersion !== 1 ? ["scope", "capturedAt"] : [],
253
+ ...root.schemaVersion === 4 ? ["projectId", "contentMode"] : []
243
254
  ], "handoff");
244
255
  const task = string(root.task, "handoff.task");
245
256
  if (!Array.isArray(root.activeConstraints))
246
257
  fail("handoff.activeConstraints: expected an array");
247
258
  if (root.schemaVersion !== 1) {
259
+ const projectId = root.schemaVersion === 4 ? identifier(root.projectId, "handoff.projectId") : undefined;
260
+ if (root.schemaVersion === 4 && root.contentMode !== "hashes" && root.contentMode !== "retained")
261
+ fail("handoff.contentMode: expected hashes or retained");
262
+ const retained = root.schemaVersion === 3 || root.schemaVersion === 4 && root.contentMode === "retained";
248
263
  const scope = identifier(root.scope, "handoff.scope");
249
264
  timestamp(root.capturedAt, "handoff.capturedAt");
250
265
  const activeConstraints2 = root.activeConstraints.map((entry, index) => {
251
266
  const path = `handoff.activeConstraints[${index}]`;
252
267
  const ref = object(entry, path);
253
- keys(ref, [
254
- "id",
255
- "revision",
256
- "contentHash",
257
- ...root.schemaVersion === 3 ? ["content"] : []
258
- ], path);
268
+ keys(ref, ["id", "revision", "contentHash", ...retained ? ["content"] : []], path);
259
269
  const contentHash = string(ref.contentHash, `${path}.contentHash`);
260
270
  if (!/^sha256:[a-f0-9]{64}(?![\s\S])/.test(contentHash))
261
271
  fail(`${path}.contentHash: expected sha256 followed by 64 lowercase hex digits`);
@@ -264,7 +274,7 @@ function parseHandoff(input) {
264
274
  revision: revision(ref.revision, `${path}.revision`),
265
275
  contentHash
266
276
  };
267
- if (root.schemaVersion === 3) {
277
+ if (retained) {
268
278
  const content = parseConstraint(ref.content, `${path}.content`, true);
269
279
  const expected = reference(content);
270
280
  if (expected.id !== parsed.id || expected.revision !== parsed.revision || expected.contentHash !== parsed.contentHash)
@@ -279,6 +289,7 @@ function parseHandoff(input) {
279
289
  unique(activeConstraints2.map((ref) => ref.id), "handoff.activeConstraints");
280
290
  return {
281
291
  schemaVersion: root.schemaVersion,
292
+ ...root.schemaVersion === 4 ? { projectId, contentMode: root.contentMode } : {},
282
293
  task,
283
294
  scope,
284
295
  capturedAt: root.capturedAt,
@@ -291,30 +302,54 @@ function parseHandoff(input) {
291
302
  }
292
303
 
293
304
  // src/config.ts
294
- async function readJson(path) {
295
- let content;
305
+ class ProfileError extends InputError {
306
+ }
307
+ function selectProfile(config, profile) {
308
+ if (profile === undefined)
309
+ return config;
310
+ identifier(profile, "--profile");
311
+ if (config.schemaVersion !== 2 || !config.profiles || !Object.hasOwn(config.profiles, profile))
312
+ throw new ProfileError(`Unknown profile '${profile}'; explicitly define it in config v2`);
313
+ return { ...config, ...config.profiles[profile] };
314
+ }
315
+ function digest(bytes) {
316
+ return `sha256:${createHash2("sha256").update(bytes).digest("hex")}`;
317
+ }
318
+ async function readJsonRecord(path) {
319
+ let bytes;
296
320
  try {
297
- content = await readFile(path, "utf8");
321
+ bytes = await readFile(path);
298
322
  } catch {
299
323
  throw new InputError(`Cannot read input file '${path}'`);
300
324
  }
325
+ let input;
301
326
  try {
302
- return JSON.parse(content);
327
+ input = JSON.parse(bytes.toString("utf8"));
303
328
  } catch {
304
329
  throw new InputError(`Invalid JSON in '${path}'`);
305
330
  }
331
+ return { input, path, sha256: digest(bytes) };
332
+ }
333
+ async function readJson(path) {
334
+ return (await readJsonRecord(path)).input;
306
335
  }
307
336
  function parseConfig(input) {
308
337
  if (!input || typeof input !== "object" || Array.isArray(input))
309
338
  throw new InputError("config: expected an object");
310
339
  const value = input;
311
- if (value.schemaVersion !== 1)
312
- throw new InputError("config.schemaVersion: expected 1");
340
+ if (value.schemaVersion !== 1 && value.schemaVersion !== 2)
341
+ throw new InputError("config.schemaVersion: expected 1 or 2");
313
342
  for (const key of Object.keys(value)) {
314
- if (!["schemaVersion", "constraints", "handoff", "scope"].includes(key))
343
+ if (![
344
+ "schemaVersion",
345
+ "constraints",
346
+ "handoff",
347
+ "scope",
348
+ ...value.schemaVersion === 2 ? ["projectId", "profiles"] : []
349
+ ].includes(key))
315
350
  throw new InputError(`config: unknown field '${key}'`);
316
351
  }
317
- const config = { schemaVersion: 1 };
352
+ const config = { schemaVersion: value.schemaVersion };
318
353
  for (const key of ["constraints", "handoff"]) {
319
354
  if (Object.hasOwn(value, key)) {
320
355
  if (typeof value[key] !== "string" || !value[key].trim())
@@ -324,13 +359,36 @@ function parseConfig(input) {
324
359
  }
325
360
  if (Object.hasOwn(value, "scope"))
326
361
  config.scope = identifier(value.scope, "config.scope");
362
+ if (Object.hasOwn(value, "projectId"))
363
+ config.projectId = identifier(value.projectId, "config.projectId");
364
+ if (Object.hasOwn(value, "profiles")) {
365
+ if (!value.profiles || typeof value.profiles !== "object" || Array.isArray(value.profiles) || !Object.keys(value.profiles).length)
366
+ throw new InputError("config.profiles: expected a nonempty named object");
367
+ config.profiles = Object.create(null);
368
+ for (const [name, entry] of Object.entries(value.profiles)) {
369
+ identifier(name, "config.profiles name");
370
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
371
+ throw new InputError(`config.profiles.${name}: expected an object`);
372
+ const p = entry;
373
+ if (Object.keys(p).some((key) => !["scope", "constraints", "handoff"].includes(key)))
374
+ throw new InputError(`config.profiles.${name}: unknown field`);
375
+ const parsed = { scope: identifier(p.scope, `config.profiles.${name}.scope`) };
376
+ for (const key of ["constraints", "handoff"])
377
+ if (Object.hasOwn(p, key)) {
378
+ if (typeof p[key] !== "string" || !p[key].trim())
379
+ throw new InputError(`config.profiles.${name}.${key}: expected non-empty path`);
380
+ parsed[key] = p[key];
381
+ }
382
+ config.profiles[name] = parsed;
383
+ }
384
+ }
327
385
  return config;
328
386
  }
329
387
  async function loadConfig(cwd, explicit) {
330
388
  const path = resolve(cwd, explicit ?? ".handoff-check.json");
331
389
  let input;
332
390
  try {
333
- input = await readFile(path, "utf8");
391
+ input = await readFile(path);
334
392
  } catch (error) {
335
393
  if (explicit === undefined && error.code === "ENOENT")
336
394
  return { config: { schemaVersion: 1 }, directory: cwd };
@@ -338,20 +396,91 @@ async function loadConfig(cwd, explicit) {
338
396
  }
339
397
  let parsed;
340
398
  try {
341
- parsed = JSON.parse(input);
399
+ parsed = JSON.parse(input.toString("utf8"));
342
400
  } catch {
343
401
  throw new InputError(`Invalid JSON in config '${path}'`);
344
402
  }
345
- return { config: parseConfig(parsed), directory: dirname(path) };
403
+ return {
404
+ config: parseConfig(parsed),
405
+ directory: dirname(path),
406
+ source: { path, sha256: digest(input) }
407
+ };
346
408
  }
347
409
 
348
- // src/doctor.ts
349
- import { lstat, readFile as readFile2, stat as stat2 } from "node:fs/promises";
350
- import { resolve as resolve3 } from "node:path";
351
-
352
- // src/lifecycle.ts
353
- import { realpath, stat } from "node:fs/promises";
354
- import { dirname as dirname2, isAbsolute, relative, resolve as resolve2, sep } from "node:path";
410
+ // src/render.ts
411
+ function terminalText(value) {
412
+ return Array.from(value, (character) => {
413
+ const code = character.codePointAt(0) ?? 0;
414
+ return /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(character) ? `\\u${code.toString(16).padStart(4, "0")}` : character;
415
+ }).join("");
416
+ }
417
+ function markdownText(value) {
418
+ return terminalText(value).replace(/[&<>\\`*_{}[\]()#+.!|~:/@-]/g, (character) => `&#${character.charCodeAt(0)};`);
419
+ }
420
+ function verificationMarkdown(result, handoff, requireActive, requireContent) {
421
+ const label = result.status === "verified" ? result.expectedConstraints.length ? "PASS" : "PASS (EMPTY)" : "FAIL";
422
+ const lines = [
423
+ "# Handoff Check verification",
424
+ "",
425
+ `- Result: ${label}`,
426
+ `- Scope: ${markdownText(result.scope)}`,
427
+ ...result.projectId === undefined ? [] : [`- Project: ${markdownText(result.projectId)}`],
428
+ `- Evaluated at: ${markdownText(result.asOf)}`,
429
+ `- Active constraints checked: ${result.expectedConstraints.length}`,
430
+ `- Tracking: ${handoff.schemaVersion === 1 ? "IDs only; content changes not checked" : handoff.schemaVersion === 3 || handoff.schemaVersion === 4 && handoff.contentMode === "retained" ? "Content hashes with retained old content" : "Content hashes; old content not retained"}`,
431
+ `- Require content-aware handoff: ${requireContent}`,
432
+ `- Require active constraints: ${requireActive}`,
433
+ ""
434
+ ];
435
+ if (!result.expectedConstraints.length)
436
+ lines.push("No active constraints apply to this scope and time.", "");
437
+ lines.push("## Findings", "");
438
+ if (!result.findings.length)
439
+ lines.push("No findings.", "");
440
+ for (const finding of result.findings) {
441
+ lines.push(`### ${finding.code}${finding.id === undefined ? "" : ` ${markdownText(finding.id)}`}`, "", markdownText(finding.message), "");
442
+ if (finding.code === "CHANGED") {
443
+ if (finding.changes) {
444
+ lines.push("| Field | Before (saved) | After (current) |", "| --- | --- | --- |");
445
+ for (const change of finding.changes)
446
+ lines.push(`| ${change.field} | ${markdownText(JSON.stringify(change.before))} | ${markdownText(JSON.stringify(change.after))} |`);
447
+ lines.push("", "Null means an absent optional field.", "");
448
+ } else
449
+ lines.push("Previous content unavailable: this baseline stores hashes only. No textual diff can be reconstructed.", "");
450
+ }
451
+ }
452
+ lines.push("A pass checks declared constraints, not agent behavior or action authorization.");
453
+ return `${lines.join(`
454
+ `)}
455
+ `;
456
+ }
457
+ function explanationText(result, markdown) {
458
+ if (markdown) {
459
+ return [
460
+ "# Handoff Check explanation",
461
+ "",
462
+ `- Scope: ${markdownText(result.scope)}`,
463
+ ...result.projectId === undefined ? [] : [`- Project: ${markdownText(result.projectId)}`],
464
+ `- Evaluated at: ${markdownText(result.asOf)}`,
465
+ `- Active constraints: ${result.activeConstraintCount}`,
466
+ "",
467
+ "| ID | Rule scope | Decision | Reason | Description | Source |",
468
+ "| --- | --- | --- | --- | --- | --- |",
469
+ ...result.rules.map((rule) => `| ${[rule.id, rule.scope, rule.decision, rule.reason, rule.description, rule.source].map(markdownText).join(" | ")} |`),
470
+ "",
471
+ "Explains manifest applicability only; no handoff was compared.",
472
+ ""
473
+ ].join(`
474
+ `);
475
+ }
476
+ return [
477
+ ...result.rules.map((rule) => `${rule.decision.padEnd(12)} ${rule.id} ${terminalText(rule.reason)}; ${terminalText(rule.description)}; source ${terminalText(rule.source)}`),
478
+ `EXPLAIN ${result.activeConstraintCount} active constraints | ${result.rules.length} manifest rules | scope ${result.scope} | as of ${result.asOf}${result.projectId === undefined ? "" : ` | project ${result.projectId}`}`,
479
+ "No handoff was compared.",
480
+ ""
481
+ ].join(`
482
+ `);
483
+ }
355
484
 
356
485
  // src/verifier.ts
357
486
  function compare(a, b) {
@@ -368,8 +497,26 @@ function inactive(rule, scope, time) {
368
497
  return "EXPIRED";
369
498
  return;
370
499
  }
500
+ function checkProject(manifest, handoff, expectedProjectId) {
501
+ if (expectedProjectId !== undefined)
502
+ identifier(expectedProjectId, "projectId");
503
+ const boundManifest = manifest.schemaVersion === 3;
504
+ const boundHandoff = handoff?.schemaVersion === 4;
505
+ if (boundManifest || boundHandoff || expectedProjectId !== undefined) {
506
+ if (!boundManifest)
507
+ throw new InputError("Project binding requires a schemaVersion 3 manifest; migrate both inputs deliberately");
508
+ const projectId = identifier(manifest.projectId, "manifest.projectId");
509
+ if (expectedProjectId !== undefined && expectedProjectId !== projectId)
510
+ throw new InputError(`Manifest project '${projectId}' does not match configured project '${expectedProjectId}'`);
511
+ if (handoff !== undefined && (!boundHandoff || handoff.projectId !== projectId))
512
+ throw new InputError(`Handoff must be schemaVersion 4 bound to project '${projectId}'; review the intended project's baseline`);
513
+ return projectId;
514
+ }
515
+ return;
516
+ }
371
517
  function verify(manifest, handoff, scope, asOf, options = {}) {
372
518
  identifier(scope, "scope");
519
+ const projectId = checkProject(manifest, handoff, options.projectId);
373
520
  if (handoff.schemaVersion !== 1 && handoff.scope !== scope)
374
521
  throw new InputError(`Handoff scope '${handoff.scope}' does not match selected scope '${scope}'`);
375
522
  const time = timestamp(asOf, "asOf");
@@ -378,7 +525,7 @@ function verify(manifest, handoff, scope, asOf, options = {}) {
378
525
  const refs = new Map(handoff.schemaVersion !== 1 ? handoff.activeConstraints.map((ref) => [ref.id, ref]) : []);
379
526
  const reportedConstraints = (handoff.schemaVersion === 1 ? [...handoff.activeConstraints] : handoff.activeConstraints.map((ref) => ref.id)).sort(compare);
380
527
  const reported = new Set(reportedConstraints);
381
- const retained = new Map(handoff.schemaVersion === 3 ? handoff.activeConstraints.map((ref) => [ref.id, ref.content]) : []);
528
+ const retained = new Map(handoff.schemaVersion === 3 || handoff.schemaVersion === 4 && handoff.contentMode === "retained" ? handoff.activeConstraints.map((ref) => [ref.id, ref.content]) : []);
382
529
  const findings = [];
383
530
  for (const id of expectedConstraints) {
384
531
  if (!reported.has(id))
@@ -430,6 +577,7 @@ function verify(manifest, handoff, scope, asOf, options = {}) {
430
577
  findings.sort((a, b) => compare(a.id ?? "", b.id ?? "") || compare(a.code, b.code));
431
578
  return {
432
579
  schemaVersion: handoff.schemaVersion,
580
+ ...projectId === undefined ? {} : { projectId },
433
581
  ...handoff.schemaVersion !== 1 ? {
434
582
  tracking: "content",
435
583
  activeConstraintCount: expectedConstraints.length
@@ -445,14 +593,32 @@ function verify(manifest, handoff, scope, asOf, options = {}) {
445
593
  function snapshot(manifest, task, scope, asOf, options = {}) {
446
594
  if (!task.trim())
447
595
  throw new InputError("--task: expected a non-empty task");
448
- const result = verify(manifest, { schemaVersion: 1, task, activeConstraints: [] }, scope, asOf);
596
+ const projectId = checkProject(manifest, undefined, options.projectId);
597
+ const result = explain(manifest, scope, asOf);
449
598
  const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
450
599
  const base = {
451
600
  task,
452
601
  scope,
453
602
  capturedAt: result.asOf
454
603
  };
455
- const rules = result.expectedConstraints.map((id) => byId.get(id));
604
+ const rules = result.rules.filter((rule) => rule.decision === "ACTIVE").map((rule) => byId.get(rule.id));
605
+ if (projectId !== undefined)
606
+ return options.includeContent ? {
607
+ ...base,
608
+ schemaVersion: 4,
609
+ projectId,
610
+ contentMode: "retained",
611
+ activeConstraints: rules.map((rule) => ({
612
+ ...reference(rule),
613
+ content: retainedContent(rule)
614
+ }))
615
+ } : {
616
+ ...base,
617
+ schemaVersion: 4,
618
+ projectId,
619
+ contentMode: "hashes",
620
+ activeConstraints: rules.map(reference)
621
+ };
456
622
  return options.includeContent ? {
457
623
  ...base,
458
624
  schemaVersion: 3,
@@ -484,6 +650,7 @@ function fieldChanges(previous, current) {
484
650
  }
485
651
  function explain(manifest, scope, asOf) {
486
652
  identifier(scope, "scope");
653
+ const projectId = checkProject(manifest);
487
654
  const time = timestamp(asOf, "asOf");
488
655
  const rules = [...manifest.constraints].sort((a, b) => compare(a.id, b.id)).map((rule) => {
489
656
  const decision = inactive(rule, scope, time) ?? "ACTIVE";
@@ -516,6 +683,7 @@ function explain(manifest, scope, asOf) {
516
683
  });
517
684
  return {
518
685
  schemaVersion: 1,
686
+ ...projectId === undefined ? {} : { projectId },
519
687
  scope,
520
688
  asOf: new Date(time).toISOString(),
521
689
  activeConstraintCount: rules.filter((rule) => rule.decision === "ACTIVE").length,
@@ -523,7 +691,88 @@ function explain(manifest, scope, asOf) {
523
691
  };
524
692
  }
525
693
 
694
+ // src/diff.ts
695
+ function diffSnapshots(before, after) {
696
+ if (before.schemaVersion === 1 || after.schemaVersion === 1)
697
+ throw new InputError("diff requires content-aware v2/v3/v4 snapshots");
698
+ if (before.scope !== after.scope)
699
+ throw new InputError("diff requires snapshots with the same scope");
700
+ const project = before.schemaVersion === 4 ? before.projectId : undefined;
701
+ if (project !== (after.schemaVersion === 4 ? after.projectId : undefined))
702
+ throw new InputError("diff requires matching project binding on both snapshots");
703
+ const previous = new Map(before.activeConstraints.map((r) => [r.id, r]));
704
+ const current = new Map(after.activeConstraints.map((r) => [r.id, r]));
705
+ const ref = (r) => ({
706
+ id: r.id,
707
+ revision: r.revision,
708
+ contentHash: r.contentHash
709
+ });
710
+ const changes = [];
711
+ let unchangedCount = 0;
712
+ for (const id of [
713
+ ...new Set([...previous.keys(), ...current.keys()])
714
+ ].sort()) {
715
+ const a = previous.get(id);
716
+ const b = current.get(id);
717
+ if (a && b && a.revision === b.revision && a.contentHash === b.contentHash) {
718
+ unchangedCount++;
719
+ continue;
720
+ }
721
+ const retained = (r) => ("content" in r);
722
+ changes.push({
723
+ id,
724
+ kind: !a ? "ADDED" : !b ? "REMOVED" : "CHANGED",
725
+ before: a ? ref(a) : null,
726
+ after: b ? ref(b) : null,
727
+ ...a && b && retained(a) && retained(b) ? { fields: fieldChanges(a.content, b.content) } : {}
728
+ });
729
+ }
730
+ return {
731
+ schemaVersion: 1,
732
+ status: changes.length ? "different" : "unchanged",
733
+ scope: before.scope,
734
+ ...project === undefined ? {} : { projectId: project },
735
+ beforeCount: previous.size,
736
+ afterCount: current.size,
737
+ unchangedCount,
738
+ changes,
739
+ notice: "Compares declared rules, not agent behavior or current applicability. Task and capture time are metadata and are not compared. Field details require retained content on both sides; additions/removals do not imply why a rule became active or inactive."
740
+ };
741
+ }
742
+ function diffText(result, markdown) {
743
+ const safe = markdown ? markdownText : terminalText;
744
+ const lines = [
745
+ markdown ? `# Handoff Check snapshot diff
746
+ ` : "SNAPSHOT DIFF",
747
+ `${result.status.toUpperCase()} | scope ${safe(result.scope)}${result.projectId ? ` | project ${safe(result.projectId)}` : ""}`,
748
+ `${result.beforeCount} before | ${result.afterCount} after | ${result.unchangedCount} unchanged`
749
+ ];
750
+ for (const change of result.changes) {
751
+ lines.push(`${change.kind} ${safe(change.id)}`);
752
+ if (change.kind === "CHANGED") {
753
+ if (change.fields) {
754
+ for (const field of change.fields)
755
+ lines.push(` ${field.field}: ${safe(JSON.stringify(field.before))} -> ${safe(JSON.stringify(field.after))}`);
756
+ } else
757
+ lines.push(" Field details unavailable: both snapshots must retain content");
758
+ lines.push(` Before: revision ${change.before?.revision}, ${change.before?.contentHash}`, ` After: revision ${change.after?.revision}, ${change.after?.contentHash}`);
759
+ }
760
+ }
761
+ lines.push(safe(result.notice));
762
+ return `${lines.join(markdown ? `
763
+
764
+ ` : `
765
+ `)}
766
+ `;
767
+ }
768
+
769
+ // src/doctor.ts
770
+ import { lstat, readFile as readFile2, stat as stat2 } from "node:fs/promises";
771
+ import { resolve as resolve3 } from "node:path";
772
+
526
773
  // src/lifecycle.ts
774
+ import { realpath, stat } from "node:fs/promises";
775
+ import { dirname as dirname2, isAbsolute, relative, resolve as resolve2, sep } from "node:path";
527
776
  var lifecycleCommand = "node";
528
777
  var projectPlaceholder = "$" + "{CLAUDE_PROJECT_DIR}";
529
778
  var lifecycleArgs = [
@@ -535,7 +784,9 @@ var lifecycleArgs = [
535
784
  `${projectPlaceholder}/.handoff-check.json`
536
785
  ];
537
786
  var lifecycleMatcher = "^(startup|resume|clear|compact)$";
538
- function hookConfig(host, requireActive = false) {
787
+ function hookConfig(host, requireActive = false, profile) {
788
+ if (profile !== undefined)
789
+ identifier(profile, "--profile");
539
790
  if (host !== "claude")
540
791
  throw new InputError("Only the claude lifecycle adapter is supported; see docs/lifecycle.md for host capabilities");
541
792
  return {
@@ -549,7 +800,8 @@ function hookConfig(host, requireActive = false) {
549
800
  command: lifecycleCommand,
550
801
  args: [
551
802
  ...lifecycleArgs,
552
- ...requireActive ? ["--require-active"] : []
803
+ ...requireActive ? ["--require-active"] : [],
804
+ ...profile === undefined ? [] : ["--profile", profile]
553
805
  ],
554
806
  timeout: 10
555
807
  }
@@ -559,6 +811,25 @@ function hookConfig(host, requireActive = false) {
559
811
  }
560
812
  };
561
813
  }
814
+ function lifecycleInvocation(args) {
815
+ if (!Array.isArray(args) || JSON.stringify(args.slice(0, lifecycleArgs.length)) !== JSON.stringify(lifecycleArgs))
816
+ return;
817
+ const tail = args.slice(lifecycleArgs.length);
818
+ let requireActive = false;
819
+ if (tail[0] === "--require-active") {
820
+ requireActive = true;
821
+ tail.shift();
822
+ }
823
+ if (!tail.length)
824
+ return { requireActive };
825
+ if (tail.length !== 2 || tail[0] !== "--profile")
826
+ return;
827
+ try {
828
+ return { requireActive, profile: identifier(tail[1], "hook profile") };
829
+ } catch {
830
+ return;
831
+ }
832
+ }
562
833
  async function readHookInput(input, timeoutMs = 2000, maxBytes = 65536) {
563
834
  return new Promise((resolveInput, reject) => {
564
835
  let size = 0;
@@ -599,7 +870,7 @@ async function readHookInput(input, timeoutMs = 2000, maxBytes = 65536) {
599
870
  input.once("close", closed);
600
871
  });
601
872
  }
602
- async function lifecycleHook(input, configPath, requireActive = false) {
873
+ async function lifecycleHook(input, configPath, requireActive = false, profile) {
603
874
  if (!input || typeof input !== "object" || Array.isArray(input))
604
875
  throw new InputError("Hook event must be an object");
605
876
  const event = input;
@@ -618,18 +889,25 @@ async function lifecycleHook(input, configPath, requireActive = false) {
618
889
  throw new InputError("Hook cwd is outside the explicit config directory; select this worktree's config");
619
890
  let summary;
620
891
  try {
621
- const { config, directory } = await loadConfig(root, configPath);
892
+ const loaded = await loadConfig(root, configPath);
893
+ const config = selectProfile(loaded.config, profile);
894
+ const directory = loaded.directory;
622
895
  const scope = identifier(config.scope, "config.scope");
623
896
  const manifest = parseManifest(await readJson(resolve2(directory, config.constraints ?? "constraints.json")));
624
897
  const handoff = parseHandoff(await readJson(resolve2(directory, config.handoff ?? "handoff.json")));
625
898
  if (handoff.schemaVersion === 1)
626
- throw new InputError("Lifecycle checks require a content-aware v2/v3 handoff; review and capture before adoption");
899
+ throw new InputError("Lifecycle checks require a content-aware v2/v3/v4 handoff; review and capture before adoption");
627
900
  const result = verify(manifest, handoff, scope, new Date().toISOString(), {
628
- requireActive
901
+ requireActive,
902
+ ...config.projectId === undefined ? {} : { projectId: config.projectId }
629
903
  });
630
904
  const count = result.expectedConstraints.length;
631
905
  const label = result.status === "verified" ? count ? "PASS" : "PASS (EMPTY)" : "FAIL";
632
906
  summary = `${label}; ${count} active constraints; scope ${scope}; as of ${result.asOf}.`;
907
+ if (result.projectId !== undefined)
908
+ summary += ` Project ${result.projectId}.`;
909
+ if (profile !== undefined)
910
+ summary += ` Profile ${profile}.`;
633
911
  if (!count)
634
912
  summary += " No active constraints apply; this is not real policy coverage.";
635
913
  if (result.findings.length)
@@ -660,8 +938,16 @@ async function doctor(cwd, options) {
660
938
  };
661
939
  let scope;
662
940
  let handoffScope;
941
+ let projectId;
942
+ let parsedManifest;
943
+ let parsedHandoff;
944
+ let savedConfig;
663
945
  try {
664
- const { config, directory } = await loadConfig(cwd, options.config);
946
+ const loaded = await loadConfig(cwd, options.config);
947
+ savedConfig = loaded.config;
948
+ const config = selectProfile(loaded.config, options.profile);
949
+ const directory = loaded.directory;
950
+ projectId = config.projectId;
665
951
  try {
666
952
  await stat2(configPath);
667
953
  add("CONFIG", "ok", "Config parsed", configPath);
@@ -678,6 +964,7 @@ async function doctor(cwd, options) {
678
964
  paths.handoff = options.handoff === undefined ? resolve3(directory, config.handoff ?? "handoff.json") : resolve3(cwd, options.handoff);
679
965
  try {
680
966
  const manifest = parseManifest(await readJson(paths.constraints));
967
+ parsedManifest = manifest;
681
968
  add("MANIFEST", "ok", `Supported manifest v${manifest.schemaVersion}; ${manifest.constraints.length} total rules (not evaluated active count)`, paths.constraints);
682
969
  if (!manifest.constraints.length)
683
970
  add("EMPTY_MANIFEST", "warning", "Zero declared rules; author reviewed constraints before relying on policy coverage");
@@ -686,15 +973,27 @@ async function doctor(cwd, options) {
686
973
  }
687
974
  try {
688
975
  const handoff = parseHandoff(await readJson(paths.handoff));
976
+ parsedHandoff = handoff;
689
977
  if (handoff.schemaVersion !== 1)
690
978
  handoffScope = handoff.scope;
691
- add("HANDOFF", handoff.schemaVersion === 1 ? "warning" : "ok", `Supported handoff v${handoff.schemaVersion}${handoff.schemaVersion === 1 ? "; IDs only, lifecycle adapter requires v2/v3" : "; content-aware"}`, paths.handoff);
979
+ add("HANDOFF", handoff.schemaVersion === 1 ? "warning" : "ok", `Supported handoff v${handoff.schemaVersion}${handoff.schemaVersion === 1 ? "; IDs only, lifecycle adapter requires v2/v3/v4" : "; content-aware"}`, paths.handoff);
692
980
  } catch (e) {
693
981
  add("HANDOFF", "error", e.message, paths.handoff);
694
982
  }
695
983
  if (scope && handoffScope && scope !== handoffScope)
696
984
  add("SCOPE_MISMATCH", "error", `Saved handoff scope '${handoffScope}' differs from selected '${scope}'`);
985
+ if (parsedManifest && parsedHandoff)
986
+ try {
987
+ const bound = checkProject(parsedManifest, parsedHandoff, config.projectId);
988
+ projectId = bound;
989
+ if (bound !== undefined)
990
+ add("PROJECT_BINDING", "ok", `Bound project: ${bound}`);
991
+ } catch (e) {
992
+ add("PROJECT_BINDING", "error", e.message);
993
+ }
697
994
  } catch (e) {
995
+ if (e instanceof ProfileError)
996
+ throw e;
698
997
  add("CONFIG", "error", e.message, configPath);
699
998
  }
700
999
  const packagedSkill = await readFile2(new URL("../skills/handoff-check/SKILL.md", import.meta.url), "utf8");
@@ -755,8 +1054,18 @@ async function doctor(cwd, options) {
755
1054
  for (const group of groups) {
756
1055
  if (group && typeof group === "object" && Array.isArray(group.hooks))
757
1056
  for (const hook of group.hooks) {
758
- if (hook?.command === lifecycleCommand && (JSON.stringify(hook.args) === JSON.stringify(lifecycleArgs) || JSON.stringify(hook.args) === JSON.stringify([...lifecycleArgs, "--require-active"]))) {
1057
+ if (hook?.command === lifecycleCommand && lifecycleInvocation(hook.args) !== undefined) {
759
1058
  configured = true;
1059
+ const invocation = lifecycleInvocation(hook.args);
1060
+ if (invocation?.profile !== undefined)
1061
+ try {
1062
+ if (!savedConfig)
1063
+ throw new Error("Config unavailable");
1064
+ selectProfile(savedConfig, invocation.profile);
1065
+ add("HOOK_PROFILE", "info", `Hook explicitly selects profile: ${invocation.profile}`, settingsPath);
1066
+ } catch {
1067
+ add("HOOK_PROFILE", "error", "Hook selects an unavailable profile; review config v2", settingsPath);
1068
+ }
760
1069
  add("CLAUDE_HOOK", group.matcher === lifecycleMatcher && hook.type === "command" && hook.timeout === 10 && hook.async !== true ? "ok" : "warning", "Recognized adapter command; review matcher/type/timeout and host /hooks for actual activation", settingsPath);
761
1070
  }
762
1071
  }
@@ -800,6 +1109,8 @@ async function doctor(cwd, options) {
800
1109
  status: diagnostics.some((d) => d.level === "warning" || d.level === "error") ? "attention" : "healthy",
801
1110
  paths,
802
1111
  ...scope ? { scope } : {},
1112
+ ...projectId === undefined ? {} : { projectId },
1113
+ ...options.profile === undefined ? {} : { profile: options.profile },
803
1114
  diagnostics,
804
1115
  notice: "Read-only local diagnostics, not handoff verification or proof that host hooks/skills executed. User/global/managed host settings are not inspected."
805
1116
  };
@@ -1013,83 +1324,205 @@ jobs:
1013
1324
  };
1014
1325
  }
1015
1326
 
1016
- // src/render.ts
1017
- function terminalText(value) {
1018
- return Array.from(value, (character) => {
1019
- const code = character.codePointAt(0) ?? 0;
1020
- return /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(character) ? `\\u${code.toString(16).padStart(4, "0")}` : character;
1021
- }).join("");
1327
+ // src/report.ts
1328
+ import { execFile } from "node:child_process";
1329
+ import { promisify } from "node:util";
1330
+ async function gitContext(cwd) {
1331
+ const run = async (args) => (await promisify(execFile)("git", ["--no-optional-locks", "-C", cwd, ...args], {
1332
+ encoding: "utf8",
1333
+ timeout: 2000,
1334
+ maxBuffer: 262144,
1335
+ windowsHide: true
1336
+ })).stdout.replace(/\r?\n$/, "");
1337
+ try {
1338
+ const worktree = await run(["rev-parse", "--show-toplevel"]);
1339
+ const commit = await run(["rev-parse", "--verify", "HEAD"]);
1340
+ const name = await run(["rev-parse", "--abbrev-ref", "HEAD"]);
1341
+ return { worktree, commit, branch: name === "HEAD" ? null : name };
1342
+ } catch {
1343
+ throw new InputError("Cannot collect requested Git context; Git and an existing commit in this worktree are required");
1344
+ }
1022
1345
  }
1023
- function markdownText(value) {
1024
- return terminalText(value).replace(/[&<>\\`*_{}[\]()#+.!|~:/@-]/g, (character) => `&#${character.charCodeAt(0)};`);
1346
+ function verificationReport(result, inputs, policies, profile, git) {
1347
+ return {
1348
+ schemaVersion: 1,
1349
+ kind: "verification-report",
1350
+ packageVersion: package_default.version,
1351
+ policies,
1352
+ inputs,
1353
+ ...profile === undefined ? {} : { profile },
1354
+ ...result.projectId === undefined ? {} : { projectId: result.projectId },
1355
+ ...git === undefined ? {} : { git },
1356
+ result,
1357
+ notice: "Local reproducibility record, not an authenticated attestation or proof of agent compliance. Git metadata and input reads are not atomic; revalidate before acting."
1358
+ };
1025
1359
  }
1026
- function verificationMarkdown(result, handoff, requireActive, requireContent) {
1027
- const label = result.status === "verified" ? result.expectedConstraints.length ? "PASS" : "PASS (EMPTY)" : "FAIL";
1360
+ function reportMarkdown(report) {
1028
1361
  const lines = [
1029
- "# Handoff Check verification",
1030
1362
  "",
1031
- `- Result: ${label}`,
1032
- `- Scope: ${markdownText(result.scope)}`,
1033
- `- Evaluated at: ${markdownText(result.asOf)}`,
1034
- `- Active constraints checked: ${result.expectedConstraints.length}`,
1035
- `- Tracking: ${handoff.schemaVersion === 1 ? "IDs only; content changes not checked" : handoff.schemaVersion === 3 ? "Content hashes with retained old content" : "Content hashes; old content not retained"}`,
1036
- `- Require content-aware handoff: ${requireContent}`,
1037
- `- Require active constraints: ${requireActive}`,
1038
- ""
1363
+ "## Reproducibility metadata",
1364
+ "",
1365
+ `- Package: ${markdownText(report.packageVersion)}`,
1366
+ `- Profile: ${report.profile === undefined ? "none selected" : markdownText(report.profile)}`
1039
1367
  ];
1040
- if (!result.expectedConstraints.length)
1041
- lines.push("No active constraints apply to this scope and time.", "");
1042
- lines.push("## Findings", "");
1043
- if (!result.findings.length)
1044
- lines.push("No findings.", "");
1045
- for (const finding of result.findings) {
1046
- lines.push(`### ${finding.code}${finding.id === undefined ? "" : ` ${markdownText(finding.id)}`}`, "", markdownText(finding.message), "");
1047
- if (finding.code === "CHANGED") {
1048
- if (finding.changes) {
1049
- lines.push("| Field | Before (saved) | After (current) |", "| --- | --- | --- |");
1050
- for (const change of finding.changes)
1051
- lines.push(`| ${change.field} | ${markdownText(JSON.stringify(change.before))} | ${markdownText(JSON.stringify(change.after))} |`);
1052
- lines.push("", "Null means an absent optional field.", "");
1053
- } else
1054
- lines.push("Previous content unavailable: this baseline stores hashes only. No textual diff can be reconstructed.", "");
1368
+ if (report.projectId)
1369
+ lines.push(`- Project: ${markdownText(report.projectId)}`);
1370
+ for (const [name, input] of Object.entries(report.inputs))
1371
+ lines.push(input ? `- ${name}: ${markdownText(input.path)}; ${markdownText(input.sha256)}` : `- ${name}: absent implicit config (no digest)`);
1372
+ if (report.git)
1373
+ lines.push(`- Git worktree: ${markdownText(report.git.worktree)}`, `- Git commit: ${markdownText(report.git.commit)}`, `- Git branch: ${report.git.branch === null ? "detached" : markdownText(report.git.branch)}`);
1374
+ lines.push("", report.notice, "");
1375
+ return lines.join(`
1376
+ `);
1377
+ }
1378
+
1379
+ // src/setup.ts
1380
+ import { lstat as lstat3, open as open2, readdir } from "node:fs/promises";
1381
+ import { resolve as resolve5 } from "node:path";
1382
+ import { createInterface } from "node:readline/promises";
1383
+ function setupPlan(answers, asOf) {
1384
+ const projectId = identifier(answers.projectId, "Project ID");
1385
+ const scopes = answers.scopes.map((scope) => identifier(scope, "Environment"));
1386
+ if (!scopes.length || scopes.length > 20 || new Set(scopes).size !== scopes.length || new Set(scopes.map((s) => s.toLowerCase())).size !== scopes.length)
1387
+ throw new InputError("Enter 1 to 20 unique environments (case-insensitive filenames)");
1388
+ const manifest = parseManifest({
1389
+ schemaVersion: 3,
1390
+ projectId,
1391
+ constraints: [
1392
+ {
1393
+ id: identifier(answers.ruleId, "Rule ID"),
1394
+ revision: 1,
1395
+ scope: "global",
1396
+ description: answers.description,
1397
+ source: answers.source
1398
+ }
1399
+ ]
1400
+ });
1401
+ const profiles = Object.fromEntries(scopes.map((scope) => [scope, { scope, handoff: `handoff-${scope}.json` }]));
1402
+ const config = parseConfig({
1403
+ schemaVersion: 2,
1404
+ projectId,
1405
+ constraints: "constraints.json",
1406
+ profiles
1407
+ });
1408
+ const json = (value) => `${JSON.stringify(value, null, 2)}
1409
+ `;
1410
+ return [
1411
+ { path: ".handoff-check.json", content: json(config) },
1412
+ { path: "constraints.json", content: json(manifest) },
1413
+ ...scopes.map((scope) => ({
1414
+ path: `handoff-${scope}.json`,
1415
+ content: json(snapshot(manifest, answers.task, scope, asOf, {
1416
+ includeContent: true,
1417
+ projectId
1418
+ }))
1419
+ }))
1420
+ ];
1421
+ }
1422
+ async function assertSetupTargets(root, files) {
1423
+ const existing = new Set((await readdir(root)).map((name) => name.normalize("NFC").toLowerCase()));
1424
+ for (const file of files) {
1425
+ if (existing.has(file.path.normalize("NFC").toLowerCase()))
1426
+ throw new InputError(`Setup requires new files; target already exists: '${file.path}'.`);
1427
+ try {
1428
+ await lstat3(resolve5(root, file.path));
1429
+ } catch (error) {
1430
+ if (error.code === "ENOENT")
1431
+ continue;
1432
+ throw error;
1055
1433
  }
1434
+ throw new InputError(`Setup requires new files; target already exists: '${file.path}'. Use init or edit existing configuration explicitly.`);
1056
1435
  }
1057
- lines.push("A pass checks declared constraints, not agent behavior or action authorization.");
1058
- return `${lines.join(`
1059
- `)}
1060
- `;
1061
1436
  }
1062
- function explanationText(result, markdown) {
1063
- if (markdown) {
1064
- return [
1065
- "# Handoff Check explanation",
1066
- "",
1067
- `- Scope: ${markdownText(result.scope)}`,
1068
- `- Evaluated at: ${markdownText(result.asOf)}`,
1069
- `- Active constraints: ${result.activeConstraintCount}`,
1070
- "",
1071
- "| ID | Rule scope | Decision | Reason | Description | Source |",
1072
- "| --- | --- | --- | --- | --- | --- |",
1073
- ...result.rules.map((rule) => `| ${[rule.id, rule.scope, rule.decision, rule.reason, rule.description, rule.source].map(markdownText).join(" | ")} |`),
1074
- "",
1075
- "Explains manifest applicability only; no handoff was compared.",
1076
- ""
1077
- ].join(`
1078
- `);
1437
+ async function writeSetup(root, files) {
1438
+ await assertSetupTargets(root, files);
1439
+ const written = [];
1440
+ for (const file of files) {
1441
+ try {
1442
+ const handle = await open2(resolve5(root, file.path), "wx", 420);
1443
+ try {
1444
+ await handle.writeFile(file.content, "utf8");
1445
+ } finally {
1446
+ await handle.close();
1447
+ }
1448
+ written.push(file.path);
1449
+ } catch {
1450
+ throw new InputError(`Setup stopped at '${file.path}'. Written files: ${written.join(", ") || "none"}. Filesystem writes are not transactional; inspect before retrying.`);
1451
+ }
1079
1452
  }
1080
- return [
1081
- ...result.rules.map((rule) => `${rule.decision.padEnd(12)} ${rule.id} ${terminalText(rule.reason)}; ${terminalText(rule.description)}; source ${terminalText(rule.source)}`),
1082
- `EXPLAIN ${result.activeConstraintCount} active constraints | ${result.rules.length} manifest rules | scope ${result.scope} | as of ${result.asOf}`,
1083
- "No handoff was compared.",
1084
- ""
1085
- ].join(`
1453
+ }
1454
+ async function guidedSetup(root, dryRun) {
1455
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
1456
+ throw new InputError("setup requires an interactive terminal; use init --scope <scope> for automation");
1457
+ await assertSetupTargets(root, [
1458
+ { path: ".handoff-check.json" },
1459
+ { path: "constraints.json" }
1460
+ ]);
1461
+ const reader = createInterface({
1462
+ input: process.stdin,
1463
+ output: process.stdout
1464
+ });
1465
+ const abort = new AbortController;
1466
+ reader.on("SIGINT", () => {
1467
+ abort.abort();
1468
+ reader.close();
1469
+ });
1470
+ reader.on("close", () => abort.abort());
1471
+ const ask = async (prompt) => {
1472
+ try {
1473
+ return (await reader.question(prompt, { signal: abort.signal })).trim();
1474
+ } catch {
1475
+ throw new InputError("Setup cancelled before approval; no files written");
1476
+ }
1477
+ };
1478
+ try {
1479
+ process.stdout.write(`Create a project-bound starter with one real rule applying to every environment.
1480
+ No agent settings, hooks, CI, or dependencies will be installed.
1086
1481
  `);
1482
+ const projectId = await ask("Project ID: ");
1483
+ const scopes = (await ask("Environments (comma-separated, e.g. staging,production): ")).split(",").map((s) => s.trim());
1484
+ const ruleId = await ask("First rule ID: ");
1485
+ const description = await ask("Rule applying to ALL environments: ");
1486
+ const source = await ask("Rule source reference (stored as text, never fetched): ");
1487
+ const task = await ask("Initial handoff task: ");
1488
+ const files = setupPlan({ projectId, scopes, ruleId, description, source, task }, new Date().toISOString());
1489
+ await assertSetupTargets(root, files);
1490
+ process.stdout.write(`
1491
+ Review the exact proposed files and retained rule content:
1492
+ `);
1493
+ for (const file of files)
1494
+ process.stdout.write(`
1495
+ --- ${file.path} ---
1496
+ ${file.content.split(`
1497
+ `).map(terminalText).join(`
1498
+ `)}
1499
+ `);
1500
+ if (dryRun) {
1501
+ process.stdout.write(`PREVIEW ONLY: no files written.
1502
+ `);
1503
+ return;
1504
+ }
1505
+ if (await ask("Adopt these reviewed rules and create these new baselines? Type yes: ") !== "yes") {
1506
+ process.stdout.write(`CANCELLED: no files written.
1507
+ `);
1508
+ return;
1509
+ }
1510
+ await writeSetup(root, files);
1511
+ process.stdout.write(`CREATED ${files.length} files.
1512
+ Next: handoff-check verify --profile ${scopes[0]} --require-content --require-active
1513
+ Edit and review constraints before relying on them. Never refresh a baseline before verifying it on resume.
1514
+ `);
1515
+ } finally {
1516
+ reader.close();
1517
+ }
1087
1518
  }
1088
1519
 
1089
1520
  // src/cli.ts
1090
1521
  var help = `Handoff Check
1091
1522
 
1092
1523
  Usage: handoff-check verify --scope <scope> [options]
1524
+ handoff-check diff --before <snapshot> --after <snapshot> [--format text|json|markdown]
1525
+ handoff-check setup [--dry-run]
1093
1526
  handoff-check init --scope <scope> [--agent both] [--dry-run] [--ci]
1094
1527
  handoff-check snapshot --task <task> [--output <new-file>] [options]
1095
1528
  handoff-check explain --scope <scope> [options]
@@ -1098,25 +1531,30 @@ Usage: handoff-check verify --scope <scope> [options]
1098
1531
  handoff-check hook --host claude --config <absolute-path> [--require-active]
1099
1532
 
1100
1533
  Options:
1534
+ --before <path> diff: saved snapshot before the change
1535
+ --after <path> diff: saved snapshot after the change
1101
1536
  --constraints <path> Manifest file (default: constraints.json)
1102
1537
  --handoff <path> Handoff file (default: handoff.json)
1103
1538
  --scope <scope> Selected scope, including global constraints
1104
1539
  --config <path> Project config (default: cwd/.handoff-check.json)
1540
+ --profile <name> Explicit config v2 profile; no scope/input overrides
1541
+ --report verify: exact input/config metadata (json/markdown only)
1542
+ --git-context verify --report: collect read-only Git context explicitly
1105
1543
  --as-of <UTC time> Fixed evaluation time (default: current time)
1106
- --require-content verify: require a v2/v3 content-aware handoff
1544
+ --require-content verify: require a v2/v3/v4 content-aware handoff
1107
1545
  --require-active verify: fail if empty; hook/hook-config: opt-in nonempty policy
1108
1546
  --task <task> snapshot: task description (required)
1109
1547
  --output <path> snapshot: create a new baseline file, never overwrite
1110
- --include-content snapshot: retain old rule text in a v3 handoff (opt-in)
1111
- --format text|json|markdown Markdown is verify/explain-only (default: text)
1548
+ --include-content snapshot: retain old rule text in unbound v3/bound v4 (opt-in)
1549
+ --format text|json|markdown Markdown is verify/explain/diff-only (default: text)
1112
1550
  --agent <agent> init: codex, claude, both (default), or none
1113
1551
  --host <host> doctor: integration target; hook/hook-config: claude
1114
- --dry-run init: preview files and instruction changes without writes
1552
+ --dry-run init/setup: preview proposed files without writes
1115
1553
  --ci init: also create a pinned GitHub Actions check
1116
1554
  --version Show package version
1117
1555
  --help Show this help
1118
1556
 
1119
- Exit codes: verify 0 verified / 1 mismatch; doctor 0 healthy / 1 attention.
1557
+ Exit codes: verify 0 verified / 1 mismatch; diff 0 unchanged / 1 different; doctor 0 healthy / 1 attention.
1120
1558
  Hook 0 means advisory response delivered (may report FAIL/INVALID), not verified.
1121
1559
  Invalid invocation/input returns 2; explain/init/snapshot/hook-config succeed with 0.
1122
1560
  `;
@@ -1143,8 +1581,13 @@ async function main() {
1143
1581
  "require-active": { type: "boolean" },
1144
1582
  "include-content": { type: "boolean" },
1145
1583
  host: { type: "string" },
1584
+ profile: { type: "string" },
1585
+ report: { type: "boolean" },
1586
+ "git-context": { type: "boolean" },
1146
1587
  task: { type: "string" },
1147
- output: { type: "string" }
1588
+ output: { type: "string" },
1589
+ before: { type: "string" },
1590
+ after: { type: "string" }
1148
1591
  }
1149
1592
  });
1150
1593
  format = values.format;
@@ -1166,13 +1609,59 @@ async function main() {
1166
1609
  "explain",
1167
1610
  "doctor",
1168
1611
  "hook",
1169
- "hook-config"
1612
+ "hook-config",
1613
+ "diff",
1614
+ "setup"
1170
1615
  ].includes(positionals[0] ?? ""))
1171
- throw new InputError("Expected command: verify, snapshot, explain, init, doctor, hook or hook-config (use --help for usage)");
1616
+ throw new InputError("Expected command: verify, snapshot, explain, init, setup, diff, doctor, hook or hook-config (use --help for usage)");
1172
1617
  const cwd = process.cwd();
1173
1618
  const command = positionals[0];
1619
+ if (command === "diff" || command === "setup") {
1620
+ const allowed = command === "diff" ? ["before", "after", "format"] : ["dry-run"];
1621
+ for (const key of Object.keys(values)) {
1622
+ if (key === "format" && values.format === "text" && !process.argv.slice(2).some((arg) => arg === "--format" || arg.startsWith("--format=")))
1623
+ continue;
1624
+ if (!allowed.includes(key))
1625
+ throw new InputError(`--${key} is not supported by ${command}`);
1626
+ }
1627
+ if (command === "setup") {
1628
+ await guidedSetup(cwd, values["dry-run"] ?? false);
1629
+ return 0;
1630
+ }
1631
+ if (!values.before?.trim() || !values.after?.trim())
1632
+ throw new InputError("diff requires --before <snapshot> and --after <snapshot>");
1633
+ const before = parseHandoff((await readJsonRecord(resolve6(cwd, values.before))).input);
1634
+ const after = parseHandoff((await readJsonRecord(resolve6(cwd, values.after))).input);
1635
+ const result2 = diffSnapshots(before, after);
1636
+ process.stdout.write(format === "json" ? `${JSON.stringify(result2, null, 2)}
1637
+ ` : diffText(result2, format === "markdown"));
1638
+ return result2.status === "unchanged" ? 0 : 1;
1639
+ }
1640
+ if (values.before !== undefined || values.after !== undefined)
1641
+ throw new InputError("--before and --after are diff-only");
1642
+ if (values.profile !== undefined) {
1643
+ identifier(values.profile, "--profile");
1644
+ if (command === "init")
1645
+ throw new InputError("--profile is not supported by init; author config v2 explicitly");
1646
+ if ([values.scope, values.constraints, values.handoff].some((v) => v !== undefined))
1647
+ throw new InputError("--profile cannot be combined with --scope, --constraints or --handoff");
1648
+ }
1649
+ if ((values.report !== undefined || values["git-context"] !== undefined) && command !== "verify")
1650
+ throw new InputError("--report and --git-context are verify-only");
1651
+ if (values["git-context"] && !values.report)
1652
+ throw new InputError("--git-context requires --report");
1653
+ if (values.report && format === "text")
1654
+ throw new InputError("--report requires --format json or markdown");
1174
1655
  if (["doctor", "hook", "hook-config"].includes(command ?? "")) {
1175
- const allowed = command === "doctor" ? ["host", "config", "scope", "constraints", "handoff", "format"] : command === "hook" ? ["host", "config", "require-active"] : ["host", "require-active"];
1656
+ const allowed = command === "doctor" ? [
1657
+ "host",
1658
+ "config",
1659
+ "scope",
1660
+ "constraints",
1661
+ "handoff",
1662
+ "format",
1663
+ "profile"
1664
+ ] : command === "hook" ? ["host", "config", "require-active", "profile"] : ["host", "require-active", "profile"];
1176
1665
  for (const key of Object.keys(values)) {
1177
1666
  if (key === "format" && values.format === "text" && !process.argv.slice(2).some((arg) => arg === "--format" || arg.startsWith("--format=")))
1178
1667
  continue;
@@ -1204,7 +1693,7 @@ ${result2.notice}
1204
1693
  if (values.host !== "claude")
1205
1694
  throw new InputError("hook and hook-config require --host claude; other host adapters are not shipped");
1206
1695
  if (command === "hook-config") {
1207
- process.stdout.write(`${JSON.stringify(hookConfig(values.host, values["require-active"] ?? false), null, 2)}
1696
+ process.stdout.write(`${JSON.stringify(hookConfig(values.host, values["require-active"] ?? false, values.profile), null, 2)}
1208
1697
  `);
1209
1698
  return 0;
1210
1699
  }
@@ -1217,7 +1706,7 @@ ${result2.notice}
1217
1706
  }, 5000);
1218
1707
  try {
1219
1708
  const event = await readHookInput(process.stdin);
1220
- const result2 = await lifecycleHook(event, values.config, values["require-active"] ?? false);
1709
+ const result2 = await lifecycleHook(event, values.config, values["require-active"] ?? false, values.profile);
1221
1710
  process.stdout.write(`${JSON.stringify(result2)}
1222
1711
  `);
1223
1712
  return 0;
@@ -1284,14 +1773,18 @@ ${result2.notice}
1284
1773
  }
1285
1774
  if (values.agent !== undefined || values["dry-run"] !== undefined || values.ci !== undefined)
1286
1775
  throw new InputError("--agent, --dry-run and --ci are only supported by init");
1287
- const { config, directory } = await loadConfig(cwd, values.config);
1776
+ const loaded = await loadConfig(cwd, values.config);
1777
+ const config = selectProfile(loaded.config, values.profile);
1778
+ const directory = loaded.directory;
1288
1779
  const scope = identifier(values.scope ?? config.scope, "--scope (or config.scope)");
1289
1780
  const asOf = values["as-of"] ?? new Date().toISOString();
1290
1781
  timestamp(asOf, "--as-of");
1291
1782
  for (const key of ["constraints", "handoff", "config"])
1292
1783
  if (values[key] !== undefined && !values[key].trim())
1293
1784
  throw new InputError(`--${key}: expected a non-empty path`);
1294
- const manifest = parseManifest(await readJson(values.constraints !== undefined ? resolve5(cwd, values.constraints) : resolve5(directory, config.constraints ?? "constraints.json")));
1785
+ const manifestRecord = await readJsonRecord(values.constraints !== undefined ? resolve6(cwd, values.constraints) : resolve6(directory, config.constraints ?? "constraints.json"));
1786
+ const manifest = parseManifest(manifestRecord.input);
1787
+ checkProject(manifest, undefined, config.projectId);
1295
1788
  if (command === "explain") {
1296
1789
  const result2 = explain(manifest, scope, asOf);
1297
1790
  process.stdout.write(format === "json" ? `${JSON.stringify(result2, null, 2)}
@@ -1304,7 +1797,8 @@ ${result2.notice}
1304
1797
  if (values.task === undefined)
1305
1798
  throw new InputError("snapshot requires --task");
1306
1799
  const captured = snapshot(manifest, values.task, scope, asOf, {
1307
- includeContent: values["include-content"] ?? false
1800
+ includeContent: values["include-content"] ?? false,
1801
+ ...config.projectId === undefined ? {} : { projectId: config.projectId }
1308
1802
  });
1309
1803
  const content = `${JSON.stringify(captured, null, 2)}
1310
1804
  `;
@@ -1313,10 +1807,10 @@ ${result2.notice}
1313
1807
  else {
1314
1808
  if (!values.output.trim())
1315
1809
  throw new InputError("--output: expected a non-empty path");
1316
- const path = resolve5(cwd, values.output);
1810
+ const path = resolve6(cwd, values.output);
1317
1811
  let handle;
1318
1812
  try {
1319
- handle = await open2(path, "wx", 420);
1813
+ handle = await open3(path, "wx", 420);
1320
1814
  } catch {
1321
1815
  throw new InputError(`Cannot create snapshot '${path}'; choose a new file with an existing parent directory`);
1322
1816
  }
@@ -1339,17 +1833,30 @@ ${result2.notice}
1339
1833
  }
1340
1834
  if (values.task !== undefined || values.output !== undefined)
1341
1835
  throw new InputError("--task and --output are only supported by snapshot");
1342
- const handoff = parseHandoff(await readJson(values.handoff !== undefined ? resolve5(cwd, values.handoff) : resolve5(directory, config.handoff ?? "handoff.json")));
1836
+ const handoffRecord = await readJsonRecord(values.handoff !== undefined ? resolve6(cwd, values.handoff) : resolve6(directory, config.handoff ?? "handoff.json"));
1837
+ const handoff = parseHandoff(handoffRecord.input);
1343
1838
  if (values["require-content"] && handoff.schemaVersion === 1)
1344
- throw new InputError("Content tracking requires a schemaVersion 2 or 3 handoff; review current rules and capture a snapshot before resuming");
1839
+ throw new InputError("Content tracking requires a schemaVersion 2, 3 or 4 handoff; review current rules and capture a snapshot before resuming");
1345
1840
  const result = verify(manifest, handoff, scope, asOf, {
1346
- requireActive: values["require-active"] ?? false
1841
+ requireActive: values["require-active"] ?? false,
1842
+ ...config.projectId === undefined ? {} : { projectId: config.projectId }
1347
1843
  });
1844
+ const report = values.report ? verificationReport(result, {
1845
+ manifest: {
1846
+ path: manifestRecord.path,
1847
+ sha256: manifestRecord.sha256
1848
+ },
1849
+ handoff: { path: handoffRecord.path, sha256: handoffRecord.sha256 },
1850
+ config: loaded.source ?? null
1851
+ }, {
1852
+ requireContent: values["require-content"] ?? false,
1853
+ requireActive: values["require-active"] ?? false
1854
+ }, values.profile, values["git-context"] ? await gitContext(cwd) : undefined) : undefined;
1348
1855
  if (format === "json") {
1349
- process.stdout.write(`${JSON.stringify(result, null, 2)}
1856
+ process.stdout.write(`${JSON.stringify(report ?? result, null, 2)}
1350
1857
  `);
1351
1858
  } else if (format === "markdown") {
1352
- process.stdout.write(verificationMarkdown(result, handoff, values["require-active"] ?? false, values["require-content"] ?? false));
1859
+ process.stdout.write(verificationMarkdown(result, handoff, values["require-active"] ?? false, values["require-content"] ?? false) + (report ? reportMarkdown(report) : ""));
1353
1860
  } else {
1354
1861
  for (const finding of result.findings) {
1355
1862
  process.stdout.write(`${finding.code.padEnd(12)} ${finding.id === undefined ? "" : `${finding.id} `}${terminalText(finding.message)}
@@ -1366,7 +1873,7 @@ ${result2.notice}
1366
1873
  }
1367
1874
  const count = result.expectedConstraints.length;
1368
1875
  const label = result.status === "verified" ? count === 0 ? "PASS (EMPTY)" : "PASS" : "FAIL";
1369
- process.stdout.write(`${label} ${count} active constraints checked | ${result.findings.length} findings | scope ${scope} | as of ${result.asOf}${handoff.schemaVersion === 1 ? " | IDs only; content changes not checked" : " | content tracked"}${count === 0 ? " | No active constraints apply to this scope and time" : ""}
1876
+ process.stdout.write(`${label} ${count} active constraints checked | ${result.findings.length} findings | scope ${scope} | as of ${result.asOf}${result.projectId === undefined ? "" : ` | project ${result.projectId}`}${handoff.schemaVersion === 1 ? " | IDs only; content changes not checked" : " | content tracked"}${count === 0 ? " | No active constraints apply to this scope and time" : ""}
1370
1877
  `);
1371
1878
  }
1372
1879
  return result.status === "verified" ? 0 : 1;