@holmes-lab/holmes-kit 0.40.0 → 0.41.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.
Files changed (119) hide show
  1. package/CHANGELOG.md +312 -0
  2. package/README.md +79 -5
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/approve-context.js +4 -3
  5. package/dist/holmes/cli/approve.js +22 -12
  6. package/dist/holmes/cli/autonomy.d.ts +21 -0
  7. package/dist/holmes/cli/autonomy.js +35 -5
  8. package/dist/holmes/cli/doctor.js +58 -6
  9. package/dist/holmes/cli/index.js +394 -267
  10. package/dist/holmes/cli/init.js +17 -6
  11. package/dist/holmes/cli/interactive-prompt.d.ts +39 -2
  12. package/dist/holmes/cli/interactive-prompt.js +98 -16
  13. package/dist/holmes/cli/ledger-witness.d.ts +61 -0
  14. package/dist/holmes/cli/ledger-witness.js +212 -0
  15. package/dist/holmes/cli/playbook-skills.d.ts +3 -56
  16. package/dist/holmes/cli/playbook-skills.js +26 -349
  17. package/dist/holmes/config/config.d.ts +21 -0
  18. package/dist/holmes/config/config.js +22 -3
  19. package/dist/holmes/governance/approval-queue.d.ts +65 -1
  20. package/dist/holmes/governance/approval-queue.js +279 -9
  21. package/dist/holmes/governance/autonomous-shell.d.ts +13 -1
  22. package/dist/holmes/governance/autonomous-shell.js +157 -4
  23. package/dist/holmes/governance/autonomy.d.ts +216 -0
  24. package/dist/holmes/governance/autonomy.js +1162 -10
  25. package/dist/holmes/governance/install-manifest.d.ts +7 -4
  26. package/dist/holmes/governance/install-manifest.js +144 -14
  27. package/dist/holmes/governance/ledger-witness.d.ts +63 -0
  28. package/dist/holmes/governance/ledger-witness.js +296 -0
  29. package/dist/holmes/governance/provenance-chain.d.ts +8 -1
  30. package/dist/holmes/governance/provenance-chain.js +23 -4
  31. package/dist/holmes/governance/push-gate-runner.d.ts +2 -0
  32. package/dist/holmes/governance/push-gate-runner.js +40 -3
  33. package/dist/holmes/governance/push-gate.d.ts +13 -2
  34. package/dist/holmes/governance/push-gate.js +106 -14
  35. package/dist/holmes/governance/recorded-pairs.d.ts +4 -0
  36. package/dist/holmes/governance/recorded-pairs.js +25 -1
  37. package/dist/holmes/governance/session-context.d.ts +7 -0
  38. package/dist/holmes/governance/session-context.js +34 -6
  39. package/dist/holmes/guardrail/advisory-line.d.ts +102 -0
  40. package/dist/holmes/guardrail/advisory-line.js +718 -0
  41. package/dist/holmes/guardrail/anchor-scope-text.d.ts +9 -0
  42. package/dist/holmes/guardrail/anchor-scope-text.js +7 -0
  43. package/dist/holmes/guardrail/command-traits.d.ts +102 -0
  44. package/dist/holmes/guardrail/command-traits.js +379 -0
  45. package/dist/holmes/guardrail/fixtures/manager-builtins.json +23 -0
  46. package/dist/holmes/guardrail/fixtures/npm-commands.json +7 -0
  47. package/dist/holmes/guardrail/impact-gate.d.ts +6 -0
  48. package/dist/holmes/guardrail/impact-gate.js +32 -5
  49. package/dist/holmes/guardrail/outward-acts.d.ts +47 -0
  50. package/dist/holmes/guardrail/outward-acts.js +1102 -0
  51. package/dist/holmes/guardrail/refusal-codes.js +8 -1
  52. package/dist/holmes/guardrail/refusal-templates.d.ts +15 -0
  53. package/dist/holmes/guardrail/refusal-templates.js +71 -0
  54. package/dist/holmes/guardrail/risk-classifier.d.ts +22 -6
  55. package/dist/holmes/guardrail/risk-classifier.js +12 -118
  56. package/dist/holmes/guardrail/shell-lexer.d.ts +69 -0
  57. package/dist/holmes/guardrail/shell-lexer.js +567 -0
  58. package/dist/holmes/guardrail/write-target.js +7 -1
  59. package/dist/holmes/hooks/pre-tool-use.d.ts +71 -0
  60. package/dist/holmes/hooks/pre-tool-use.js +1466 -14
  61. package/dist/holmes/hooks/session-start.js +27 -1
  62. package/dist/holmes/hooks/stop.d.ts +7 -0
  63. package/dist/holmes/hooks/stop.js +39 -2
  64. package/dist/holmes/mcp/elicit-approval.d.ts +0 -21
  65. package/dist/holmes/mcp/elicit-approval.js +5 -2
  66. package/dist/holmes/mcp/handlers/approval-ask.js +3 -2
  67. package/dist/holmes/mcp/handlers/entity-integration.d.ts +1 -1
  68. package/dist/holmes/mcp/handlers/entity-integration.js +9 -6
  69. package/dist/holmes/mcp/handlers/entity-renumber.js +2 -1
  70. package/dist/holmes/mcp/handlers/entity-store.js +7 -2
  71. package/dist/holmes/mcp/handlers/maintenance-analysis.d.ts +13 -0
  72. package/dist/holmes/mcp/handlers/maintenance-analysis.js +59 -2
  73. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +2 -0
  74. package/dist/holmes/mcp/handlers/operator-inspection.js +25 -4
  75. package/dist/holmes/mcp/handlers/spec-approval.d.ts +3 -1
  76. package/dist/holmes/mcp/handlers/spec-approval.js +28 -10
  77. package/dist/holmes/mcp/handlers/spec-lifecycle.js +10 -7
  78. package/dist/holmes/mcp/handlers/test-execution.d.ts +470 -3
  79. package/dist/holmes/mcp/handlers/test-execution.js +201 -21
  80. package/dist/holmes/mcp/handlers.d.ts +473 -8
  81. package/dist/holmes/mcp/handlers.js +6 -1
  82. package/dist/holmes/mcp/maintenance-analyze.d.ts +5 -0
  83. package/dist/holmes/mcp/maintenance-analyze.js +4 -2
  84. package/dist/holmes/mcp/maintenance-evidence.d.ts +9 -0
  85. package/dist/holmes/mcp/maintenance-evidence.js +4 -1
  86. package/dist/holmes/mcp/tool-schemas.js +16 -10
  87. package/dist/holmes/project/baseline.d.ts +15 -2
  88. package/dist/holmes/project/baseline.js +11 -6
  89. package/dist/holmes/project/bounded-io.d.ts +1 -0
  90. package/dist/holmes/project/bounded-io.js +4 -2
  91. package/dist/holmes/project/change-source.d.ts +4 -0
  92. package/dist/holmes/project/change-source.js +13 -5
  93. package/dist/holmes/project/playbook-reference.d.ts +50 -0
  94. package/dist/holmes/project/playbook-reference.js +259 -0
  95. package/dist/holmes/project/playbook-skill-states.d.ts +94 -0
  96. package/dist/holmes/project/playbook-skill-states.js +396 -0
  97. package/dist/holmes/project/root.d.ts +9 -1
  98. package/dist/holmes/project/root.js +26 -3
  99. package/dist/holmes/project/running-package.d.ts +15 -0
  100. package/dist/holmes/project/running-package.js +87 -0
  101. package/dist/holmes/review/evidence-mode.d.ts +21 -0
  102. package/dist/holmes/review/evidence-mode.js +33 -0
  103. package/dist/holmes/review/head-worktree.d.ts +55 -0
  104. package/dist/holmes/review/head-worktree.js +329 -0
  105. package/dist/holmes/review/mrp.js +13 -3
  106. package/dist/holmes/review/run-provenance.d.ts +45 -0
  107. package/dist/holmes/review/run-provenance.js +314 -0
  108. package/dist/holmes/review/test-evidence.d.ts +174 -0
  109. package/dist/holmes/review/test-evidence.js +330 -2
  110. package/dist/holmes/review/test-reports.d.ts +94 -0
  111. package/dist/holmes/review/test-reports.js +382 -0
  112. package/dist/holmes/review/test-runner.d.ts +178 -65
  113. package/dist/holmes/review/test-runner.js +551 -319
  114. package/dist/holmes/review/test-units.d.ts +159 -0
  115. package/dist/holmes/review/test-units.js +814 -0
  116. package/dist/holmes/spec/entity-integration-transaction.d.ts +19 -2
  117. package/dist/holmes/spec/entity-integration-transaction.js +68 -7
  118. package/package.json +5 -2
  119. package/playbooks/publish/PLAYBOOK.md +2 -1
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TOOL_SCHEMAS = exports.HOOK_ENFORCED_TOOLS = void 0;
4
4
  exports.isWireTool = isWireTool;
5
5
  exports.wireDispatch = wireDispatch;
6
- // @implements A-SPEC-743, A-SPEC-736, A-SPEC-735, A-SPEC-729, A-SPEC-719, A-SPEC-720, A-SPEC-718, A-SPEC-703, A-SPEC-629, A-SPEC-628, A-SPEC-623, A-SPEC-277, A-SPEC-624, A-SPEC-627, A-SPEC-713, A-SPEC-774.25, A-SPEC-255.1
6
+ // @implements A-SPEC-794.85, A-SPEC-128.2, A-SPEC-128.4, A-SPEC-128.5, A-SPEC-128.7, A-SPEC-128.10, A-SPEC-743,A-SPEC-736,A-SPEC-735, A-SPEC-729, A-SPEC-719, A-SPEC-720, A-SPEC-718, A-SPEC-703, A-SPEC-629, A-SPEC-628, A-SPEC-623, A-SPEC-277, A-SPEC-624, A-SPEC-627, A-SPEC-713, A-SPEC-774.25, A-SPEC-255.1, A-SPEC-466.1, A-SPEC-466.2, A-SPEC-466.3, A-SPEC-466.4, A-SPEC-466.6
7
7
  // @implements A-SPEC-495 — the maintenance_analyze description carries the semantic-evidence
8
8
  // consumer contract (sem-verify / semCos / semanticAlternates) beside the anti-prediction warning.
9
9
  // @implements A-SPEC-642
@@ -87,7 +87,7 @@ exports.TOOL_SCHEMAS = {
87
87
  inputSchema: { type: 'object', properties: { root: ROOT_ANY, operation: { type: 'string', enum: ['plan', 'apply', 'recovery-plan', 'recover', 'abandon'] }, changes: { type: 'array', items: { type: 'object', properties: { entityId: { type: 'string' }, newDisplayId: { type: 'string' } }, required: ['entityId', 'newDisplayId'], additionalProperties: false } }, plan: { type: 'object' } } },
88
88
  },
89
89
  entity_store: {
90
- description: 'Inspect or plan entity adoption without writes by default. Explicit adopt requires config-write approval for the exact returned plan and preserves sealed document bytes. Adopted stores retain entity identity through journaled document creation, edits and classification moves. recovery-plan reports interrupted targets without changing them. recover requires separate exact-plan approval to complete interrupted transactions or release locks for verified completed writes. Sealing, unsealing and retirement additionally require current spec-approve authority for the affected ID and the same transition policy as official spec tools. Live or unknown owners, external changes and noncanonical transitions refuse. Recovery audit completion across crashes remains under development.',
90
+ description: 'Inspect or plan entity adoption without writes by default. Explicit adopt requires config-write approval for the exact returned plan and preserves sealed document bytes. Adopted stores retain entity identity through journaled document creation, edits and classification moves. recovery-plan reports interrupted targets without changing them. recover requires separate exact-plan approval to complete interrupted transactions or release locks for verified completed writes. Sealing, unsealing and retirement additionally require current authority of the kind of that transition for the affected ID (spec-approve, spec-unseal, spec-retire) and the same transition policy as official spec tools. Live or unknown owners, external changes and noncanonical transitions refuse. Recovery audit completion across crashes remains under development.',
91
91
  inputSchema: { type: 'object', properties: { root: ROOT_ANY, operation: { type: 'string', enum: ['status', 'plan-adoption', 'adopt', 'recovery-plan', 'recover'] }, plan: { type: 'object', description: 'The complete unmodified plan returned by plan-adoption or recovery-plan.' } } },
92
92
  },
93
93
  workspace_preflight: {
@@ -182,7 +182,7 @@ exports.TOOL_SCHEMAS = {
182
182
  },
183
183
  },
184
184
  spec_retire: {
185
- description: "Move ONE named spec to `status: outdated` — the only path to that state. Retirement WITHDRAWS authority, so it needs no approval key by default; two cases invert that, because there the withdrawal opens a gate. A SEALED spec requires the same out-of-band HOLMES_APPROVAL as spec_approve, fail-closed: retiring the approved T-SPEC that blocks the code gate would remove the demand, making retirement an approval bypass. And a spec that an APPROVED spec depends on is refused outright, with the dependents named — that chain is holding something up right now. Records `spec-retired` in the provenance ledger, writes the reason into `retired_reason` (omitted when blank, or when `superseded_by` already answers why), and is idempotent: retiring an already-outdated spec writes nothing rather than overwriting the first retirement's reason.",
185
+ description: "Move ONE named spec to `status: outdated` — the only path to that state. Retirement WITHDRAWS authority, so it needs no approval key by default; two cases invert that, because there the withdrawal opens a gate. A SEALED spec requires an out-of-band approval of its own kind, spec-retire (a spec-approve approval does not cover it), fail-closed: retiring the approved T-SPEC that blocks the code gate would remove the demand, making retirement an approval bypass. And a spec that an APPROVED spec depends on is refused outright, with the dependents named — that chain is holding something up right now. Records `spec-retired` in the provenance ledger, writes the reason into `retired_reason` (omitted when blank, or when `superseded_by` already answers why), and is idempotent: retiring an already-outdated spec writes nothing rather than overwriting the first retirement's reason.",
186
186
  inputSchema: {
187
187
  type: 'object',
188
188
  properties: {
@@ -229,7 +229,7 @@ exports.TOOL_SCHEMAS = {
229
229
  },
230
230
  },
231
231
  spec_unseal: {
232
- description: "The inverse of spec_approve: return ONE sealed (approved) spec to an editable `status: draft`, clearing `approved_digest` and `parent_digests` in a single ACT, and record `spec-unsealed` in the provenance ledger. Un-sealing WITHDRAWS a seal, so it requires the same out-of-band HOLMES_APPROVAL as spec_approve/spec_retire's sealed path (fail-closed): un-sealing an approved T-SPEC removes the code gate's demand, which unguarded would be an approval bypass. Refuses when an APPROVED spec depends on the target — that dependent's parent_digests would silently go stale — naming the blockers. Idempotent: un-sealing a spec that is already draft (never sealed) writes nothing and returns unsealed:false. Written only at the version this act read; a concurrent edit wins and the un-seal is refused for retry. Distinct from spec_retire (which withdraws authority to status:outdated); un-seal keeps the spec alive and editable.",
232
+ description: "The inverse of spec_approve: return ONE sealed (approved) spec to an editable `status: draft`, clearing `approved_digest` and `parent_digests` in a single ACT, and record `spec-unsealed` in the provenance ledger. Un-sealing WITHDRAWS a seal, so it requires an out-of-band approval of its own kind, spec-unseal (a spec-approve approval does not cover it), fail-closed: un-sealing an approved T-SPEC removes the code gate's demand, which unguarded would be an approval bypass. Refuses when an APPROVED spec depends on the target — that dependent's parent_digests would silently go stale — naming the blockers. Idempotent: un-sealing a spec that is already draft (never sealed) writes nothing and returns unsealed:false. Written only at the version this act read; a concurrent edit wins and the un-seal is refused for retry. Distinct from spec_retire (which withdraws authority to status:outdated); un-seal keeps the spec alive and editable.",
233
233
  inputSchema: {
234
234
  type: 'object',
235
235
  properties: {
@@ -444,18 +444,24 @@ exports.TOOL_SCHEMAS = {
444
444
  },
445
445
  },
446
446
  test_run: {
447
- description: 'Compute the intelligent regression scope, RUN the selected tier (jest or pytest), and record per-A-SPEC EXECUTION evidence. Scopes against a git range when given, otherwise against a baseline — so it works on a project with no version control. A passing run records the baseline the next run scopes against.',
447
+ description: 'Compute the intelligent regression scope, RUN the selected tier (jest or pytest), and record per-A-SPEC EXECUTION evidence. Scopes against a git range when given, otherwise against a baseline — so it works on a project with no version control. A passing FULL run records the baseline the next run scopes against, and the test evidence the push gate reads; a scoped run records only `.ax/ledger/scoped-evidence.json`.',
448
448
  inputSchema: {
449
449
  type: 'object',
450
450
  properties: {
451
451
  root: ROOT_ANY,
452
452
  base: str('Base rev (e.g. HEAD~1). Optional — omit to compare against a baseline.'),
453
453
  head: str('Head rev (e.g. HEAD). Optional — omit to compare against a baseline.'),
454
- since: str('Baseline label to compare against when no git range is given (default `last-green`, recorded by a passing test_run). Works with or without version control.'),
455
- mark: str('Baseline label to record when the run passes (default `last-green`). Nothing is recorded for a red or skipped run.'),
454
+ since: str('Baseline label to compare against when no git range is given (default `last-green`, recorded by a passing full test_run). Works with or without version control.'),
455
+ mark: str('Baseline label to record when a full run passes (default `last-green`). Nothing is recorded for a red, skipped or scoped run.'),
456
+ // @implements A-SPEC-128.4
457
+ full: bool('Run the whole suite, whatever changed — the run the push gate accepts as evidence. It runs every execution unit (the root, and each directory with its own build or runner configuration) in its own directory, over the files git sees minus ax.config.json testRun.excludeDirs (a slash makes an entry a root-relative path; without one it is a directory name). Afterwards every detected test must have run (notExecuted) and every build root with code must have an executed test (untestedCode). A refusal is fix-tests, collect, rerun or environment. The budget defaults to 120 minutes. Refused together with base/head or mutate.'),
456
458
  mutate: str('T-SPEC id (e.g. T-SPEC-129.1). When set, runs that spec’s declared `kills` mutations against the A-SPEC’s source and reports which SURVIVED — a discriminating-power gap. Selective, opt-in; the ordinary run is skipped.'),
459
+ workers: num('jest worker count, passed as `--maxWorkers`: an integer from 1 to 64; any other number is refused before the run, and null reads as omitted. Optional — omit to keep the project’s own setting. The answer’s `workers` is the count jest applied (null when none). Runners other than jest take no count; when a count was given and such a runner ran, the answer lists them in `workersIgnoredBy`; when nothing took it, `workersIgnored` says why (`mutate`, `no jest group`, `nothing ran`).'),
460
+ timeoutMinutes: num('The time budget in minutes for each runner child of the run (jest, the other adapters, a mutation’s jest run): an integer from 1 to 180; when omitted or null, 30, or 120 for a full: true run; any other number is refused before the run. A run with a child past it ends "not judged": it records no evidence, and a full run records a full attempt that the push gate refuses. The answer and the evidence carry the applied value.'),
457
461
  },
458
462
  required: ['root'],
463
+ // @implements A-SPEC-466.2 — an undeclared key (`maxWorkers`) is refused, never run with that key ignored
464
+ additionalProperties: false,
459
465
  },
460
466
  },
461
467
  issue_localize: {
@@ -571,7 +577,7 @@ exports.TOOL_SCHEMAS = {
571
577
  root: ROOT_ANY,
572
578
  base: str('Base git ref of the diff range. Optional — omit to compare against a baseline.'),
573
579
  head: str('Head git ref of the diff range. Optional — omit to compare against a baseline.'),
574
- since: str('Baseline label to compare against when no git range is given (default `last-green`, recorded by a passing test_run). Works with or without version control.'),
580
+ since: str('Baseline label to compare against when no git range is given (default `last-green`, recorded by a passing full test_run). Works with or without version control.'),
575
581
  },
576
582
  required: ['root'],
577
583
  },
@@ -592,7 +598,7 @@ exports.TOOL_SCHEMAS = {
592
598
  description: 'Compute the graph-scoped review scope for base..head (impacted specs/tests + unscanned changed files).',
593
599
  inputSchema: {
594
600
  type: 'object',
595
- properties: { root: ROOT_ANY, base: str('Base git ref. Optional — omit to compare against a baseline instead.'), head: str('Head git ref. Optional — omit to compare against a baseline instead.'), since: str('Baseline label to compare against when no git range is given (default `last-green`, recorded by a passing test_run). Works with or without version control.'), },
601
+ properties: { root: ROOT_ANY, base: str('Base git ref. Optional — omit to compare against a baseline instead.'), head: str('Head git ref. Optional — omit to compare against a baseline instead.'), since: str('Baseline label to compare against when no git range is given (default `last-green`, recorded by a passing full test_run). Works with or without version control.'), },
596
602
  required: ['root'],
597
603
  },
598
604
  },
@@ -604,7 +610,7 @@ exports.TOOL_SCHEMAS = {
604
610
  root: ROOT_ANY,
605
611
  base: str('Base git ref. Optional — omit to compare against a baseline instead.'),
606
612
  head: str('Head git ref. Optional — omit to compare against a baseline instead.'),
607
- since: str('Baseline label to compare against when no git range is given (default `last-green`, recorded by a passing test_run). Works with or without version control.'),
613
+ since: str('Baseline label to compare against when no git range is given (default `last-green`, recorded by a passing full test_run). Works with or without version control.'),
608
614
  budget: num('Optional token budget for the review package (default 4000).'),
609
615
  },
610
616
  required: ['root'],
@@ -1,3 +1,4 @@
1
+ import { type FullMode } from '../review/evidence-mode';
1
2
  /**
2
3
  * A NAMED reference point: "the tree as it was when this label was taken".
3
4
  *
@@ -20,6 +21,16 @@ export interface Baseline {
20
21
  takenAt: string;
21
22
  /** Project-relative POSIX path -> content hash. */
22
23
  files: Record<string, string>;
24
+ /** @implements A-SPEC-128.2 — the run that verified this tree; absent before 128.2. Informational: trust reads the anchor. */
25
+ tier?: string;
26
+ mode?: string;
27
+ ranFileCount?: number;
28
+ }
29
+ /** @implements A-SPEC-128.2 — what a passing run says about itself when it records a baseline. */
30
+ export interface BaselineMeta {
31
+ tier: string;
32
+ mode: FullMode;
33
+ ranFileCount: number;
23
34
  }
24
35
  /**
25
36
  * @implements A-SPEC-134
@@ -30,7 +41,7 @@ export interface Baseline {
30
41
  */
31
42
  export declare function baselineDigest(files: Record<string, string>): string;
32
43
  /** Write (or replace) a labelled baseline. One label holds exactly one reference point. */
33
- export declare function writeBaseline(root: string, label: string, files: Record<string, string>): Baseline;
44
+ export declare function writeBaseline(root: string, label: string, files: Record<string, string>, meta?: BaselineMeta): Baseline;
34
45
  /**
35
46
  * @implements A-SPEC-134
36
47
  * Is this baseline still the one that was recorded? Recompute its digest from the on-disk files and
@@ -38,7 +49,9 @@ export declare function writeBaseline(root: string, label: string, files: Record
38
49
  * digest and no entry matches → false. A missing baseline or missing/unreadable chain → false:
39
50
  * cannot-verify is not permission to narrow (the caller degrades to full scope).
40
51
  */
41
- export declare function isBaselineTrusted(root: string, label: string, ledgerFile: string): boolean;
52
+ export declare function isBaselineTrusted(root: string, label: string, ledgerFile: string, opts?: {
53
+ requireMode?: FullMode;
54
+ }): boolean;
42
55
  /**
43
56
  * Read a baseline, or null when there is none.
44
57
  *
@@ -40,11 +40,12 @@ exports.isBaselineTrusted = isBaselineTrusted;
40
40
  exports.readBaseline = readBaseline;
41
41
  exports.shouldRecordBaseline = shouldRecordBaseline;
42
42
  exports.listBaselines = listBaselines;
43
- // @implements A-SPEC-128, A-SPEC-222.10
43
+ // @implements A-SPEC-128, A-SPEC-222.10, A-SPEC-128.2, A-SPEC-128.4, A-SPEC-128.5
44
44
  const fs = __importStar(require("node:fs"));
45
45
  const path = __importStar(require("node:path"));
46
46
  const node_crypto_1 = require("node:crypto");
47
47
  const ledger_store_1 = require("../governance/ledger-store");
48
+ const evidence_mode_1 = require("../review/evidence-mode");
48
49
  /**
49
50
  * A NAMED reference point: "the tree as it was when this label was taken".
50
51
  *
@@ -87,14 +88,14 @@ function baselineDigest(files) {
87
88
  }
88
89
  const ledgerFor = (root) => path.join(root, '.ax', 'ledger', 'provenance.jsonl');
89
90
  /** Write (or replace) a labelled baseline. One label holds exactly one reference point. */
90
- function writeBaseline(root, label, files) {
91
+ function writeBaseline(root, label, files, meta) {
91
92
  assertLabel(label);
92
93
  // Keys sorted so the stored file is byte-stable for the same input; a diffable baseline is easier
93
94
  // to inspect, and instability here would show up as noise in any tooling that reads it.
94
95
  const sorted = {};
95
96
  for (const k of Object.keys(files).sort())
96
97
  sorted[k] = files[k];
97
- const baseline = { label, takenAt: new Date().toISOString(), files: sorted };
98
+ const baseline = { label, takenAt: new Date().toISOString(), files: sorted, ...(meta ?? {}) };
98
99
  fs.mkdirSync(path.dirname(fileFor(root, label)), { recursive: true });
99
100
  fs.writeFileSync(fileFor(root, label), `${JSON.stringify(baseline, null, 2)}\n`);
100
101
  // @implements A-SPEC-134
@@ -106,7 +107,9 @@ function writeBaseline(root, label, files) {
106
107
  new ledger_store_1.FileLedgerStore(path.dirname(ledgerFor(root))).append({
107
108
  ts: baseline.takenAt, actor: 'holmes-kit', kind: 'baseline-recorded',
108
109
  summary: `baseline ${label} recorded (${Object.keys(sorted).length} files)`,
109
- inputs: [label, baselineDigest(sorted)], rationale: '', authorization: '',
110
+ // @implements A-SPEC-128.2 — the run's mode rides on the chain, where a hand-edit of the file cannot reach it
111
+ // @implements A-SPEC-128.4 — the token comes from the one module that spells it
112
+ inputs: [label, baselineDigest(sorted), ...(meta ? [(0, evidence_mode_1.modeAnchor)(meta.mode)] : [])], rationale: '', authorization: '',
110
113
  });
111
114
  }
112
115
  catch { /* unanchored baseline degrades to untrusted on read, never throws the write */ }
@@ -119,7 +122,7 @@ function writeBaseline(root, label, files) {
119
122
  * digest and no entry matches → false. A missing baseline or missing/unreadable chain → false:
120
123
  * cannot-verify is not permission to narrow (the caller degrades to full scope).
121
124
  */
122
- function isBaselineTrusted(root, label, ledgerFile) {
125
+ function isBaselineTrusted(root, label, ledgerFile, opts = {}) {
123
126
  const baseline = readBaseline(root, label);
124
127
  if (!baseline)
125
128
  return false;
@@ -154,7 +157,9 @@ function isBaselineTrusted(root, label, ledgerFile) {
154
157
  }
155
158
  for (const evt of events) {
156
159
  if (evt.kind === 'baseline-recorded' && Array.isArray(evt.inputs)
157
- && evt.inputs.includes(label) && evt.inputs.includes(digest))
160
+ && evt.inputs.includes(label) && evt.inputs.includes(digest)
161
+ // @implements A-SPEC-128.2 — a reader that narrows trusts only a tree a full run verified
162
+ && (!opts.requireMode || evt.inputs.includes((0, evidence_mode_1.modeAnchor)(opts.requireMode))))
158
163
  return true;
159
164
  }
160
165
  return false;
@@ -48,6 +48,7 @@ export declare function gitOnce(root: string, args: string[], kind: GitKind, opt
48
48
  env?: NodeJS.ProcessEnv;
49
49
  pinned?: JudgmentPins;
50
50
  ignoreBlock?: boolean;
51
+ record?: boolean;
51
52
  }): SpawnSyncReturns<string>;
52
53
  /**
53
54
  * @implements A-SPEC-222.13 — gitOnce with stdout as bytes: a batch of blobs is cut at byte offsets, so its output must
@@ -50,7 +50,7 @@ exports.judgmentPins = judgmentPins;
50
50
  exports.inertDriverArgs = inertDriverArgs;
51
51
  exports.inertGitConfig = inertGitConfig;
52
52
  exports.gitUnanswered = gitUnanswered;
53
- // @implements A-SPEC-734, A-SPEC-222.13, A-SPEC-102.30, A-SPEC-102.31
53
+ // @implements A-SPEC-734, A-SPEC-222.13, A-SPEC-102.30, A-SPEC-102.31, A-SPEC-333.9
54
54
  /**
55
55
  * Bounded I/O shared by every caller on a hook, MCP or scan path (A-SPEC-734 round 12).
56
56
  *
@@ -119,7 +119,9 @@ function gitOnce(root, args, kind, opts = {}) {
119
119
  const env = { ...gitEnv(opts.env ?? process.env), ...pinnedOnly(opts.pinned) };
120
120
  const r = (0, node_child_process_1.spawnSync)('git', args, { cwd: opts.cwd ?? root, input: opts.input, encoding: 'utf8', timeout: opts.timeout ?? exports.GIT_TIMEOUT_MS, killSignal: 'SIGKILL',
121
121
  maxBuffer: exports.GIT_MAX_BUFFER, windowsHide: true, env, stdio: [opts.input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] });
122
- noteGitFailure(root, r, kind);
122
+ // @implements A-SPEC-333.9 — `record: false`: a timeout set by the caller's own deadline is not the root's slowness
123
+ if (opts.record !== false)
124
+ noteGitFailure(root, r, kind);
123
125
  return r;
124
126
  }
125
127
  /**
@@ -1,3 +1,4 @@
1
+ import type { FullMode } from '../review/evidence-mode';
1
2
  /**
2
3
  * "What changed since a reference point" — the one question that genuinely needed version control,
3
4
  * behind a port with two adapters so it does not need it any more.
@@ -62,9 +63,12 @@ export declare class SnapshotChangeSource implements ChangeSource {
62
63
  constructor(root: string, label: string, opts?: {
63
64
  isIgnored?: (relPath: string) => boolean;
64
65
  verify?: string;
66
+ requireMode?: FullMode;
65
67
  });
66
68
  /** Trusted iff a baseline exists AND (no verify requested OR its digest is anchored on the chain). */
67
69
  private trustedBaseline;
70
+ /** @implements A-SPEC-128.2 — anchored, but not as a full run's tree. */
71
+ private notFromFullRun;
68
72
  changes(): ChangeSet | null;
69
73
  describe(): ChangeSourceInfo;
70
74
  }
@@ -36,7 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.EMPTY_CHANGE_SET = exports.GitChangeSource = exports.SnapshotChangeSource = exports.hashOf = exports.isDerivedState = void 0;
37
37
  exports.hashTree = hashTree;
38
38
  exports.diffHashes = diffHashes;
39
- // @implements A-SPEC-128, A-SPEC-734, A-SPEC-794.58
39
+ // @implements A-SPEC-128, A-SPEC-734, A-SPEC-794.58, A-SPEC-128.2, A-SPEC-128.5
40
40
  const fs = __importStar(require("node:fs"));
41
41
  const path = __importStar(require("node:path"));
42
42
  const node_crypto_1 = require("node:crypto");
@@ -134,6 +134,8 @@ class SnapshotChangeSource {
134
134
  // @implements A-SPEC-134 — `verify` is the provenance ledger path. When set, a baseline whose
135
135
  // digest is not anchored on the chain (tampered, or written unanchored) is treated as ABSENT:
136
136
  // a forged narrowing must never be honored. Omitted (pure unit tests) → today's behavior.
137
+ // @implements A-SPEC-128.2 — `requireMode: 'full'` (with `verify`): only an anchor that says a full run verified the
138
+ // tree is trusted; a scoped green or a legacy anchor degrades to full scope.
137
139
  opts = {}) {
138
140
  this.root = root;
139
141
  this.label = label;
@@ -144,10 +146,14 @@ class SnapshotChangeSource {
144
146
  const baseline = (0, baseline_1.readBaseline)(this.root, this.label);
145
147
  if (!baseline)
146
148
  return null;
147
- if (this.opts.verify && !(0, baseline_1.isBaselineTrusted)(this.root, this.label, this.opts.verify))
149
+ if (this.opts.verify && !(0, baseline_1.isBaselineTrusted)(this.root, this.label, this.opts.verify, { requireMode: this.opts.requireMode }))
148
150
  return null;
149
151
  return baseline;
150
152
  }
153
+ /** @implements A-SPEC-128.2 — anchored, but not as a full run's tree. */
154
+ notFromFullRun() {
155
+ return !!this.opts.verify && !!this.opts.requireMode && (0, baseline_1.isBaselineTrusted)(this.root, this.label, this.opts.verify);
156
+ }
151
157
  changes() {
152
158
  const baseline = this.trustedBaseline();
153
159
  if (!baseline)
@@ -164,9 +170,11 @@ class SnapshotChangeSource {
164
170
  detectsRenames: false,
165
171
  available: trusted !== null,
166
172
  ...(trusted ? {} : {
167
- reason: tampered
168
- ? `baseline "${this.label}" failed its integrity check (not anchored on the provenance chain) — treating as absent, full scope`
169
- : `no baseline named "${this.label}" — run a passing test_run, or take one explicitly`,
173
+ reason: tampered && this.notFromFullRun()
174
+ ? `baseline "${this.label}" is not from a full run (its anchor does not say mode:full) — treating as absent, full scope`
175
+ : tampered
176
+ ? `baseline "${this.label}" failed its integrity check (not anchored on the provenance chain) — treating as absent, full scope`
177
+ : `no baseline named "${this.label}" — run a passing full test_run, or take one explicitly`,
170
178
  }),
171
179
  };
172
180
  }
@@ -0,0 +1,50 @@
1
+ import { type PlaybookSkillState } from './playbook-skill-states';
2
+ export type SkillReference = {
3
+ kind: 'package';
4
+ } | {
5
+ kind: 'ledger';
6
+ recordedAt: string;
7
+ commit: string;
8
+ replica: string;
9
+ } | {
10
+ kind: 'closed';
11
+ reason: string;
12
+ };
13
+ export interface JudgedSkills {
14
+ states: {
15
+ name: string;
16
+ state: PlaybookSkillState;
17
+ }[];
18
+ reference: SkillReference;
19
+ /** With a ledger reference: the playbooks whose working-tree body is not the recorded one (changed, added or gone since). */
20
+ moved: string[];
21
+ }
22
+ /**
23
+ * The `playbook:<name>:<sha256>` inputs a `principle7-baseline` row carries: one per playbook the package ships, the
24
+ * sha256 of its PLAYBOOK.md bytes. The digest is of the playbook's body, not of the installed skill: the row is written
25
+ * by the hook that runs BEFORE the build, and must not depend on that build's marker format. A playbook that cannot be
26
+ * read, or whose name could not be told apart in the input, is not recorded — so its skill is never `current`.
27
+ */
28
+ export declare function playbookDigestInputs(packageRoot: string): string[];
29
+ /**
30
+ * A-SPEC-794.113 — which digests a new baseline row may carry. `now` are the working tree's inputs, `before` the
31
+ * inputs of the latest digest-bearing row of this writer's chain, `anchored` the playbooks whose content a person's
32
+ * window of this chain saw and names now, `removed` those whose removal such a window names. A digest unchanged since
33
+ * `before`, or anchored, is written; any other keeps the digest `before` carried — the reference does not move for it —
34
+ * or, when `before` had none for it, is left out. A playbook the working tree no longer holds is carried on with the
35
+ * digest `before` had, unless it is in `removed`.
36
+ */
37
+ export declare function anchoredPlaybookInputs(now: string[], before: string[], anchored: ReadonlySet<string>, removed?: ReadonlySet<string>): string[];
38
+ /**
39
+ * The one choice of "the latest row" for the reader and the record (review A, L3: the two chose by different orders): in
40
+ * one writer's chain the sequence is the order rows were written in.
41
+ */
42
+ export declare function latestBySequence<T extends {
43
+ seq?: unknown;
44
+ }>(rows: T[]): T | null;
45
+ /**
46
+ * Every recovery skill's state in `target`, against the reference `packageRoot` has. With a ledger reference a playbook's
47
+ * working-tree body is the reference body only when its sha256 is the recorded one; otherwise its skill cannot be
48
+ * `current` and the playbook is listed in `moved`. Closed: no skill is `current`.
49
+ */
50
+ export declare function judgedSkillStates(packageRoot: string, target: string): JudgedSkills;
@@ -0,0 +1,259 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.playbookDigestInputs = playbookDigestInputs;
37
+ exports.anchoredPlaybookInputs = anchoredPlaybookInputs;
38
+ exports.latestBySequence = latestBySequence;
39
+ exports.judgedSkillStates = judgedSkillStates;
40
+ // @implements A-SPEC-794.110, A-SPEC-794.113
41
+ /**
42
+ * What an installed recovery skill is judged against — decided here, once, for doctor, init and the product-installed
43
+ * judgement of the autonomous shell approval. None of the three chooses a reference, so they agree when they run from
44
+ * the same install (doctor run from another install than the one the sessions load judges with that install's).
45
+ *
46
+ * The judgement was repaired three times in a row because the judged workspace could choose the reference: the working
47
+ * tree (794.100), HEAD (794.106), then a baseline commit whose binding read the target's index and core.worktree and whose
48
+ * commit could be rolled back through a fallback (794.107; re-check of d77e59d9, A 1/1/2/2). The contract now:
49
+ *
50
+ * - Binding: the running package's real path (project/running-package.ts). Deployed — a `node_modules` segment — is
51
+ * judged against the package's own playbook files. The hook refuses a write from the session to that package's
52
+ * playbooks and dist (A-SPEC-794.113, pre-tool-use.ts `referenceInputWrite`; measured 2026-11-12 before it: the
53
+ * playbooks were writable by the file tools and the shell, the dist by the shell and, outside the project, by the
54
+ * file tools too). No git command and no file of the target decides the binding.
55
+ * - Any other package is a checkout whose playbooks the workspace may be editing. Its reference is the playbook digests
56
+ * the gate recorded at its last allowed build, in the latest `principle7-baseline` row of THIS WRITER'S OWN ledger chain
57
+ * (the chain file in the working tree, read through the trusted read). Another replica's chain is not read: the trusted
58
+ * read takes it from HEAD's blob, which a ref move changes. Git decides nothing about the reference: neither this
59
+ * module nor the record reads a git object. The record (governance/autonomy.ts, recordBaseline) writes a digest only
60
+ * when it is the one the latest digest-bearing row of this chain carried, or when a person's window of this chain
61
+ * names the playbook in the build's own judgement and a window row after the baseline holds those bytes. So a
62
+ * chain's first digests are made by a window that names the playbooks, and the reference moves forward only
63
+ * (A-SPEC-794.113).
64
+ * - Closed, never a fallback: no such row, a latest row without digests, an own chain that does not verify, or a ledger
65
+ * that cannot be read. No skill is `current` then, and the reason is one line that names the way out.
66
+ *
67
+ * The ledger is as strong as a person's seal is: both are rows of the same protected chain (the hook refuses a shell
68
+ * append, copy, move, interpreter write and git checkout over it — measured 2026-11-12, A-SPEC-794.111).
69
+ */
70
+ const crypto = __importStar(require("node:crypto"));
71
+ const fs = __importStar(require("node:fs"));
72
+ const path = __importStar(require("node:path"));
73
+ const playbook_skill_states_1 = require("./playbook-skill-states");
74
+ const sha256 = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
75
+ const PLAYBOOK_INPUT = /^playbook:([^:\s]+):([0-9a-f]{64})$/;
76
+ const playbookFile = (packageRoot, name) => path.join(packageRoot, 'playbooks', name, 'PLAYBOOK.md');
77
+ const digestOfPlaybook = (packageRoot, name) => {
78
+ try {
79
+ return sha256(fs.readFileSync(playbookFile(packageRoot, name)));
80
+ }
81
+ catch {
82
+ return null;
83
+ } // [no-substitution: unreadable → no digest, so its skill is never `current`]
84
+ };
85
+ /**
86
+ * The `playbook:<name>:<sha256>` inputs a `principle7-baseline` row carries: one per playbook the package ships, the
87
+ * sha256 of its PLAYBOOK.md bytes. The digest is of the playbook's body, not of the installed skill: the row is written
88
+ * by the hook that runs BEFORE the build, and must not depend on that build's marker format. A playbook that cannot be
89
+ * read, or whose name could not be told apart in the input, is not recorded — so its skill is never `current`.
90
+ */
91
+ function playbookDigestInputs(packageRoot) {
92
+ const out = [];
93
+ for (const name of (0, playbook_skill_states_1.playbookNames)(packageRoot)) {
94
+ const digest = digestOfPlaybook(packageRoot, name);
95
+ const input = `playbook:${name}:${digest}`;
96
+ if (digest !== null && PLAYBOOK_INPUT.test(input))
97
+ out.push(input);
98
+ }
99
+ return out.sort();
100
+ }
101
+ /**
102
+ * A-SPEC-794.113 — which digests a new baseline row may carry. `now` are the working tree's inputs, `before` the
103
+ * inputs of the latest digest-bearing row of this writer's chain, `anchored` the playbooks whose content a person's
104
+ * window of this chain saw and names now, `removed` those whose removal such a window names. A digest unchanged since
105
+ * `before`, or anchored, is written; any other keeps the digest `before` carried — the reference does not move for it —
106
+ * or, when `before` had none for it, is left out. A playbook the working tree no longer holds is carried on with the
107
+ * digest `before` had, unless it is in `removed`.
108
+ */
109
+ function anchoredPlaybookInputs(now, before, anchored, removed = new Set()) {
110
+ const parse = (i) => PLAYBOOK_INPUT.exec(i);
111
+ const earlier = new Map();
112
+ for (const i of before) {
113
+ const m = parse(i);
114
+ if (m)
115
+ earlier.set(m[1], m[2]);
116
+ }
117
+ const out = [];
118
+ const present = new Set();
119
+ for (const i of now) {
120
+ const m = parse(i);
121
+ if (!m)
122
+ continue;
123
+ const [, name, digest] = m;
124
+ present.add(name);
125
+ if (earlier.get(name) === digest || anchored.has(name))
126
+ out.push(i);
127
+ else if (earlier.has(name))
128
+ out.push(`playbook:${name}:${earlier.get(name)}`);
129
+ }
130
+ // a playbook the earlier row carried and the tree no longer holds (or that cannot be read now) is carried on: the
131
+ // reference does not forget it unless a person's window names its removal
132
+ for (const [name, digest] of earlier)
133
+ if (!present.has(name) && !removed.has(name))
134
+ out.push(`playbook:${name}:${digest}`);
135
+ return out.sort();
136
+ }
137
+ /**
138
+ * The one choice of "the latest row" for the reader and the record (review A, L3: the two chose by different orders): in
139
+ * one writer's chain the sequence is the order rows were written in.
140
+ */
141
+ function latestBySequence(rows) {
142
+ return rows.length === 0 ? null : rows.reduce((a, b) => (Number(b.seq) > Number(a.seq) ? b : a));
143
+ }
144
+ /** The latest build the gate recorded in this writer's own chain, or why there is none to trust (one line). */
145
+ function recordedBuild(packageRoot) {
146
+ // review B (low 2) — a package reached through a link (npm link, a file: dependency, a workspace) is the checkout the
147
+ // link points at: the text shows that path and says so, not the linked path that looks like an install
148
+ const real = (() => { try {
149
+ return fs.realpathSync.native(packageRoot);
150
+ }
151
+ catch {
152
+ return path.resolve(packageRoot);
153
+ } })(); // [no-substitution: nothing exists at the path → its spelling, where no ledger is found and the reference is closed]
154
+ const where = real === path.resolve(packageRoot)
155
+ // (review B, confirming, low 1 — the gate passes a real path, so a link is not seen here: the text says it once)
156
+ ? `this holmes-kit at ${real} is not an npm-installed package (one reached through npm link, a file: dependency or a workspace link is a checkout too)`
157
+ : `this holmes-kit at ${packageRoot} is a link to the checkout ${real}, not an npm-installed package`;
158
+ // review B (medium 2) — what records a build is the hook of a governed agent session, not the build script itself
159
+ // (worded without "in a terminal": the census of typed approval commands reads that phrase after "record" as one)
160
+ const governed = 'a build run in a governed agent session (a build run outside such a session records nothing)';
161
+ // review B (confirming, M1 and L4) — the causes as they are (a run and a changed replica id write a chain of their
162
+ // own, as a new clone or worktree does), and which seal opens it: one naming the playbooks, in a session here
163
+ const makes = `a person seals, in a session in this checkout, an A-SPEC whose Files to Touch names the playbooks (each \`playbooks/<name>/PLAYBOOK.md\`, or \`playbooks/**\`), and ${governed} inside that window records them`;
164
+ const noBaseline = `${where}, and this checkout has no baseline of its own (a new clone or worktree, a run or another replica id — each writes a chain of its own — or a package unpacked by hand) — ${makes}; `
165
+ + 'or install holmes-kit with npm, wire the project to that install (holmes-kit init) and reconnect the MCP server';
166
+ const dir = path.join(real, '.ax', 'ledger');
167
+ if (!fs.existsSync(dir))
168
+ return { closed: noBaseline };
169
+ let rows;
170
+ let own;
171
+ try {
172
+ const { TrustedLedgerStore } = require('../governance/recorded-pairs');
173
+ const store = new TrustedLedgerStore(dir);
174
+ own = store.replicaId();
175
+ // A-SPEC-794.114 — the chain must be the one this repository wrote (a tree move takes it back with the tree, and a
176
+ // chain extended outside comes in by git): otherwise no recorded build is trusted
177
+ // (the witness module itself, not autonomy.ts's helper: autonomy.ts imports this module — no cycle, A-SPEC-574.3)
178
+ const { chainWitnessVerdict } = require('../governance/ledger-witness');
179
+ const { writerChainFile } = require('../governance/ledger-store');
180
+ const witnessed = chainWitnessVerdict(writerChainFile(dir));
181
+ if (!witnessed.ok) {
182
+ return { closed: `${where}, and its provenance ledger is not the one this repository wrote (${witnessed.kind}: ${witnessed.detail}) — return the tree if it moved, or a person vouches for the chain as it is (\`holmes-kit ledger witness\`, decided in the session's approval form); nothing here stands in for it` };
183
+ }
184
+ if (store.ownChainBroken()) {
185
+ // review B (low 4) — the command, where one fits
186
+ return { closed: `${where}, and this writer's ledger chain under ${dir} does not verify, so no recorded build is trusted — a person repairs the ledger (\`holmes-kit ledger rechain\` re-chains a chain a merge forked; a row added or changed by hand is the person's to judge); nothing here stands in for it` };
187
+ }
188
+ rows = store.loadAll().filter((e) => e.replicaId === own && e.kind === 'principle7-baseline' && e.actor === 'holmes-kit'
189
+ && typeof e.ts === 'string' && Array.isArray(e.inputs) && e.inputs.some((i) => /^commit:[0-9a-f]{40,64}$/.test(String(i))));
190
+ }
191
+ catch { // [no-substitution: unreadable ledger → closed]
192
+ return { closed: `${where}, and its ledger under ${dir} cannot be read, so no recorded build is trusted — a person repairs the ledger; nothing here stands in for it` };
193
+ }
194
+ const latest = latestBySequence(rows);
195
+ // (which chain was read: a run, a worktree and a changed replica id each have their own)
196
+ if (latest === null)
197
+ return { closed: `${noBaseline} (the chain read: ${own})` };
198
+ const inputs = latest.inputs.map(String);
199
+ const commit = inputs.find((i) => /^commit:[0-9a-f]{40,64}$/.test(i)).slice('commit:'.length);
200
+ const digests = new Map();
201
+ for (const i of inputs) {
202
+ const m = PLAYBOOK_INPUT.exec(i);
203
+ if (m)
204
+ digests.set(m[1], m[2]);
205
+ }
206
+ if (digests.size === 0) {
207
+ // no fallback to an older row that has them: the latest allowed build is the product, and this one says nothing.
208
+ // The first digests of a chain are made by a window that names the playbooks (no bootstrap from the commit).
209
+ return { closed: `${where}, and the latest build its gate recorded (${String(latest.ts)}, ${commit.slice(0, 12)}, chain ${own}) carries no playbook digests yet (a gate older than 0.41.0 recorded it, or no window has named the playbooks here) — ${makes}` };
210
+ }
211
+ return { ts: String(latest.ts), commit, digests, replica: own };
212
+ }
213
+ /** Each playbook's bytes, read once (null when it cannot be read). */
214
+ function playbookBytes(packageRoot, names) {
215
+ return new Map(names.map((name) => { try {
216
+ return [name, fs.readFileSync(playbookFile(packageRoot, name))];
217
+ }
218
+ catch {
219
+ return [name, null];
220
+ } })); // [no-substitution: unreadable → null, and a skill with no body to compare is not `current`]
221
+ }
222
+ /**
223
+ * Every recovery skill's state in `target`, against the reference `packageRoot` has. With a ledger reference a playbook's
224
+ * working-tree body is the reference body only when its sha256 is the recorded one; otherwise its skill cannot be
225
+ * `current` and the playbook is listed in `moved`. Closed: no skill is `current`.
226
+ */
227
+ function judgedSkillStates(packageRoot, target) {
228
+ const running = require('./running-package');
229
+ if (running.isDeployedPackage(packageRoot))
230
+ return { states: (0, playbook_skill_states_1.playbookSkillStates)(packageRoot, target), reference: { kind: 'package' }, moved: [] };
231
+ // review A (L1) — each playbook is read once: the body the verdict compares the skill with and the digest compared
232
+ // with the record are the same bytes (two reads let a write between them split the two)
233
+ const names = (0, playbook_skill_states_1.playbookNames)(packageRoot);
234
+ const bytes = playbookBytes(packageRoot, names);
235
+ const working = (0, playbook_skill_states_1.playbookSkillStates)(packageRoot, target, { names: () => names, body: (name) => bytes.get(name)?.toString('utf8') ?? null });
236
+ const notCurrent = (s) => (s.state === 'current' ? { name: s.name, state: 'drifted' } : s);
237
+ const recorded = recordedBuild(packageRoot);
238
+ if ('closed' in recorded)
239
+ return { states: working.map(notCurrent), reference: { kind: 'closed', reason: recorded.closed }, moved: [] };
240
+ const shipped = new Set(names);
241
+ const moved = [];
242
+ // a playbook the recorded build shipped and the working tree no longer holds: the package's own damage, not an orphan
243
+ const gone = [...recorded.digests.keys()].filter((name) => !shipped.has(name));
244
+ const goneSkills = new Set(gone.map(playbook_skill_states_1.invocableSkillName));
245
+ const states = working.filter((s) => !(s.state === 'orphaned' && goneSkills.has(s.name))).map((s) => {
246
+ if (!shipped.has(s.name) || s.state === 'orphaned')
247
+ return s;
248
+ const b = bytes.get(s.name) ?? null;
249
+ if (b !== null && recorded.digests.get(s.name) === sha256(b))
250
+ return s;
251
+ moved.push(s.name);
252
+ return notCurrent(s);
253
+ });
254
+ for (const name of gone) {
255
+ moved.push(name);
256
+ states.push({ name, state: 'source-unreadable' });
257
+ }
258
+ return { states, reference: { kind: 'ledger', recordedAt: recorded.ts, commit: recorded.commit, replica: recorded.replica }, moved: moved.sort() };
259
+ }