@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
@@ -19,6 +19,21 @@ import { ExecutionContext } from '../project/execution-context';
19
19
  * provenance chain already use, so a reader learns no new model.
20
20
  */
21
21
  export declare const QUEUE_RELPATH: string;
22
+ /**
23
+ * @implements A-SPEC-794.85 — the one table from a spec lifecycle transition to the approval kind that authorizes it.
24
+ * Every path that seals, un-seals or retires a spec (the MCP acts, entity recovery, the integration audit, renumber,
25
+ * approval_status) names the kind through it; the review of 794.81 found five files holding their own literal.
26
+ */
27
+ export declare const SPEC_TRANSITION_KIND: {
28
+ readonly seal: "spec-approve";
29
+ readonly unseal: "spec-unseal";
30
+ readonly retire: "spec-retire";
31
+ };
32
+ export type SpecTransition = keyof typeof SPEC_TRANSITION_KIND;
33
+ /** @implements A-SPEC-794.85 — the transition a spec's target status makes: approved seals, draft un-seals, outdated retires. */
34
+ export declare function specTransitionOfStatus(status: string): SpecTransition | null;
35
+ /** @implements A-SPEC-794.90 — true for the three kinds of the table. */
36
+ export declare function isSpecTransitionKind(kind: string | undefined): boolean;
22
37
  export declare const DECISION_KINDS: ReadonlySet<string>;
23
38
  /**
24
39
  * The line a refusal ends with to name its pending request and the operator command.
@@ -96,8 +111,15 @@ export interface PendingRequest {
96
111
  requesterRun?: string;
97
112
  /** @implements A-SPEC-779.7 — the MCP server instance that filed it (`<pid>:<startedAt>`), which may withdraw it. */
98
113
  requesterServer?: string;
114
+ /**
115
+ * @implements A-SPEC-794.90 — for a refusal-log request, the occurrence bound a decision on it records: all of the id's
116
+ * occurrences when it is decided (a count of the open ones reopened decided occurrences on a second decision).
117
+ */
118
+ through?: number;
99
119
  }
100
120
  export declare function setRequesterServer(instance: string | undefined): void;
121
+ /** @implements A-SPEC-794.81 — the MCP server instance this process runs as, or undefined outside the server. */
122
+ export declare function requesterServerInstance(): string | undefined;
101
123
  export interface QueueState {
102
124
  pending: PendingRequest[];
103
125
  /**
@@ -110,6 +132,14 @@ export interface QueueState {
110
132
  expired: PendingRequest[];
111
133
  /** Broken lines are counted, never swallowed: an empty-looking queue must be distinguishable from a corrupted one. */
112
134
  malformedLines: number;
135
+ /**
136
+ * @implements A-SPEC-794.84 — requests closed unrun after 24 hours without a requester (`closed-expired`, actor
137
+ * `policy:ttl`): not a decision; a later filing reopens the request. Present only when one was closed.
138
+ */
139
+ closed?: Record<string, {
140
+ ts: string;
141
+ covered?: number;
142
+ }>;
113
143
  /**
114
144
  * The LAST decision per request id.
115
145
  *
@@ -199,6 +229,8 @@ export declare function foldQueue(lines: string[], opts?: {
199
229
  now?: number;
200
230
  ttlMs?: number;
201
231
  includeAllKinds?: boolean;
232
+ /** @implements A-SPEC-794.92 (round 2) — how many occurrences of `id` were filed at or before `ts` (refusal logs). */
233
+ occurrencesThrough?: (id: string, ts: string) => number;
202
234
  }): QueueState;
203
235
  /**
204
236
  * Append a request event. Fire-and-forget.
@@ -284,6 +316,38 @@ export declare function queueHint(root: string, req: {
284
316
  * unreadable store counts 0 (the list itself still renders as today).
285
317
  */
286
318
  export declare function refusalsOutsideInbox(root: string): number;
319
+ /**
320
+ * @implements A-SPEC-794.84 — what last ended a request: its decision or its closure, whichever covered more occurrences
321
+ * (else the later). The refusal-log fallback reads the occurrences past it, so a filing after a closure is a new request.
322
+ */
323
+ export declare function closingOf(state: QueueState, id: string): {
324
+ ts: string;
325
+ covered?: number;
326
+ } | undefined;
327
+ /** @implements A-SPEC-794.84 — the request expiry: 24 hours after the last filing. */
328
+ export declare const REQUEST_EXPIRY_MS: number;
329
+ export declare const CLOSED_EXPIRED_ACTOR = "policy:ttl";
330
+ /** @implements A-SPEC-794.84 — what a lookup says about a closed id, or null. */
331
+ export declare function closedExpiredNote(state: QueueState, id: string): string | null;
332
+ /**
333
+ * @implements A-SPEC-794.84 — closes, unrun, each grantable request that no requester can follow up (no requester run,
334
+ * no requester server: a hook's or a CLI's filing), that no person held, and whose last filing is more than 24 hours
335
+ * old. One `closed-expired` event per request, actor `policy:ttl`; the refusal log is not touched. Returns how many.
336
+ */
337
+ export declare function closeExpiredRequests(root: string, now?: number, deps?: {
338
+ append?: (rows: Array<Record<string, unknown>>) => boolean;
339
+ }): number;
340
+ /**
341
+ * @implements A-SPEC-794.92 (L-2) — the queue's writer lock: a directory beside the queue, taken by mkdir. It is
342
+ * re-entrant within this process; a lock older than 30 s is a holder that died and is broken; a lock not taken within
343
+ * 2 s returns `fallback` without running `fn`. Every caller decides which way that fails.
344
+ */
345
+ export declare function withQueueLock<T>(root: string, fn: () => T, fallback: T): T;
346
+ /**
347
+ * @implements A-SPEC-794.95 — several queue events in one write, under the same discipline as appendQueueEvent (an
348
+ * existing `.ax`, a plain queue file, the actor judged at the seam, the time and execution attached).
349
+ */
350
+ export declare function appendQueueEvents(root: string, events: Array<Record<string, unknown>>): boolean;
287
351
  export declare function grantableRequests(root: string): PendingRequest[];
288
352
  /**
289
353
  * @implements A-SPEC-690
@@ -303,4 +367,4 @@ export declare function openOccurrences(all: readonly RefusalRecord[], decided?:
303
367
  * One id's refusals, in the shape a queue entry has — so the decision surface reads the same
304
368
  * whichever store the request came from.
305
369
  */
306
- export declare function asPendingRequest(id: string, occurrences: readonly RefusalRecord[]): PendingRequest;
370
+ export declare function asPendingRequest(id: string, occurrences: readonly RefusalRecord[], through?: number): PendingRequest;
@@ -33,7 +33,9 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.DEV_KEYS = exports.DECISION_KINDS = exports.QUEUE_RELPATH = void 0;
36
+ exports.CLOSED_EXPIRED_ACTOR = exports.REQUEST_EXPIRY_MS = exports.DEV_KEYS = exports.DECISION_KINDS = exports.SPEC_TRANSITION_KIND = exports.QUEUE_RELPATH = void 0;
37
+ exports.specTransitionOfStatus = specTransitionOfStatus;
38
+ exports.isSpecTransitionKind = isSpecTransitionKind;
37
39
  exports.requestLabel = requestLabel;
38
40
  exports.pendingRequestLine = pendingRequestLine;
39
41
  exports.approvalAskLine = approvalAskLine;
@@ -41,6 +43,7 @@ exports.refusalsFilename = refusalsFilename;
41
43
  exports.isRefusalsFilename = isRefusalsFilename;
42
44
  exports.readRefusals = readRefusals;
43
45
  exports.setRequesterServer = setRequesterServer;
46
+ exports.requesterServerInstance = requesterServerInstance;
44
47
  exports.approvalRequestId = approvalRequestId;
45
48
  exports.devFiledNote = devFiledNote;
46
49
  exports.devFiledRefusal = devFiledRefusal;
@@ -51,10 +54,15 @@ exports.appendQueueEvent = appendQueueEvent;
51
54
  exports.readQueue = readQueue;
52
55
  exports.queueHint = queueHint;
53
56
  exports.refusalsOutsideInbox = refusalsOutsideInbox;
57
+ exports.closingOf = closingOf;
58
+ exports.closedExpiredNote = closedExpiredNote;
59
+ exports.closeExpiredRequests = closeExpiredRequests;
60
+ exports.withQueueLock = withQueueLock;
61
+ exports.appendQueueEvents = appendQueueEvents;
54
62
  exports.grantableRequests = grantableRequests;
55
63
  exports.openOccurrences = openOccurrences;
56
64
  exports.asPendingRequest = asPendingRequest;
57
- // @implements A-SPEC-134.2, A-SPEC-794.31, A-SPEC-794.32, A-SPEC-794.33, A-SPEC-794.34,A-SPEC-244,A-SPEC-626, A-SPEC-752, A-SPEC-754, A-SPEC-770.3, A-SPEC-770.6, A-SPEC-770.12, A-SPEC-779.2
65
+ // @implements A-SPEC-794.95, A-SPEC-794.92, A-SPEC-794.90, A-SPEC-794.85, A-SPEC-794.84, A-SPEC-794.81, A-SPEC-134.2, A-SPEC-794.31, A-SPEC-794.32, A-SPEC-794.33, A-SPEC-794.34,A-SPEC-244,A-SPEC-626, A-SPEC-752, A-SPEC-754, A-SPEC-770.3, A-SPEC-770.6, A-SPEC-770.12, A-SPEC-779.2
58
66
  const execution_context_1 = require("../project/execution-context");
59
67
  const run_mode_1 = require("./run-mode");
60
68
  const root_1 = require("../project/root");
@@ -97,8 +105,25 @@ exports.QUEUE_RELPATH = path.join('.ax', 'approvals', 'queue.jsonl');
97
105
  // @implements A-SPEC-134.2 — `code-write` is a decision too: the constitution-debt refusal points the operator at
98
106
  // `holmes-kit approve`, and its target is a project-relative path, not a command line, so the reason shell
99
107
  // requests stay out of the tracked queue does not apply.
108
+ /**
109
+ * @implements A-SPEC-794.85 — the one table from a spec lifecycle transition to the approval kind that authorizes it.
110
+ * Every path that seals, un-seals or retires a spec (the MCP acts, entity recovery, the integration audit, renumber,
111
+ * approval_status) names the kind through it; the review of 794.81 found five files holding their own literal.
112
+ */
113
+ exports.SPEC_TRANSITION_KIND = { seal: 'spec-approve', unseal: 'spec-unseal', retire: 'spec-retire' };
114
+ /** @implements A-SPEC-794.85 — the transition a spec's target status makes: approved seals, draft un-seals, outdated retires. */
115
+ function specTransitionOfStatus(status) {
116
+ return status === 'approved' ? 'seal' : status === 'draft' ? 'unseal' : status === 'outdated' ? 'retire' : null;
117
+ }
118
+ /** @implements A-SPEC-794.90 — true for the three kinds of the table. */
119
+ function isSpecTransitionKind(kind) {
120
+ return kind === exports.SPEC_TRANSITION_KIND.seal || kind === exports.SPEC_TRANSITION_KIND.unseal || kind === exports.SPEC_TRANSITION_KIND.retire;
121
+ }
100
122
  exports.DECISION_KINDS = new Set([
101
123
  'spec-approve', 'config-write', 'autonomy-grant', 'spec-reappraisal', 'review-resolve', 'governance-wiring', 'code-write',
124
+ 'spec-unseal', 'spec-retire', // A-SPEC-794.81 — un-seal and retire are decided under their own kinds
125
+ // A-SPEC-794.114 — a person vouches for this repository's provenance chain as it is, and approves a rechain's plan
126
+ 'ledger-witness', 'ledger-rechain',
102
127
  ]);
103
128
  /**
104
129
  * The line a refusal ends with to name its pending request and the operator command.
@@ -185,6 +210,10 @@ let requesterServer;
185
210
  function setRequesterServer(instance) {
186
211
  requesterServer = typeof instance === 'string' && instance !== '' ? instance.slice(0, 120) : undefined;
187
212
  }
213
+ /** @implements A-SPEC-794.81 — the MCP server instance this process runs as, or undefined outside the server. */
214
+ function requesterServerInstance() {
215
+ return requesterServer;
216
+ }
188
217
  /**
189
218
  * Deterministic request id from the action's identity.
190
219
  *
@@ -248,6 +277,22 @@ function foldQueue(lines, opts) {
248
277
  const holds = {};
249
278
  const subjects = {};
250
279
  const devFiled = {};
280
+ const closed = {}; // A-SPEC-794.84
281
+ // @implements A-SPEC-794.92 — each id's last outcome bound, and a decision row's bound: `through` when 0.41 wrote it,
282
+ // else the last outcome's bound plus `covered` (a 0.40 CLI counts the occurrences it decided from the last outcome)
283
+ const lastBound = new Map();
284
+ // A-SPEC-794.92 (round 2, review B H1) — a row without `through` cannot bound more occurrences than were filed by its own
285
+ // time: a consumer workspace's 0.40.1 rows reached 121 for 27 occurrences and hid a request filed again after them
286
+ const boundOf = (rid, row) => {
287
+ let b = typeof row.through === 'number' ? row.through
288
+ : typeof row.covered === 'number' ? (lastBound.get(rid) ?? 0) + row.covered : undefined;
289
+ if (b !== undefined && typeof row.through !== 'number' && opts?.occurrencesThrough && typeof row.ts === 'string') {
290
+ b = Math.min(b, opts.occurrencesThrough(rid, row.ts));
291
+ }
292
+ if (b !== undefined)
293
+ lastBound.set(rid, b);
294
+ return b;
295
+ };
251
296
  let malformedLines = 0;
252
297
  for (const raw of Array.isArray(lines) ? lines : []) {
253
298
  const line = String(raw ?? '').trim();
@@ -312,6 +357,7 @@ function foldQueue(lines, opts) {
312
357
  malformedLines++;
313
358
  break;
314
359
  }
360
+ delete closed[id]; // A-SPEC-794.84 — asking again reopens a closed request
315
361
  // @implements A-SPEC-650 — remembered for every kind, before the inbox filter: a decided shell
316
362
  // refusal still has a subject to show on the status surface.
317
363
  if (!subjects[id])
@@ -357,14 +403,17 @@ function foldQueue(lines, opts) {
357
403
  }
358
404
  case 'granted':
359
405
  case 'denied':
406
+ // A-SPEC-794.90 — a closure is not a decision: every decision a person wrote after it is recorded and stands
407
+ // (794.84 dropped one that did not cover more than the closure, while its grant file still covered)
360
408
  if (id) {
361
409
  pending.delete(id);
362
410
  delete holds[id]; // @implements A-SPEC-563.2 — a decision answers the question
411
+ const b = boundOf(id, e);
363
412
  decisions[id] = {
364
413
  event: e.event,
365
414
  ...(typeof e.reason === 'string' ? { reason: e.reason } : {}),
366
415
  ts: typeof e.ts === 'string' ? e.ts : '',
367
- ...(typeof e.covered === 'number' ? { covered: e.covered } : {}),
416
+ ...(b !== undefined ? { covered: b } : {}),
368
417
  ...(execution ? { execution } : {}),
369
418
  // @implements A-SPEC-650 — when a grant expires and who decided, for the outcome rows.
370
419
  ...(typeof e.expires === 'string' ? { expires: e.expires } : {}),
@@ -393,16 +442,29 @@ function foldQueue(lines, opts) {
393
442
  if (id) {
394
443
  pending.delete(id);
395
444
  delete holds[id];
445
+ const b = boundOf(id, e);
396
446
  decisions[id] = {
397
447
  event: 'withdrawn',
398
448
  ...(typeof e.reason === 'string' ? { reason: e.reason } : {}),
399
449
  ts: typeof e.ts === 'string' ? e.ts : '',
400
- ...(typeof e.covered === 'number' ? { covered: e.covered } : {}),
450
+ ...(b !== undefined ? { covered: b } : {}),
401
451
  ...(typeof e.run === 'string' ? { run: e.run } : {}),
402
452
  ...(execution ? { execution } : {}),
403
453
  };
404
454
  }
405
455
  break;
456
+ // @implements A-SPEC-794.84 — closed unrun after 24 hours without a requester: it leaves pending, and it is not a
457
+ // decision (no denial to finalise, no id that must not be filed again)
458
+ case 'closed-expired':
459
+ if (id) {
460
+ pending.delete(id);
461
+ // A-SPEC-794.92 — a closure's bound: `through`, or (794.84's rows) its covered, which was already a bound
462
+ const cb = typeof e.through === 'number' ? e.through : typeof e.covered === 'number' ? e.covered : undefined;
463
+ if (cb !== undefined)
464
+ lastBound.set(id, cb);
465
+ closed[id] = { ts: typeof e.ts === 'string' ? e.ts : '', ...(cb !== undefined ? { covered: cb } : {}) };
466
+ }
467
+ break;
406
468
  case 'held': {
407
469
  const entry = id ? pending.get(id) : undefined;
408
470
  if (entry) {
@@ -440,7 +502,8 @@ function foldQueue(lines, opts) {
440
502
  const all = [...pending.values()];
441
503
  const ttl = typeof opts?.ttlMs === 'number' && typeof opts?.now === 'number'
442
504
  ? { ttlMs: opts.ttlMs, now: opts.now } : null;
443
- const withSubjects = { ...(Object.keys(subjects).length > 0 ? { subjects } : {}), ...(Object.keys(devFiled).length > 0 ? { devFiled } : {}) };
505
+ const withSubjects = { ...(Object.keys(subjects).length > 0 ? { subjects } : {}), ...(Object.keys(devFiled).length > 0 ? { devFiled } : {}),
506
+ ...(Object.keys(closed).length > 0 ? { closed } : {}) };
444
507
  if (ttl === null)
445
508
  return { pending: all, expired: [], malformedLines, decisions, holds, ...withSubjects };
446
509
  // @implements A-SPEC-507.1 — strict excess only, and an unparseable lastTs stays ACTIVE: a
@@ -612,6 +675,44 @@ function appendQueueEvent(root, event) {
612
675
  return false;
613
676
  }
614
677
  }
678
+ /**
679
+ * @implements A-SPEC-794.92 (round 2) — occurrences of an id filed at or before a time, from the refusal logs, read once
680
+ * and only when a row without `through` asks. An unreadable log cuts nothing (the row's own bound stands).
681
+ */
682
+ function occurrenceCounter(root) {
683
+ let index;
684
+ return (id, ts) => {
685
+ if (index === undefined) {
686
+ try {
687
+ index = new Map();
688
+ for (const r of readRefusals(root)) {
689
+ const l = index.get(r.id);
690
+ if (l)
691
+ l.push(r.ts);
692
+ else
693
+ index.set(r.id, [r.ts]);
694
+ }
695
+ for (const l of index.values())
696
+ l.sort();
697
+ }
698
+ catch {
699
+ index = null;
700
+ }
701
+ }
702
+ if (index === null)
703
+ return Number.POSITIVE_INFINITY;
704
+ const l = index.get(id) ?? [];
705
+ let lo = 0, hi = l.length;
706
+ while (lo < hi) {
707
+ const mid = (lo + hi) >> 1;
708
+ if (l[mid] <= ts)
709
+ lo = mid + 1;
710
+ else
711
+ hi = mid;
712
+ }
713
+ return lo;
714
+ };
715
+ }
615
716
  /** Read and fold the queue on disk. A missing file is an empty queue, not an error. */
616
717
  function readQueue(root, opts) {
617
718
  const file = path.join(root, exports.QUEUE_RELPATH);
@@ -624,7 +725,7 @@ function readQueue(root, opts) {
624
725
  if (!fs.lstatSync(file).isFile())
625
726
  return { pending: [], expired: [], malformedLines: 1, decisions: {}, holds: {} };
626
727
  const raw = fs.readFileSync(file, 'utf8');
627
- return foldQueue(raw.split('\n'), opts);
728
+ return foldQueue(raw.split('\n'), { ...opts, occurrencesThrough: occurrenceCounter(root) });
628
729
  }
629
730
  catch {
630
731
  return { pending: [], expired: [], malformedLines: 0, decisions: {}, holds: {} };
@@ -711,6 +812,174 @@ function refusalsOutsideInbox(root) {
711
812
  return 0;
712
813
  }
713
814
  }
815
+ /**
816
+ * @implements A-SPEC-794.84 — what last ended a request: its decision or its closure, whichever covered more occurrences
817
+ * (else the later). The refusal-log fallback reads the occurrences past it, so a filing after a closure is a new request.
818
+ */
819
+ function closingOf(state, id) {
820
+ const d = state.decisions[id];
821
+ const c = state.closed?.[id];
822
+ if (c === undefined)
823
+ return d;
824
+ if (d === undefined)
825
+ return c;
826
+ // A-SPEC-794.90 — on an equal bound the decision stands
827
+ if (typeof d.covered === 'number' && typeof c.covered === 'number')
828
+ return c.covered > d.covered ? c : d;
829
+ return c.ts > d.ts ? c : d;
830
+ }
831
+ /** @implements A-SPEC-794.84 — the request expiry: 24 hours after the last filing. */
832
+ exports.REQUEST_EXPIRY_MS = 24 * 3_600_000;
833
+ exports.CLOSED_EXPIRED_ACTOR = 'policy:ttl';
834
+ /** @implements A-SPEC-794.84 — what a lookup says about a closed id, or null. */
835
+ function closedExpiredNote(state, id) {
836
+ const c = state.closed?.[id];
837
+ if (c === undefined)
838
+ return null;
839
+ const d = state.decisions[id];
840
+ if (d !== undefined && d.ts >= c.ts)
841
+ return null; // A-SPEC-794.90 — a later decision is what the id says now
842
+ return `[expired] request ${id.slice(0, 40)} was closed unrun after 24 hours without a requester (closed-expired) — nothing ran; asking again files a new request`;
843
+ }
844
+ /**
845
+ * @implements A-SPEC-794.84 — closes, unrun, each grantable request that no requester can follow up (no requester run,
846
+ * no requester server: a hook's or a CLI's filing), that no person held, and whose last filing is more than 24 hours
847
+ * old. One `closed-expired` event per request, actor `policy:ttl`; the refusal log is not touched. Returns how many.
848
+ */
849
+ function closeExpiredRequests(root, now = Date.now(), deps) {
850
+ if (!fs.existsSync(path.join(root, '.ax')))
851
+ return 0;
852
+ // A-SPEC-794.92 (L-2) — read and close under the queue lock; a lock this sweep cannot take closes nothing (a closure
853
+ // waits for the next session, a person's write does not wait for a closure)
854
+ return withQueueLock(root, () => sweepExpired(root, now, deps?.append ?? ((rows) => appendQueueEvents(root, rows))), 0);
855
+ }
856
+ const QUEUE_LOCK_STALE_MS = 30_000;
857
+ const QUEUE_LOCK_WAIT_MS = 2_000;
858
+ /** @implements A-SPEC-794.95 (A-L1, B-L2) — re-entry is per root: holding one root's lock is not holding another's. */
859
+ const queueLockDepth = new Map();
860
+ /**
861
+ * @implements A-SPEC-794.92 (L-2) — the queue's writer lock: a directory beside the queue, taken by mkdir. It is
862
+ * re-entrant within this process; a lock older than 30 s is a holder that died and is broken; a lock not taken within
863
+ * 2 s returns `fallback` without running `fn`. Every caller decides which way that fails.
864
+ */
865
+ function withQueueLock(root, fn, fallback) {
866
+ const lock = path.join(root, '.ax', 'approvals', 'queue.lock');
867
+ const held = queueLockDepth.get(lock) ?? 0;
868
+ if (held > 0) {
869
+ queueLockDepth.set(lock, held + 1);
870
+ try {
871
+ return fn();
872
+ }
873
+ finally {
874
+ queueLockDepth.set(lock, (queueLockDepth.get(lock) ?? 1) - 1);
875
+ }
876
+ }
877
+ try {
878
+ fs.mkdirSync(path.dirname(lock), { recursive: true });
879
+ }
880
+ catch {
881
+ return fallback;
882
+ }
883
+ const deadline = Date.now() + QUEUE_LOCK_WAIT_MS;
884
+ for (;;) {
885
+ try {
886
+ fs.mkdirSync(lock);
887
+ break;
888
+ }
889
+ catch (e) {
890
+ if (e.code !== 'EEXIST')
891
+ return fallback;
892
+ try {
893
+ const st = fs.lstatSync(lock);
894
+ // A-SPEC-794.95 (B-L2) — a stale lock is reclaimed by renaming it away first: two processes that both judged it
895
+ // stale cannot both remove it, and neither removes a lock the other just took
896
+ if (st.isDirectory() && Date.now() - st.mtimeMs > QUEUE_LOCK_STALE_MS) {
897
+ const aside = `${lock}.stale-${process.pid}-${Date.now()}`;
898
+ try {
899
+ fs.renameSync(lock, aside);
900
+ fs.rmdirSync(aside);
901
+ }
902
+ catch { /* another process reclaimed it */ }
903
+ continue;
904
+ }
905
+ }
906
+ catch {
907
+ continue;
908
+ }
909
+ if (Date.now() >= deadline)
910
+ return fallback;
911
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
912
+ }
913
+ }
914
+ queueLockDepth.set(lock, 1);
915
+ try {
916
+ return fn();
917
+ }
918
+ finally {
919
+ queueLockDepth.delete(lock);
920
+ try {
921
+ fs.rmdirSync(lock);
922
+ }
923
+ catch { /* already broken */ }
924
+ }
925
+ }
926
+ /**
927
+ * @implements A-SPEC-794.95 — several queue events in one write, under the same discipline as appendQueueEvent (an
928
+ * existing `.ax`, a plain queue file, the actor judged at the seam, the time and execution attached).
929
+ */
930
+ function appendQueueEvents(root, events) {
931
+ if (events.length === 0)
932
+ return true;
933
+ try {
934
+ let execution;
935
+ try {
936
+ execution = (0, execution_context_1.executionForRoot)((0, root_1.resolveProjectRoot)(root).root);
937
+ }
938
+ catch {
939
+ execution = undefined;
940
+ }
941
+ const file = path.join(root, exports.QUEUE_RELPATH);
942
+ if (!fs.existsSync(path.join(root, '.ax')))
943
+ return false;
944
+ fs.mkdirSync(path.dirname(file), { recursive: true });
945
+ if (!isPlainFile(file))
946
+ return false;
947
+ const ts = new Date().toISOString();
948
+ fs.appendFileSync(file, events.map((event) => {
949
+ const judged = 'actor' in event ? { ...event, actor: (0, human_channel_1.ledgerActor)(event.actor) } : event;
950
+ return JSON.stringify({ ...judged, ts, ...(execution ? { execution } : {}) });
951
+ }).join('\n') + '\n');
952
+ return true;
953
+ }
954
+ catch {
955
+ return false;
956
+ }
957
+ }
958
+ function sweepExpired(root, now, append) {
959
+ const state = readQueue(root, { includeAllKinds: true });
960
+ const totals = new Map();
961
+ try {
962
+ for (const r of readRefusals(root))
963
+ totals.set(r.id, (totals.get(r.id) ?? 0) + 1);
964
+ }
965
+ catch { /* the log's requests stay open */ }
966
+ const queued = new Set(state.pending.map((p) => p.id));
967
+ const rows = [];
968
+ for (const p of grantableRequests(root)) {
969
+ if (p.requesterRun !== undefined || p.requesterServer !== undefined)
970
+ continue;
971
+ if (p.hold === true || state.holds[p.id] !== undefined)
972
+ continue;
973
+ const last = Date.parse(p.lastTs);
974
+ if (!Number.isFinite(last) || last + exports.REQUEST_EXPIRY_MS >= now)
975
+ continue;
976
+ const covered = queued.has(p.id) ? p.count : (totals.get(p.id) ?? p.count);
977
+ rows.push({ event: 'closed-expired', id: p.id, actor: exports.CLOSED_EXPIRED_ACTOR,
978
+ reason: 'no requester can follow it up and no one decided it in 24 hours; nothing ran', covered, through: covered }); // A-SPEC-794.92
979
+ }
980
+ // A-SPEC-794.95 — one write for the sweep (each row was its own append: 6.3 s on a consumer workspace's first sweep, 18.9 s here)
981
+ return rows.length > 0 && append(rows) ? rows.length : 0;
982
+ }
714
983
  function grantableRequests(root) {
715
984
  const state = readQueue(root, { includeAllKinds: true });
716
985
  const seen = new Set(state.pending.map((p) => p.id));
@@ -738,10 +1007,10 @@ function grantableRequests(root) {
738
1007
  // not. When both exist the queue wins, or granting once would stop closing the request.
739
1008
  if (seen.has(id))
740
1009
  continue;
741
- const live = openOccurrences(all, state.decisions[id]);
1010
+ const live = openOccurrences(all, closingOf(state, id)); // A-SPEC-794.84 — past a decision or a closure
742
1011
  if (live.length === 0)
743
1012
  continue;
744
- out.push(asPendingRequest(id, live));
1013
+ out.push(asPendingRequest(id, live, all.length)); // A-SPEC-794.90 — the occurrence bound a decision records
745
1014
  }
746
1015
  return out;
747
1016
  }
@@ -766,10 +1035,11 @@ function openOccurrences(all, decided) {
766
1035
  * One id's refusals, in the shape a queue entry has — so the decision surface reads the same
767
1036
  * whichever store the request came from.
768
1037
  */
769
- function asPendingRequest(id, occurrences) {
1038
+ function asPendingRequest(id, occurrences, through) {
770
1039
  const latest = occurrences[occurrences.length - 1];
771
1040
  return {
772
1041
  id,
1042
+ ...(typeof through === 'number' ? { through } : {}), // A-SPEC-794.90
773
1043
  // The NEWEST occurrence is what the operator just saw, so it is what the decision names.
774
1044
  kind: latest.kind,
775
1045
  target: latest.target,
@@ -1,3 +1,4 @@
1
+ import { Spec } from '../spec/spec-parser';
1
2
  export type ShellVerdict = {
2
3
  ok: true;
3
4
  paths: string[];
@@ -37,7 +38,17 @@ export interface ShellDeps {
37
38
  readBytes(rel: string): Buffer | null;
38
39
  /** The repository's object format, which names its blobs (SHA-1 when absent). */
39
40
  objectFormat?(): 'sha1' | 'sha256';
41
+ /** @implements A-SPEC-794.86 — a spec of the store by id (R1 reads parents), or null. */
42
+ specById?(id: string): Spec | null;
43
+ /** @implements A-SPEC-794.91 (L-a) — every spec of the store (R1 reads the A-SPECs beneath a REQ or an H-SPEC). */
44
+ allSpecs?(): Spec[];
40
45
  }
46
+ /**
47
+ * @implements A-SPEC-794.86 — R1 sealed-spec-staging: a staged spec is approved without a person only when its approval
48
+ * chain is unbroken and its scope is outside the gate category. The seal itself is the prover's (the seal holds and a
49
+ * trusted spec-approved event names [id, digest]); this adds the chain and the scope. Null when R1 holds.
50
+ */
51
+ export declare function r1Problem(rel: string, text: string, deps: ShellDeps): string | null;
41
52
  export declare function governanceStagingOnly(reasons: readonly string[]): boolean;
42
53
  /** 1. Grammar: `git add|stage` (-A, --all or literal paths), then `&& git status …` with an optional counted pipe. */
43
54
  export declare function stagingGrammar(command: string): {
@@ -54,8 +65,9 @@ export declare function autonomousShellVerdict(input: {
54
65
  specsRel?: string;
55
66
  base?: string;
56
67
  specStaging?: boolean;
68
+ specRow?: 'on' | 'off';
57
69
  }, deps: ShellDeps): ShellVerdict;
58
70
  /** The real readers: git in the workspace, its provenance ledger, its queue and its install manifest. */
59
- export declare function realShellDeps(root: string): ShellDeps;
71
+ export declare function realShellDeps(root: string, specsRel?: string): ShellDeps;
60
72
  /** For approve --list: the last autonomous shell approvals (time, command digest, path count). */
61
73
  export declare function renderAutonomousApprovals(events: LedgerEventLike[], limit?: number): string;