@holmes-lab/holmes-kit 0.28.0 → 0.30.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 (83) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/README.md +24 -21
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/agents-guidance-history.d.ts +1 -1
  5. package/dist/holmes/cli/agents-guidance-history.js +11 -2
  6. package/dist/holmes/cli/agents-guidance.d.ts +1 -0
  7. package/dist/holmes/cli/agents-guidance.js +11 -8
  8. package/dist/holmes/cli/codex-toml.d.ts +23 -1
  9. package/dist/holmes/cli/codex-toml.js +151 -4
  10. package/dist/holmes/cli/doctor.d.ts +11 -1
  11. package/dist/holmes/cli/doctor.js +113 -13
  12. package/dist/holmes/cli/init.d.ts +2 -0
  13. package/dist/holmes/cli/init.js +20 -40
  14. package/dist/holmes/cli/interactive-prompt.js +2 -2
  15. package/dist/holmes/cli/worktree-readiness.d.ts +1 -0
  16. package/dist/holmes/cli/worktree-readiness.js +17 -3
  17. package/dist/holmes/cpg/ast-mutation.d.ts +2 -0
  18. package/dist/holmes/cpg/ast-mutation.js +4 -2
  19. package/dist/holmes/cpg/foundation/cfg.d.ts +10 -0
  20. package/dist/holmes/cpg/foundation/cfg.js +27 -1
  21. package/dist/holmes/governance/autonomy.d.ts +9 -0
  22. package/dist/holmes/governance/autonomy.js +28 -1
  23. package/dist/holmes/hooks/rtm-refresh-child.d.ts +22 -1
  24. package/dist/holmes/hooks/rtm-refresh-child.js +100 -18
  25. package/dist/holmes/hooks/rtm-refresh.d.ts +20 -1
  26. package/dist/holmes/hooks/rtm-refresh.js +56 -15
  27. package/dist/holmes/mcp/approval-adapters.d.ts +22 -0
  28. package/dist/holmes/mcp/approval-adapters.js +21 -0
  29. package/dist/holmes/mcp/approval-commit.d.ts +21 -0
  30. package/dist/holmes/mcp/approval-commit.js +92 -0
  31. package/dist/holmes/mcp/approval-intent.d.ts +44 -0
  32. package/dist/holmes/mcp/approval-intent.js +67 -0
  33. package/dist/holmes/mcp/approval-policy.d.ts +14 -0
  34. package/dist/holmes/mcp/approval-policy.js +18 -0
  35. package/dist/holmes/mcp/elicit-approval.d.ts +2 -0
  36. package/dist/holmes/mcp/elicit-approval.js +5 -2
  37. package/dist/holmes/mcp/handlers/graph-operations.d.ts +24 -1
  38. package/dist/holmes/mcp/handlers/graph-operations.js +38 -6
  39. package/dist/holmes/mcp/handlers/maintenance-evidence.js +1 -1
  40. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +142 -0
  41. package/dist/holmes/mcp/handlers/requirement-triage.js +220 -0
  42. package/dist/holmes/mcp/handlers/review-evidence.d.ts +2 -1
  43. package/dist/holmes/mcp/handlers/review-evidence.js +9 -5
  44. package/dist/holmes/mcp/handlers/slice-orchestration.d.ts +7 -0
  45. package/dist/holmes/mcp/handlers/slice-orchestration.js +8 -1
  46. package/dist/holmes/mcp/handlers/spec-approval.d.ts +26 -2
  47. package/dist/holmes/mcp/handlers/spec-approval.js +72 -47
  48. package/dist/holmes/mcp/handlers/spec-authoring.js +20 -2
  49. package/dist/holmes/mcp/handlers.d.ts +153 -0
  50. package/dist/holmes/mcp/handlers.js +67 -13
  51. package/dist/holmes/mcp/maintenance-analyze.js +28 -4
  52. package/dist/holmes/mcp/maintenance-evidence.js +1 -1
  53. package/dist/holmes/mcp/requirement-triage-evidence.d.ts +45 -0
  54. package/dist/holmes/mcp/requirement-triage-evidence.js +149 -0
  55. package/dist/holmes/mcp/server.js +5 -3
  56. package/dist/holmes/mcp/supervisor.js +7 -3
  57. package/dist/holmes/mcp/tool-schemas.d.ts +8 -0
  58. package/dist/holmes/mcp/tool-schemas.js +44 -1
  59. package/dist/holmes/refresh/freshness-coordinator.d.ts +67 -0
  60. package/dist/holmes/refresh/freshness-coordinator.js +230 -0
  61. package/dist/holmes/review/condition-hunk-replay.d.ts +45 -0
  62. package/dist/holmes/review/condition-hunk-replay.js +122 -0
  63. package/dist/holmes/review/condition-hunk-resolution.d.ts +65 -0
  64. package/dist/holmes/review/condition-hunk-resolution.js +258 -0
  65. package/dist/holmes/review/requirement-triage-benchmark.d.ts +45 -0
  66. package/dist/holmes/review/requirement-triage-benchmark.js +72 -0
  67. package/dist/holmes/review/requirement-triage-human-records.d.ts +59 -0
  68. package/dist/holmes/review/requirement-triage-human-records.js +119 -0
  69. package/dist/holmes/review/requirement-triage.d.ts +61 -0
  70. package/dist/holmes/review/requirement-triage.js +143 -0
  71. package/dist/holmes/review/scope.js +6 -1
  72. package/dist/holmes/review/test-outcomes.d.ts +28 -0
  73. package/dist/holmes/review/test-outcomes.js +90 -1
  74. package/dist/holmes/semantic/local-model.d.ts +3 -3
  75. package/dist/holmes/semantic/local-model.js +10 -12
  76. package/dist/holmes/semantic/model-cache.d.ts +15 -6
  77. package/dist/holmes/semantic/model-cache.js +77 -21
  78. package/dist/holmes/semantic/tier.d.ts +5 -1
  79. package/dist/holmes/semantic/tier.js +7 -6
  80. package/dist/holmes/semantic/vector-coverage.d.ts +17 -0
  81. package/dist/holmes/semantic/vector-coverage.js +37 -0
  82. package/docs/install-guide.md +19 -24
  83. package/package.json +1 -1
@@ -33,6 +33,10 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.recordRefreshFailure = recordRefreshFailure;
37
+ exports.runRefreshChild = runRefreshChild;
38
+ exports.defaultRefreshChildDeps = defaultRefreshChildDeps;
39
+ // @implements A-SPEC-719
36
40
  // @implements A-SPEC-566.4
37
41
  /**
38
42
  * The detached refresh child — the ONLY place this slice touches the scan/build machinery. Spawned
@@ -42,26 +46,104 @@ Object.defineProperty(exports, "__esModule", { value: true });
42
46
  */
43
47
  const fs = __importStar(require("node:fs"));
44
48
  const path = __importStar(require("node:path"));
45
- if (require.main === module) {
49
+ const freshness_coordinator_1 = require("../refresh/freshness-coordinator");
50
+ const currentHead = (root) => {
51
+ try {
52
+ const { headOf } = require('../mcp/handlers/graph-operations');
53
+ return headOf(root);
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ };
59
+ /** The detached worker must publish its own failure; the parent is intentionally non-blocking. */
60
+ function recordRefreshFailure(root, generation, head, now) {
61
+ return (0, freshness_coordinator_1.completeRefresh)(root, generation, {
62
+ graph: 'failed', sourceSemantic: 'failed', requirementSemantic: 'failed', head,
63
+ }, now);
64
+ }
65
+ /**
66
+ * One refresh run for one lease generation. Every phase that writes is preceded by a lease check,
67
+ * so a superseded worker, or one whose root was removed, stops without writing (A-SPEC-724). Any
68
+ * failure — synchronous module load included — is published as bounded retry for this generation
69
+ * rather than left as a `refreshing` lease that only expiry can clear (A-SPEC-719).
70
+ */
71
+ async function runRefreshChild(root, generation, deps) {
72
+ if (!fs.existsSync(path.join(root, '.ax')))
73
+ return;
74
+ if (!(0, freshness_coordinator_1.ownsLease)(root, generation))
75
+ return; // spawned late behind a newer lease: not even the graph
46
76
  try {
47
- const root = process.argv[2];
48
- if (root && fs.existsSync(path.join(root, '.ax'))) {
77
+ await deps.refreshGraph(root);
78
+ // @implements A-SPEC-683 — the vectors ride the channel that already refreshes the graph.
79
+ // Measured 2026-09-19: without this, coverage reached 0 of 602 in twelve days while the graph
80
+ // stayed current.
81
+ if (!(0, freshness_coordinator_1.ownsLease)(root, generation))
82
+ return;
83
+ const source = await deps.refreshSource(root);
84
+ if (!(0, freshness_coordinator_1.ownsLease)(root, generation))
85
+ return;
86
+ let requirement;
87
+ try {
88
+ requirement = await deps.refreshRequirement(root);
89
+ }
90
+ catch {
91
+ requirement = { status: 'unavailable' };
92
+ }
93
+ (0, freshness_coordinator_1.completeRefresh)(root, generation, {
94
+ graph: 'current',
95
+ sourceSemantic: source.lane,
96
+ requirementSemantic: requirement.status === 'discharged' ? 'current'
97
+ : requirement.status === 'not-applicable' ? 'not-adopted'
98
+ : requirement.status === 'suppressed' ? 'suppressed' : 'failed',
99
+ head: deps.head(root),
100
+ }, new Date());
101
+ }
102
+ catch {
103
+ try {
104
+ recordRefreshFailure(root, generation, deps.head(root), new Date());
105
+ }
106
+ catch { /* fail-soft */ }
107
+ }
108
+ }
109
+ /** The production phases: the scan/build machinery, loaded only inside the detached child. */
110
+ function defaultRefreshChildDeps(env = process.env) {
111
+ // @implements A-SPEC-719 — the owner's transfer switch covers requirement documents too: the
112
+ // background child must not embed them when it is set, whatever tier is configured.
113
+ const suppressed = typeof env.HOLMES_NO_SEMANTIC_WARM === 'string' && env.HOLMES_NO_SEMANTIC_WARM !== '';
114
+ return {
115
+ head: currentHead,
116
+ refreshGraph: async (root) => {
49
117
  const { makeHandlers } = require('../mcp/handlers');
50
118
  const { LocalMarkdownRepository } = require('../spec/spec-store');
51
119
  const h = makeHandlers(new LocalMarkdownRepository(path.join(root, '.ax', 'specs')));
52
- void h.rtm_impact({ root, changed: [] }).then(() => {
53
- // @implements A-SPEC-683 — the vectors ride the channel that already refreshes the graph.
54
- // Detached, TTL-gated and fail-soft are properties this child already has; warming inherits
55
- // all three rather than needing a schedule of its own. Measured 2026-09-19: without this,
56
- // coverage reached 0 of 602 in twelve days while the graph stayed current.
57
- const { refreshSemanticVectors } = require('../mcp/handlers/graph-operations');
58
- const { CpgScanner } = require('../cpg/cpg-scanner');
59
- const { ScanFileCache } = require('../cpg/scan-cache');
60
- const crypto = require('node:crypto');
61
- const dir = path.join(require('node:os').tmpdir(), 'holmes-cpg-cache-' + crypto.createHash('sha256').update(root).digest('hex').slice(0, 16));
62
- return refreshSemanticVectors(root, process.env, undefined, () => new CpgScanner(undefined, new ScanFileCache(dir)).scan(root, root));
63
- }).catch(() => undefined);
64
- }
65
- }
66
- catch { /* fail-soft: a failed refresh leaves the old graph, which the advisory tolerates */ }
120
+ return h.rtm_impact({ root, changed: [] });
121
+ },
122
+ refreshSource: async (root) => {
123
+ const { refreshSemanticVectors } = require('../mcp/handlers/graph-operations');
124
+ const { CpgScanner } = require('../cpg/cpg-scanner');
125
+ const { ScanFileCache } = require('../cpg/scan-cache');
126
+ const crypto = require('node:crypto');
127
+ const dir = path.join(require('node:os').tmpdir(), 'holmes-cpg-cache-' + crypto.createHash('sha256').update(root).digest('hex').slice(0, 16));
128
+ return refreshSemanticVectors(root, env, undefined, () => new CpgScanner(undefined, new ScanFileCache(dir)).scan(root, root));
129
+ },
130
+ refreshRequirement: async (root) => {
131
+ if (suppressed)
132
+ return { status: 'suppressed' };
133
+ return warmRequirements(root);
134
+ },
135
+ };
136
+ }
137
+ async function warmRequirements(root) {
138
+ const { LocalMarkdownRepository } = require('../spec/spec-store');
139
+ const graphOps = require('../mcp/handlers/graph-operations');
140
+ const specs = await new LocalMarkdownRepository(path.join(root, '.ax', 'specs')).list();
141
+ return graphOps.warmRequirementSemanticCache(root, specs);
142
+ }
143
+ if (require.main === module) {
144
+ const root = process.argv[2];
145
+ const generation = process.argv[3];
146
+ // fail-soft: a failed refresh leaves the old graph, which the advisory tolerates
147
+ if (root && generation)
148
+ void runRefreshChild(root, generation, defaultRefreshChildDeps()).catch(() => undefined);
67
149
  }
@@ -1,3 +1,4 @@
1
+ /** @deprecated A compatibility observation interval; receipt leases are the source of truth. */
1
2
  export declare const RTM_REFRESH_TTL_MS: number;
2
3
  export declare const RTM_REFRESH_MARKER: string;
3
4
  export interface RtmRefreshOpts {
@@ -9,5 +10,23 @@ export interface RtmRefreshOpts {
9
10
  unref?: () => void;
10
11
  };
11
12
  ttlMs?: number;
13
+ head?: string | null;
12
14
  }
13
- export declare function maybeSpawnRtmRefresh(opts: RtmRefreshOpts): void;
15
+ export type FreshnessBridgeObservation = {
16
+ status: 'spawned';
17
+ generation: string;
18
+ } | {
19
+ status: 'coalesced';
20
+ generation: string;
21
+ } | {
22
+ status: 'failed';
23
+ };
24
+ /**
25
+ * Request a detached refresh without making the caller wait. A failed child
26
+ * launch is itself durable evidence: close the lease as retry-at so a later
27
+ * request can retry instead of treating a stranded `refreshing` marker as
28
+ * progress.
29
+ */
30
+ export declare function maybeSpawnRtmRefresh(opts: RtmRefreshOpts): FreshnessBridgeObservation;
31
+ /** The MCP-side bridge uses the same lease and child as the end-of-turn hook. */
32
+ export declare function requestBackgroundFreshness(root: string): FreshnessBridgeObservation;
@@ -35,7 +35,8 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.RTM_REFRESH_MARKER = exports.RTM_REFRESH_TTL_MS = void 0;
37
37
  exports.maybeSpawnRtmRefresh = maybeSpawnRtmRefresh;
38
- // @implements A-SPEC-566.4
38
+ exports.requestBackgroundFreshness = requestBackgroundFreshness;
39
+ // @implements A-SPEC-724, A-SPEC-723, A-SPEC-719
39
40
  /**
40
41
  * Graph freshness, kept by the product itself. The impact advisory's quality factor was MEASURED to
41
42
  * be staleness (an 8-day-old graph found 7 advisories; a 1-second reindex found 17), so the Stop
@@ -45,32 +46,72 @@ exports.maybeSpawnRtmRefresh = maybeSpawnRtmRefresh;
45
46
  */
46
47
  const fs = __importStar(require("node:fs"));
47
48
  const path = __importStar(require("node:path"));
48
- exports.RTM_REFRESH_TTL_MS = 30 * 60 * 1000;
49
+ const freshness_coordinator_1 = require("../refresh/freshness-coordinator");
50
+ /** Same resolution as the child's `headOf`: full commit id, or null outside a repository. */
51
+ function gitHead(root) {
52
+ try {
53
+ const { execFileSync } = require('node:child_process');
54
+ return execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000 }).trim() || null;
55
+ }
56
+ catch {
57
+ return null;
58
+ } // bounded: a hung git must never hold the Stop hook
59
+ }
60
+ /** @deprecated A compatibility observation interval; receipt leases are the source of truth. */
61
+ exports.RTM_REFRESH_TTL_MS = freshness_coordinator_1.FRESHNESS_LEASE_MS;
49
62
  exports.RTM_REFRESH_MARKER = path.join('.ax', 'state', 'rtm-refresh-last');
63
+ /**
64
+ * Request a detached refresh without making the caller wait. A failed child
65
+ * launch is itself durable evidence: close the lease as retry-at so a later
66
+ * request can retry instead of treating a stranded `refreshing` marker as
67
+ * progress.
68
+ */
50
69
  function maybeSpawnRtmRefresh(opts) {
51
70
  try {
52
71
  if (!fs.existsSync(path.join(opts.root, '.ax')))
53
- return; // nothing to refresh
72
+ return { status: 'failed' }; // nothing to refresh
73
+ // The lease must name the HEAD the child completes against (A-SPEC-719): a null lease in a git
74
+ // workspace could only ever complete as stale, so intake would never see current evidence.
75
+ const decision = (0, freshness_coordinator_1.requestRefresh)(opts.root, {
76
+ workspaceId: (0, freshness_coordinator_1.workspaceIdFor)(opts.root), head: opts.head !== undefined ? opts.head : gitHead(opts.root), now: new Date(opts.now),
77
+ });
78
+ if (!decision.spawn)
79
+ return { status: 'coalesced', generation: decision.receipt.generation };
80
+ // Retained only for tools that still display the former marker. The receipt
81
+ // above is the authority for coalescing and retrying; this write is never read.
54
82
  const marker = path.join(opts.root, exports.RTM_REFRESH_MARKER);
55
- const ttl = opts.ttlMs ?? exports.RTM_REFRESH_TTL_MS;
56
- try {
57
- const age = opts.now - fs.statSync(marker).mtimeMs;
58
- if (age < ttl)
59
- return; // one refresh per window
60
- }
61
- catch { /* absent marker → refresh is due */ }
62
- // Touch BEFORE spawning: a burst of Stops inside one window must not stampede children.
63
83
  try {
64
84
  fs.mkdirSync(path.dirname(marker), { recursive: true });
65
85
  fs.writeFileSync(marker, String(opts.now));
66
86
  fs.utimesSync(marker, new Date(opts.now), new Date(opts.now));
67
87
  }
68
88
  catch { /* an unwritable marker is not a reason to skip the refresh itself */ }
69
- const child = opts.spawn(opts.execPath, [opts.scriptPath, opts.root], { detached: true, stdio: 'ignore' });
70
- child?.unref?.();
89
+ try {
90
+ const child = opts.spawn(opts.execPath, [opts.scriptPath, opts.root, decision.receipt.generation], { detached: true, stdio: 'ignore' });
91
+ child?.unref?.();
92
+ return { status: 'spawned', generation: decision.receipt.generation };
93
+ }
94
+ catch {
95
+ (0, freshness_coordinator_1.completeRefresh)(opts.root, decision.receipt.generation, {
96
+ graph: 'failed', sourceSemantic: 'failed', requirementSemantic: 'failed', head: decision.receipt.head,
97
+ }, new Date(opts.now));
98
+ return { status: 'failed' };
99
+ }
71
100
  }
72
- catch { /* freshness is maintenance, never a hook failure */ }
101
+ catch {
102
+ return { status: 'failed' };
103
+ } // freshness is maintenance, never a hook failure
104
+ }
105
+ /** The MCP-side bridge uses the same lease and child as the end-of-turn hook. */
106
+ function requestBackgroundFreshness(root) {
107
+ const cp = require('node:child_process');
108
+ return maybeSpawnRtmRefresh({
109
+ root, now: Date.now(), execPath: process.execPath,
110
+ scriptPath: path.resolve(__dirname, 'rtm-refresh-child.js'),
111
+ spawn: (cmd, args, opts) => cp.spawn(cmd, args, opts),
112
+ });
73
113
  }
74
114
  // The child lives in rtm-refresh-child.ts, NOT here: this module is required by the Stop hook, and
75
115
  // the gate path must never carry the AST substrate (A-SPEC-510.2 pinned it, and its static check
76
- // caught the first cut of this slice doing exactly that). The gate side is fs+path only.
116
+ // caught the first cut of this slice doing exactly that). The gate side is fs+path plus one lazy
117
+ // `git rev-parse HEAD` (child_process, no AST substrate) to bind the lease to its HEAD.
@@ -0,0 +1,22 @@
1
+ /**
2
+ * A capability is evidence, a client name is not. Direct MCP elicitation is selected only when
3
+ * it was advertised at initialize; the named installed harnesses otherwise receive the explicit
4
+ * host-gated continuation tool. Unknown clients keep the durable approval queue fallback.
5
+ */
6
+ export type ApprovalAdapter = {
7
+ kind: 'direct-form';
8
+ timeoutObservable: true;
9
+ } | {
10
+ kind: 'host-gated-tool';
11
+ timeoutObservable: false;
12
+ } | {
13
+ kind: 'queue-fallback';
14
+ timeoutObservable: false;
15
+ };
16
+ /** A generic or URL-only elicitation declaration cannot receive an MCP form. */
17
+ export declare function supportsFormElicitation(capabilities: unknown): boolean;
18
+ export declare function selectApprovalAdapter(input: {
19
+ harness: string;
20
+ formElicitation?: boolean;
21
+ elicitation?: boolean;
22
+ }): ApprovalAdapter;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.supportsFormElicitation = supportsFormElicitation;
4
+ exports.selectApprovalAdapter = selectApprovalAdapter;
5
+ const HOST_GATED_HARNESSES = new Set(['claude', 'codex', 'antigravity']);
6
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
7
+ /** A generic or URL-only elicitation declaration cannot receive an MCP form. */
8
+ function supportsFormElicitation(capabilities) {
9
+ if (!object(capabilities) || !object(capabilities.elicitation))
10
+ return false;
11
+ return object(capabilities.elicitation.form);
12
+ }
13
+ function selectApprovalAdapter(input) {
14
+ // The legacy boolean is retained for in-process callers. Live negotiation
15
+ // passes `formElicitation`, derived from the exact MCP capability shape.
16
+ if (input.formElicitation ?? input.elicitation ?? false)
17
+ return { kind: 'direct-form', timeoutObservable: true };
18
+ return HOST_GATED_HARNESSES.has(input.harness.trim().toLowerCase())
19
+ ? { kind: 'host-gated-tool', timeoutObservable: false }
20
+ : { kind: 'queue-fallback', timeoutObservable: false };
21
+ }
@@ -0,0 +1,21 @@
1
+ import { ApprovalIntent, IntentBinding } from './approval-intent';
2
+ import { Approval } from '../guardrail/risk-gate';
3
+ /**
4
+ * Memory-only continuations deliberately die with the MCP session. A rejected or malformed
5
+ * commit never burns a valid pending intent; only an exact, live host-gated commit can be consumed
6
+ * by the original action, exactly once.
7
+ */
8
+ export declare class ApprovalContinuationStore {
9
+ private readonly pending;
10
+ private readonly committed;
11
+ prepare(intent: ApprovalIntent): void;
12
+ commit(candidate: ApprovalIntent, now?: Date): {
13
+ ok: true;
14
+ } | {
15
+ ok: false;
16
+ reason: string;
17
+ };
18
+ consume(candidate: ApprovalIntent, now?: Date): Approval | undefined;
19
+ /** The retried original action has no authority fields; match only server-derived action identity. */
20
+ consumeForAction(candidate: Omit<IntentBinding, 'challenge'>, now?: Date): Approval | undefined;
21
+ }
@@ -0,0 +1,92 @@
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.ApprovalContinuationStore = void 0;
37
+ // @implements A-SPEC-718
38
+ const crypto = __importStar(require("node:crypto"));
39
+ const approval_intent_1 = require("./approval-intent");
40
+ /**
41
+ * Memory-only continuations deliberately die with the MCP session. A rejected or malformed
42
+ * commit never burns a valid pending intent; only an exact, live host-gated commit can be consumed
43
+ * by the original action, exactly once.
44
+ */
45
+ class ApprovalContinuationStore {
46
+ pending = new Map();
47
+ committed = new Map();
48
+ prepare(intent) {
49
+ this.pending.set(intent.id, intent);
50
+ }
51
+ commit(candidate, now = new Date()) {
52
+ const pending = this.pending.get(candidate.id);
53
+ if (!pending)
54
+ return { ok: false, reason: 'unknown-or-consumed-intent' };
55
+ const binding = candidate;
56
+ const failure = (0, approval_intent_1.intentBindingFailure)(pending, binding, now);
57
+ if (failure !== null)
58
+ return { ok: false, reason: failure };
59
+ this.pending.delete(candidate.id);
60
+ this.committed.set(candidate.id, pending);
61
+ return { ok: true };
62
+ }
63
+ consume(candidate, now = new Date()) {
64
+ const committed = this.committed.get(candidate.id);
65
+ if (!committed || (0, approval_intent_1.intentBindingFailure)(committed, candidate, now) !== null)
66
+ return undefined;
67
+ this.committed.delete(candidate.id);
68
+ return {
69
+ actor: `host-gated:${committed.harness}`,
70
+ token: crypto.randomUUID(),
71
+ rationale: `host-gated in-session approval for ${committed.kind} ${committed.target}`,
72
+ };
73
+ }
74
+ /** The retried original action has no authority fields; match only server-derived action identity. */
75
+ consumeForAction(candidate, now = new Date()) {
76
+ for (const intent of this.committed.values()) {
77
+ if (Date.parse(intent.expiresAt) <= now.getTime())
78
+ continue;
79
+ if (intent.kind !== candidate.kind || intent.target !== candidate.target || intent.subject !== candidate.subject
80
+ || intent.workspace !== candidate.workspace || intent.runId !== candidate.runId)
81
+ continue;
82
+ this.committed.delete(intent.id);
83
+ return {
84
+ actor: `host-gated:${intent.harness}`,
85
+ token: crypto.randomUUID(),
86
+ rationale: `host-gated in-session approval for ${intent.kind} ${intent.target}`,
87
+ };
88
+ }
89
+ return undefined;
90
+ }
91
+ }
92
+ exports.ApprovalContinuationStore = ApprovalContinuationStore;
@@ -0,0 +1,44 @@
1
+ export type ApprovalPresentationResult = {
2
+ kind: 'approve';
3
+ reason?: string;
4
+ } | {
5
+ kind: 'deny';
6
+ reason?: string;
7
+ } | {
8
+ kind: 'question';
9
+ reason: string;
10
+ } | {
11
+ kind: 'cancel';
12
+ } | {
13
+ kind: 'timeout';
14
+ } | {
15
+ kind: 'malformed';
16
+ } | {
17
+ kind: 'unavailable';
18
+ };
19
+ export interface ApprovalIntent {
20
+ id: string;
21
+ challenge: string;
22
+ kind: string;
23
+ target: string;
24
+ subject: string;
25
+ workspace: string;
26
+ runId: string;
27
+ harness: string;
28
+ expiresAt: string;
29
+ }
30
+ export interface ApprovalIntentInput {
31
+ kind: string;
32
+ target: string;
33
+ subject: string;
34
+ workspace: string;
35
+ runId: string;
36
+ harness: string;
37
+ now?: Date;
38
+ ttlMs?: number;
39
+ }
40
+ /** Create an opaque, single-use action identity. The caller owns storage and consumption. */
41
+ export declare function createApprovalIntent(input: ApprovalIntentInput): ApprovalIntent;
42
+ export type IntentBinding = Pick<ApprovalIntent, 'challenge' | 'kind' | 'target' | 'subject' | 'workspace' | 'runId'>;
43
+ /** Verify every server-derived binding before an intent is consumed. */
44
+ export declare function intentBindingFailure(intent: ApprovalIntent, candidate: IntentBinding, now?: Date): string | null;
@@ -0,0 +1,67 @@
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.createApprovalIntent = createApprovalIntent;
37
+ exports.intentBindingFailure = intentBindingFailure;
38
+ // @implements A-SPEC-718
39
+ const crypto = __importStar(require("node:crypto"));
40
+ /** Create an opaque, single-use action identity. The caller owns storage and consumption. */
41
+ function createApprovalIntent(input) {
42
+ const now = input.now ?? new Date();
43
+ const ttlMs = input.ttlMs ?? 120_000;
44
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0)
45
+ throw new Error('approval intent ttl must be positive');
46
+ for (const [name, value] of Object.entries(input)) {
47
+ if (['now', 'ttlMs'].includes(name))
48
+ continue;
49
+ if (typeof value !== 'string' || value.trim() === '')
50
+ throw new Error(`approval intent ${name} is required`);
51
+ }
52
+ return {
53
+ id: crypto.randomUUID(), challenge: crypto.randomBytes(32).toString('base64url'),
54
+ kind: input.kind, target: input.target, subject: input.subject, workspace: input.workspace,
55
+ runId: input.runId, harness: input.harness, expiresAt: new Date(now.getTime() + ttlMs).toISOString(),
56
+ };
57
+ }
58
+ /** Verify every server-derived binding before an intent is consumed. */
59
+ function intentBindingFailure(intent, candidate, now = new Date()) {
60
+ if (Date.parse(intent.expiresAt) <= now.getTime())
61
+ return 'expired';
62
+ for (const key of ['challenge', 'kind', 'target', 'subject', 'workspace', 'runId']) {
63
+ if (candidate[key] !== intent[key])
64
+ return `mismatched-${key}`;
65
+ }
66
+ return null;
67
+ }
@@ -0,0 +1,14 @@
1
+ import { ApprovalPresentationResult } from './approval-intent';
2
+ export type ApprovalPolicyDecision = {
3
+ kind: 'approved';
4
+ actor: string;
5
+ reason?: string;
6
+ } | {
7
+ kind: 'hold';
8
+ reason: string;
9
+ };
10
+ /** The sole response transition table; timeout is never a synonym for cancel or deny. */
11
+ export declare function resolveApprovalPresentation(result: ApprovalPresentationResult, options: {
12
+ autonomous: boolean;
13
+ harness: string;
14
+ }): ApprovalPolicyDecision;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveApprovalPresentation = resolveApprovalPresentation;
4
+ /** The sole response transition table; timeout is never a synonym for cancel or deny. */
5
+ function resolveApprovalPresentation(result, options) {
6
+ const harness = options.harness.trim() || 'unknown';
7
+ switch (result.kind) {
8
+ case 'approve': return { kind: 'approved', actor: `elicitation:${harness}`, ...(result.reason ? { reason: result.reason } : {}) };
9
+ case 'timeout': return options.autonomous
10
+ ? { kind: 'approved', actor: `autonomous-timeout:${harness}`, reason: 'in-session approval timeout' }
11
+ : { kind: 'hold', reason: 'approval prompt timed out' };
12
+ case 'deny': return { kind: 'hold', reason: result.reason ? `denied: ${result.reason}` : 'denied' };
13
+ case 'question': return { kind: 'hold', reason: `question: ${result.reason}` };
14
+ case 'cancel': return { kind: 'hold', reason: 'cancelled' };
15
+ case 'malformed': return { kind: 'hold', reason: 'malformed response' };
16
+ case 'unavailable': return { kind: 'hold', reason: 'in-session approval unavailable' };
17
+ }
18
+ }
@@ -34,6 +34,8 @@ export interface ElicitApprovalRequest {
34
34
  target: string;
35
35
  /** Human-facing one-liner: what is being approved (id, title, sealed-or-not). */
36
36
  summary: string;
37
+ /** Server-derived outcome wording; only explicit autonomy may select automatic approval. */
38
+ timeoutBehavior?: 'queue' | 'autonomous-approve';
37
39
  }
38
40
  /** The human's decision. `null` from interpretElicitResult means "no answer in this shape". */
39
41
  export interface ElicitDecision {
@@ -9,7 +9,7 @@ exports.buildDecisionForm = buildDecisionForm;
9
9
  exports.buildReasonForm = buildReasonForm;
10
10
  exports.runElicitFlow = runElicitFlow;
11
11
  exports.interpretElicitResult = interpretElicitResult;
12
- // @implements A-SPEC-263.1
12
+ // @implements A-SPEC-718, A-SPEC-263.1
13
13
  const npx_bin_1 = require("../project/npx-bin");
14
14
  /**
15
15
  * The decision comes INTO the session (REQ-263): an approval-shaped refusal (spec_approve without a
@@ -108,11 +108,14 @@ const flat = (s, max) => s.replace(/[\u0000-\u001f\u007f\u0085\u2028\u2029\u200b
108
108
  */
109
109
  function buildDecisionForm(req, attempt, timeoutMs) {
110
110
  const redisplay = attempt > 1 ? `⚠ 재표시 ${attempt}/${exports.MAX_PRESENTATIONS} — 이전 다이얼로그는 만료되어 무효입니다\n` : '';
111
+ const timeoutNotice = req.timeoutBehavior === 'autonomous-approve'
112
+ ? `⏱ ${timeoutMs / 1000}초 내 미결정 시 이 요청만 자동 승인됩니다(autonomous mode).`
113
+ : `⏱ ${timeoutMs / 1000}초 내 미결정 시 승인 큐로 회송됩니다(운영자: ${(0, npx_bin_1.npxBin)()} holmes-kit approve).`;
111
114
  return {
112
115
  // @implements A-SPEC-497.1 — the forewarning is the LAST line and template-owned: it survives a
113
116
  // cap-filling summary (appended after the caps) and tells the human, before the clock runs out,
114
117
  // where an undecided request goes and where the decision still lives.
115
- message: `${redisplay}[Holmes-Kit 승인 요청] ${flat(req.kind, 40)} — ${flat(req.target, 80)}\n${flat(req.summary, 200)}\n승인(approve) / 거부(deny) / 질문(question) 을 선택하세요. 사유는 거부·질문을 고르면 이어서 묻습니다.\n⏱ ${timeoutMs / 1000}초 내 미결정 시 승인 큐로 회송됩니다(운영자: ${(0, npx_bin_1.npxBin)()} holmes-kit approve).`,
118
+ message: `${redisplay}[Holmes-Kit 승인 요청] ${flat(req.kind, 40)} — ${flat(req.target, 80)}\n${flat(req.summary, 200)}\n승인(approve) / 거부(deny) / 질문(question) 을 선택하세요. 사유는 거부·질문을 고르면 이어서 묻습니다.\n${timeoutNotice}`,
116
119
  requestedSchema: {
117
120
  type: 'object',
118
121
  properties: {