@evomap/evolver-cli 2.0.42 → 2.0.44

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 (50) hide show
  1. package/dist/autoRecall.d.ts +24 -5
  2. package/dist/autoRecall.js +233 -12
  3. package/dist/autoexec.d.ts +69 -10
  4. package/dist/autoexec.js +847 -137
  5. package/dist/cli.d.ts +1 -1
  6. package/dist/cli.js +71 -26
  7. package/dist/cliContracts.js +29 -7
  8. package/dist/cliEntry.d.ts +3 -0
  9. package/dist/cliEntry.js +63 -0
  10. package/dist/commandCatalog.d.ts +1 -0
  11. package/dist/commandCatalog.js +1 -0
  12. package/dist/contextDelivery.d.ts +12 -0
  13. package/dist/contextDelivery.js +139 -0
  14. package/dist/cycleConsumer.js +9 -1
  15. package/dist/dispatch.js +6 -0
  16. package/dist/feedbackOutbox.d.ts +96 -0
  17. package/dist/feedbackOutbox.js +510 -0
  18. package/dist/feedbackOutboxCli.d.ts +7 -0
  19. package/dist/feedbackOutboxCli.js +208 -0
  20. package/dist/index.d.ts +3 -0
  21. package/dist/index.js +286 -69
  22. package/dist/lifecycle.d.ts +18 -0
  23. package/dist/lifecycle.js +130 -3
  24. package/dist/lifecycleBootstrapTransaction.js +1 -6
  25. package/dist/liveStatus.d.ts +27 -0
  26. package/dist/liveStatus.js +197 -0
  27. package/dist/outboxLock.d.ts +7 -0
  28. package/dist/outboxLock.js +141 -0
  29. package/dist/promptRecallHook.d.ts +7 -22
  30. package/dist/promptRecallHook.js +20 -489
  31. package/dist/promptRecallRuntime.d.ts +24 -0
  32. package/dist/promptRecallRuntime.js +678 -0
  33. package/dist/promptRecallShared.d.ts +18 -0
  34. package/dist/promptRecallShared.js +119 -0
  35. package/dist/recall.js +27 -6
  36. package/dist/runtimeTelemetry.d.ts +9 -0
  37. package/dist/runtimeTelemetry.js +16 -0
  38. package/dist/sessionIngest.d.ts +25 -2
  39. package/dist/sessionIngest.js +196 -32
  40. package/dist/setupHooks.js +63 -13
  41. package/dist/setupHooksLifecycle.js +39 -17
  42. package/dist/skill2gep.d.ts +11 -0
  43. package/dist/skill2gep.js +23 -3
  44. package/dist/solo/mode.js +4 -0
  45. package/dist/taskCommitments.d.ts +4 -2
  46. package/dist/taskCommitments.js +208 -114
  47. package/dist/taskOutcomeOutbox.d.ts +83 -0
  48. package/dist/taskOutcomeOutbox.js +553 -0
  49. package/dist/workflowRuntime.js +12 -0
  50. package/package.json +11 -7
@@ -1,501 +1,32 @@
1
- import { assetstore, events, hub, signals } from '@evomap/evolver-core';
2
- import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
3
- import { lstatSync } from 'node:fs';
4
- import { join } from 'node:path';
5
- import { performance } from 'node:perf_hooks';
6
- /** The hook sees a raw user prompt, so reject oversized payloads instead of retaining a partial JSON document. */
7
- export const MAX_PROMPT_RECALL_STDIN_BYTES = 64 * 1024;
8
- export const MAX_PROMPT_RECALL_LOCAL_FILE_BYTES = 4 * 1024 * 1024;
9
- export const MAX_PROMPT_RECALL_LOCAL_TOTAL_BYTES = 8 * 1024 * 1024;
10
- const PROMPT_RECALL_STDIN_TIMEOUT_MS = 250;
11
- const PROMPT_RECALL_SELECTION_TIMEOUT_MS = 750;
12
- const PROMPT_RECALL_SCAN_LIMIT = 1000;
13
- const PROMPT_RECALL_CONTEXT_MAX_CHARS = 800;
14
- const PROMPT_RECALL_DEFAULT_MAX_GENES = 1;
15
- const PROMPT_RECALL_MAX_GENES = 10;
16
- const PROMPT_RECALL_MATCH_CHARS = 16 * 1024;
17
- const PROMPT_RECALL_MATCH_TOKENS = 512;
18
- const PROMPT_RECALL_SIGNAL_PATTERNS = 16;
19
- const PROMPT_RECALL_SIGNAL_PATTERN_CHARS = 512;
20
- const PROMPT_RECALL_SIGNAL_ALIASES = 4;
21
- const PROMPT_RECALL_SIGNAL_ALIAS_CHARS = 192;
22
- const PROMPT_RECALL_SIGNAL_ALIAS_TOKENS = 12;
23
- const PROMPT_RECALL_TOKEN_CHARS = 96;
24
- const PROMPT_RECALL_GENE_FIELD_CHARS = 512;
25
- const PROMPT_RECALL_YIELD_EVERY_GENES = 8;
26
- const NON_SPACE_SCRIPT = /[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Thai}]/u;
27
- const PROMPT_RECALL_LOCAL_FILES = [
28
- 'genes.jsonl',
29
- 'capsules.jsonl',
30
- 'events.jsonl',
31
- 'anti-genes.jsonl',
32
- 'review.jsonl',
33
- 'provenance.jsonl',
34
- ];
35
- export function promptRecallMode(env = process.env) {
36
- const value = String(env['EVOLVER_RECALL_MODE'] ?? '').trim().toLowerCase();
37
- return value === 'shadow' || value === 'enforce' ? value : 'off';
38
- }
39
- function promptRecallMaxGenes(env) {
40
- const parsed = Number.parseInt(String(env['EVOLVER_RECALL_MAX'] ?? ''), 10);
41
- return Number.isFinite(parsed) && parsed > 0 && parsed <= PROMPT_RECALL_MAX_GENES
42
- ? parsed
43
- : PROMPT_RECALL_DEFAULT_MAX_GENES;
44
- }
45
- function readStdinBounded(timeoutMs = PROMPT_RECALL_STDIN_TIMEOUT_MS, maxBytes = MAX_PROMPT_RECALL_STDIN_BYTES) {
46
- return new Promise((resolve) => {
47
- const stdin = process.stdin;
48
- if (stdin.isTTY) {
49
- resolve(undefined);
50
- return;
51
- }
52
- let data = '';
53
- let bytes = 0;
54
- let settled = false;
55
- const finish = (value) => {
56
- if (settled)
57
- return;
58
- settled = true;
59
- clearTimeout(timer);
60
- stdin.removeListener('data', onData);
61
- stdin.removeListener('end', onEnd);
62
- stdin.removeListener('error', onError);
63
- try {
64
- stdin.pause();
65
- }
66
- catch { /* already closed */ }
67
- resolve(value);
68
- };
69
- const onData = (chunk) => {
70
- const text = chunk.toString();
71
- bytes += Buffer.byteLength(text, 'utf8');
72
- if (bytes > maxBytes) {
73
- finish(undefined);
74
- return;
75
- }
76
- data += text;
77
- };
78
- const onEnd = () => finish(data);
79
- const onError = () => finish(undefined);
80
- const timer = setTimeout(() => finish(undefined), timeoutMs);
81
- timer.unref?.();
82
- stdin.setEncoding('utf8');
83
- stdin.on('data', onData);
84
- stdin.on('end', onEnd);
85
- stdin.on('error', onError);
86
- try {
87
- stdin.resume();
88
- }
89
- catch {
90
- finish(undefined);
91
- }
92
- });
93
- }
94
- async function readHookPayload(readHookInput) {
95
- const raw = readHookInput ? await readHookInput() : await readStdinBounded();
96
- if (typeof raw !== 'string' || Buffer.byteLength(raw, 'utf8') > MAX_PROMPT_RECALL_STDIN_BYTES)
97
- return undefined;
98
- return raw;
99
- }
100
- function normalizedTokens(text, maxChars, maxTokens) {
101
- const bounded = text.slice(0, maxChars);
102
- const matches = bounded
103
- .toLowerCase()
104
- .normalize('NFKC')
105
- .match(/[\p{L}\p{N}]+/gu)
106
- ?.filter((token) => (token.length >= 2 || /^\d+$/.test(token)) && token.length <= PROMPT_RECALL_TOKEN_CHARS)
107
- ?? [];
108
- // A character-boundary cut can leave a partial final token. Dropping it is conservative: it avoids a false
109
- // literal match while keeping prompt processing independent of the raw prompt's total size.
110
- if (text.length > maxChars && matches.length > 0)
111
- matches.pop();
112
- return matches.slice(0, maxTokens);
113
- }
114
- function normalizedAliasTokens(text) {
115
- const runs = text
116
- .toLowerCase()
117
- .normalize('NFKC')
118
- .match(/[\p{L}\p{N}]+/gu) ?? [];
119
- if (runs.some((token) => token.length > PROMPT_RECALL_TOKEN_CHARS))
120
- return [];
121
- const tokens = runs.filter((token) => token.length >= 2 || /^\d+$/.test(token));
122
- return tokens.length <= PROMPT_RECALL_SIGNAL_ALIAS_TOKENS ? tokens : [];
123
- }
124
- function promptTokenSegments(prompt) {
125
- if (prompt.length <= PROMPT_RECALL_MATCH_CHARS) {
126
- return [normalizedTokens(prompt, PROMPT_RECALL_MATCH_CHARS, PROMPT_RECALL_MATCH_TOKENS)];
127
- }
128
- const segmentChars = Math.floor(PROMPT_RECALL_MATCH_CHARS / 2);
129
- const segmentTokens = Math.floor(PROMPT_RECALL_MATCH_TOKENS / 2);
130
- const tailTokens = normalizedTokens(prompt.slice(-segmentChars), segmentChars, segmentTokens);
131
- // The tail slice may begin in the middle of a token. Discard its first run rather than admit a prefix match.
132
- tailTokens.shift();
133
- return [
134
- normalizedTokens(prompt, segmentChars, segmentTokens),
135
- tailTokens,
136
- ];
137
- }
138
- function promptLiteralSegments(prompt) {
139
- const limit = PROMPT_RECALL_MATCH_CHARS;
140
- const segments = prompt.length <= limit
141
- ? [prompt]
142
- : [prompt.slice(0, limit / 2), prompt.slice(-limit / 2)];
143
- // Keep the windows separate: a signal must never span the omitted middle. Bound normalization expansion too.
144
- return segments.flatMap((segment, index) => {
145
- const normalized = segment.toLowerCase().normalize('NFKC');
146
- if (segments.length === 1 && normalized.length > limit) {
147
- return [
148
- { text: normalized.slice(0, limit / 2), cutStart: false, cutEnd: true },
149
- { text: normalized.slice(-limit / 2), cutStart: true, cutEnd: false },
150
- ];
151
- }
152
- const maxChars = limit / segments.length;
153
- const isTail = index > 0;
154
- return [{
155
- // Preserve the real prompt end when normalization expands the tail window.
156
- text: isTail ? normalized.slice(-maxChars) : normalized.slice(0, maxChars),
157
- cutStart: isTail,
158
- cutEnd: !isTail && (normalized.length > maxChars || segments.length > 1),
159
- }];
160
- }).filter((segment) => NON_SPACE_SCRIPT.test(segment.text));
161
- }
162
- function hasNonSpaceLetter(text) {
163
- return Array.from(text).some((character) => NON_SPACE_SCRIPT.test(character) && /\p{L}/u.test(character));
164
- }
165
- function containsNonSpaceLiteral(segments, alias) {
166
- const literal = alias.toLowerCase().normalize('NFKC');
167
- if (!NON_SPACE_SCRIPT.test(literal))
168
- return false;
169
- // Script_Extensions also includes shared punctuation and combining marks, which are not useful signals alone.
170
- if (!hasNonSpaceLetter(literal) || /^\p{M}/u.test(literal))
171
- return false;
172
- const characters = Array.from(literal);
173
- const runs = literal.match(/[\p{L}\p{N}\p{M}]+/gu) ?? [];
174
- if (runs.length > PROMPT_RECALL_SIGNAL_ALIAS_TOKENS
175
- || runs.some((run) => run.length > PROMPT_RECALL_TOKEN_CHARS))
176
- return false;
177
- const needsBoundary = (character) => /[\p{L}\p{N}\p{M}]/u.test(character)
178
- && !NON_SPACE_SCRIPT.test(character);
179
- const leftBoundary = needsBoundary(characters[0]);
180
- const rightBoundary = needsBoundary(characters.at(-1));
181
- for (const { text, cutStart, cutEnd } of segments) {
182
- for (let at = text.indexOf(literal); at !== -1; at = text.indexOf(literal, at + 1)) {
183
- if ((at === 0 && cutStart) || (at + literal.length === text.length && cutEnd))
184
- continue;
185
- const before = Array.from(text.slice(Math.max(0, at - 2), at)).at(-1) ?? '';
186
- const after = String.fromCodePoint(text.codePointAt(at + literal.length) ?? 0);
187
- // Mixed aliases retain Latin word boundaries; a Thai/Kana combining mark must not be cut off.
188
- if ((!leftBoundary || !needsBoundary(before))
189
- && (!rightBoundary || !needsBoundary(after)) && !/\p{M}/u.test(after))
190
- return true;
191
- }
192
- }
193
- return false;
194
- }
195
- function buildPromptSequenceIndex(segments) {
196
- const root = { children: new Map() };
197
- for (const tokens of segments) {
198
- for (let start = 0; start < tokens.length; start += 1) {
199
- let node = root;
200
- const end = Math.min(tokens.length, start + PROMPT_RECALL_SIGNAL_ALIAS_TOKENS);
201
- for (let offset = start; offset < end; offset += 1) {
202
- const token = tokens[offset];
203
- let child = node.children.get(token);
204
- if (!child) {
205
- child = { children: new Map() };
206
- node.children.set(token, child);
207
- }
208
- node = child;
209
- }
210
- }
211
- }
212
- return root;
213
- }
214
- function containsSequence(index, needle) {
215
- if (needle.length === 0)
216
- return false;
217
- let node = index;
218
- for (const token of needle) {
219
- const child = node.children.get(token);
220
- if (!child)
221
- return false;
222
- node = child;
223
- }
224
- return true;
225
- }
226
- function boundedSignalPatterns(gene) {
227
- const patterns = Array.isArray(gene['signals_match']) ? gene['signals_match'] : [];
228
- return patterns
229
- .slice(0, PROMPT_RECALL_SIGNAL_PATTERNS)
230
- .filter((pattern) => (typeof pattern === 'string' && pattern.length <= PROMPT_RECALL_SIGNAL_PATTERN_CHARS));
231
- }
1
+ import { loadEnvFileFromEnv } from '@evomap/evolver-mcp/env-file';
2
+ import { promptRecallMode, waitContextDelivery, writeHookStdout } from './promptRecallShared.js';
3
+ export { MAX_PROMPT_RECALL_STDIN_BYTES, MAX_PROMPT_RECALL_LOCAL_FILE_BYTES, MAX_PROMPT_RECALL_LOCAL_TOTAL_BYTES, promptRecallMode, wrapGeneContext, } from './promptRecallShared.js';
232
4
  /**
233
- * V1 required a real local signals_match hit before prompt-time injection. Keep that conservative gate: aliases
234
- * separated by `|` are matched as normalized token sequences, with bounded literal matching for scripts that
235
- * do not require spaces between words. Regex-looking patterns are never evaluated
236
- * (a persisted pattern must not be able to run an expensive regular expression on a private prompt).
237
- */
238
- function literalSignalHits(promptIndex, patterns, literalSegments) {
239
- let hits = 0;
240
- for (const pattern of patterns) {
241
- const aliases = pattern.split('|', PROMPT_RECALL_SIGNAL_ALIASES + 1).slice(0, PROMPT_RECALL_SIGNAL_ALIASES);
242
- const matched = aliases.some((alias) => {
243
- const trimmed = alias.trim();
244
- if (!trimmed
245
- || trimmed.length > PROMPT_RECALL_SIGNAL_ALIAS_CHARS
246
- || (trimmed.startsWith('/') && trimmed.lastIndexOf('/') > 0))
247
- return false;
248
- return containsSequence(promptIndex, normalizedAliasTokens(trimmed))
249
- || (literalSegments.length > 0 && containsNonSpaceLiteral(literalSegments, trimmed));
250
- });
251
- if (matched)
252
- hits += 1;
253
- }
254
- return hits;
255
- }
256
- function boundedGeneField(value) {
257
- return typeof value === 'string' ? value.slice(0, PROMPT_RECALL_GENE_FIELD_CHARS) : undefined;
258
- }
259
- function geneText(gene, signalsMatch) {
260
- return [boundedGeneField(gene['id']), boundedGeneField(gene['category']), boundedGeneField(gene['summary']), ...signalsMatch]
261
- .filter((value) => typeof value === 'string')
262
- .join(' ');
263
- }
264
- function selectionExpired(budget) {
265
- return budget.cancelled || performance.now() >= budget.deadlineMs;
266
- }
267
- function localRecallFilesWithinBudget(store) {
268
- if (!(store instanceof assetstore.LocalJsonlProvider))
269
- return true;
270
- try {
271
- lstatSync(join(store.baseDir, '.assetstore.lock'));
272
- return false;
273
- }
274
- catch (error) {
275
- if (error.code !== 'ENOENT')
276
- return false;
277
- }
278
- let totalBytes = 0;
279
- for (const file of PROMPT_RECALL_LOCAL_FILES) {
280
- try {
281
- const stat = lstatSync(join(store.baseDir, file));
282
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_PROMPT_RECALL_LOCAL_FILE_BYTES)
283
- return false;
284
- totalBytes += stat.size;
285
- if (totalBytes > MAX_PROMPT_RECALL_LOCAL_TOTAL_BYTES)
286
- return false;
287
- }
288
- catch (error) {
289
- if (error.code !== 'ENOENT')
290
- return false;
291
- }
292
- }
293
- return true;
294
- }
295
- function yieldToEventLoop() {
296
- return new Promise((resolve) => setImmediate(resolve));
297
- }
298
- async function selectPromptGenes(prompt, store, review, provenance, maxGenes, budget, benchmark) {
299
- const tokenSegments = promptTokenSegments(prompt);
300
- const promptTokens = tokenSegments.flat();
301
- const literalSegments = promptLiteralSegments(prompt);
302
- if (promptTokens.length === 0 && literalSegments.length === 0)
303
- return [];
304
- const promptIndex = buildPromptSequenceIndex(tokenSegments);
305
- const boundedPrompt = promptTokens.join(' ');
306
- const receipts = new Map();
307
- const approved = await assetstore.listApprovedGenes(store, review, PROMPT_RECALL_SCAN_LIMIT, provenance, {
308
- ...(benchmark ? { benchmark } : {}),
309
- onQualification: (values) => { for (const receipt of values)
310
- receipts.set(receipt.assetId, receipt); },
311
- });
312
- if (selectionExpired(budget))
313
- return [];
314
- const ranked = [];
315
- for (let index = 0; index < approved.length; index += 1) {
316
- if (selectionExpired(budget))
317
- return [];
318
- const gene = approved[index];
319
- const signalsMatch = boundedSignalPatterns(gene);
320
- const literalHits = literalSignalHits(promptIndex, signalsMatch, literalSegments);
321
- if (literalHits > 0) {
322
- const semanticScore = signals.tagOverlapScore(promptTokens, {
323
- signalsMatch,
324
- geneId: boundedGeneField(gene['id']),
325
- category: boundedGeneField(gene['category']),
326
- summary: boundedGeneField(gene['summary']),
327
- }) + signals.bagCosine(boundedPrompt, geneText(gene, signalsMatch));
328
- ranked.push({
329
- gene,
330
- literalHits,
331
- semanticScore,
332
- assetKey: String(gene.asset_id).slice(0, 128),
333
- ...(receipts.has(gene.asset_id) ? { sourceQualification: receipts.get(gene.asset_id) } : {}),
334
- });
335
- }
336
- if ((index + 1) % PROMPT_RECALL_YIELD_EVERY_GENES === 0) {
337
- await yieldToEventLoop();
338
- if (selectionExpired(budget))
339
- return [];
340
- }
341
- }
342
- if (selectionExpired(budget))
343
- return [];
344
- ranked.sort((left, right) => (right.literalHits - left.literalHits
345
- || right.semanticScore - left.semanticScore
346
- || left.assetKey.localeCompare(right.assetKey)));
347
- return ranked.slice(0, benchmark ? Math.min(maxGenes, 8) : maxGenes);
348
- }
349
- function renderGeneLine(gene) {
350
- const id = (typeof gene['id'] === 'string' ? gene['id'] : String(gene.asset_id)).slice(0, 128);
351
- const category = typeof gene['category'] === 'string' ? gene['category'].slice(0, 96) : '';
352
- const summary = typeof gene['summary'] === 'string'
353
- ? gene['summary'].slice(0, PROMPT_RECALL_GENE_FIELD_CHARS).replace(/\s+/g, ' ').trim()
354
- : '';
355
- return `- ${id}${category ? ` [${category}]` : ''}${summary ? `: ${summary.slice(0, 240)}` : ''}`;
356
- }
357
- function renderPromptRecallContext(genes) {
358
- const header = '[Evolver memory - relevant prior capability]';
359
- const footer = 'Use only when directly relevant. Adapt and verify before applying; do not mention this memory block unless asked or materially relevant.';
360
- const lines = [header];
361
- const rendered = [];
362
- for (const ranked of genes) {
363
- const { gene } = ranked;
364
- const line = renderGeneLine(gene);
365
- if ([...lines, line, footer].join('\n').length > PROMPT_RECALL_CONTEXT_MAX_CHARS)
366
- break;
367
- lines.push(line);
368
- rendered.push(ranked);
369
- }
370
- if (lines.length === 1)
371
- return { text: '', genes: [] };
372
- lines.push(footer);
373
- return { text: lines.join('\n'), genes: rendered };
374
- }
375
- function boundedAuditString(value) {
376
- if (typeof value !== 'string')
377
- return undefined;
378
- const trimmed = value.trim();
379
- return trimmed ? trimmed.slice(0, 256) : undefined;
380
- }
381
- function logPromptRecallSelections(genes, mode, sessionId, env, injectedLog) {
382
- if (genes.length === 0)
383
- return;
384
- const callLog = injectedLog ?? new hub.AssetCallLog(events.assetCallLogPath(env));
385
- const runId = `recall:${boundedAuditString(sessionId) ?? 'unknown'}`;
386
- for (const ranked of genes) {
387
- const sourceNodeId = boundedAuditString(ranked.gene['source_node_id'] ?? ranked.gene['author_node_id']);
388
- const chainId = boundedAuditString(ranked.gene['chain_id']);
389
- try {
390
- callLog.append({
391
- run_id: runId,
392
- action: mode === 'enforce' ? 'asset_inject' : 'asset_inject_shadow',
393
- asset_id: ranked.assetKey,
394
- asset_type: 'Gene',
395
- ...(sourceNodeId ? { source_node_id: sourceNodeId } : {}),
396
- ...(chainId ? { chain_id: chainId } : {}),
397
- score: ranked.semanticScore,
398
- reason: 'local_gene_pattern_hit',
399
- extra: {
400
- via: 'prompt_recall',
401
- attribution: 'correlational_local',
402
- origin: 'local',
403
- literal_hits: ranked.literalHits,
404
- ...(ranked.sourceQualification ? assetstore.compactQualificationReceipts([ranked.sourceQualification]) : {}),
405
- },
406
- });
407
- }
408
- catch { /* local attribution must never block prompt submission */ }
409
- }
410
- }
411
- async function withSelectionBudget(timeoutMs, fallback, run) {
412
- const boundedTimeoutMs = Number.isFinite(timeoutMs) ? Math.max(0, timeoutMs) : PROMPT_RECALL_SELECTION_TIMEOUT_MS;
413
- const budget = {
414
- deadlineMs: performance.now() + boundedTimeoutMs,
415
- cancelled: false,
416
- };
417
- let timer;
418
- try {
419
- return await Promise.race([
420
- Promise.resolve().then(() => run(budget)),
421
- new Promise((resolve) => {
422
- timer = setTimeout(() => {
423
- budget.cancelled = true;
424
- resolve(fallback);
425
- }, boundedTimeoutMs);
426
- }),
427
- ]);
428
- }
429
- finally {
430
- if (timer)
431
- clearTimeout(timer);
432
- }
433
- }
434
- /**
435
- * Shared Claude Code/Codex UserPromptSubmit entrypoint. It is intentionally local-only and fail-open: no Hub
436
- * query, no transcript read, no prompt persistence, and exactly one JSON object on stdout for every outcome.
5
+ * Cold hook entry: env-file/off/argument gates must precede importing the local
6
+ * selection runtime. This matters for npm's unbundled, stable-obfuscated ESM, not
7
+ * just tree-shaken binaries. Off never reads prompt stdin or loads core stores.
437
8
  */
438
9
  export async function runPromptRecallHook(argv, deps = {}) {
439
- const write = deps.stdout ?? ((text) => { process.stdout.write(text); });
440
- let output = {};
441
10
  const env = deps.env ?? process.env;
442
11
  const envFile = loadEnvFileFromEnv(env);
443
- if (env['EVOLVER_ENV_FILE']?.trim() && !envFile.loaded) {
444
- write('{}\n');
445
- return 0;
446
- }
447
- const mode = promptRecallMode(env);
448
- // Privacy invariant from V1: default-off does not even read the prompt-bearing stdin payload.
449
- if (mode === 'off' || !argv.includes('--hook-stdin')) {
450
- write('{}\n');
12
+ if ((env['EVOLVER_ENV_FILE']?.trim() && !envFile.loaded)
13
+ || promptRecallMode(env) === 'off' || !argv.includes('--hook-stdin')) {
14
+ try {
15
+ await waitContextDelivery(Promise.resolve().then(() => (deps.stdout ?? writeHookStdout)('{}\n')), 1000);
16
+ }
17
+ catch { /* One attempt only, including EPIPE. Off has no audit. */ }
451
18
  return 0;
452
19
  }
20
+ let run;
453
21
  try {
454
- const raw = await readHookPayload(deps.readHookInput);
455
- if (!raw?.trim())
456
- throw new Error('empty hook payload');
457
- const input = JSON.parse(raw);
458
- if (typeof input.hook_event_name === 'string' && input.hook_event_name !== 'UserPromptSubmit') {
459
- throw new Error('unexpected hook event');
460
- }
461
- const prompt = input.prompt;
462
- if (typeof prompt !== 'string')
463
- throw new Error('prompt is not recallable');
464
- const trimmedPrompt = prompt.trim();
465
- if (trimmedPrompt.length < 8) {
466
- const normalizedPrompt = trimmedPrompt.toLowerCase().normalize('NFKC');
467
- if (!hasNonSpaceLetter(normalizedPrompt)
468
- || (normalizedPrompt.match(/[\p{L}\p{N}]/gu)?.length ?? 0) < 2) {
469
- throw new Error('prompt is not recallable');
470
- }
471
- }
472
- const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
473
- // These cold-loaded JSONL files are parsed synchronously inside the existing store/ledger APIs. Preflight
474
- // their footprint before entering those APIs so an append-only sidecar cannot defeat the hook deadline.
475
- if (!localRecallFilesWithinBudget(store))
476
- throw new Error('local recall files exceed the prompt-hook budget');
477
- const review = deps.review ?? assetstore.reviewLedgerForStore(store);
478
- const provenance = deps.provenance ?? assetstore.provenanceStoreForStore(store);
479
- const timeoutMs = deps.selectionTimeoutMs ?? PROMPT_RECALL_SELECTION_TIMEOUT_MS;
480
- const ranked = await withSelectionBudget(timeoutMs, [], (budget) => selectPromptGenes(prompt, store, review, provenance, promptRecallMaxGenes(env), budget, assetstore.benchmarkContext(env['EVOLVER_BENCHMARK_ID'])));
481
- if (ranked.length > 0) {
482
- const rendered = renderPromptRecallContext(ranked);
483
- if (rendered.text) {
484
- logPromptRecallSelections(rendered.genes, mode, input.session_id, env, deps.callLog);
485
- }
486
- if (mode === 'enforce' && rendered.text) {
487
- output = {
488
- hookSpecificOutput: {
489
- hookEventName: 'UserPromptSubmit',
490
- additionalContext: rendered.text,
491
- },
492
- };
493
- }
494
- }
22
+ ({ runPromptRecallHook: run } = await import('./promptRecallRuntime.js'));
495
23
  }
496
24
  catch {
497
- output = {};
25
+ try {
26
+ await waitContextDelivery(Promise.resolve().then(() => (deps.stdout ?? writeHookStdout)('{}\n')), 1000);
27
+ }
28
+ catch { /* Failed loading must not block submission or retry a failed write. */ }
29
+ return 0;
498
30
  }
499
- write(`${JSON.stringify(output)}\n`);
500
- return 0;
31
+ return run(argv, deps);
501
32
  }
@@ -0,0 +1,24 @@
1
+ import * as recall from '@evomap/evolver-core/prompt-recall';
2
+ type HookInputReader = (signal?: AbortSignal) => string | undefined | Promise<string | undefined>;
3
+ export interface PromptRecallHookDeps {
4
+ store?: recall.AssetStoreProvider;
5
+ review?: recall.ReviewLedger;
6
+ provenance?: recall.ProvenanceStore;
7
+ callLog?: Pick<recall.AssetCallLog, 'append'> & Partial<Pick<recall.AssetCallLog, 'appendBounded'>>;
8
+ env?: NodeJS.ProcessEnv;
9
+ /** Cooperative input reader; late results are discarded after the same 250ms stdin budget. */
10
+ readHookInput?: HookInputReader;
11
+ stdout?: (text: string) => void | Promise<void>;
12
+ stdoutWithSettlement?: (text: string, onSettled: (written: boolean) => void) => Promise<void>;
13
+ /** CLI lifecycle notification after the single stdout write; not host/model acknowledgement. */
14
+ onOutputWritten?: () => void;
15
+ /** External delivery writers must own preparation, projection and terminal release. */
16
+ ingestor?: Pick<recall.Ingestor, 'prepareContextDelivery'> & Partial<Pick<recall.Ingestor, 'prepareContextDeliveryAsync' | 'recoverContextDeliveries'>>;
17
+ selectionTimeoutMs?: number;
18
+ }
19
+ /**
20
+ * Shared Claude Code/Codex UserPromptSubmit entrypoint. It is intentionally local-only and fail-open: no Hub
21
+ * query, no transcript read, no prompt persistence, and exactly one JSON object on stdout for every outcome.
22
+ */
23
+ export declare function runPromptRecallHook(argv: readonly string[], deps?: PromptRecallHookDeps): Promise<number>;
24
+ export {};