@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
@@ -0,0 +1,678 @@
1
+ import * as recall from '@evomap/evolver-core/prompt-recall';
2
+ import { createHash } from 'node:crypto';
3
+ import { performance } from 'node:perf_hooks';
4
+ import { deliverContextOutput, waitContextDelivery } from './contextDelivery.js';
5
+ import { MAX_PROMPT_RECALL_STDIN_BYTES, MAX_PROMPT_RECALL_LOCAL_FILE_BYTES, MAX_PROMPT_RECALL_LOCAL_TOTAL_BYTES, promptRecallMode, wrapGeneContext, writeHookStdout, writeContextReadDiagnostic } from './promptRecallShared.js';
6
+ const PROMPT_RECALL_STDIN_TIMEOUT_MS = 250;
7
+ const PROMPT_RECALL_SELECTION_TIMEOUT_MS = 750;
8
+ const PROMPT_RECALL_SCAN_LIMIT = 1000;
9
+ const PROMPT_RECALL_CONTEXT_MAX_CHARS = 800;
10
+ const PROMPT_RECALL_DEFAULT_MAX_GENES = 1;
11
+ const PROMPT_RECALL_MAX_GENES = 10;
12
+ const PROMPT_RECALL_MATCH_CHARS = 16 * 1024;
13
+ const PROMPT_RECALL_MATCH_TOKENS = 512;
14
+ const PROMPT_RECALL_SIGNAL_PATTERNS = 16;
15
+ const PROMPT_RECALL_SIGNAL_PATTERN_CHARS = 512;
16
+ const PROMPT_RECALL_SIGNAL_ALIASES = 4;
17
+ const PROMPT_RECALL_SIGNAL_ALIAS_CHARS = 192;
18
+ const PROMPT_RECALL_SIGNAL_ALIAS_TOKENS = 12;
19
+ const PROMPT_RECALL_TOKEN_CHARS = 96;
20
+ const PROMPT_RECALL_GENE_FIELD_CHARS = 512;
21
+ const PROMPT_RECALL_YIELD_EVERY_GENES = 8;
22
+ 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;
23
+ function promptRecallMaxGenes(env) {
24
+ const parsed = Number.parseInt(String(env['EVOLVER_RECALL_MAX'] ?? ''), 10);
25
+ return Number.isFinite(parsed) && parsed > 0 && parsed <= PROMPT_RECALL_MAX_GENES
26
+ ? parsed
27
+ : PROMPT_RECALL_DEFAULT_MAX_GENES;
28
+ }
29
+ function readStdinBounded(timeoutMs = PROMPT_RECALL_STDIN_TIMEOUT_MS, maxBytes = MAX_PROMPT_RECALL_STDIN_BYTES) {
30
+ return new Promise((resolve) => {
31
+ const stdin = process.stdin;
32
+ if (stdin.isTTY) {
33
+ resolve(undefined);
34
+ return;
35
+ }
36
+ let data = '';
37
+ let bytes = 0;
38
+ let settled = false;
39
+ const finish = (value) => {
40
+ if (settled)
41
+ return;
42
+ settled = true;
43
+ clearTimeout(timer);
44
+ stdin.removeListener('data', onData);
45
+ stdin.removeListener('end', onEnd);
46
+ stdin.removeListener('error', onError);
47
+ try {
48
+ stdin.pause();
49
+ }
50
+ catch { /* already closed */ }
51
+ resolve(value);
52
+ };
53
+ const onData = (chunk) => {
54
+ const text = chunk.toString();
55
+ bytes += Buffer.byteLength(text, 'utf8');
56
+ if (bytes > maxBytes) {
57
+ finish(undefined);
58
+ return;
59
+ }
60
+ data += text;
61
+ };
62
+ const onEnd = () => finish(data);
63
+ const onError = () => finish(undefined);
64
+ const timer = setTimeout(() => finish(undefined), timeoutMs);
65
+ timer.unref?.();
66
+ stdin.setEncoding('utf8');
67
+ stdin.on('data', onData);
68
+ stdin.on('end', onEnd);
69
+ stdin.on('error', onError);
70
+ try {
71
+ stdin.resume();
72
+ }
73
+ catch {
74
+ finish(undefined);
75
+ }
76
+ });
77
+ }
78
+ async function readHookPayload(readHookInput) {
79
+ const raw = readHookInput
80
+ ? await withSelectionBudget(PROMPT_RECALL_STDIN_TIMEOUT_MS, undefined, budget => Promise.resolve(readHookInput(budget.signal)))
81
+ : await readStdinBounded();
82
+ if (typeof raw !== 'string' || Buffer.byteLength(raw, 'utf8') > MAX_PROMPT_RECALL_STDIN_BYTES)
83
+ return undefined;
84
+ return raw;
85
+ }
86
+ function normalizedTokens(text, maxChars, maxTokens, cutStart = false) {
87
+ let bounded = text.slice(0, maxChars).toLowerCase().normalize('NFKC');
88
+ // Remove only a run actually cut by the window, before filtering tokens. A
89
+ // delimiter at the boundary proves the adjacent token is complete.
90
+ if (cutStart)
91
+ bounded = bounded.replace(/^[\p{L}\p{N}]+/u, '');
92
+ if (text.length > maxChars && /^[\p{L}\p{N}\p{M}]/u.test(text.slice(maxChars, maxChars + 2).normalize('NFKC'))) {
93
+ bounded = bounded.replace(/[\p{L}\p{N}]+$/u, '');
94
+ }
95
+ const matches = bounded
96
+ .match(/[\p{L}\p{N}]+/gu)
97
+ ?.filter((token) => (token.length >= 2 || /^\d+$/.test(token)) && token.length <= PROMPT_RECALL_TOKEN_CHARS)
98
+ ?? [];
99
+ return matches.slice(0, maxTokens);
100
+ }
101
+ function normalizedAliasTokens(text) {
102
+ const runs = text
103
+ .toLowerCase()
104
+ .normalize('NFKC')
105
+ .match(/[\p{L}\p{N}]+/gu) ?? [];
106
+ if (runs.some((token) => token.length > PROMPT_RECALL_TOKEN_CHARS))
107
+ return [];
108
+ const tokens = runs.filter((token) => token.length >= 2 || /^\d+$/.test(token));
109
+ return tokens.length <= PROMPT_RECALL_SIGNAL_ALIAS_TOKENS ? tokens : [];
110
+ }
111
+ function promptTokenSegments(prompt) {
112
+ if (prompt.length <= PROMPT_RECALL_MATCH_CHARS) {
113
+ return [normalizedTokens(prompt, PROMPT_RECALL_MATCH_CHARS, PROMPT_RECALL_MATCH_TOKENS)];
114
+ }
115
+ const segmentChars = Math.floor(PROMPT_RECALL_MATCH_CHARS / 2);
116
+ const segmentTokens = Math.floor(PROMPT_RECALL_MATCH_TOKENS / 2);
117
+ const start = prompt.length - segmentChars;
118
+ const cutStart = /[\p{L}\p{N}\p{M}]$/u.test(prompt.slice(Math.max(0, start - 2), start).normalize('NFKC'));
119
+ const tailTokens = normalizedTokens(prompt.slice(start), segmentChars, segmentTokens, cutStart);
120
+ return [
121
+ normalizedTokens(prompt, segmentChars, segmentTokens),
122
+ tailTokens,
123
+ ];
124
+ }
125
+ function promptLiteralSegments(prompt) {
126
+ const limit = PROMPT_RECALL_MATCH_CHARS;
127
+ const segments = prompt.length <= limit
128
+ ? [prompt]
129
+ : [prompt.slice(0, limit / 2), prompt.slice(-limit / 2)];
130
+ // Keep the windows separate: a signal must never span the omitted middle. Bound normalization expansion too.
131
+ return segments.flatMap((segment, index) => {
132
+ const normalized = segment.toLowerCase().normalize('NFKC');
133
+ if (segments.length === 1 && normalized.length > limit) {
134
+ return [
135
+ { text: normalized.slice(0, limit / 2), cutStart: false, cutEnd: true },
136
+ { text: normalized.slice(-limit / 2), cutStart: true, cutEnd: false },
137
+ ];
138
+ }
139
+ const maxChars = limit / segments.length;
140
+ const isTail = index > 0;
141
+ return [{
142
+ // Preserve the real prompt end when normalization expands the tail window.
143
+ text: isTail ? normalized.slice(-maxChars) : normalized.slice(0, maxChars),
144
+ cutStart: isTail,
145
+ cutEnd: !isTail && (normalized.length > maxChars || segments.length > 1),
146
+ }];
147
+ }).filter((segment) => NON_SPACE_SCRIPT.test(segment.text));
148
+ }
149
+ function hasNonSpaceLetter(text) {
150
+ return Array.from(text).some((character) => NON_SPACE_SCRIPT.test(character) && /\p{L}/u.test(character));
151
+ }
152
+ function containsNonSpaceLiteral(segments, alias) {
153
+ const literal = alias.toLowerCase().normalize('NFKC');
154
+ if (!NON_SPACE_SCRIPT.test(literal))
155
+ return false;
156
+ // Script_Extensions also includes shared punctuation and combining marks, which are not useful signals alone.
157
+ if (!hasNonSpaceLetter(literal) || /^\p{M}/u.test(literal))
158
+ return false;
159
+ const characters = Array.from(literal);
160
+ const runs = literal.match(/[\p{L}\p{N}\p{M}]+/gu) ?? [];
161
+ if (runs.length > PROMPT_RECALL_SIGNAL_ALIAS_TOKENS
162
+ || runs.some((run) => run.length > PROMPT_RECALL_TOKEN_CHARS))
163
+ return false;
164
+ const needsBoundary = (character) => /[\p{L}\p{N}\p{M}]/u.test(character)
165
+ && !NON_SPACE_SCRIPT.test(character);
166
+ const leftBoundary = needsBoundary(characters[0]);
167
+ const rightBoundary = needsBoundary(characters.at(-1));
168
+ for (const { text, cutStart, cutEnd } of segments) {
169
+ for (let at = text.indexOf(literal); at !== -1; at = text.indexOf(literal, at + 1)) {
170
+ if ((at === 0 && cutStart) || (at + literal.length === text.length && cutEnd))
171
+ continue;
172
+ const before = Array.from(text.slice(Math.max(0, at - 2), at)).at(-1) ?? '';
173
+ const after = String.fromCodePoint(text.codePointAt(at + literal.length) ?? 0);
174
+ // Mixed aliases retain Latin word boundaries; a Thai/Kana combining mark must not be cut off.
175
+ if ((!leftBoundary || !needsBoundary(before))
176
+ && (!rightBoundary || !needsBoundary(after)) && !/\p{M}/u.test(after))
177
+ return true;
178
+ }
179
+ }
180
+ return false;
181
+ }
182
+ function buildPromptSequenceIndex(segments) {
183
+ const root = { children: new Map() };
184
+ for (const tokens of segments) {
185
+ for (let start = 0; start < tokens.length; start += 1) {
186
+ let node = root;
187
+ const end = Math.min(tokens.length, start + PROMPT_RECALL_SIGNAL_ALIAS_TOKENS);
188
+ for (let offset = start; offset < end; offset += 1) {
189
+ const token = tokens[offset];
190
+ let child = node.children.get(token);
191
+ if (!child) {
192
+ child = { children: new Map() };
193
+ node.children.set(token, child);
194
+ }
195
+ node = child;
196
+ }
197
+ }
198
+ }
199
+ return root;
200
+ }
201
+ function containsSequence(index, needle) {
202
+ if (needle.length === 0)
203
+ return false;
204
+ let node = index;
205
+ for (const token of needle) {
206
+ const child = node.children.get(token);
207
+ if (!child)
208
+ return false;
209
+ node = child;
210
+ }
211
+ return true;
212
+ }
213
+ function boundedSignalPatterns(gene) {
214
+ const patterns = Array.isArray(gene['signals_match']) ? gene['signals_match'] : [];
215
+ return patterns
216
+ .slice(0, PROMPT_RECALL_SIGNAL_PATTERNS)
217
+ .filter((pattern) => (typeof pattern === 'string' && pattern.length <= PROMPT_RECALL_SIGNAL_PATTERN_CHARS));
218
+ }
219
+ /**
220
+ * V1 required a real local signals_match hit before prompt-time injection. Keep that conservative gate: aliases
221
+ * separated by `|` are matched as normalized token sequences, with bounded literal matching for scripts that
222
+ * do not require spaces between words. Regex-looking patterns are never evaluated
223
+ * (a persisted pattern must not be able to run an expensive regular expression on a private prompt).
224
+ */
225
+ function literalSignalHits(promptIndex, patterns, literalSegments) {
226
+ let hits = 0;
227
+ for (const pattern of patterns) {
228
+ const aliases = pattern.split('|', PROMPT_RECALL_SIGNAL_ALIASES + 1).slice(0, PROMPT_RECALL_SIGNAL_ALIASES);
229
+ const matched = aliases.some((alias) => {
230
+ const trimmed = alias.trim();
231
+ if (!trimmed
232
+ || trimmed.length > PROMPT_RECALL_SIGNAL_ALIAS_CHARS
233
+ || (trimmed.startsWith('/') && trimmed.lastIndexOf('/') > 0))
234
+ return false;
235
+ return containsSequence(promptIndex, normalizedAliasTokens(trimmed))
236
+ || (literalSegments.length > 0 && containsNonSpaceLiteral(literalSegments, trimmed));
237
+ });
238
+ if (matched)
239
+ hits += 1;
240
+ }
241
+ return hits;
242
+ }
243
+ function boundedGeneField(value) {
244
+ return typeof value === 'string' ? value.slice(0, PROMPT_RECALL_GENE_FIELD_CHARS) : undefined;
245
+ }
246
+ function geneText(gene, signalsMatch) {
247
+ return [boundedGeneField(gene['id']), boundedGeneField(gene['category']), boundedGeneField(gene['summary']), ...signalsMatch]
248
+ .filter((value) => typeof value === 'string')
249
+ .join(' ');
250
+ }
251
+ function selectionExpired(budget) {
252
+ return budget.cancelled || performance.now() >= budget.deadlineMs;
253
+ }
254
+ function yieldToEventLoop() {
255
+ return new Promise((resolve) => setImmediate(resolve));
256
+ }
257
+ async function selectPromptGenes(prompt, snapshot, maxGenes, budget, benchmark) {
258
+ const tokenSegments = promptTokenSegments(prompt);
259
+ const promptTokens = tokenSegments.flat();
260
+ const literalSegments = promptLiteralSegments(prompt);
261
+ if (promptTokens.length === 0 && literalSegments.length === 0)
262
+ return [];
263
+ const promptIndex = buildPromptSequenceIndex(tokenSegments);
264
+ const boundedPrompt = promptTokens.join(' ');
265
+ const receipts = new Map();
266
+ const approved = recall.approvedGenesFromSnapshot(snapshot, PROMPT_RECALL_SCAN_LIMIT, {
267
+ signal: budget.signal, deadlineAt: budget.deadlineAt,
268
+ ...(benchmark ? { benchmark } : {}),
269
+ onQualification: (values) => { for (const receipt of values)
270
+ receipts.set(receipt.assetId, receipt); },
271
+ });
272
+ if (selectionExpired(budget))
273
+ return [];
274
+ const ranked = [];
275
+ for (let index = 0; index < approved.length; index += 1) {
276
+ if (selectionExpired(budget))
277
+ return [];
278
+ const gene = approved[index];
279
+ const signalsMatch = boundedSignalPatterns(gene);
280
+ const literalHits = literalSignalHits(promptIndex, signalsMatch, literalSegments);
281
+ if (literalHits > 0) {
282
+ const semanticScore = recall.tagOverlapScore(promptTokens, {
283
+ signalsMatch,
284
+ geneId: boundedGeneField(gene['id']),
285
+ category: boundedGeneField(gene['category']),
286
+ summary: boundedGeneField(gene['summary']),
287
+ }) + recall.bagCosine(boundedPrompt, geneText(gene, signalsMatch));
288
+ ranked.push({
289
+ gene,
290
+ literalHits,
291
+ semanticScore,
292
+ assetKey: String(gene.asset_id).slice(0, 128),
293
+ ...(receipts.has(gene.asset_id) ? { sourceQualification: receipts.get(gene.asset_id) } : {}),
294
+ });
295
+ }
296
+ if ((index + 1) % PROMPT_RECALL_YIELD_EVERY_GENES === 0) {
297
+ await yieldToEventLoop();
298
+ if (selectionExpired(budget))
299
+ return [];
300
+ }
301
+ }
302
+ if (selectionExpired(budget))
303
+ return [];
304
+ ranked.sort((left, right) => (right.literalHits - left.literalHits
305
+ || right.semanticScore - left.semanticScore
306
+ || left.assetKey.localeCompare(right.assetKey)));
307
+ return ranked.slice(0, benchmark ? Math.min(maxGenes, 8) : maxGenes);
308
+ }
309
+ function renderGeneLine(gene) {
310
+ // Every metadata field belongs to this single bullet, including line breaks
311
+ // carried by logical ids/categories. Redact the final normalized sequence.
312
+ const singleLine = (value, limit) => value.slice(0, limit).replace(/\s+/g, ' ').trim();
313
+ const id = singleLine(typeof gene['id'] === 'string' ? gene['id'] : String(gene.asset_id), 128);
314
+ const category = typeof gene['category'] === 'string' ? singleLine(gene['category'], 96) : '';
315
+ const summary = typeof gene['summary'] === 'string'
316
+ ? singleLine(gene['summary'], PROMPT_RECALL_GENE_FIELD_CHARS)
317
+ : '';
318
+ return recall.redactString(`- ${id}${category ? ` [${category}]` : ''}${summary ? `: ${summary.slice(0, 240)}` : ''}`);
319
+ }
320
+ function renderPromptRecallContext(genes) {
321
+ const header = '[Evolver memory - relevant prior capability]';
322
+ const footer = 'Use only when directly relevant. Adapt and verify before applying; do not mention this memory block unless asked or materially relevant.';
323
+ const lines = [header];
324
+ const rendered = [];
325
+ for (const ranked of genes) {
326
+ const { gene } = ranked;
327
+ const line = renderGeneLine(gene);
328
+ if ([...lines, line, footer].join('\n').length > PROMPT_RECALL_CONTEXT_MAX_CHARS)
329
+ break;
330
+ lines.push(line);
331
+ rendered.push(ranked);
332
+ }
333
+ if (lines.length === 1)
334
+ return { text: '', genes: [] };
335
+ lines.push(footer);
336
+ return { text: lines.join('\n'), genes: rendered };
337
+ }
338
+ function boundedAuditString(value) {
339
+ if (typeof value !== 'string')
340
+ return undefined;
341
+ const trimmed = value.trim();
342
+ return trimmed ? trimmed.slice(0, 256) : undefined;
343
+ }
344
+ /** Optional correlation metadata must retain its original identity or be omitted.
345
+ * Redacted/truncated values are not new session, source or chain identities.
346
+ */
347
+ function safeAuditIdentity(value) {
348
+ const bounded = boundedAuditString(value);
349
+ if (!bounded || typeof value !== 'string' || bounded !== value.trim()
350
+ || recall.redactString(bounded) !== bounded)
351
+ return undefined;
352
+ if (Array.from(bounded).some(character => {
353
+ const point = character.codePointAt(0);
354
+ return point < 32 || (point >= 127 && point <= 159)
355
+ || (point >= 0x202a && point <= 0x202e) || (point >= 0x2066 && point <= 0x2069);
356
+ }))
357
+ return undefined;
358
+ return bounded;
359
+ }
360
+ async function logPromptRecallSelections(genes, mode, sessionId, env, deadlineAt, injectedLog) {
361
+ if (genes.length === 0)
362
+ return;
363
+ const callLog = injectedLog ?? new recall.AssetCallLog(recall.assetCallLogPath(env));
364
+ const safeSessionId = safeAuditIdentity(sessionId);
365
+ const runId = safeSessionId ? `recall:${safeSessionId}` : boundedAuditString(sessionId) ? undefined : 'recall:unknown';
366
+ for (const ranked of genes) {
367
+ const sourceNodeId = safeAuditIdentity(ranked.gene['source_node_id'] ?? ranked.gene['author_node_id']);
368
+ const chainId = safeAuditIdentity(ranked.gene['chain_id']);
369
+ try {
370
+ if (Date.now() >= deadlineAt)
371
+ return;
372
+ const entry = {
373
+ ...(runId ? { run_id: runId } : {}),
374
+ action: mode === 'enforce' ? 'asset_inject' : 'asset_inject_shadow',
375
+ asset_id: ranked.assetKey,
376
+ asset_type: 'Gene',
377
+ ...(sourceNodeId ? { source_node_id: sourceNodeId } : {}),
378
+ ...(chainId ? { chain_id: chainId } : {}),
379
+ score: ranked.semanticScore,
380
+ reason: 'local_gene_pattern_hit',
381
+ extra: {
382
+ via: 'prompt_recall',
383
+ attribution: 'correlational_local',
384
+ origin: 'local',
385
+ literal_hits: ranked.literalHits,
386
+ ...(ranked.sourceQualification ? recall.compactQualificationReceipts([ranked.sourceQualification]) : {}),
387
+ },
388
+ };
389
+ if (callLog.appendBounded)
390
+ await callLog.appendBounded(entry, { deadlineAt });
391
+ else
392
+ callLog.append(entry); // explicit legacy injection only; production never takes this synchronous path
393
+ }
394
+ catch { /* local attribution must never block prompt submission */ }
395
+ }
396
+ }
397
+ async function withSelectionBudget(timeoutMs, fallback, run) {
398
+ const boundedTimeoutMs = Number.isFinite(timeoutMs) ? Math.max(0, timeoutMs) : PROMPT_RECALL_SELECTION_TIMEOUT_MS;
399
+ const controller = new AbortController();
400
+ const budget = {
401
+ deadlineMs: performance.now() + boundedTimeoutMs,
402
+ deadlineAt: Date.now() + boundedTimeoutMs,
403
+ signal: controller.signal,
404
+ cancelled: false,
405
+ reads: new Set(),
406
+ };
407
+ let timer;
408
+ try {
409
+ return await Promise.race([
410
+ Promise.resolve().then(() => {
411
+ if (selectionExpired(budget) || Date.now() >= budget.deadlineAt) {
412
+ budget.cancelled = true;
413
+ controller.abort();
414
+ return fallback;
415
+ }
416
+ return run(budget);
417
+ }),
418
+ new Promise((resolve) => {
419
+ timer = setTimeout(() => {
420
+ budget.cancelled = true;
421
+ controller.abort();
422
+ resolve(fallback);
423
+ }, boundedTimeoutMs);
424
+ }),
425
+ ]);
426
+ }
427
+ finally {
428
+ if (timer)
429
+ clearTimeout(timer);
430
+ controller.abort();
431
+ // A timed-out injected provider must become terminal before the hook
432
+ // returns. A signal merely requests cancellation; it is not proof.
433
+ if (budget.cancelled && budget.reads.size > 0) {
434
+ await Promise.all([...budget.reads].map(read => read.cancelAndSettle()));
435
+ }
436
+ }
437
+ }
438
+ async function ownPromptRead(budget, store, begin) {
439
+ // Own admission before invoking an injected adapter. A thrown begin() may
440
+ // already have dispatched work, so without an operation receipt its slot
441
+ // cannot be released safely.
442
+ const release = recall.acquireContextRead(store);
443
+ let begun = false;
444
+ let terminal = false;
445
+ let operation;
446
+ let owner;
447
+ try {
448
+ begun = true;
449
+ operation = begin();
450
+ if (operation?.version !== 1 || !operation.result || typeof operation.result.then !== 'function'
451
+ || typeof operation.cancelAndSettle !== 'function')
452
+ throw new Error('invalid_context_read_operation_v1');
453
+ let settlement;
454
+ owner = { cancelAndSettle: () => settlement ??= Promise.resolve().then(() => operation.cancelAndSettle()) };
455
+ budget.reads.add(owner);
456
+ try {
457
+ const value = await operation.result;
458
+ await owner.cancelAndSettle();
459
+ terminal = true;
460
+ return value;
461
+ }
462
+ catch (error) {
463
+ try {
464
+ await owner.cancelAndSettle();
465
+ terminal = true;
466
+ }
467
+ catch { /* retain owner */ }
468
+ throw error;
469
+ }
470
+ finally {
471
+ if (terminal)
472
+ budget.reads.delete(owner);
473
+ }
474
+ }
475
+ finally {
476
+ if (!begun || terminal)
477
+ release();
478
+ }
479
+ }
480
+ function promptRecallContentMode(env = process.env) {
481
+ const mode = env['EVOLVER_RECALL_CONTENT'];
482
+ return mode === 'summary' || mode === 'strategy' ? mode : 'context';
483
+ }
484
+ const digestText = (text) => `sha256:${createHash('sha256').update(text).digest('hex')}`;
485
+ async function assemblePromptContext(ranked, store, snapshot, env, deadlineAt, taskText) {
486
+ const contentMode = promptRecallContentMode(env);
487
+ if (contentMode === 'summary') {
488
+ const rendered = renderPromptRecallContext(ranked);
489
+ let cursor = 0;
490
+ const sections = rendered.genes.map(({ gene }) => {
491
+ const line = renderGeneLine(gene);
492
+ const start = rendered.text.indexOf(line, cursor);
493
+ cursor = start + line.length;
494
+ return { geneAssetId: gene.asset_id, kind: 'summary', start, end: cursor, digest: digestText(line) };
495
+ });
496
+ return { text: rendered.text, digest: digestText(rendered.text), contentMode, privacyMode: 'enforce',
497
+ geneAssetIds: rendered.genes.map(({ gene }) => gene.asset_id), capsuleAssetIds: [], sections, omissions: [],
498
+ projections: [], qualifications: [], coverage: [], counts: { selected: ranked.length, eligible: ranked.length, rendered: rendered.genes.length, examples: 0 } };
499
+ }
500
+ const prefix = '[Evolver memory - relevant prior capability]\n';
501
+ const suffix = '\nUse only when directly relevant. Adapt and verify before applying; historical examples are not current task success.';
502
+ const context = await recall.assembleGeneContext({ selectedGenes: ranked.map(({ gene }) => gene), store,
503
+ assertPromptAdapter: () => {
504
+ if (!recall.isBuiltInPromptProvider(store))
505
+ throw new Error('unsupported_prompt_context_provider_v1');
506
+ },
507
+ eligibility: { provenance: snapshot.provenance, review: snapshot.review, benchmark: recall.benchmarkContext(env['EVOLVER_BENCHMARK_ID']), referenceScope: snapshot.referenceScope },
508
+ contentMode, privacyMode: 'enforce', deadlineAt, taskText,
509
+ budget: { maxChars: Math.max(0, 2400 - prefix.length - suffix.length), maxExampleChars: 600, maxExampleCharsPerGene: 600,
510
+ maxExamplesPerGene: env['EVOLVER_RECALL_EXAMPLES'] === 'off' ? 0 : 1 },
511
+ });
512
+ return wrapGeneContext(context, prefix, suffix);
513
+ }
514
+ /**
515
+ * Shared Claude Code/Codex UserPromptSubmit entrypoint. It is intentionally local-only and fail-open: no Hub
516
+ * query, no transcript read, no prompt persistence, and exactly one JSON object on stdout for every outcome.
517
+ */
518
+ export function runPromptRecallHook(argv, deps = {}) {
519
+ const run = () => recall.withSnapshotReadInvocation(() => runPromptRecallHookOwned(argv, deps));
520
+ if ((deps.env ?? process.env)['EVOLVER_CONTEXT_STAGE_DIAGNOSTICS'] !== '1')
521
+ return run();
522
+ return recall.withContextReadDiagnostics(true, run, writeContextReadDiagnostic);
523
+ }
524
+ async function runPromptRecallHookOwned(argv, deps) {
525
+ const write = deps.stdout ?? writeHookStdout;
526
+ let output = {};
527
+ let pending;
528
+ const env = deps.env ?? process.env;
529
+ const mode = promptRecallMode(env);
530
+ // Privacy invariant from V1: default-off does not even read the prompt-bearing stdin payload.
531
+ if (mode === 'off' || !argv.includes('--hook-stdin')) {
532
+ try {
533
+ await write('{}\n');
534
+ }
535
+ catch { /* one write attempt, never retry EPIPE */ }
536
+ return 0;
537
+ }
538
+ try {
539
+ const raw = await readHookPayload(deps.readHookInput);
540
+ if (!raw?.trim())
541
+ throw new Error('empty hook payload');
542
+ const input = JSON.parse(raw);
543
+ if (typeof input.hook_event_name === 'string' && input.hook_event_name !== 'UserPromptSubmit') {
544
+ throw new Error('unexpected hook event');
545
+ }
546
+ const prompt = input.prompt;
547
+ if (typeof prompt !== 'string')
548
+ throw new Error('prompt is not recallable');
549
+ const trimmedPrompt = prompt.trim();
550
+ if (trimmedPrompt.length < 8) {
551
+ const normalizedPrompt = trimmedPrompt.toLowerCase().normalize('NFKC');
552
+ if (!hasNonSpaceLetter(normalizedPrompt)
553
+ || (normalizedPrompt.match(/[\p{L}\p{N}]/gu)?.length ?? 0) < 2) {
554
+ throw new Error('prompt is not recallable');
555
+ }
556
+ }
557
+ // The default prompt path constructs no writable store/ledger: all authority,
558
+ // reference and trust reads happen asynchronously inside the one selection budget.
559
+ const store = deps.store ?? new recall.ForeignJsonlSource(recall.assetsDir(env));
560
+ if (!recall.isBuiltInPromptProvider(store))
561
+ throw new Error('unsupported_prompt_context_provider_v1');
562
+ const timeoutMs = deps.selectionTimeoutMs ?? PROMPT_RECALL_SELECTION_TIMEOUT_MS;
563
+ const outerDeadline = performance.now() + Math.max(0, Number.isFinite(timeoutMs) ? timeoutMs : PROMPT_RECALL_SELECTION_TIMEOUT_MS);
564
+ let snapshot;
565
+ const ranked = await recall.measureContextReadStage('prompt_selection', () => withSelectionBudget(timeoutMs, [], async (budget) => {
566
+ {
567
+ snapshot = await ownPromptRead(budget, store, () => {
568
+ if (!recall.isBuiltInPromptProvider(store))
569
+ throw new Error('unsupported_prompt_context_provider_v1');
570
+ return store.beginPromptGeneSnapshotV1({
571
+ deadlineAt: budget.deadlineAt, signal: budget.signal,
572
+ maxFileBytes: MAX_PROMPT_RECALL_LOCAL_FILE_BYTES, maxTotalBytes: MAX_PROMPT_RECALL_LOCAL_TOTAL_BYTES
573
+ });
574
+ });
575
+ if (selectionExpired(budget))
576
+ return [];
577
+ // Explicit dependencies remain authoritative for embedders/tests. Production
578
+ // never constructs these synchronous ledger APIs on the prompt path.
579
+ if (deps.review)
580
+ snapshot = { ...snapshot, review: deps.review.snapshot() };
581
+ if (deps.provenance)
582
+ snapshot = { ...snapshot, provenance: deps.provenance.snapshot() };
583
+ }
584
+ return selectPromptGenes(prompt, snapshot, promptRecallMaxGenes(env), budget, recall.benchmarkContext(env['EVOLVER_BENCHMARK_ID']));
585
+ }));
586
+ try {
587
+ if (ranked.length > 0 && snapshot) {
588
+ // Convert the remaining monotonic budget to core's epoch deadline; never mix the two clocks.
589
+ const context = await recall.measureContextReadStage('prompt_assembly', () => assemblePromptContext(ranked, store, snapshot, env, Date.now() + Math.max(0, outerDeadline - performance.now()), prompt));
590
+ if (context.text)
591
+ pending = { context, genes: ranked.filter(({ gene }) => context.geneAssetIds.includes(gene.asset_id)), sessionId: input.session_id, referenceScope: snapshot.referenceScope };
592
+ if (mode === 'enforce' && context.text) {
593
+ output = { hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: context.text } };
594
+ }
595
+ }
596
+ }
597
+ finally {
598
+ if (snapshot) {
599
+ // Recovery owns a separate audit budget. Drain before new admission, even
600
+ // without context, without spending the selection/Capsule assembly deadline.
601
+ const scope = snapshot.referenceScope;
602
+ const recover = Promise.resolve().then(() => deps.ingestor
603
+ ? deps.ingestor.recoverContextDeliveries?.({ deadlineAt: Date.now() + 100 })
604
+ : recall.Ingestor.recoverContextDeliveries({ path: recall.rootEventsPath(env), referenceScope: scope, deadlineAt: Date.now() + 100 }));
605
+ await waitContextDelivery(recover.catch(() => undefined), 120);
606
+ }
607
+ }
608
+ }
609
+ catch {
610
+ output = {};
611
+ pending = undefined;
612
+ }
613
+ if (pending && mode === 'enforce') {
614
+ const selected = pending;
615
+ const sessionId = safeAuditIdentity(selected.sessionId);
616
+ const event = { type: recall.GENE_CONTEXT_DELIVERY_EVENT, human: { title: 'Gene context stdout written' },
617
+ payload: { receipt: recall.geneContextDeliveryReceipt(selected.context), entrypoint: 'prompt_recall',
618
+ transport: 'stdout_written', hostReceived: 'unknown', ...(sessionId ? { sessionId } : {}) } };
619
+ const prepare = deps.ingestor ? ((options) => {
620
+ if (typeof deps.ingestor?.prepareContextDeliveryAsync === 'function')
621
+ return deps.ingestor.prepareContextDeliveryAsync(event, options);
622
+ if (!deps.ingestor?.prepareContextDelivery)
623
+ throw new Error('unsupported_context_delivery_sink_v1');
624
+ return deps.ingestor.prepareContextDelivery(event, options);
625
+ })
626
+ : (options) => recall.Ingestor.prepareContextDeliveryAsync(event, { ...options, path: recall.rootEventsPath(env), referenceScope: selected.referenceScope });
627
+ const result = await deliverContextOutput({ text: `${JSON.stringify(output)}\n`,
628
+ prepare, ...(deps.stdout ? { stdout: deps.stdout } : {}),
629
+ ...(deps.stdoutWithSettlement ? { stdoutWithSettlement: deps.stdoutWithSettlement } : {}),
630
+ ...(deps.onOutputWritten ? { onOutputWritten: deps.onOutputWritten } : {}) });
631
+ if (result === 'prepare_failed') {
632
+ try {
633
+ await write('{}\n');
634
+ }
635
+ catch { /* One fallback; no context was dispatched. */ }
636
+ return 0;
637
+ }
638
+ if (result === 'written')
639
+ await logPromptRecallSelections(selected.genes, mode, selected.sessionId, env, Date.now() + 150, deps.callLog);
640
+ return 0;
641
+ }
642
+ try {
643
+ await write(`${JSON.stringify(output)}\n`);
644
+ }
645
+ catch {
646
+ return 0;
647
+ }
648
+ try {
649
+ deps.onOutputWritten?.();
650
+ }
651
+ catch { /* An observer cannot invalidate confirmed stdout. */ }
652
+ if (pending) {
653
+ // Shadow is an advisory would-render event, never a prepared stdout-written receipt.
654
+ await logPromptRecallSelections(pending.genes, mode, pending.sessionId, env, Date.now() + 150, deps.callLog);
655
+ try {
656
+ const sessionId = safeAuditIdentity(pending.sessionId);
657
+ const event = { type: recall.GENE_CONTEXT_DELIVERY_EVENT,
658
+ human: { title: mode === 'shadow' ? 'Gene context would render' : 'Gene context stdout written' },
659
+ payload: { receipt: recall.geneContextDeliveryReceipt(pending.context), entrypoint: 'prompt_recall',
660
+ transport: mode === 'shadow' ? 'would_render' : 'stdout_written', hostReceived: 'unknown',
661
+ ...(sessionId ? { sessionId } : {}) } };
662
+ if (recall.fitsRootEventLine(event)) {
663
+ // Only the known local Ingestor has the bounded audit writer. A caller-supplied
664
+ // Promise-only sink has no terminal ownership proof and is never dispatched.
665
+ if (!deps.ingestor)
666
+ await recall.Ingestor.ingestBoundedReceipt(event, { path: recall.rootEventsPath(env),
667
+ referenceScope: pending.referenceScope, deadlineAt: Date.now() + 200 });
668
+ else if (deps.ingestor instanceof recall.Ingestor
669
+ && Object.getPrototypeOf(deps.ingestor) === recall.Ingestor.prototype
670
+ && deps.ingestor.ingestBoundedReceipt === recall.Ingestor.prototype.ingestBoundedReceipt) {
671
+ await deps.ingestor.ingestBoundedReceipt(event, { deadlineAt: Date.now() + 200 });
672
+ }
673
+ }
674
+ }
675
+ catch { /* audit failure cannot block user submission */ }
676
+ }
677
+ return 0;
678
+ }