handoff-check 0.5.0 → 0.6.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
@@ -7,7 +7,7 @@ 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.6.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,11 +396,15 @@ 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
410
  // src/doctor.ts
@@ -368,8 +430,26 @@ function inactive(rule, scope, time) {
368
430
  return "EXPIRED";
369
431
  return;
370
432
  }
433
+ function checkProject(manifest, handoff, expectedProjectId) {
434
+ if (expectedProjectId !== undefined)
435
+ identifier(expectedProjectId, "projectId");
436
+ const boundManifest = manifest.schemaVersion === 3;
437
+ const boundHandoff = handoff?.schemaVersion === 4;
438
+ if (boundManifest || boundHandoff || expectedProjectId !== undefined) {
439
+ if (!boundManifest)
440
+ throw new InputError("Project binding requires a schemaVersion 3 manifest; migrate both inputs deliberately");
441
+ const projectId = identifier(manifest.projectId, "manifest.projectId");
442
+ if (expectedProjectId !== undefined && expectedProjectId !== projectId)
443
+ throw new InputError(`Manifest project '${projectId}' does not match configured project '${expectedProjectId}'`);
444
+ if (handoff !== undefined && (!boundHandoff || handoff.projectId !== projectId))
445
+ throw new InputError(`Handoff must be schemaVersion 4 bound to project '${projectId}'; review the intended project's baseline`);
446
+ return projectId;
447
+ }
448
+ return;
449
+ }
371
450
  function verify(manifest, handoff, scope, asOf, options = {}) {
372
451
  identifier(scope, "scope");
452
+ const projectId = checkProject(manifest, handoff, options.projectId);
373
453
  if (handoff.schemaVersion !== 1 && handoff.scope !== scope)
374
454
  throw new InputError(`Handoff scope '${handoff.scope}' does not match selected scope '${scope}'`);
375
455
  const time = timestamp(asOf, "asOf");
@@ -378,7 +458,7 @@ function verify(manifest, handoff, scope, asOf, options = {}) {
378
458
  const refs = new Map(handoff.schemaVersion !== 1 ? handoff.activeConstraints.map((ref) => [ref.id, ref]) : []);
379
459
  const reportedConstraints = (handoff.schemaVersion === 1 ? [...handoff.activeConstraints] : handoff.activeConstraints.map((ref) => ref.id)).sort(compare);
380
460
  const reported = new Set(reportedConstraints);
381
- const retained = new Map(handoff.schemaVersion === 3 ? handoff.activeConstraints.map((ref) => [ref.id, ref.content]) : []);
461
+ const retained = new Map(handoff.schemaVersion === 3 || handoff.schemaVersion === 4 && handoff.contentMode === "retained" ? handoff.activeConstraints.map((ref) => [ref.id, ref.content]) : []);
382
462
  const findings = [];
383
463
  for (const id of expectedConstraints) {
384
464
  if (!reported.has(id))
@@ -430,6 +510,7 @@ function verify(manifest, handoff, scope, asOf, options = {}) {
430
510
  findings.sort((a, b) => compare(a.id ?? "", b.id ?? "") || compare(a.code, b.code));
431
511
  return {
432
512
  schemaVersion: handoff.schemaVersion,
513
+ ...projectId === undefined ? {} : { projectId },
433
514
  ...handoff.schemaVersion !== 1 ? {
434
515
  tracking: "content",
435
516
  activeConstraintCount: expectedConstraints.length
@@ -445,14 +526,32 @@ function verify(manifest, handoff, scope, asOf, options = {}) {
445
526
  function snapshot(manifest, task, scope, asOf, options = {}) {
446
527
  if (!task.trim())
447
528
  throw new InputError("--task: expected a non-empty task");
448
- const result = verify(manifest, { schemaVersion: 1, task, activeConstraints: [] }, scope, asOf);
529
+ const projectId = checkProject(manifest, undefined, options.projectId);
530
+ const result = explain(manifest, scope, asOf);
449
531
  const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
450
532
  const base = {
451
533
  task,
452
534
  scope,
453
535
  capturedAt: result.asOf
454
536
  };
455
- const rules = result.expectedConstraints.map((id) => byId.get(id));
537
+ const rules = result.rules.filter((rule) => rule.decision === "ACTIVE").map((rule) => byId.get(rule.id));
538
+ if (projectId !== undefined)
539
+ return options.includeContent ? {
540
+ ...base,
541
+ schemaVersion: 4,
542
+ projectId,
543
+ contentMode: "retained",
544
+ activeConstraints: rules.map((rule) => ({
545
+ ...reference(rule),
546
+ content: retainedContent(rule)
547
+ }))
548
+ } : {
549
+ ...base,
550
+ schemaVersion: 4,
551
+ projectId,
552
+ contentMode: "hashes",
553
+ activeConstraints: rules.map(reference)
554
+ };
456
555
  return options.includeContent ? {
457
556
  ...base,
458
557
  schemaVersion: 3,
@@ -484,6 +583,7 @@ function fieldChanges(previous, current) {
484
583
  }
485
584
  function explain(manifest, scope, asOf) {
486
585
  identifier(scope, "scope");
586
+ const projectId = checkProject(manifest);
487
587
  const time = timestamp(asOf, "asOf");
488
588
  const rules = [...manifest.constraints].sort((a, b) => compare(a.id, b.id)).map((rule) => {
489
589
  const decision = inactive(rule, scope, time) ?? "ACTIVE";
@@ -516,6 +616,7 @@ function explain(manifest, scope, asOf) {
516
616
  });
517
617
  return {
518
618
  schemaVersion: 1,
619
+ ...projectId === undefined ? {} : { projectId },
519
620
  scope,
520
621
  asOf: new Date(time).toISOString(),
521
622
  activeConstraintCount: rules.filter((rule) => rule.decision === "ACTIVE").length,
@@ -535,7 +636,9 @@ var lifecycleArgs = [
535
636
  `${projectPlaceholder}/.handoff-check.json`
536
637
  ];
537
638
  var lifecycleMatcher = "^(startup|resume|clear|compact)$";
538
- function hookConfig(host, requireActive = false) {
639
+ function hookConfig(host, requireActive = false, profile) {
640
+ if (profile !== undefined)
641
+ identifier(profile, "--profile");
539
642
  if (host !== "claude")
540
643
  throw new InputError("Only the claude lifecycle adapter is supported; see docs/lifecycle.md for host capabilities");
541
644
  return {
@@ -549,7 +652,8 @@ function hookConfig(host, requireActive = false) {
549
652
  command: lifecycleCommand,
550
653
  args: [
551
654
  ...lifecycleArgs,
552
- ...requireActive ? ["--require-active"] : []
655
+ ...requireActive ? ["--require-active"] : [],
656
+ ...profile === undefined ? [] : ["--profile", profile]
553
657
  ],
554
658
  timeout: 10
555
659
  }
@@ -559,6 +663,25 @@ function hookConfig(host, requireActive = false) {
559
663
  }
560
664
  };
561
665
  }
666
+ function lifecycleInvocation(args) {
667
+ if (!Array.isArray(args) || JSON.stringify(args.slice(0, lifecycleArgs.length)) !== JSON.stringify(lifecycleArgs))
668
+ return;
669
+ const tail = args.slice(lifecycleArgs.length);
670
+ let requireActive = false;
671
+ if (tail[0] === "--require-active") {
672
+ requireActive = true;
673
+ tail.shift();
674
+ }
675
+ if (!tail.length)
676
+ return { requireActive };
677
+ if (tail.length !== 2 || tail[0] !== "--profile")
678
+ return;
679
+ try {
680
+ return { requireActive, profile: identifier(tail[1], "hook profile") };
681
+ } catch {
682
+ return;
683
+ }
684
+ }
562
685
  async function readHookInput(input, timeoutMs = 2000, maxBytes = 65536) {
563
686
  return new Promise((resolveInput, reject) => {
564
687
  let size = 0;
@@ -599,7 +722,7 @@ async function readHookInput(input, timeoutMs = 2000, maxBytes = 65536) {
599
722
  input.once("close", closed);
600
723
  });
601
724
  }
602
- async function lifecycleHook(input, configPath, requireActive = false) {
725
+ async function lifecycleHook(input, configPath, requireActive = false, profile) {
603
726
  if (!input || typeof input !== "object" || Array.isArray(input))
604
727
  throw new InputError("Hook event must be an object");
605
728
  const event = input;
@@ -618,18 +741,25 @@ async function lifecycleHook(input, configPath, requireActive = false) {
618
741
  throw new InputError("Hook cwd is outside the explicit config directory; select this worktree's config");
619
742
  let summary;
620
743
  try {
621
- const { config, directory } = await loadConfig(root, configPath);
744
+ const loaded = await loadConfig(root, configPath);
745
+ const config = selectProfile(loaded.config, profile);
746
+ const directory = loaded.directory;
622
747
  const scope = identifier(config.scope, "config.scope");
623
748
  const manifest = parseManifest(await readJson(resolve2(directory, config.constraints ?? "constraints.json")));
624
749
  const handoff = parseHandoff(await readJson(resolve2(directory, config.handoff ?? "handoff.json")));
625
750
  if (handoff.schemaVersion === 1)
626
- throw new InputError("Lifecycle checks require a content-aware v2/v3 handoff; review and capture before adoption");
751
+ throw new InputError("Lifecycle checks require a content-aware v2/v3/v4 handoff; review and capture before adoption");
627
752
  const result = verify(manifest, handoff, scope, new Date().toISOString(), {
628
- requireActive
753
+ requireActive,
754
+ ...config.projectId === undefined ? {} : { projectId: config.projectId }
629
755
  });
630
756
  const count = result.expectedConstraints.length;
631
757
  const label = result.status === "verified" ? count ? "PASS" : "PASS (EMPTY)" : "FAIL";
632
758
  summary = `${label}; ${count} active constraints; scope ${scope}; as of ${result.asOf}.`;
759
+ if (result.projectId !== undefined)
760
+ summary += ` Project ${result.projectId}.`;
761
+ if (profile !== undefined)
762
+ summary += ` Profile ${profile}.`;
633
763
  if (!count)
634
764
  summary += " No active constraints apply; this is not real policy coverage.";
635
765
  if (result.findings.length)
@@ -660,8 +790,16 @@ async function doctor(cwd, options) {
660
790
  };
661
791
  let scope;
662
792
  let handoffScope;
793
+ let projectId;
794
+ let parsedManifest;
795
+ let parsedHandoff;
796
+ let savedConfig;
663
797
  try {
664
- const { config, directory } = await loadConfig(cwd, options.config);
798
+ const loaded = await loadConfig(cwd, options.config);
799
+ savedConfig = loaded.config;
800
+ const config = selectProfile(loaded.config, options.profile);
801
+ const directory = loaded.directory;
802
+ projectId = config.projectId;
665
803
  try {
666
804
  await stat2(configPath);
667
805
  add("CONFIG", "ok", "Config parsed", configPath);
@@ -678,6 +816,7 @@ async function doctor(cwd, options) {
678
816
  paths.handoff = options.handoff === undefined ? resolve3(directory, config.handoff ?? "handoff.json") : resolve3(cwd, options.handoff);
679
817
  try {
680
818
  const manifest = parseManifest(await readJson(paths.constraints));
819
+ parsedManifest = manifest;
681
820
  add("MANIFEST", "ok", `Supported manifest v${manifest.schemaVersion}; ${manifest.constraints.length} total rules (not evaluated active count)`, paths.constraints);
682
821
  if (!manifest.constraints.length)
683
822
  add("EMPTY_MANIFEST", "warning", "Zero declared rules; author reviewed constraints before relying on policy coverage");
@@ -686,15 +825,27 @@ async function doctor(cwd, options) {
686
825
  }
687
826
  try {
688
827
  const handoff = parseHandoff(await readJson(paths.handoff));
828
+ parsedHandoff = handoff;
689
829
  if (handoff.schemaVersion !== 1)
690
830
  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);
831
+ 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
832
  } catch (e) {
693
833
  add("HANDOFF", "error", e.message, paths.handoff);
694
834
  }
695
835
  if (scope && handoffScope && scope !== handoffScope)
696
836
  add("SCOPE_MISMATCH", "error", `Saved handoff scope '${handoffScope}' differs from selected '${scope}'`);
837
+ if (parsedManifest && parsedHandoff)
838
+ try {
839
+ const bound = checkProject(parsedManifest, parsedHandoff, config.projectId);
840
+ projectId = bound;
841
+ if (bound !== undefined)
842
+ add("PROJECT_BINDING", "ok", `Bound project: ${bound}`);
843
+ } catch (e) {
844
+ add("PROJECT_BINDING", "error", e.message);
845
+ }
697
846
  } catch (e) {
847
+ if (e instanceof ProfileError)
848
+ throw e;
698
849
  add("CONFIG", "error", e.message, configPath);
699
850
  }
700
851
  const packagedSkill = await readFile2(new URL("../skills/handoff-check/SKILL.md", import.meta.url), "utf8");
@@ -755,8 +906,18 @@ async function doctor(cwd, options) {
755
906
  for (const group of groups) {
756
907
  if (group && typeof group === "object" && Array.isArray(group.hooks))
757
908
  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"]))) {
909
+ if (hook?.command === lifecycleCommand && lifecycleInvocation(hook.args) !== undefined) {
759
910
  configured = true;
911
+ const invocation = lifecycleInvocation(hook.args);
912
+ if (invocation?.profile !== undefined)
913
+ try {
914
+ if (!savedConfig)
915
+ throw new Error("Config unavailable");
916
+ selectProfile(savedConfig, invocation.profile);
917
+ add("HOOK_PROFILE", "info", `Hook explicitly selects profile: ${invocation.profile}`, settingsPath);
918
+ } catch {
919
+ add("HOOK_PROFILE", "error", "Hook selects an unavailable profile; review config v2", settingsPath);
920
+ }
760
921
  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
922
  }
762
923
  }
@@ -800,6 +961,8 @@ async function doctor(cwd, options) {
800
961
  status: diagnostics.some((d) => d.level === "warning" || d.level === "error") ? "attention" : "healthy",
801
962
  paths,
802
963
  ...scope ? { scope } : {},
964
+ ...projectId === undefined ? {} : { projectId },
965
+ ...options.profile === undefined ? {} : { profile: options.profile },
803
966
  diagnostics,
804
967
  notice: "Read-only local diagnostics, not handoff verification or proof that host hooks/skills executed. User/global/managed host settings are not inspected."
805
968
  };
@@ -1030,9 +1193,10 @@ function verificationMarkdown(result, handoff, requireActive, requireContent) {
1030
1193
  "",
1031
1194
  `- Result: ${label}`,
1032
1195
  `- Scope: ${markdownText(result.scope)}`,
1196
+ ...result.projectId === undefined ? [] : [`- Project: ${markdownText(result.projectId)}`],
1033
1197
  `- Evaluated at: ${markdownText(result.asOf)}`,
1034
1198
  `- 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"}`,
1199
+ `- 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"}`,
1036
1200
  `- Require content-aware handoff: ${requireContent}`,
1037
1201
  `- Require active constraints: ${requireActive}`,
1038
1202
  ""
@@ -1065,6 +1229,7 @@ function explanationText(result, markdown) {
1065
1229
  "# Handoff Check explanation",
1066
1230
  "",
1067
1231
  `- Scope: ${markdownText(result.scope)}`,
1232
+ ...result.projectId === undefined ? [] : [`- Project: ${markdownText(result.projectId)}`],
1068
1233
  `- Evaluated at: ${markdownText(result.asOf)}`,
1069
1234
  `- Active constraints: ${result.activeConstraintCount}`,
1070
1235
  "",
@@ -1079,13 +1244,65 @@ function explanationText(result, markdown) {
1079
1244
  }
1080
1245
  return [
1081
1246
  ...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}`,
1247
+ `EXPLAIN ${result.activeConstraintCount} active constraints | ${result.rules.length} manifest rules | scope ${result.scope} | as of ${result.asOf}${result.projectId === undefined ? "" : ` | project ${result.projectId}`}`,
1083
1248
  "No handoff was compared.",
1084
1249
  ""
1085
1250
  ].join(`
1086
1251
  `);
1087
1252
  }
1088
1253
 
1254
+ // src/report.ts
1255
+ import { execFile } from "node:child_process";
1256
+ import { promisify } from "node:util";
1257
+ async function gitContext(cwd) {
1258
+ const run = async (args) => (await promisify(execFile)("git", ["--no-optional-locks", "-C", cwd, ...args], {
1259
+ encoding: "utf8",
1260
+ timeout: 2000,
1261
+ maxBuffer: 262144,
1262
+ windowsHide: true
1263
+ })).stdout.replace(/\r?\n$/, "");
1264
+ try {
1265
+ const worktree = await run(["rev-parse", "--show-toplevel"]);
1266
+ const commit = await run(["rev-parse", "--verify", "HEAD"]);
1267
+ const name = await run(["rev-parse", "--abbrev-ref", "HEAD"]);
1268
+ return { worktree, commit, branch: name === "HEAD" ? null : name };
1269
+ } catch {
1270
+ throw new InputError("Cannot collect requested Git context; Git and an existing commit in this worktree are required");
1271
+ }
1272
+ }
1273
+ function verificationReport(result, inputs, policies, profile, git) {
1274
+ return {
1275
+ schemaVersion: 1,
1276
+ kind: "verification-report",
1277
+ packageVersion: package_default.version,
1278
+ policies,
1279
+ inputs,
1280
+ ...profile === undefined ? {} : { profile },
1281
+ ...result.projectId === undefined ? {} : { projectId: result.projectId },
1282
+ ...git === undefined ? {} : { git },
1283
+ result,
1284
+ notice: "Local reproducibility record, not an authenticated attestation or proof of agent compliance. Git metadata and input reads are not atomic; revalidate before acting."
1285
+ };
1286
+ }
1287
+ function reportMarkdown(report) {
1288
+ const lines = [
1289
+ "",
1290
+ "## Reproducibility metadata",
1291
+ "",
1292
+ `- Package: ${markdownText(report.packageVersion)}`,
1293
+ `- Profile: ${report.profile === undefined ? "none selected" : markdownText(report.profile)}`
1294
+ ];
1295
+ if (report.projectId)
1296
+ lines.push(`- Project: ${markdownText(report.projectId)}`);
1297
+ for (const [name, input] of Object.entries(report.inputs))
1298
+ lines.push(input ? `- ${name}: ${markdownText(input.path)}; ${markdownText(input.sha256)}` : `- ${name}: absent implicit config (no digest)`);
1299
+ if (report.git)
1300
+ 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)}`);
1301
+ lines.push("", report.notice, "");
1302
+ return lines.join(`
1303
+ `);
1304
+ }
1305
+
1089
1306
  // src/cli.ts
1090
1307
  var help = `Handoff Check
1091
1308
 
@@ -1102,12 +1319,15 @@ Options:
1102
1319
  --handoff <path> Handoff file (default: handoff.json)
1103
1320
  --scope <scope> Selected scope, including global constraints
1104
1321
  --config <path> Project config (default: cwd/.handoff-check.json)
1322
+ --profile <name> Explicit config v2 profile; no scope/input overrides
1323
+ --report verify: exact input/config metadata (json/markdown only)
1324
+ --git-context verify --report: collect read-only Git context explicitly
1105
1325
  --as-of <UTC time> Fixed evaluation time (default: current time)
1106
- --require-content verify: require a v2/v3 content-aware handoff
1326
+ --require-content verify: require a v2/v3/v4 content-aware handoff
1107
1327
  --require-active verify: fail if empty; hook/hook-config: opt-in nonempty policy
1108
1328
  --task <task> snapshot: task description (required)
1109
1329
  --output <path> snapshot: create a new baseline file, never overwrite
1110
- --include-content snapshot: retain old rule text in a v3 handoff (opt-in)
1330
+ --include-content snapshot: retain old rule text in unbound v3/bound v4 (opt-in)
1111
1331
  --format text|json|markdown Markdown is verify/explain-only (default: text)
1112
1332
  --agent <agent> init: codex, claude, both (default), or none
1113
1333
  --host <host> doctor: integration target; hook/hook-config: claude
@@ -1143,6 +1363,9 @@ async function main() {
1143
1363
  "require-active": { type: "boolean" },
1144
1364
  "include-content": { type: "boolean" },
1145
1365
  host: { type: "string" },
1366
+ profile: { type: "string" },
1367
+ report: { type: "boolean" },
1368
+ "git-context": { type: "boolean" },
1146
1369
  task: { type: "string" },
1147
1370
  output: { type: "string" }
1148
1371
  }
@@ -1171,8 +1394,29 @@ async function main() {
1171
1394
  throw new InputError("Expected command: verify, snapshot, explain, init, doctor, hook or hook-config (use --help for usage)");
1172
1395
  const cwd = process.cwd();
1173
1396
  const command = positionals[0];
1397
+ if (values.profile !== undefined) {
1398
+ identifier(values.profile, "--profile");
1399
+ if (command === "init")
1400
+ throw new InputError("--profile is not supported by init; author config v2 explicitly");
1401
+ if ([values.scope, values.constraints, values.handoff].some((v) => v !== undefined))
1402
+ throw new InputError("--profile cannot be combined with --scope, --constraints or --handoff");
1403
+ }
1404
+ if ((values.report !== undefined || values["git-context"] !== undefined) && command !== "verify")
1405
+ throw new InputError("--report and --git-context are verify-only");
1406
+ if (values["git-context"] && !values.report)
1407
+ throw new InputError("--git-context requires --report");
1408
+ if (values.report && format === "text")
1409
+ throw new InputError("--report requires --format json or markdown");
1174
1410
  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"];
1411
+ const allowed = command === "doctor" ? [
1412
+ "host",
1413
+ "config",
1414
+ "scope",
1415
+ "constraints",
1416
+ "handoff",
1417
+ "format",
1418
+ "profile"
1419
+ ] : command === "hook" ? ["host", "config", "require-active", "profile"] : ["host", "require-active", "profile"];
1176
1420
  for (const key of Object.keys(values)) {
1177
1421
  if (key === "format" && values.format === "text" && !process.argv.slice(2).some((arg) => arg === "--format" || arg.startsWith("--format=")))
1178
1422
  continue;
@@ -1204,7 +1448,7 @@ ${result2.notice}
1204
1448
  if (values.host !== "claude")
1205
1449
  throw new InputError("hook and hook-config require --host claude; other host adapters are not shipped");
1206
1450
  if (command === "hook-config") {
1207
- process.stdout.write(`${JSON.stringify(hookConfig(values.host, values["require-active"] ?? false), null, 2)}
1451
+ process.stdout.write(`${JSON.stringify(hookConfig(values.host, values["require-active"] ?? false, values.profile), null, 2)}
1208
1452
  `);
1209
1453
  return 0;
1210
1454
  }
@@ -1217,7 +1461,7 @@ ${result2.notice}
1217
1461
  }, 5000);
1218
1462
  try {
1219
1463
  const event = await readHookInput(process.stdin);
1220
- const result2 = await lifecycleHook(event, values.config, values["require-active"] ?? false);
1464
+ const result2 = await lifecycleHook(event, values.config, values["require-active"] ?? false, values.profile);
1221
1465
  process.stdout.write(`${JSON.stringify(result2)}
1222
1466
  `);
1223
1467
  return 0;
@@ -1284,14 +1528,18 @@ ${result2.notice}
1284
1528
  }
1285
1529
  if (values.agent !== undefined || values["dry-run"] !== undefined || values.ci !== undefined)
1286
1530
  throw new InputError("--agent, --dry-run and --ci are only supported by init");
1287
- const { config, directory } = await loadConfig(cwd, values.config);
1531
+ const loaded = await loadConfig(cwd, values.config);
1532
+ const config = selectProfile(loaded.config, values.profile);
1533
+ const directory = loaded.directory;
1288
1534
  const scope = identifier(values.scope ?? config.scope, "--scope (or config.scope)");
1289
1535
  const asOf = values["as-of"] ?? new Date().toISOString();
1290
1536
  timestamp(asOf, "--as-of");
1291
1537
  for (const key of ["constraints", "handoff", "config"])
1292
1538
  if (values[key] !== undefined && !values[key].trim())
1293
1539
  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")));
1540
+ const manifestRecord = await readJsonRecord(values.constraints !== undefined ? resolve5(cwd, values.constraints) : resolve5(directory, config.constraints ?? "constraints.json"));
1541
+ const manifest = parseManifest(manifestRecord.input);
1542
+ checkProject(manifest, undefined, config.projectId);
1295
1543
  if (command === "explain") {
1296
1544
  const result2 = explain(manifest, scope, asOf);
1297
1545
  process.stdout.write(format === "json" ? `${JSON.stringify(result2, null, 2)}
@@ -1304,7 +1552,8 @@ ${result2.notice}
1304
1552
  if (values.task === undefined)
1305
1553
  throw new InputError("snapshot requires --task");
1306
1554
  const captured = snapshot(manifest, values.task, scope, asOf, {
1307
- includeContent: values["include-content"] ?? false
1555
+ includeContent: values["include-content"] ?? false,
1556
+ ...config.projectId === undefined ? {} : { projectId: config.projectId }
1308
1557
  });
1309
1558
  const content = `${JSON.stringify(captured, null, 2)}
1310
1559
  `;
@@ -1339,17 +1588,30 @@ ${result2.notice}
1339
1588
  }
1340
1589
  if (values.task !== undefined || values.output !== undefined)
1341
1590
  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")));
1591
+ const handoffRecord = await readJsonRecord(values.handoff !== undefined ? resolve5(cwd, values.handoff) : resolve5(directory, config.handoff ?? "handoff.json"));
1592
+ const handoff = parseHandoff(handoffRecord.input);
1343
1593
  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");
1594
+ throw new InputError("Content tracking requires a schemaVersion 2, 3 or 4 handoff; review current rules and capture a snapshot before resuming");
1345
1595
  const result = verify(manifest, handoff, scope, asOf, {
1346
- requireActive: values["require-active"] ?? false
1596
+ requireActive: values["require-active"] ?? false,
1597
+ ...config.projectId === undefined ? {} : { projectId: config.projectId }
1347
1598
  });
1599
+ const report = values.report ? verificationReport(result, {
1600
+ manifest: {
1601
+ path: manifestRecord.path,
1602
+ sha256: manifestRecord.sha256
1603
+ },
1604
+ handoff: { path: handoffRecord.path, sha256: handoffRecord.sha256 },
1605
+ config: loaded.source ?? null
1606
+ }, {
1607
+ requireContent: values["require-content"] ?? false,
1608
+ requireActive: values["require-active"] ?? false
1609
+ }, values.profile, values["git-context"] ? await gitContext(cwd) : undefined) : undefined;
1348
1610
  if (format === "json") {
1349
- process.stdout.write(`${JSON.stringify(result, null, 2)}
1611
+ process.stdout.write(`${JSON.stringify(report ?? result, null, 2)}
1350
1612
  `);
1351
1613
  } else if (format === "markdown") {
1352
- process.stdout.write(verificationMarkdown(result, handoff, values["require-active"] ?? false, values["require-content"] ?? false));
1614
+ process.stdout.write(verificationMarkdown(result, handoff, values["require-active"] ?? false, values["require-content"] ?? false) + (report ? reportMarkdown(report) : ""));
1353
1615
  } else {
1354
1616
  for (const finding of result.findings) {
1355
1617
  process.stdout.write(`${finding.code.padEnd(12)} ${finding.id === undefined ? "" : `${finding.id} `}${terminalText(finding.message)}
@@ -1366,7 +1628,7 @@ ${result2.notice}
1366
1628
  }
1367
1629
  const count = result.expectedConstraints.length;
1368
1630
  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" : ""}
1631
+ 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
1632
  `);
1371
1633
  }
1372
1634
  return result.status === "verified" ? 0 : 1;