handoff-check 0.4.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
@@ -2,12 +2,12 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { open as open2 } from "node:fs/promises";
5
- import { resolve as resolve3 } from "node:path";
5
+ import { resolve as resolve5 } 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.4.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,17 +396,582 @@ 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
+ };
408
+ }
409
+
410
+ // src/doctor.ts
411
+ import { lstat, readFile as readFile2, stat as stat2 } from "node:fs/promises";
412
+ import { resolve as resolve3 } from "node:path";
413
+
414
+ // src/lifecycle.ts
415
+ import { realpath, stat } from "node:fs/promises";
416
+ import { dirname as dirname2, isAbsolute, relative, resolve as resolve2, sep } from "node:path";
417
+
418
+ // src/verifier.ts
419
+ function compare(a, b) {
420
+ return a < b ? -1 : a > b ? 1 : 0;
421
+ }
422
+ function inactive(rule, scope, time) {
423
+ if (rule.scope !== "global" && rule.scope !== scope)
424
+ return "OUT_OF_SCOPE";
425
+ if (rule.revokedAt !== undefined && time >= Date.parse(rule.revokedAt))
426
+ return "REVOKED";
427
+ if (rule.supersededAt !== undefined && time >= Date.parse(rule.supersededAt))
428
+ return "SUPERSEDED";
429
+ if (rule.expiresAt !== undefined && time >= Date.parse(rule.expiresAt))
430
+ return "EXPIRED";
431
+ return;
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
+ }
450
+ function verify(manifest, handoff, scope, asOf, options = {}) {
451
+ identifier(scope, "scope");
452
+ const projectId = checkProject(manifest, handoff, options.projectId);
453
+ if (handoff.schemaVersion !== 1 && handoff.scope !== scope)
454
+ throw new InputError(`Handoff scope '${handoff.scope}' does not match selected scope '${scope}'`);
455
+ const time = timestamp(asOf, "asOf");
456
+ const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
457
+ const expectedConstraints = manifest.constraints.filter((rule) => inactive(rule, scope, time) === undefined).map((rule) => rule.id).sort(compare);
458
+ const refs = new Map(handoff.schemaVersion !== 1 ? handoff.activeConstraints.map((ref) => [ref.id, ref]) : []);
459
+ const reportedConstraints = (handoff.schemaVersion === 1 ? [...handoff.activeConstraints] : handoff.activeConstraints.map((ref) => ref.id)).sort(compare);
460
+ const reported = new Set(reportedConstraints);
461
+ const retained = new Map(handoff.schemaVersion === 3 || handoff.schemaVersion === 4 && handoff.contentMode === "retained" ? handoff.activeConstraints.map((ref) => [ref.id, ref.content]) : []);
462
+ const findings = [];
463
+ for (const id of expectedConstraints) {
464
+ if (!reported.has(id))
465
+ findings.push({
466
+ code: "MISSING",
467
+ id,
468
+ message: `Include active constraint: ${byId.get(id)?.description}`
469
+ });
470
+ }
471
+ for (const id of reportedConstraints) {
472
+ const rule = byId.get(id);
473
+ const code = rule ? inactive(rule, scope, time) : "UNKNOWN";
474
+ if (code) {
475
+ const detail = code === "SUPERSEDED" ? `; replaced by '${rule?.replacedBy}'` : "";
476
+ findings.push({
477
+ code,
478
+ id,
479
+ message: `Remove ${code.toLowerCase().replaceAll("_", "-")} constraint${detail}${rule ? `: ${rule.description}` : ""}`
480
+ });
481
+ } else if (rule && handoff.schemaVersion !== 1) {
482
+ const current = reference(rule);
483
+ const previous = refs.get(id);
484
+ if (previous && (current.revision !== previous.revision || current.contentHash !== previous.contentHash)) {
485
+ findings.push({
486
+ code: "CHANGED",
487
+ id,
488
+ message: `Review changed constraint: ${rule.description}; handoff revision ${previous.revision}, current revision ${current.revision}${current.contentHash !== previous.contentHash ? "; content hash differs" : ""}`,
489
+ expected: {
490
+ revision: current.revision,
491
+ contentHash: current.contentHash
492
+ },
493
+ reported: {
494
+ revision: previous.revision,
495
+ contentHash: previous.contentHash
496
+ },
497
+ ...retained.has(id) ? {
498
+ changes: fieldChanges(retained.get(id), rule)
499
+ } : {}
500
+ });
501
+ }
502
+ }
503
+ }
504
+ if (options.requireActive && expectedConstraints.length === 0) {
505
+ findings.push({
506
+ code: "NO_ACTIVE_CONSTRAINTS",
507
+ message: "No active constraints apply to the selected scope and time; --require-active requires at least one"
508
+ });
509
+ }
510
+ findings.sort((a, b) => compare(a.id ?? "", b.id ?? "") || compare(a.code, b.code));
511
+ return {
512
+ schemaVersion: handoff.schemaVersion,
513
+ ...projectId === undefined ? {} : { projectId },
514
+ ...handoff.schemaVersion !== 1 ? {
515
+ tracking: "content",
516
+ activeConstraintCount: expectedConstraints.length
517
+ } : {},
518
+ status: findings.length ? "mismatch" : "verified",
519
+ scope,
520
+ asOf: new Date(time).toISOString(),
521
+ expectedConstraints,
522
+ reportedConstraints,
523
+ findings
524
+ };
525
+ }
526
+ function snapshot(manifest, task, scope, asOf, options = {}) {
527
+ if (!task.trim())
528
+ throw new InputError("--task: expected a non-empty task");
529
+ const projectId = checkProject(manifest, undefined, options.projectId);
530
+ const result = explain(manifest, scope, asOf);
531
+ const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
532
+ const base = {
533
+ task,
534
+ scope,
535
+ capturedAt: result.asOf
536
+ };
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
+ };
555
+ return options.includeContent ? {
556
+ ...base,
557
+ schemaVersion: 3,
558
+ activeConstraints: rules.map((rule) => ({
559
+ ...reference(rule),
560
+ content: retainedContent(rule)
561
+ }))
562
+ } : { ...base, schemaVersion: 2, activeConstraints: rules.map(reference) };
563
+ }
564
+ var fields = [
565
+ "id",
566
+ "scope",
567
+ "description",
568
+ "source",
569
+ "expiresAt",
570
+ "revokedAt",
571
+ "replacedBy",
572
+ "supersededAt",
573
+ "revision"
574
+ ];
575
+ function fieldChanges(previous, current) {
576
+ const before = retainedContent(previous);
577
+ const after = retainedContent(current);
578
+ return fields.filter((field) => before[field] !== after[field]).map((field) => ({
579
+ field,
580
+ before: before[field] ?? null,
581
+ after: after[field] ?? null
582
+ }));
583
+ }
584
+ function explain(manifest, scope, asOf) {
585
+ identifier(scope, "scope");
586
+ const projectId = checkProject(manifest);
587
+ const time = timestamp(asOf, "asOf");
588
+ const rules = [...manifest.constraints].sort((a, b) => compare(a.id, b.id)).map((rule) => {
589
+ const decision = inactive(rule, scope, time) ?? "ACTIVE";
590
+ let reason;
591
+ switch (decision) {
592
+ case "ACTIVE":
593
+ reason = `${rule.scope === "global" ? "Global rule" : "Selected scope matches"}; no lifecycle transition is effective`;
594
+ break;
595
+ case "OUT_OF_SCOPE":
596
+ reason = `Rule scope '${rule.scope}' does not match '${scope}' and is not global`;
597
+ break;
598
+ case "REVOKED":
599
+ reason = `Revoked at ${new Date(rule.revokedAt ?? "").toISOString()}`;
600
+ break;
601
+ case "SUPERSEDED":
602
+ reason = `Superseded at ${new Date(rule.supersededAt ?? "").toISOString()}; replaced by '${rule.replacedBy}'`;
603
+ break;
604
+ case "EXPIRED":
605
+ reason = `Expired at ${new Date(rule.expiresAt ?? "").toISOString()}`;
606
+ break;
607
+ }
608
+ return {
609
+ id: rule.id,
610
+ scope: rule.scope,
611
+ description: rule.description,
612
+ source: rule.source,
613
+ decision,
614
+ reason
615
+ };
616
+ });
617
+ return {
618
+ schemaVersion: 1,
619
+ ...projectId === undefined ? {} : { projectId },
620
+ scope,
621
+ asOf: new Date(time).toISOString(),
622
+ activeConstraintCount: rules.filter((rule) => rule.decision === "ACTIVE").length,
623
+ rules
624
+ };
625
+ }
626
+
627
+ // src/lifecycle.ts
628
+ var lifecycleCommand = "node";
629
+ var projectPlaceholder = "$" + "{CLAUDE_PROJECT_DIR}";
630
+ var lifecycleArgs = [
631
+ `${projectPlaceholder}/node_modules/handoff-check/dist/cli.js`,
632
+ "hook",
633
+ "--host",
634
+ "claude",
635
+ "--config",
636
+ `${projectPlaceholder}/.handoff-check.json`
637
+ ];
638
+ var lifecycleMatcher = "^(startup|resume|clear|compact)$";
639
+ function hookConfig(host, requireActive = false, profile) {
640
+ if (profile !== undefined)
641
+ identifier(profile, "--profile");
642
+ if (host !== "claude")
643
+ throw new InputError("Only the claude lifecycle adapter is supported; see docs/lifecycle.md for host capabilities");
644
+ return {
645
+ hooks: {
646
+ SessionStart: [
647
+ {
648
+ matcher: lifecycleMatcher,
649
+ hooks: [
650
+ {
651
+ type: "command",
652
+ command: lifecycleCommand,
653
+ args: [
654
+ ...lifecycleArgs,
655
+ ...requireActive ? ["--require-active"] : [],
656
+ ...profile === undefined ? [] : ["--profile", profile]
657
+ ],
658
+ timeout: 10
659
+ }
660
+ ]
661
+ }
662
+ ]
663
+ }
664
+ };
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
+ }
685
+ async function readHookInput(input, timeoutMs = 2000, maxBytes = 65536) {
686
+ return new Promise((resolveInput, reject) => {
687
+ let size = 0;
688
+ const chunks = [];
689
+ const finish = (error) => {
690
+ clearTimeout(timer);
691
+ input.removeListener("data", data);
692
+ input.removeListener("end", end);
693
+ input.removeListener("error", failure);
694
+ input.removeListener("close", closed);
695
+ if (error) {
696
+ input.pause();
697
+ reject(error);
698
+ }
699
+ };
700
+ const failure = () => finish(new InputError("Cannot read hook event"));
701
+ const closed = () => finish(new InputError("Hook event stream closed before completion"));
702
+ const data = (chunk) => {
703
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
704
+ size += buffer.length;
705
+ if (size > maxBytes)
706
+ finish(new InputError("Hook event exceeds 65536 bytes"));
707
+ else
708
+ chunks.push(buffer);
709
+ };
710
+ const end = () => {
711
+ finish();
712
+ try {
713
+ resolveInput(JSON.parse(Buffer.concat(chunks).toString("utf8")));
714
+ } catch {
715
+ reject(new InputError("Hook event must be valid JSON"));
716
+ }
717
+ };
718
+ const timer = setTimeout(() => finish(new InputError("Timed out waiting for hook event")), timeoutMs);
719
+ input.on("data", data);
720
+ input.once("end", end);
721
+ input.once("error", failure);
722
+ input.once("close", closed);
723
+ });
724
+ }
725
+ async function lifecycleHook(input, configPath, requireActive = false, profile) {
726
+ if (!input || typeof input !== "object" || Array.isArray(input))
727
+ throw new InputError("Hook event must be an object");
728
+ const event = input;
729
+ if (event.hook_event_name !== "SessionStart" || typeof event.source !== "string" || !["startup", "resume", "clear", "compact"].includes(event.source))
730
+ throw new InputError("Expected supported Claude SessionStart source: startup, resume, clear or compact");
731
+ if (typeof event.cwd !== "string" || !isAbsolute(event.cwd) || event.cwd.includes("\x00"))
732
+ throw new InputError("Hook cwd must be an absolute directory path");
733
+ if (!isAbsolute(configPath))
734
+ throw new InputError("hook requires an absolute --config path");
735
+ const root = await realpath(dirname2(configPath));
736
+ const cwd = await realpath(event.cwd);
737
+ if (!(await stat(root)).isDirectory() || !(await stat(cwd)).isDirectory())
738
+ throw new InputError("Hook cwd and config directory must be directories");
739
+ const rel = relative(root, cwd);
740
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel))
741
+ throw new InputError("Hook cwd is outside the explicit config directory; select this worktree's config");
742
+ let summary;
743
+ try {
744
+ const loaded = await loadConfig(root, configPath);
745
+ const config = selectProfile(loaded.config, profile);
746
+ const directory = loaded.directory;
747
+ const scope = identifier(config.scope, "config.scope");
748
+ const manifest = parseManifest(await readJson(resolve2(directory, config.constraints ?? "constraints.json")));
749
+ const handoff = parseHandoff(await readJson(resolve2(directory, config.handoff ?? "handoff.json")));
750
+ if (handoff.schemaVersion === 1)
751
+ throw new InputError("Lifecycle checks require a content-aware v2/v3/v4 handoff; review and capture before adoption");
752
+ const result = verify(manifest, handoff, scope, new Date().toISOString(), {
753
+ requireActive,
754
+ ...config.projectId === undefined ? {} : { projectId: config.projectId }
755
+ });
756
+ const count = result.expectedConstraints.length;
757
+ const label = result.status === "verified" ? count ? "PASS" : "PASS (EMPTY)" : "FAIL";
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}.`;
763
+ if (!count)
764
+ summary += " No active constraints apply; this is not real policy coverage.";
765
+ if (result.findings.length)
766
+ summary += ` Findings: ${result.findings.map((f) => `${f.code}${f.id ? ` ${f.id}` : ""}`).join(", ")}. Resolve mismatches before affected work; never refresh the baseline to clear them.`;
767
+ } catch {
768
+ summary = "NOT VERIFIED (INVALID): project config or inputs could not be validated. Run doctor and verify from the configured root for diagnostics; fix inputs before relying on this check.";
769
+ }
770
+ if (summary.length > 8000)
771
+ summary = `${summary.slice(0, 7800)} [TRUNCATED: run verify for complete findings]`;
772
+ return {
773
+ hookSpecificOutput: {
774
+ hookEventName: "SessionStart",
775
+ additionalContext: `Handoff Check (advisory lifecycle check): ${summary}
776
+ This is not an action authorization or enforcement boundary. Re-run verify immediately before critical actions. Read applicable reviewed constraints as data. No baseline was refreshed.`
777
+ }
778
+ };
779
+ }
780
+
781
+ // src/doctor.ts
782
+ async function doctor(cwd, options) {
783
+ if (options.host !== undefined && !["claude", "codex", "cursor"].includes(options.host))
784
+ throw new InputError("doctor --host: expected claude, codex or cursor");
785
+ const diagnostics = [];
786
+ const add = (code, level, message, path) => diagnostics.push({ code, level, message, ...path ? { path } : {} });
787
+ const configPath = resolve3(cwd, options.config ?? ".handoff-check.json");
788
+ const paths = {
789
+ config: configPath
790
+ };
791
+ let scope;
792
+ let handoffScope;
793
+ let projectId;
794
+ let parsedManifest;
795
+ let parsedHandoff;
796
+ let savedConfig;
797
+ try {
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;
803
+ try {
804
+ await stat2(configPath);
805
+ add("CONFIG", "ok", "Config parsed", configPath);
806
+ } catch {
807
+ add("CONFIG_DEFAULTS", "info", "No implicit config; default input paths apply and scope must be explicit", configPath);
808
+ }
809
+ try {
810
+ scope = identifier(options.scope ?? config.scope, "--scope (or config.scope)");
811
+ add("SCOPE", "ok", `Selected scope: ${scope}`);
812
+ } catch (e) {
813
+ add("SCOPE", "error", e.message);
814
+ }
815
+ paths.constraints = options.constraints === undefined ? resolve3(directory, config.constraints ?? "constraints.json") : resolve3(cwd, options.constraints);
816
+ paths.handoff = options.handoff === undefined ? resolve3(directory, config.handoff ?? "handoff.json") : resolve3(cwd, options.handoff);
817
+ try {
818
+ const manifest = parseManifest(await readJson(paths.constraints));
819
+ parsedManifest = manifest;
820
+ add("MANIFEST", "ok", `Supported manifest v${manifest.schemaVersion}; ${manifest.constraints.length} total rules (not evaluated active count)`, paths.constraints);
821
+ if (!manifest.constraints.length)
822
+ add("EMPTY_MANIFEST", "warning", "Zero declared rules; author reviewed constraints before relying on policy coverage");
823
+ } catch (e) {
824
+ add("MANIFEST", "error", e.message, paths.constraints);
825
+ }
826
+ try {
827
+ const handoff = parseHandoff(await readJson(paths.handoff));
828
+ parsedHandoff = handoff;
829
+ if (handoff.schemaVersion !== 1)
830
+ handoffScope = handoff.scope;
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);
832
+ } catch (e) {
833
+ add("HANDOFF", "error", e.message, paths.handoff);
834
+ }
835
+ if (scope && handoffScope && scope !== handoffScope)
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
+ }
846
+ } catch (e) {
847
+ if (e instanceof ProfileError)
848
+ throw e;
849
+ add("CONFIG", "error", e.message, configPath);
850
+ }
851
+ const packagedSkill = await readFile2(new URL("../skills/handoff-check/SKILL.md", import.meta.url), "utf8");
852
+ for (const host of ["codex", "claude"]) {
853
+ const skillPath = resolve3(cwd, host === "codex" ? ".agents/skills/handoff-check/SKILL.md" : ".claude/skills/handoff-check/SKILL.md");
854
+ for (const [kind, path] of [
855
+ ["SKILL", skillPath],
856
+ [
857
+ "INSTRUCTIONS",
858
+ resolve3(cwd, host === "codex" ? "AGENTS.md" : "CLAUDE.md")
859
+ ]
860
+ ]) {
861
+ try {
862
+ const text = await readFile2(path, "utf8");
863
+ if (kind === "SKILL")
864
+ add(`${host}_${kind}`, text === packagedSkill ? "ok" : "warning", text === packagedSkill ? "Packaged skill matches" : "Skill differs from this package; review differences explicitly", path);
865
+ else {
866
+ const start = text.indexOf("<!-- handoff-check:begin -->");
867
+ const end = text.indexOf("<!-- handoff-check:end -->");
868
+ if (start < 0 && end < 0)
869
+ add(`${host}_${kind}`, options.host === host ? "warning" : "info", "No managed instruction block; custom prose is not assessed", path);
870
+ else if (start < 0 || end < start || text.split("<!-- handoff-check:begin -->").length !== 2 || text.split("<!-- handoff-check:end -->").length !== 2)
871
+ add(`${host}_${kind}`, "error", "Malformed managed instruction markers; review before init", path);
872
+ else {
873
+ const pins = [
874
+ ...text.slice(start, end).matchAll(/handoff-check@([\w.+-]+)/g)
875
+ ].map((m) => m[1]);
876
+ add(`${host}_${kind}`, pins.length > 0 && pins.every((pin) => pin === package_default.version) ? "ok" : "warning", `Managed package pins: ${pins.join(", ") || "none"}; current ${package_default.version}`, path);
877
+ }
878
+ }
879
+ } catch (e) {
880
+ add(`${host}_${kind}`, e.code === "ENOENT" ? options.host === host ? "warning" : "info" : "error", e.code === "ENOENT" ? "Integration not installed; init can create it after preview" : "Cannot read integration", path);
881
+ }
882
+ }
883
+ }
884
+ const ciPath = resolve3(cwd, ".github/workflows/handoff-check.yml");
885
+ try {
886
+ const ci = await readFile2(ciPath, "utf8");
887
+ const pins = [...ci.matchAll(/handoff-check@([\w.+-]+)/g)].map((m) => m[1]);
888
+ add("CI_PIN", pins.length && pins.every((pin) => pin === package_default.version) ? "ok" : "warning", `Textual CI pins: ${pins.join(", ") || "none"}; workflow execution is not assessed`, ciPath);
889
+ } catch (e) {
890
+ add("CI", e.code === "ENOENT" ? "info" : "error", "CI not inspected; no workflow present or readable", ciPath);
891
+ }
892
+ const settingsPath = resolve3(cwd, ".claude/settings.json");
893
+ let configured = false;
894
+ try {
895
+ const settings = await readJson(settingsPath);
896
+ if (!settings || typeof settings !== "object" || Array.isArray(settings))
897
+ throw new Error("Expected settings object");
898
+ if (settings.hooks !== undefined && (!settings.hooks || typeof settings.hooks !== "object" || Array.isArray(settings.hooks)))
899
+ throw new Error("Expected hooks object");
900
+ if (settings.hooks?.SessionStart !== undefined && !Array.isArray(settings.hooks.SessionStart))
901
+ throw new Error("Expected SessionStart array");
902
+ if (settings.disableAllHooks === true)
903
+ add("CLAUDE_HOOK_DISABLED", "warning", "Project settings disable hooks", settingsPath);
904
+ const groups = settings.hooks?.SessionStart;
905
+ if (Array.isArray(groups))
906
+ for (const group of groups) {
907
+ if (group && typeof group === "object" && Array.isArray(group.hooks))
908
+ for (const hook of group.hooks) {
909
+ if (hook?.command === lifecycleCommand && lifecycleInvocation(hook.args) !== undefined) {
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
+ }
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);
922
+ }
923
+ }
924
+ }
925
+ if (!configured)
926
+ add("CLAUDE_HOOK", options.host === "claude" ? "warning" : "info", "No recognized lifecycle adapter; use hook-config --host claude and merge explicitly", settingsPath);
927
+ } catch {
928
+ try {
929
+ await stat2(settingsPath);
930
+ add("CLAUDE_SETTINGS", "error", "Settings unreadable or invalid JSON/shape; no settings were changed", settingsPath);
931
+ } catch {
932
+ add("CLAUDE_HOOK", options.host === "claude" ? "warning" : "info", "No project lifecycle settings inspected; use hook-config --host claude", settingsPath);
933
+ }
934
+ }
935
+ if (configured) {
936
+ const packagePath = resolve3(cwd, "node_modules/handoff-check/package.json");
937
+ try {
938
+ const pkg = await readJson(packagePath);
939
+ await stat2(resolve3(cwd, "node_modules/handoff-check/dist/cli.js"));
940
+ add("LOCAL_ADAPTER", pkg.name === "handoff-check" && pkg.version === package_default.version ? "ok" : "warning", `Local adapter package version ${pkg.version ?? "unknown"}; current ${package_default.version}`, packagePath);
941
+ } catch {
942
+ add("LOCAL_ADAPTER", "error", `Install project-local handoff-check@${package_default.version} before enabling this hook`, packagePath);
943
+ }
944
+ }
945
+ if (options.host === "codex" || options.host === "cursor")
946
+ add("HOST_ADAPTER", "warning", `${options.host} lifecycle adapter is not shipped in this version; use explicit CLI/CI and see docs/lifecycle.md`);
947
+ for (const path of [
948
+ paths.config,
949
+ paths.constraints,
950
+ paths.handoff,
951
+ settingsPath
952
+ ].filter((p) => p !== undefined)) {
953
+ try {
954
+ if ((await lstat(path)).isSymbolicLink())
955
+ add("SYMLINK", "info", "Path is a symlink; input reads follow its target, as verify does", path);
956
+ } catch {}
957
+ }
958
+ return {
959
+ schemaVersion: 1,
960
+ packageVersion: package_default.version,
961
+ status: diagnostics.some((d) => d.level === "warning" || d.level === "error") ? "attention" : "healthy",
962
+ paths,
963
+ ...scope ? { scope } : {},
964
+ ...projectId === undefined ? {} : { projectId },
965
+ ...options.profile === undefined ? {} : { profile: options.profile },
966
+ diagnostics,
967
+ notice: "Read-only local diagnostics, not handoff verification or proof that host hooks/skills executed. User/global/managed host settings are not inspected."
968
+ };
346
969
  }
347
970
 
348
971
  // src/initialize.ts
349
972
  import { constants } from "node:fs";
350
- import { lstat, mkdir, open, readFile as readFile2 } from "node:fs/promises";
351
- import { dirname as dirname2, isAbsolute, relative, resolve as resolve2, sep } from "node:path";
973
+ import { lstat as lstat2, mkdir, open, readFile as readFile3 } from "node:fs/promises";
974
+ import { dirname as dirname3, isAbsolute as isAbsolute2, relative as relative2, resolve as resolve4, sep as sep2 } from "node:path";
352
975
  var begin = "<!-- handoff-check:begin -->";
353
976
  var end = "<!-- handoff-check:end -->";
354
977
  var instruction = `${begin}
@@ -370,15 +993,15 @@ never refresh the baseline before verifying it when resuming work.
370
993
  ${end}
371
994
  `;
372
995
  async function inspect(root, path) {
373
- const rel = relative(root, path);
374
- if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel))
996
+ const rel = relative2(root, path);
997
+ if (!rel || rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute2(rel))
375
998
  throw new InputError(`Initialization target must be inside the project: '${path}'`);
376
999
  let current = root;
377
- const parts = rel.split(sep);
1000
+ const parts = rel.split(sep2);
378
1001
  for (const [index, part] of parts.entries()) {
379
- current = resolve2(current, part);
1002
+ current = resolve4(current, part);
380
1003
  try {
381
- const info = await lstat(current);
1004
+ const info = await lstat2(current);
382
1005
  if (info.isSymbolicLink())
383
1006
  throw new InputError(`Refusing symlink initialization target: '${current}'`);
384
1007
  if (index < parts.length - 1 && !info.isDirectory())
@@ -391,13 +1014,13 @@ async function inspect(root, path) {
391
1014
  throw error;
392
1015
  }
393
1016
  }
394
- return readFile2(path, "utf8");
1017
+ return readFile3(path, "utf8");
395
1018
  }
396
1019
  async function initialize(root, options) {
397
1020
  if (!["codex", "claude", "both", "none"].includes(options.agent))
398
1021
  throw new InputError("--agent: expected codex, claude, both, or none");
399
1022
  const plan = [];
400
- const configPath = resolve2(root, ".handoff-check.json");
1023
+ const configPath = resolve4(root, ".handoff-check.json");
401
1024
  const previous = await inspect(root, configPath);
402
1025
  const config = previous === undefined ? { schemaVersion: 1 } : parseConfig(await readJson(configPath));
403
1026
  const scope = identifier(options.scope ?? config.scope, "init --scope (or config.scope)");
@@ -437,7 +1060,7 @@ async function initialize(root, options) {
437
1060
  parseHandoff
438
1061
  ]
439
1062
  ]) {
440
- const path = resolve2(root, config[key] ?? fallback);
1063
+ const path = resolve4(root, config[key] ?? fallback);
441
1064
  const old = await inspect(root, path);
442
1065
  if (old !== undefined)
443
1066
  validate(await readJson(path));
@@ -447,10 +1070,10 @@ async function initialize(root, options) {
447
1070
  content: old ?? json(starter)
448
1071
  });
449
1072
  }
450
- const skill = options.agent === "none" ? "" : await readFile2(new URL("../skills/handoff-check/SKILL.md", import.meta.url), "utf8");
1073
+ const skill = options.agent === "none" ? "" : await readFile3(new URL("../skills/handoff-check/SKILL.md", import.meta.url), "utf8");
451
1074
  const selected = options.agent === "both" ? ["codex", "claude"] : options.agent === "none" ? [] : [options.agent];
452
1075
  for (const agent of selected) {
453
- const skillPath = resolve2(root, agent === "codex" ? ".agents/skills/handoff-check/SKILL.md" : ".claude/skills/handoff-check/SKILL.md");
1076
+ const skillPath = resolve4(root, agent === "codex" ? ".agents/skills/handoff-check/SKILL.md" : ".claude/skills/handoff-check/SKILL.md");
454
1077
  const oldSkill = await inspect(root, skillPath);
455
1078
  if (oldSkill !== undefined && oldSkill !== skill)
456
1079
  throw new InputError(`Existing skill differs; review it before replacing: '${skillPath}'`);
@@ -459,7 +1082,7 @@ async function initialize(root, options) {
459
1082
  action: oldSkill === undefined ? "create" : "preserve",
460
1083
  content: skill
461
1084
  });
462
- const path = resolve2(root, agent === "codex" ? "AGENTS.md" : "CLAUDE.md");
1085
+ const path = resolve4(root, agent === "codex" ? "AGENTS.md" : "CLAUDE.md");
463
1086
  const before = await inspect(root, path);
464
1087
  if (before === undefined)
465
1088
  plan.push({ path, action: "create", content: instruction });
@@ -484,7 +1107,7 @@ async function initialize(root, options) {
484
1107
  }
485
1108
  }
486
1109
  if (options.ci) {
487
- const path = resolve2(root, ".github/workflows/handoff-check.yml");
1110
+ const path = resolve4(root, ".github/workflows/handoff-check.yml");
488
1111
  const content = `name: Handoff constraints
489
1112
  on: [push, pull_request]
490
1113
  permissions:
@@ -513,7 +1136,7 @@ jobs:
513
1136
  throw new InputError("Initialization paths overlap; use separate config, manifest, handoff and integration files");
514
1137
  const written = [];
515
1138
  for (const file of plan) {
516
- if (plan.some((other) => other !== file && pathKey(other.path).startsWith(`${pathKey(file.path)}${sep}`)))
1139
+ if (plan.some((other) => other !== file && pathKey(other.path).startsWith(`${pathKey(file.path)}${sep2}`)))
517
1140
  throw new InputError("Initialization paths overlap as file and directory; choose separate paths");
518
1141
  }
519
1142
  if (!options.dryRun) {
@@ -524,7 +1147,7 @@ jobs:
524
1147
  const current = await inspect(root, file.path);
525
1148
  if (file.action === "create" && current !== undefined || file.action === "append" && current !== file.before)
526
1149
  throw new InputError("Target changed after planning");
527
- await mkdir(dirname2(file.path), { recursive: true });
1150
+ await mkdir(dirname3(file.path), { recursive: true });
528
1151
  await inspect(root, file.path);
529
1152
  const flags = file.action === "create" ? constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL : constants.O_WRONLY | constants.O_APPEND | (constants.O_NOFOLLOW ?? 0);
530
1153
  const handle = await open(file.path, flags, 420);
@@ -533,10 +1156,10 @@ jobs:
533
1156
  } finally {
534
1157
  await handle.close();
535
1158
  }
536
- written.push(relative(root, file.path));
1159
+ written.push(relative2(root, file.path));
537
1160
  } catch (error) {
538
1161
  const message = error instanceof Error ? error.message : "write failed";
539
- throw new InputError(`Initialization stopped at '${relative(root, file.path)}': ${message}. Written files: ${written.join(", ") || "none"}. Inspect these paths before retrying; filesystem failures are not transactional.`);
1162
+ throw new InputError(`Initialization stopped at '${relative2(root, file.path)}': ${message}. Written files: ${written.join(", ") || "none"}. Inspect these paths before retrying; filesystem failures are not transactional.`);
540
1163
  }
541
1164
  }
542
1165
  }
@@ -545,7 +1168,7 @@ jobs:
545
1168
  status: options.dryRun ? "preview" : "initialized",
546
1169
  scope,
547
1170
  files: plan.map((file) => ({
548
- path: relative(root, file.path),
1171
+ path: relative2(root, file.path),
549
1172
  action: file.action,
550
1173
  ...file.action === "preserve" ? {} : { content: file.content }
551
1174
  })),
@@ -570,9 +1193,10 @@ function verificationMarkdown(result, handoff, requireActive, requireContent) {
570
1193
  "",
571
1194
  `- Result: ${label}`,
572
1195
  `- Scope: ${markdownText(result.scope)}`,
1196
+ ...result.projectId === undefined ? [] : [`- Project: ${markdownText(result.projectId)}`],
573
1197
  `- Evaluated at: ${markdownText(result.asOf)}`,
574
1198
  `- Active constraints checked: ${result.expectedConstraints.length}`,
575
- `- 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"}`,
576
1200
  `- Require content-aware handoff: ${requireContent}`,
577
1201
  `- Require active constraints: ${requireActive}`,
578
1202
  ""
@@ -605,6 +1229,7 @@ function explanationText(result, markdown) {
605
1229
  "# Handoff Check explanation",
606
1230
  "",
607
1231
  `- Scope: ${markdownText(result.scope)}`,
1232
+ ...result.projectId === undefined ? [] : [`- Project: ${markdownText(result.projectId)}`],
608
1233
  `- Evaluated at: ${markdownText(result.asOf)}`,
609
1234
  `- Active constraints: ${result.activeConstraintCount}`,
610
1235
  "",
@@ -619,182 +1244,64 @@ function explanationText(result, markdown) {
619
1244
  }
620
1245
  return [
621
1246
  ...result.rules.map((rule) => `${rule.decision.padEnd(12)} ${rule.id} ${terminalText(rule.reason)}; ${terminalText(rule.description)}; source ${terminalText(rule.source)}`),
622
- `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}`}`,
623
1248
  "No handoff was compared.",
624
1249
  ""
625
1250
  ].join(`
626
1251
  `);
627
1252
  }
628
1253
 
629
- // src/verifier.ts
630
- function compare(a, b) {
631
- return a < b ? -1 : a > b ? 1 : 0;
632
- }
633
- function inactive(rule, scope, time) {
634
- if (rule.scope !== "global" && rule.scope !== scope)
635
- return "OUT_OF_SCOPE";
636
- if (rule.revokedAt !== undefined && time >= Date.parse(rule.revokedAt))
637
- return "REVOKED";
638
- if (rule.supersededAt !== undefined && time >= Date.parse(rule.supersededAt))
639
- return "SUPERSEDED";
640
- if (rule.expiresAt !== undefined && time >= Date.parse(rule.expiresAt))
641
- return "EXPIRED";
642
- return;
643
- }
644
- function verify(manifest, handoff, scope, asOf, options = {}) {
645
- identifier(scope, "scope");
646
- if (handoff.schemaVersion !== 1 && handoff.scope !== scope)
647
- throw new InputError(`Handoff scope '${handoff.scope}' does not match selected scope '${scope}'`);
648
- const time = timestamp(asOf, "asOf");
649
- const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
650
- const expectedConstraints = manifest.constraints.filter((rule) => inactive(rule, scope, time) === undefined).map((rule) => rule.id).sort(compare);
651
- const refs = new Map(handoff.schemaVersion !== 1 ? handoff.activeConstraints.map((ref) => [ref.id, ref]) : []);
652
- const reportedConstraints = (handoff.schemaVersion === 1 ? [...handoff.activeConstraints] : handoff.activeConstraints.map((ref) => ref.id)).sort(compare);
653
- const reported = new Set(reportedConstraints);
654
- const retained = new Map(handoff.schemaVersion === 3 ? handoff.activeConstraints.map((ref) => [ref.id, ref.content]) : []);
655
- const findings = [];
656
- for (const id of expectedConstraints) {
657
- if (!reported.has(id))
658
- findings.push({
659
- code: "MISSING",
660
- id,
661
- message: `Include active constraint: ${byId.get(id)?.description}`
662
- });
663
- }
664
- for (const id of reportedConstraints) {
665
- const rule = byId.get(id);
666
- const code = rule ? inactive(rule, scope, time) : "UNKNOWN";
667
- if (code) {
668
- const detail = code === "SUPERSEDED" ? `; replaced by '${rule?.replacedBy}'` : "";
669
- findings.push({
670
- code,
671
- id,
672
- message: `Remove ${code.toLowerCase().replaceAll("_", "-")} constraint${detail}${rule ? `: ${rule.description}` : ""}`
673
- });
674
- } else if (rule && handoff.schemaVersion !== 1) {
675
- const current = reference(rule);
676
- const previous = refs.get(id);
677
- if (previous && (current.revision !== previous.revision || current.contentHash !== previous.contentHash)) {
678
- findings.push({
679
- code: "CHANGED",
680
- id,
681
- message: `Review changed constraint: ${rule.description}; handoff revision ${previous.revision}, current revision ${current.revision}${current.contentHash !== previous.contentHash ? "; content hash differs" : ""}`,
682
- expected: {
683
- revision: current.revision,
684
- contentHash: current.contentHash
685
- },
686
- reported: {
687
- revision: previous.revision,
688
- contentHash: previous.contentHash
689
- },
690
- ...retained.has(id) ? {
691
- changes: fieldChanges(retained.get(id), rule)
692
- } : {}
693
- });
694
- }
695
- }
696
- }
697
- if (options.requireActive && expectedConstraints.length === 0) {
698
- findings.push({
699
- code: "NO_ACTIVE_CONSTRAINTS",
700
- message: "No active constraints apply to the selected scope and time; --require-active requires at least one"
701
- });
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");
702
1271
  }
703
- findings.sort((a, b) => compare(a.id ?? "", b.id ?? "") || compare(a.code, b.code));
704
- return {
705
- schemaVersion: handoff.schemaVersion,
706
- ...handoff.schemaVersion !== 1 ? {
707
- tracking: "content",
708
- activeConstraintCount: expectedConstraints.length
709
- } : {},
710
- status: findings.length ? "mismatch" : "verified",
711
- scope,
712
- asOf: new Date(time).toISOString(),
713
- expectedConstraints,
714
- reportedConstraints,
715
- findings
716
- };
717
- }
718
- function snapshot(manifest, task, scope, asOf, options = {}) {
719
- if (!task.trim())
720
- throw new InputError("--task: expected a non-empty task");
721
- const result = verify(manifest, { schemaVersion: 1, task, activeConstraints: [] }, scope, asOf);
722
- const byId = new Map(manifest.constraints.map((rule) => [rule.id, rule]));
723
- const base = {
724
- task,
725
- scope,
726
- capturedAt: result.asOf
727
- };
728
- const rules = result.expectedConstraints.map((id) => byId.get(id));
729
- return options.includeContent ? {
730
- ...base,
731
- schemaVersion: 3,
732
- activeConstraints: rules.map((rule) => ({
733
- ...reference(rule),
734
- content: retainedContent(rule)
735
- }))
736
- } : { ...base, schemaVersion: 2, activeConstraints: rules.map(reference) };
737
- }
738
- var fields = [
739
- "id",
740
- "scope",
741
- "description",
742
- "source",
743
- "expiresAt",
744
- "revokedAt",
745
- "replacedBy",
746
- "supersededAt",
747
- "revision"
748
- ];
749
- function fieldChanges(previous, current) {
750
- const before = retainedContent(previous);
751
- const after = retainedContent(current);
752
- return fields.filter((field) => before[field] !== after[field]).map((field) => ({
753
- field,
754
- before: before[field] ?? null,
755
- after: after[field] ?? null
756
- }));
757
1272
  }
758
- function explain(manifest, scope, asOf) {
759
- identifier(scope, "scope");
760
- const time = timestamp(asOf, "asOf");
761
- const rules = [...manifest.constraints].sort((a, b) => compare(a.id, b.id)).map((rule) => {
762
- const decision = inactive(rule, scope, time) ?? "ACTIVE";
763
- let reason;
764
- switch (decision) {
765
- case "ACTIVE":
766
- reason = `${rule.scope === "global" ? "Global rule" : "Selected scope matches"}; no lifecycle transition is effective`;
767
- break;
768
- case "OUT_OF_SCOPE":
769
- reason = `Rule scope '${rule.scope}' does not match '${scope}' and is not global`;
770
- break;
771
- case "REVOKED":
772
- reason = `Revoked at ${new Date(rule.revokedAt ?? "").toISOString()}`;
773
- break;
774
- case "SUPERSEDED":
775
- reason = `Superseded at ${new Date(rule.supersededAt ?? "").toISOString()}; replaced by '${rule.replacedBy}'`;
776
- break;
777
- case "EXPIRED":
778
- reason = `Expired at ${new Date(rule.expiresAt ?? "").toISOString()}`;
779
- break;
780
- }
781
- return {
782
- id: rule.id,
783
- scope: rule.scope,
784
- description: rule.description,
785
- source: rule.source,
786
- decision,
787
- reason
788
- };
789
- });
1273
+ function verificationReport(result, inputs, policies, profile, git) {
790
1274
  return {
791
1275
  schemaVersion: 1,
792
- scope,
793
- asOf: new Date(time).toISOString(),
794
- activeConstraintCount: rules.filter((rule) => rule.decision === "ACTIVE").length,
795
- rules
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."
796
1285
  };
797
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
+ }
798
1305
 
799
1306
  // src/cli.ts
800
1307
  var help = `Handoff Check
@@ -803,26 +1310,35 @@ Usage: handoff-check verify --scope <scope> [options]
803
1310
  handoff-check init --scope <scope> [--agent both] [--dry-run] [--ci]
804
1311
  handoff-check snapshot --task <task> [--output <new-file>] [options]
805
1312
  handoff-check explain --scope <scope> [options]
1313
+ handoff-check doctor [--host claude|codex|cursor] [--format text|json]
1314
+ handoff-check hook-config --host claude [--require-active]
1315
+ handoff-check hook --host claude --config <absolute-path> [--require-active]
806
1316
 
807
1317
  Options:
808
1318
  --constraints <path> Manifest file (default: constraints.json)
809
1319
  --handoff <path> Handoff file (default: handoff.json)
810
1320
  --scope <scope> Selected scope, including global constraints
811
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
812
1325
  --as-of <UTC time> Fixed evaluation time (default: current time)
813
- --require-content verify: require a v2/v3 content-aware handoff
814
- --require-active verify: fail if no constraints apply to scope/time
1326
+ --require-content verify: require a v2/v3/v4 content-aware handoff
1327
+ --require-active verify: fail if empty; hook/hook-config: opt-in nonempty policy
815
1328
  --task <task> snapshot: task description (required)
816
1329
  --output <path> snapshot: create a new baseline file, never overwrite
817
- --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)
818
1331
  --format text|json|markdown Markdown is verify/explain-only (default: text)
819
1332
  --agent <agent> init: codex, claude, both (default), or none
1333
+ --host <host> doctor: integration target; hook/hook-config: claude
820
1334
  --dry-run init: preview files and instruction changes without writes
821
1335
  --ci init: also create a pinned GitHub Actions check
822
1336
  --version Show package version
823
1337
  --help Show this help
824
1338
 
825
- Exit codes: 0 verified/explained/captured/initialized, 1 rule/policy mismatch, 2 invalid input
1339
+ Exit codes: verify 0 verified / 1 mismatch; doctor 0 healthy / 1 attention.
1340
+ Hook 0 means advisory response delivered (may report FAIL/INVALID), not verified.
1341
+ Invalid invocation/input returns 2; explain/init/snapshot/hook-config succeed with 0.
826
1342
  `;
827
1343
  async function main() {
828
1344
  let format = "text";
@@ -846,6 +1362,10 @@ async function main() {
846
1362
  "require-content": { type: "boolean" },
847
1363
  "require-active": { type: "boolean" },
848
1364
  "include-content": { type: "boolean" },
1365
+ host: { type: "string" },
1366
+ profile: { type: "string" },
1367
+ report: { type: "boolean" },
1368
+ "git-context": { type: "boolean" },
849
1369
  task: { type: "string" },
850
1370
  output: { type: "string" }
851
1371
  }
@@ -862,10 +1382,96 @@ async function main() {
862
1382
  `);
863
1383
  return 0;
864
1384
  }
865
- if (positionals.length !== 1 || !["verify", "init", "snapshot", "explain"].includes(positionals[0] ?? ""))
866
- throw new InputError("Expected command: verify, snapshot, explain or init (use --help for usage)");
1385
+ if (positionals.length !== 1 || ![
1386
+ "verify",
1387
+ "init",
1388
+ "snapshot",
1389
+ "explain",
1390
+ "doctor",
1391
+ "hook",
1392
+ "hook-config"
1393
+ ].includes(positionals[0] ?? ""))
1394
+ throw new InputError("Expected command: verify, snapshot, explain, init, doctor, hook or hook-config (use --help for usage)");
867
1395
  const cwd = process.cwd();
868
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");
1410
+ if (["doctor", "hook", "hook-config"].includes(command ?? "")) {
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"];
1420
+ for (const key of Object.keys(values)) {
1421
+ if (key === "format" && values.format === "text" && !process.argv.slice(2).some((arg) => arg === "--format" || arg.startsWith("--format=")))
1422
+ continue;
1423
+ if (!allowed.includes(key))
1424
+ throw new InputError(`--${key} is not supported by ${command}`);
1425
+ }
1426
+ if (command === "doctor") {
1427
+ if (values.scope !== undefined)
1428
+ identifier(values.scope, "--scope");
1429
+ for (const key of ["config", "constraints", "handoff"])
1430
+ if (values[key] !== undefined && !values[key].trim())
1431
+ throw new InputError(`--${key}: expected a non-empty path`);
1432
+ if (format === "markdown")
1433
+ throw new InputError("doctor supports text or json");
1434
+ const result2 = await doctor(cwd, values);
1435
+ if (format === "json")
1436
+ process.stdout.write(`${JSON.stringify(result2, null, 2)}
1437
+ `);
1438
+ else {
1439
+ for (const d of result2.diagnostics)
1440
+ process.stdout.write(`${d.level.toUpperCase()} ${d.code} ${terminalText(d.message)}${d.path ? ` | ${terminalText(d.path)}` : ""}
1441
+ `);
1442
+ process.stdout.write(`DOCTOR ${result2.status.toUpperCase()}
1443
+ ${result2.notice}
1444
+ `);
1445
+ }
1446
+ return result2.status === "healthy" ? 0 : 1;
1447
+ }
1448
+ if (values.host !== "claude")
1449
+ throw new InputError("hook and hook-config require --host claude; other host adapters are not shipped");
1450
+ if (command === "hook-config") {
1451
+ process.stdout.write(`${JSON.stringify(hookConfig(values.host, values["require-active"] ?? false, values.profile), null, 2)}
1452
+ `);
1453
+ return 0;
1454
+ }
1455
+ if (!values.config)
1456
+ throw new InputError("hook requires --config <absolute-path>");
1457
+ const watchdog = setTimeout(() => {
1458
+ process.stderr.write(`INVALID Hook check exceeded 5 seconds; not verified
1459
+ `);
1460
+ process.exit(2);
1461
+ }, 5000);
1462
+ try {
1463
+ const event = await readHookInput(process.stdin);
1464
+ const result2 = await lifecycleHook(event, values.config, values["require-active"] ?? false, values.profile);
1465
+ process.stdout.write(`${JSON.stringify(result2)}
1466
+ `);
1467
+ return 0;
1468
+ } finally {
1469
+ clearTimeout(watchdog);
1470
+ process.stdin.destroy();
1471
+ }
1472
+ }
1473
+ if (values.host !== undefined)
1474
+ throw new InputError("--host is only supported by doctor, hook and hook-config");
869
1475
  if (format === "markdown" && command !== "verify" && command !== "explain")
870
1476
  throw new InputError("--format markdown is only supported by verify and explain");
871
1477
  if (values["include-content"] !== undefined && command !== "snapshot")
@@ -922,14 +1528,18 @@ ${result2.notice}
922
1528
  }
923
1529
  if (values.agent !== undefined || values["dry-run"] !== undefined || values.ci !== undefined)
924
1530
  throw new InputError("--agent, --dry-run and --ci are only supported by init");
925
- 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;
926
1534
  const scope = identifier(values.scope ?? config.scope, "--scope (or config.scope)");
927
1535
  const asOf = values["as-of"] ?? new Date().toISOString();
928
1536
  timestamp(asOf, "--as-of");
929
1537
  for (const key of ["constraints", "handoff", "config"])
930
1538
  if (values[key] !== undefined && !values[key].trim())
931
1539
  throw new InputError(`--${key}: expected a non-empty path`);
932
- const manifest = parseManifest(await readJson(values.constraints !== undefined ? resolve3(cwd, values.constraints) : resolve3(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);
933
1543
  if (command === "explain") {
934
1544
  const result2 = explain(manifest, scope, asOf);
935
1545
  process.stdout.write(format === "json" ? `${JSON.stringify(result2, null, 2)}
@@ -942,7 +1552,8 @@ ${result2.notice}
942
1552
  if (values.task === undefined)
943
1553
  throw new InputError("snapshot requires --task");
944
1554
  const captured = snapshot(manifest, values.task, scope, asOf, {
945
- includeContent: values["include-content"] ?? false
1555
+ includeContent: values["include-content"] ?? false,
1556
+ ...config.projectId === undefined ? {} : { projectId: config.projectId }
946
1557
  });
947
1558
  const content = `${JSON.stringify(captured, null, 2)}
948
1559
  `;
@@ -951,7 +1562,7 @@ ${result2.notice}
951
1562
  else {
952
1563
  if (!values.output.trim())
953
1564
  throw new InputError("--output: expected a non-empty path");
954
- const path = resolve3(cwd, values.output);
1565
+ const path = resolve5(cwd, values.output);
955
1566
  let handle;
956
1567
  try {
957
1568
  handle = await open2(path, "wx", 420);
@@ -977,17 +1588,30 @@ ${result2.notice}
977
1588
  }
978
1589
  if (values.task !== undefined || values.output !== undefined)
979
1590
  throw new InputError("--task and --output are only supported by snapshot");
980
- const handoff = parseHandoff(await readJson(values.handoff !== undefined ? resolve3(cwd, values.handoff) : resolve3(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);
981
1593
  if (values["require-content"] && handoff.schemaVersion === 1)
982
- 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");
983
1595
  const result = verify(manifest, handoff, scope, asOf, {
984
- requireActive: values["require-active"] ?? false
1596
+ requireActive: values["require-active"] ?? false,
1597
+ ...config.projectId === undefined ? {} : { projectId: config.projectId }
985
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;
986
1610
  if (format === "json") {
987
- process.stdout.write(`${JSON.stringify(result, null, 2)}
1611
+ process.stdout.write(`${JSON.stringify(report ?? result, null, 2)}
988
1612
  `);
989
1613
  } else if (format === "markdown") {
990
- 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) : ""));
991
1615
  } else {
992
1616
  for (const finding of result.findings) {
993
1617
  process.stdout.write(`${finding.code.padEnd(12)} ${finding.id === undefined ? "" : `${finding.id} `}${terminalText(finding.message)}
@@ -1004,7 +1628,7 @@ ${result2.notice}
1004
1628
  }
1005
1629
  const count = result.expectedConstraints.length;
1006
1630
  const label = result.status === "verified" ? count === 0 ? "PASS (EMPTY)" : "PASS" : "FAIL";
1007
- 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" : ""}
1008
1632
  `);
1009
1633
  }
1010
1634
  return result.status === "verified" ? 0 : 1;