@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,18 @@
1
+ import type * as assetstore from '@evomap/evolver-core/prompt-recall';
2
+ export type PromptRecallMode = 'off' | 'shadow' | 'enforce';
3
+ /** Reject oversized prompt payloads rather than retaining partial private JSON. */
4
+ export declare const MAX_PROMPT_RECALL_STDIN_BYTES: number;
5
+ export declare const MAX_PROMPT_RECALL_LOCAL_FILE_BYTES: number;
6
+ export declare const MAX_PROMPT_RECALL_LOCAL_TOTAL_BYTES: number;
7
+ /** Called after hook settlement; diagnostics cannot spend the admission budget. */
8
+ export declare function writeContextReadDiagnostic(report: assetstore.ContextReadDiagnosticReport): void;
9
+ /** Bound caller latency while the original continuation retains actual operation ownership. */
10
+ export declare function waitContextDelivery<T>(promise: Promise<T>, timeoutMs?: number): Promise<T | undefined>;
11
+ export declare function promptRecallMode(env?: NodeJS.ProcessEnv): PromptRecallMode;
12
+ /** Rebind section offsets/digest to the actual prompt, including wrappers; never slice an assembled body. */
13
+ export declare function wrapGeneContext(context: assetstore.AssembledGeneContext, prefix: string, suffix: string): assetstore.AssembledGeneContext;
14
+ /** A successful callback means stdout_written, not host_received. One attempt only, even on EPIPE. */
15
+ export declare function writeHookStdout(text: string, options?: {
16
+ destroyOnTimeout?: boolean;
17
+ onSettled?: (written: boolean) => void;
18
+ }): Promise<void>;
@@ -0,0 +1,119 @@
1
+ import { createHash } from 'node:crypto';
2
+ /** Reject oversized prompt payloads rather than retaining partial private JSON. */
3
+ export const MAX_PROMPT_RECALL_STDIN_BYTES = 64 * 1024;
4
+ export const MAX_PROMPT_RECALL_LOCAL_FILE_BYTES = 4 * 1024 * 1024;
5
+ export const MAX_PROMPT_RECALL_LOCAL_TOTAL_BYTES = 8 * 1024 * 1024;
6
+ /** Called after hook settlement; diagnostics cannot spend the admission budget. */
7
+ export function writeContextReadDiagnostic(report) {
8
+ const stream = process.stderr;
9
+ const line = `context-read-stage-diagnostic ${JSON.stringify(report)}\n`;
10
+ if (Buffer.byteLength(line) > 2048)
11
+ return;
12
+ const ignoreError = () => undefined;
13
+ stream.once('error', ignoreError);
14
+ try {
15
+ stream.write(line, error => {
16
+ if (!error)
17
+ stream.removeListener('error', ignoreError);
18
+ });
19
+ }
20
+ catch {
21
+ stream.removeListener('error', ignoreError);
22
+ }
23
+ }
24
+ /** Bound caller latency while the original continuation retains actual operation ownership. */
25
+ export async function waitContextDelivery(promise, timeoutMs = 220) {
26
+ let timer;
27
+ try {
28
+ return await Promise.race([promise, new Promise(resolve => { timer = setTimeout(() => resolve(undefined), timeoutMs); })]);
29
+ }
30
+ finally {
31
+ if (timer)
32
+ clearTimeout(timer);
33
+ }
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
+ const digestText = (text) => `sha256:${createHash('sha256').update(text).digest('hex')}`;
40
+ /** Rebind section offsets/digest to the actual prompt, including wrappers; never slice an assembled body. */
41
+ export function wrapGeneContext(context, prefix, suffix) {
42
+ if (!context.text)
43
+ return context;
44
+ const text = prefix + context.text + suffix;
45
+ return { ...context, text, digest: digestText(text), sections: context.sections.map((s) => ({ ...s, start: s.start + prefix.length, end: s.end + prefix.length })) };
46
+ }
47
+ // One submitted write owns the stream until callback/close, including after
48
+ // caller timeout. Refuse retries instead of accumulating listeners and queued bytes.
49
+ const pendingStdoutWrites = new WeakMap();
50
+ /** A successful callback means stdout_written, not host_received. One attempt only, even on EPIPE. */
51
+ export function writeHookStdout(text, options = {}) {
52
+ return new Promise((resolve, reject) => {
53
+ const stdout = process.stdout;
54
+ if (pendingStdoutWrites.has(stdout)) {
55
+ options.onSettled?.(false);
56
+ reject(new Error('hook_stdout_unconfirmed'));
57
+ return;
58
+ }
59
+ const owner = {};
60
+ pendingStdoutWrites.set(stdout, owner);
61
+ let settled = false;
62
+ let actualSettled = false;
63
+ const actual = (written) => {
64
+ if (actualSettled)
65
+ return;
66
+ actualSettled = true;
67
+ try {
68
+ options.onSettled?.(written);
69
+ }
70
+ catch { /* Callback owns its durable retry, never the stream. */ }
71
+ };
72
+ const release = () => {
73
+ stdout.removeListener('error', onError);
74
+ stdout.removeListener('close', onClose);
75
+ if (pendingStdoutWrites.get(stdout) === owner)
76
+ pendingStdoutWrites.delete(stdout);
77
+ };
78
+ const onClose = () => { actual(false); finish(new Error('hook_stdout_unconfirmed')); release(); };
79
+ const finish = (error) => {
80
+ if (settled)
81
+ return;
82
+ settled = true;
83
+ clearTimeout(timer);
84
+ if (error)
85
+ reject(error);
86
+ else
87
+ resolve();
88
+ };
89
+ // Timeout settles the caller, not the submitted stream write. Own its late error
90
+ // until callback/close, even when library code cannot destroy shared stdout.
91
+ // A shared stream may emit an error independently of this write's callback;
92
+ // the event rejects our caller but is not evidence that queued bytes settled.
93
+ const onError = (error) => { finish(error); };
94
+ const written = (error) => {
95
+ actual(!error);
96
+ finish(error);
97
+ // Writable emits error after its failed callback, before the next immediate.
98
+ if (error)
99
+ setImmediate(release);
100
+ else
101
+ release();
102
+ };
103
+ const timer = setTimeout(() => {
104
+ // Only the disposable executable owns the process-wide stream. A library
105
+ // call cannot destroy stdout used by other requests or embedding code.
106
+ if (options.destroyOnTimeout)
107
+ stdout.destroy();
108
+ finish(new Error('hook_stdout_unconfirmed'));
109
+ }, 1000);
110
+ stdout.on('error', onError);
111
+ stdout.once('close', onClose);
112
+ try {
113
+ stdout.write(text, written);
114
+ }
115
+ catch (error) {
116
+ written(error instanceof Error ? error : new Error('hook_stdout_failed'));
117
+ }
118
+ });
119
+ }
package/dist/recall.js CHANGED
@@ -23,6 +23,13 @@ export function pickInjectEvent(evts, sessionId) {
23
23
  let bestMatch;
24
24
  let bestAny;
25
25
  for (const e of evts) {
26
+ if (e.type === ops.GENE_CONTEXT_DELIVERY_EVENT) {
27
+ // New receipts must be session-matched. Never fall back to another session or consume shadow attempts.
28
+ if (sessionId !== undefined && e.payload?.['sessionId'] === sessionId && e.payload['transport'] === 'stdout_written'
29
+ && ops.readGeneContextDeliveryReceipt(e.payload['receipt']) && (bestMatch === undefined || e.seq > bestMatch.seq))
30
+ bestMatch = e;
31
+ continue;
32
+ }
26
33
  if (e.type !== ops.VALUE_INJECT_EVENT)
27
34
  continue;
28
35
  if (bestAny === undefined || e.seq > bestAny.seq)
@@ -33,6 +40,8 @@ export function pickInjectEvent(evts, sessionId) {
33
40
  return bestMatch ?? bestAny;
34
41
  }
35
42
  export function geneIdsOf(e) {
43
+ if (e?.type === ops.GENE_CONTEXT_DELIVERY_EVENT)
44
+ return ops.readGeneContextDeliveryReceipt(e.payload?.['receipt'])?.geneAssetIds ?? [];
36
45
  const ids = e?.payload?.['geneIds'];
37
46
  return Array.isArray(ids) ? ids.filter((x) => typeof x === 'string') : [];
38
47
  }
@@ -45,6 +54,10 @@ export function geneFromAsset(a) {
45
54
  }
46
55
  /** 仅来源资格事件中的实际 canonical 引用保留版本身份,历史和独立手动参数仍按 logical ID 归因。 */
47
56
  export function geneFromRecallSelection(asset, requestedId, inject) {
57
+ if (inject?.type === ops.GENE_CONTEXT_DELIVERY_EVENT) {
58
+ // A content digest without a trusted turn boundary cannot establish use of this delivery.
59
+ return asset.asset_id === requestedId && geneIdsOf(inject).includes(requestedId) ? { geneId: requestedId } : null;
60
+ }
48
61
  const canonicalReference = inject?.payload?.['sourceQualificationSchema'] === 'benchmark-source-references.v1'
49
62
  && geneIdsOf(inject).includes(requestedId);
50
63
  if (!canonicalReference)
@@ -95,6 +108,7 @@ export async function runRecall(argv, deps = {}) {
95
108
  const err = deps.err ?? ((s) => process.stderr.write(`${s}\n`));
96
109
  const { transcript, geneIds, fromInject } = parseArgs(argv);
97
110
  let selectedInject;
111
+ const injectedIds = new Set();
98
112
  // --from-inject: pull the geneIds off the most recent value.inject root_event so the operator does not have to
99
113
  // retype them (a semi-automatic step toward the auto-loop, which still needs the inject<->session key #205 to
100
114
  // pick the RIGHT inject for THIS transcript). Union with any explicit --gene; dedupe preserving order.
@@ -120,9 +134,11 @@ export async function runRecall(argv, deps = {}) {
120
134
  // inject is stamped at all (the precise-match path is simply dormant — e.g. pre-#205 events).
121
135
  err(`recall: no value.inject matched session ${wantSession}; using the most recent inject instead`);
122
136
  }
123
- for (const id of fromEvent)
137
+ for (const id of fromEvent) {
138
+ injectedIds.add(id);
124
139
  if (!geneIds.includes(id))
125
140
  geneIds.push(id);
141
+ }
126
142
  }
127
143
  if (!transcript || geneIds.length === 0) {
128
144
  err('用法: evolver recall <session-transcript> (--gene <id> ... | --from-inject)');
@@ -148,25 +164,30 @@ export async function runRecall(argv, deps = {}) {
148
164
  // for "unrecognized format" — a transcript of pure heartbeats correctly yields 'unknown' per gene.
149
165
  const turns = parsed.filter((t) => !t.isMeta).map((t) => ({ role: t.role, text: t.text }));
150
166
  const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
151
- const genes = [];
167
+ const genes = new Map();
152
168
  for (const id of geneIds) {
153
169
  const a = await resolveGene(store, id);
154
170
  if (!a) {
155
171
  err(`recall: gene not found in local store: ${id}`);
156
172
  continue;
157
173
  }
158
- const gene = geneFromRecallSelection(a, id, selectedInject);
174
+ // Only identities actually supplied by the event inherit its receipt rules.
175
+ // Independent manual arguments retain legacy attribution; overlapping IDs
176
+ // still use the receipt and cannot turn delivered context into lexical proof.
177
+ const gene = geneFromRecallSelection(a, id, injectedIds.has(id) ? selectedInject : undefined);
159
178
  if (!gene) {
160
179
  err(`recall: injected gene identity mismatch: ${id}`);
161
180
  continue;
162
181
  }
163
- genes.push(gene);
182
+ // Event-bound attribution wins over a manual alias; Map preserves the first asset's position.
183
+ if (!genes.has(a.asset_id) || injectedIds.has(id))
184
+ genes.set(a.asset_id, gene);
164
185
  }
165
- if (genes.length === 0) {
186
+ if (genes.size === 0) {
166
187
  err('recall: no resolvable genes');
167
188
  return 1;
168
189
  }
169
- const results = ops.verifyInjectedGenes(genes, turns);
190
+ const results = ops.verifyInjectedGenes([...genes.values()], turns);
170
191
  const sum = ops.summarizeRecall(results);
171
192
  for (const r of results) {
172
193
  log(`${r.recalled.toUpperCase().padEnd(7)} ${r.geneId} score=${r.score.toFixed(2)} matched=[${r.matched.join(', ')}]`);
@@ -0,0 +1,9 @@
1
+ import { util } from '@evomap/evolver-core';
2
+ export interface IngestionTelemetry {
3
+ state: 'disabled' | 'unknown' | 'observed' | 'degraded';
4
+ lastTickAt?: number;
5
+ recorded?: number;
6
+ parseFailures?: number;
7
+ }
8
+ export declare function runtimeOwnerGeneration(owner: util.FileLockOwnerRecord): string;
9
+ export declare function autoexecHeartbeatTelemetry(owner: util.FileLockOwnerRecord, lastTickAt: number, lastTickOutcome: 'completed' | 'failed' | 'blocked', heartbeatIntervalMs: number, ingestion: IngestionTelemetry): Record<string, unknown>;
@@ -0,0 +1,16 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { util } from '@evomap/evolver-core';
3
+ export function runtimeOwnerGeneration(owner) {
4
+ return createHash('sha256').update(util.serializeFileLockOwnerRecord(owner)).digest('hex');
5
+ }
6
+ export function autoexecHeartbeatTelemetry(owner, lastTickAt, lastTickOutcome, heartbeatIntervalMs, ingestion) {
7
+ return {
8
+ pid: owner.pid,
9
+ generation: runtimeOwnerGeneration(owner),
10
+ processStartIdentity: owner.processStartIdentity,
11
+ lastTickAt,
12
+ lastTickOutcome,
13
+ ...(Number.isSafeInteger(heartbeatIntervalMs) && heartbeatIntervalMs >= 0 ? { heartbeatIntervalMs } : {}),
14
+ ingestion: { ...ingestion },
15
+ };
16
+ }
@@ -1,4 +1,4 @@
1
- import { events, material as materialNs } from '@evomap/evolver-core';
1
+ import { events, material as materialNs, ops } from '@evomap/evolver-core';
2
2
  import { type RuntimeSessionMaterialSnapshotV1 } from './materialSnapshot.js';
3
3
  import { type RuntimeSessionParseDiagnostics, type RuntimeSessionSource } from './runtimeSessionSource.js';
4
4
  /**
@@ -16,6 +16,14 @@ export interface IngestDeps {
16
16
  ingestor?: events.Ingestor;
17
17
  /** User home whose native runtime directories may contribute resumable session identities. */
18
18
  nativeSessionHome?: string;
19
+ /** Bounded delivery-log catch-up bytes per tick; production default 512 KiB. */
20
+ contextIndexMaxBytes?: number;
21
+ }
22
+ export interface SessionIngestDeps extends IngestDeps {
23
+ /** Explicit sink-free context writer for the same logical and canonical event
24
+ * target. Material remains on ingestor's ObserverBus; callbacks cannot own an
25
+ * automatic context observation's durable acknowledgement. */
26
+ contextIngestor?: events.Ingestor;
19
27
  }
20
28
  export interface SessionIngestTickResult {
21
29
  recorded: number;
@@ -25,7 +33,22 @@ export interface SessionIngestTickResult {
25
33
  invalidJsonRows?: number;
26
34
  /** Cursor databases that could not be opened or parsed; no path or native error text is exposed. */
27
35
  parseFailures?: number;
36
+ /** Partial history or unconfirmed index cleanup is unknown; recorded material remains acknowledged. */
37
+ contextObservationIndex?: ops.ContextIndexProgress;
38
+ /** Independent outbox recovery outcome; a complete root-log index does not certify delivery recovery. */
39
+ contextDeliveryRecovery?: SessionContextDeliveryRecovery;
28
40
  }
41
+ export type SessionContextDeliveryRecovery = {
42
+ status: 'complete' | 'pending' | 'unknown';
43
+ journal: events.ContextDeliveryStatus;
44
+ } | {
45
+ status: 'unknown';
46
+ reason: 'recovery_failed' | 'deadline';
47
+ };
48
+ /** Resolve context ownership before any recovery/index I/O. Physical aliases
49
+ * alone are insufficient: protected audit namespaces retain the exact logical
50
+ * name, so a separately supplied writer must also keep that name unchanged. */
51
+ export declare function resolveContextObservationWriter(ingestor: events.Ingestor, contextIngestor?: events.Ingestor): events.Ingestor | undefined;
29
52
  export declare function resolveIngestDeps(deps: IngestDeps): {
30
53
  materialStore: materialNs.MaterialStore;
31
54
  watermarkStore: materialNs.WatermarkStore;
@@ -40,4 +63,4 @@ export declare function recordSessionMaterial(sourceAgent: materialNs.BuildMater
40
63
  /** Recursively enumerate recognized runtime-session sources, skipping inaccessible directories. */
41
64
  export declare function scanSessionDirs(dirs: readonly string[]): string[];
42
65
  /** Record all new or changed runtime sessions as material for the auto-distill loop. */
43
- export declare function runSessionIngestTick(dirs: readonly string[], deps?: IngestDeps): Promise<SessionIngestTickResult>;
66
+ export declare function runSessionIngestTick(dirs: readonly string[], deps?: SessionIngestDeps): Promise<SessionIngestTickResult>;
@@ -1,10 +1,13 @@
1
1
  import { readdirSync } from 'node:fs';
2
2
  import { join, resolve } from 'node:path';
3
- import { events, material as materialNs, signals } from '@evomap/evolver-core';
3
+ import { events, material as materialNs, ops, signals, util } from '@evomap/evolver-core';
4
4
  import { isCursorStateVscdbPath } from '@evomap/evolver-runtime-adapters';
5
5
  import { emitSessionRecall } from './autoRecall.js';
6
+ import { waitContextDelivery } from './contextDelivery.js';
6
7
  import { buildRuntimeSessionMaterialSnapshot } from './materialSnapshot.js';
7
8
  import { isRuntimeSessionSourcePath, parseRuntimeSessionSourcesWithDiagnostics, } from './runtimeSessionSource.js';
9
+ const builtInObservationSink = events.Ingestor.isBuiltInObservationSink;
10
+ const builtInDeliveryRecovery = events.Ingestor.prototype.recoverContextDeliveries;
8
11
  /** Wire-form `task_domain:` tokens embedded in session text (case-insensitive match; resolver fail-closes). */
9
12
  const TASK_DOMAIN_TOKEN_RE = /\btask_domain:[A-Za-z0-9][A-Za-z0-9-]{0,63}\b/gi;
10
13
  /**
@@ -31,6 +34,50 @@ export function stampResolvedTaskDomain(sources) {
31
34
  }
32
35
  /** Material consumer group shared by ingestion and the downstream cycle consumer. */
33
36
  export const INGEST_CONSUMER_GROUP = 'cycle';
37
+ /** Resolve context ownership before any recovery/index I/O. Physical aliases
38
+ * alone are insufficient: protected audit namespaces retain the exact logical
39
+ * name, so a separately supplied writer must also keep that name unchanged. */
40
+ export function resolveContextObservationWriter(ingestor, contextIngestor = ingestor) {
41
+ // Reject structural adapters before reading their path or callback properties.
42
+ if (!builtInObservationSink(contextIngestor))
43
+ return undefined;
44
+ try {
45
+ if (Object.getOwnPropertyDescriptor(contextIngestor, 'recoverContextDeliveries') !== undefined
46
+ || contextIngestor.recoverContextDeliveries !== builtInDeliveryRecovery)
47
+ return undefined;
48
+ const contextPath = contextIngestor.path;
49
+ if (contextPath !== ingestor.path
50
+ || util.canonicalEventPath(contextPath) !== util.canonicalEventPath(ingestor.path))
51
+ return undefined;
52
+ return contextIngestor;
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
57
+ }
58
+ async function recoverSessionDeliveries(ingestor) {
59
+ // Legacy injected sinks have no local durable recovery capability to report.
60
+ if (!ingestor.recoverContextDeliveries)
61
+ return undefined;
62
+ const actual = Promise.resolve()
63
+ .then(() => ingestor.recoverContextDeliveries({ deadlineAt: Date.now() + 150 }))
64
+ .then(journal => ({ journal }), () => ({ failed: true }));
65
+ const outcome = await waitContextDelivery(actual, 170);
66
+ // Report the original wait deadline, but do not let a synchronous root writer
67
+ // starve the native cleanup still owned by this exact recovery operation.
68
+ if (!outcome)
69
+ await actual;
70
+ if (!outcome)
71
+ return { status: 'unknown', reason: 'deadline' };
72
+ if ('failed' in outcome || !outcome.journal)
73
+ return { status: 'unknown', reason: 'recovery_failed' };
74
+ const journal = { ...outcome.journal, reasons: { ...outcome.journal.reasons } };
75
+ // Busy includes unavailable/corrupt journals. Unknown output/projection rows
76
+ // remain unknown even when the separate material/index pass succeeds.
77
+ const status = journal.busy !== false || journal.outputUnknown !== 0 || journal.projectionUnknown !== 0
78
+ ? 'unknown' : journal.confirmedPending === 0 ? 'complete' : journal.confirmedPending > 0 ? 'pending' : 'unknown';
79
+ return { status, journal };
80
+ }
34
81
  export function resolveIngestDeps(deps) {
35
82
  return {
36
83
  materialStore: deps.materialStore ?? new materialNs.MaterialStore({ path: events.materialStorePath() }),
@@ -118,9 +165,46 @@ export function scanSessionDirs(dirs) {
118
165
  function sortedStrings(values) {
119
166
  return [...new Set([...values].map(String).filter(Boolean))].sort();
120
167
  }
168
+ // A completed material/observation write must not be replayed to recover index
169
+ // cleanup. Keep the actual tick owner until close succeeds, including across
170
+ // later calls for other sessions sharing this event log.
171
+ const MAX_SESSION_INGEST_INDEXES = 64;
172
+ const ownedSessionIndexes = new Map();
173
+ function finishSessionIndexCleanup(path) {
174
+ const owned = ownedSessionIndexes.get(path);
175
+ if (!owned)
176
+ return 'ready';
177
+ if (owned.active)
178
+ return 'busy';
179
+ try {
180
+ owned.index.close();
181
+ ownedSessionIndexes.delete(path);
182
+ return 'ready';
183
+ }
184
+ catch {
185
+ return 'unavailable';
186
+ }
187
+ }
121
188
  /** Record all new or changed runtime sessions as material for the auto-distill loop. */
122
189
  export async function runSessionIngestTick(dirs, deps = {}) {
123
190
  const resolvedDeps = resolveIngestDeps(deps);
191
+ const contextIngestor = resolveContextObservationWriter(resolvedDeps.ingestor, deps.contextIngestor);
192
+ const contextDeliveryRecovery = contextIngestor
193
+ ? await recoverSessionDeliveries(contextIngestor) : undefined;
194
+ if (contextIngestor) {
195
+ // A failed/late protected RPC can outlive its client wait. The existing
196
+ // ordered status RPC joins the service's turn before deciding root admission.
197
+ const journal = contextDeliveryRecovery && 'journal' in contextDeliveryRecovery
198
+ ? contextDeliveryRecovery.journal : events.Ingestor.contextDeliveryStatus(contextIngestor.path);
199
+ if (journal.confirmedPending > 0 || journal.reasons.cleanup_pending)
200
+ return {
201
+ recorded: 0, sourceAgents: [], signalKinds: [], signalStrengths: [],
202
+ ...(contextDeliveryRecovery ? { contextDeliveryRecovery } : {}),
203
+ ...(process.env['EVOLVER_AUTO_RECALL'] === '1' ? { contextObservationIndex: {
204
+ status: 'unknown', bytesRead: 0, indexedThroughSeq: 0, reason: 'busy',
205
+ } } : {}),
206
+ };
207
+ }
124
208
  let recorded = 0;
125
209
  const sourceAgents = new Set();
126
210
  const signalKinds = new Set();
@@ -128,49 +212,129 @@ export async function runSessionIngestTick(dirs, deps = {}) {
128
212
  let invalidJsonRows = 0;
129
213
  let parseFailures = 0;
130
214
  const autoRecallOn = process.env['EVOLVER_AUTO_RECALL'] === '1';
131
- for (const file of scanSessionDirs(dirs)) {
132
- let parsed;
133
- try {
134
- parsed = parseRuntimeSessionSourcesWithDiagnostics(file, undefined, deps.nativeSessionHome);
215
+ let contextIndex;
216
+ let ownedContextIndex;
217
+ let contextIndexPath;
218
+ let contextObservationIndex;
219
+ // The legacy lexical rail keeps its historical input, but loads it lazily once per tick, not per session.
220
+ let legacyEvents;
221
+ const readLegacyEvents = () => legacyEvents ??= events.readEvents(contextIngestor.path);
222
+ // The lexical reader is cached only until an observation attempt. A durable
223
+ // intent and the real writer own ambiguous outcomes; the tick must never
224
+ // substitute a wrapper that cannot prove the writer has stopped.
225
+ if (autoRecallOn) {
226
+ if (!contextIngestor) {
227
+ // Material collection may use an injected sink, but product auto-recall
228
+ // must report that its writer cannot prove terminal, durable ownership.
229
+ contextObservationIndex = { status: 'unknown', bytesRead: 0, indexedThroughSeq: 0, reason: 'unsupported_sink' };
135
230
  }
136
- catch {
137
- if (isCursorStateVscdbPath(file))
138
- parseFailures += 1;
139
- continue;
140
- }
141
- try {
142
- const parsedSources = stampResolvedTaskDomain(parsed.sources);
143
- const agent = parsedSources[0] ? toMaterialSourceAgent(parsedSources[0].agent) : undefined;
144
- if (parsedSources.length === 0 || !agent)
231
+ else
232
+ try {
233
+ contextIndexPath = util.canonicalEventPath(contextIngestor.path);
234
+ const cleanup = finishSessionIndexCleanup(contextIndexPath);
235
+ if (cleanup === 'ready' && ownedSessionIndexes.size >= MAX_SESSION_INGEST_INDEXES) {
236
+ // Old logs may never tick again. Retry only their retained cleanup, at
237
+ // most 64 owners, and stop as soon as one slot is genuinely released.
238
+ // finishSessionIndexCleanup leaves active and still-failing owners owned.
239
+ for (const retainedPath of [...ownedSessionIndexes.keys()]) {
240
+ finishSessionIndexCleanup(retainedPath);
241
+ if (ownedSessionIndexes.size < MAX_SESSION_INGEST_INDEXES)
242
+ break;
243
+ }
244
+ }
245
+ if (cleanup !== 'ready' || ownedSessionIndexes.size >= MAX_SESSION_INGEST_INDEXES) {
246
+ contextObservationIndex = { status: 'unknown', bytesRead: 0, indexedThroughSeq: 0,
247
+ reason: cleanup === 'busy' ? 'busy' : 'unavailable' };
248
+ }
249
+ else {
250
+ contextIndex = new ops.GeneContextObservationIndex(contextIndexPath);
251
+ ownedContextIndex = { index: contextIndex, active: true };
252
+ ownedSessionIndexes.set(contextIndexPath, ownedContextIndex);
253
+ contextObservationIndex = contextIndex.beginTick(deps.contextIndexMaxBytes);
254
+ }
255
+ }
256
+ catch {
257
+ // Keep the independently registered cleanup owner, but never dispatch an
258
+ // observation through an index whose tick was not successfully started.
259
+ contextIndex = undefined;
260
+ contextObservationIndex = { status: 'unknown', bytesRead: 0, indexedThroughSeq: 0, reason: 'unavailable' };
261
+ }
262
+ }
263
+ try {
264
+ for (const file of scanSessionDirs(dirs)) {
265
+ let parsed;
266
+ try {
267
+ parsed = parseRuntimeSessionSourcesWithDiagnostics(file, undefined, deps.nativeSessionHome);
268
+ }
269
+ catch {
270
+ if (isCursorStateVscdbPath(file))
271
+ parseFailures += 1;
145
272
  continue;
146
- const signalsBySource = parsedSources.map((source) => signals.extractSignals(source.turns));
147
- const snapshot = buildRuntimeSessionMaterialSnapshot(parsedSources);
148
- const result = await recordSessionMaterial(agent, file, signalsBySource.reduce((sum, sourceSignals) => sum + sourceSignals.length, 0), resolvedDeps, parsedSources.length, snapshot, parsed.diagnostics);
149
- if (result.emitted)
150
- invalidJsonRows += parsed.diagnostics.invalidJson;
151
- if (result.recorded) {
152
- recorded += 1;
153
- sourceAgents.add(agent);
154
- for (const sourceSignals of signalsBySource) {
155
- for (const signal of sourceSignals) {
156
- signalKinds.add(signal.kind);
157
- signalStrengths.add(signal.strength);
273
+ }
274
+ try {
275
+ const parsedSources = stampResolvedTaskDomain(parsed.sources);
276
+ const agent = parsedSources[0] ? toMaterialSourceAgent(parsedSources[0].agent) : undefined;
277
+ if (parsedSources.length === 0 || !agent)
278
+ continue;
279
+ const signalsBySource = parsedSources.map((source) => signals.extractSignals(source.turns));
280
+ const snapshot = buildRuntimeSessionMaterialSnapshot(parsedSources);
281
+ const result = await recordSessionMaterial(agent, file, signalsBySource.reduce((sum, sourceSignals) => sum + sourceSignals.length, 0), resolvedDeps, parsedSources.length, snapshot, parsed.diagnostics);
282
+ if (result.emitted)
283
+ invalidJsonRows += parsed.diagnostics.invalidJson;
284
+ if (result.recorded) {
285
+ recorded += 1;
286
+ sourceAgents.add(agent);
287
+ for (const sourceSignals of signalsBySource) {
288
+ for (const signal of sourceSignals) {
289
+ signalKinds.add(signal.kind);
290
+ signalStrengths.add(signal.strength);
291
+ }
158
292
  }
159
293
  }
294
+ if (autoRecallOn && contextIndex)
295
+ for (const source of parsedSources) {
296
+ if (!source.sessionId && parsedSources.length !== 1)
297
+ continue;
298
+ const turns = source.turns
299
+ .filter((turn) => !turn.isMeta)
300
+ .map((turn) => ({ role: turn.role, text: turn.text }));
301
+ try {
302
+ await emitSessionRecall(file, turns, { ingestor: contextIngestor, contextIndex, readEvents: readLegacyEvents,
303
+ ...(source.sessionId ? { sessionId: source.sessionId, contextOnly: true } : {}) });
304
+ }
305
+ finally {
306
+ // A committed append can precede a later index or journal exception.
307
+ // The next session must read authoritative history even on failure.
308
+ legacyEvents = undefined;
309
+ }
310
+ }
160
311
  }
161
- if (autoRecallOn && parsedSources.length === 1 && !parsedSources[0].sessionId) {
162
- const turns = parsedSources[0].turns
163
- .filter((turn) => !turn.isMeta)
164
- .map((turn) => ({ role: turn.role, text: turn.text }));
165
- await emitSessionRecall(file, turns, { ingestor: resolvedDeps.ingestor });
312
+ catch {
313
+ // Individual session files are best-effort and must not stop the daemon scan.
166
314
  }
167
315
  }
316
+ }
317
+ finally {
318
+ try {
319
+ if (contextIndex)
320
+ contextObservationIndex = contextIndex.currentProgress;
321
+ }
168
322
  catch {
169
- // Individual session files are best-effort and must not stop the daemon scan.
323
+ contextObservationIndex = { status: 'unknown', bytesRead: 0, indexedThroughSeq: 0, reason: 'unavailable' };
324
+ }
325
+ if (ownedContextIndex && contextIndexPath) {
326
+ ownedContextIndex.active = false;
327
+ if (finishSessionIndexCleanup(contextIndexPath) !== 'ready') {
328
+ contextObservationIndex = { ...contextObservationIndex,
329
+ status: 'unknown', bytesRead: contextObservationIndex?.bytesRead ?? 0,
330
+ indexedThroughSeq: contextObservationIndex?.indexedThroughSeq ?? 0, reason: 'unavailable' };
331
+ }
170
332
  }
171
333
  }
172
334
  return {
173
335
  recorded,
336
+ ...(contextObservationIndex ? { contextObservationIndex } : {}),
337
+ ...(contextDeliveryRecovery ? { contextDeliveryRecovery } : {}),
174
338
  sourceAgents: sortedStrings(sourceAgents),
175
339
  signalKinds: sortedStrings(signalKinds),
176
340
  signalStrengths: sortedStrings(signalStrengths),