@remnic/core 10.0.195 → 10.0.196

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 (110) hide show
  1. package/dist/access-admin-ops-surface.js +18 -18
  2. package/dist/access-cli.js +18 -18
  3. package/dist/access-coding-context-resolution.js +2 -2
  4. package/dist/access-extraction-force-flush-preempt.js +18 -18
  5. package/dist/access-extraction-force-flush.js +18 -18
  6. package/dist/access-http-briefing.js +18 -18
  7. package/dist/access-http-query.js +18 -18
  8. package/dist/access-http.js +18 -18
  9. package/dist/access-identity-continuity-surface.js +18 -18
  10. package/dist/access-lcm-surface.js +18 -18
  11. package/dist/access-mcp.d.ts.map +1 -1
  12. package/dist/access-mcp.js +18 -18
  13. package/dist/access-observe-write-category.js +2 -2
  14. package/dist/access-observe-write-surface.js +18 -18
  15. package/dist/access-operations-batch.js +18 -18
  16. package/dist/access-operations.js +18 -18
  17. package/dist/access-recall-concurrency.d.ts +4 -0
  18. package/dist/access-recall-concurrency.d.ts.map +1 -1
  19. package/dist/access-recall-concurrency.js +18 -18
  20. package/dist/access-recall-response.d.ts.map +1 -1
  21. package/dist/access-recall-response.js +18 -18
  22. package/dist/access-recall-surface.d.ts.map +1 -1
  23. package/dist/access-recall-surface.js +18 -18
  24. package/dist/access-schema.d.ts +1 -0
  25. package/dist/access-schema.d.ts.map +1 -1
  26. package/dist/access-schema.js +1 -1
  27. package/dist/access-service.d.ts.map +1 -1
  28. package/dist/access-service.js +18 -18
  29. package/dist/buffer.js +3 -3
  30. package/dist/{chunk-F2MVWUNF.js → chunk-374E2HYZ.js} +10 -2
  31. package/dist/chunk-374E2HYZ.js.map +1 -0
  32. package/dist/{chunk-3ZS3NUEI.js → chunk-3DSLTUK6.js} +2 -2
  33. package/dist/{chunk-CRS2NY44.js → chunk-7O6H7BPW.js} +2 -2
  34. package/dist/{chunk-ME63JKWJ.js → chunk-7TK5Q6LQ.js} +64 -35
  35. package/dist/chunk-7TK5Q6LQ.js.map +1 -0
  36. package/dist/{chunk-76LBLH62.js → chunk-AUDLHIHI.js} +2 -2
  37. package/dist/{chunk-4GVSMPBP.js → chunk-CRKT2JXN.js} +2 -2
  38. package/dist/{chunk-JJ42IDJU.js → chunk-FEGQI5KR.js} +2 -2
  39. package/dist/{chunk-KQIOW3TG.js → chunk-HUDE2SQA.js} +2 -2
  40. package/dist/{chunk-Q2GDUJSK.js → chunk-JRUOIEFL.js} +4 -4
  41. package/dist/{chunk-JKMIGCK6.js → chunk-KDGEEZOI.js} +3 -2
  42. package/dist/chunk-KDGEEZOI.js.map +1 -0
  43. package/dist/{chunk-BD26CK6T.js → chunk-ODGVLSCQ.js} +2 -2
  44. package/dist/{chunk-YCTD3XET.js → chunk-PNDTRIOI.js} +2 -2
  45. package/dist/{chunk-XDNVWY7I.js → chunk-PX4AMRAN.js} +2 -2
  46. package/dist/{chunk-QW5LZTKA.js → chunk-QO5QZR2U.js} +2 -2
  47. package/dist/{chunk-NFQKIZK3.js → chunk-QXEF66SC.js} +2 -2
  48. package/dist/{chunk-HD7M55OI.js → chunk-VAE6QCZQ.js} +2 -2
  49. package/dist/{chunk-QZPAOOU7.js → chunk-WLP3XJCO.js} +2 -2
  50. package/dist/{chunk-SFUS2V2V.js → chunk-XII23FXP.js} +1 -1
  51. package/dist/chunk-XII23FXP.js.map +1 -0
  52. package/dist/{chunk-IT4G6HTG.js → chunk-YQUGYQRY.js} +2 -2
  53. package/dist/cli.js +18 -18
  54. package/dist/coding/export-okf-codegraph.js +3 -3
  55. package/dist/deep-recall-http-glue.js +2 -2
  56. package/dist/eval-trajectory-store.js +2 -2
  57. package/dist/eval-trajectory.js +2 -2
  58. package/dist/evals.d.ts.map +1 -1
  59. package/dist/evals.js +1 -1
  60. package/dist/explicit-capture.js +18 -18
  61. package/dist/extraction.js +4 -4
  62. package/dist/index.js +18 -18
  63. package/dist/memory-browse.js +3 -3
  64. package/dist/operator-toolkit.js +2 -2
  65. package/dist/orchestration/backlog-scheduler.js +19 -19
  66. package/dist/orchestration/buffer-drain-runner.js +19 -19
  67. package/dist/orchestration/orchestrator-helpers.d.ts +2 -0
  68. package/dist/orchestration/orchestrator-helpers.d.ts.map +1 -1
  69. package/dist/orchestration/recall-entry.d.ts +2 -2
  70. package/dist/orchestration/recall-entry.d.ts.map +1 -1
  71. package/dist/orchestration/recall-internal.d.ts.map +1 -1
  72. package/dist/orchestrator.d.ts.map +1 -1
  73. package/dist/orchestrator.js +18 -18
  74. package/dist/recall-navigation.js +18 -18
  75. package/dist/recall-state-view-admission.js +3 -3
  76. package/dist/recall-why-service.js +3 -3
  77. package/dist/source-agent-qualifier.js +3 -3
  78. package/package.json +2 -2
  79. package/src/access-mcp.ts +8 -0
  80. package/src/access-recall-concurrency.ts +35 -2
  81. package/src/access-recall-response.ts +3 -1
  82. package/src/access-recall-surface.ts +1 -0
  83. package/src/access-schema.ts +8 -0
  84. package/src/access-service-recall-concurrency.test.ts +65 -0
  85. package/src/access-service.ts +4 -3
  86. package/src/evals.ts +6 -6
  87. package/src/orchestration/orchestrator-helpers.ts +2 -0
  88. package/src/orchestration/recall-entry.ts +7 -7
  89. package/src/orchestration/recall-internal.ts +14 -4
  90. package/src/orchestrator.ts +3 -2
  91. package/src/recall-client-deadline-trace.test.ts +209 -0
  92. package/dist/chunk-F2MVWUNF.js.map +0 -1
  93. package/dist/chunk-JKMIGCK6.js.map +0 -1
  94. package/dist/chunk-ME63JKWJ.js.map +0 -1
  95. package/dist/chunk-SFUS2V2V.js.map +0 -1
  96. /package/dist/{chunk-3ZS3NUEI.js.map → chunk-3DSLTUK6.js.map} +0 -0
  97. /package/dist/{chunk-CRS2NY44.js.map → chunk-7O6H7BPW.js.map} +0 -0
  98. /package/dist/{chunk-76LBLH62.js.map → chunk-AUDLHIHI.js.map} +0 -0
  99. /package/dist/{chunk-4GVSMPBP.js.map → chunk-CRKT2JXN.js.map} +0 -0
  100. /package/dist/{chunk-JJ42IDJU.js.map → chunk-FEGQI5KR.js.map} +0 -0
  101. /package/dist/{chunk-KQIOW3TG.js.map → chunk-HUDE2SQA.js.map} +0 -0
  102. /package/dist/{chunk-Q2GDUJSK.js.map → chunk-JRUOIEFL.js.map} +0 -0
  103. /package/dist/{chunk-BD26CK6T.js.map → chunk-ODGVLSCQ.js.map} +0 -0
  104. /package/dist/{chunk-YCTD3XET.js.map → chunk-PNDTRIOI.js.map} +0 -0
  105. /package/dist/{chunk-XDNVWY7I.js.map → chunk-PX4AMRAN.js.map} +0 -0
  106. /package/dist/{chunk-QW5LZTKA.js.map → chunk-QO5QZR2U.js.map} +0 -0
  107. /package/dist/{chunk-NFQKIZK3.js.map → chunk-QXEF66SC.js.map} +0 -0
  108. /package/dist/{chunk-HD7M55OI.js.map → chunk-VAE6QCZQ.js.map} +0 -0
  109. /package/dist/{chunk-QZPAOOU7.js.map → chunk-WLP3XJCO.js.map} +0 -0
  110. /package/dist/{chunk-IT4G6HTG.js.map → chunk-YQUGYQRY.js.map} +0 -0
@@ -14,6 +14,7 @@
14
14
  * caller signal / flight object alone).
15
15
  */
16
16
  import { abortError, isAbortError, raceAbort, throwIfAborted } from "./abort-error.js";
17
+ import { log } from "./logger.js";
17
18
  import { hashAccessIdempotencyPayload } from "./access-idempotency.js";
18
19
  import {
19
20
  EngramAccessDeadlineExceededError,
@@ -68,6 +69,10 @@ interface RecallFlight {
68
69
  promise: Promise<RecallExecResult>;
69
70
  controller: AbortController;
70
71
  live: number;
72
+ /** The leader's caller-supplied trace ID, when it sent one — used to log the
73
+ * follower->leader association when a coalesced caller attaches with its
74
+ * own ID (issue #3499 review). */
75
+ leaderTraceId?: string;
71
76
  /** Set true the instant the shared pipeline acquires its concurrency slot and
72
77
  * begins executing. Before this, a KEYED flight whose only caller aborts must
73
78
  * cancel (nothing has committed); after it, a keyed flight must persist
@@ -369,6 +374,13 @@ export async function consumeFlight(
369
374
  cancelOnAbort: boolean = race,
370
375
  ): Promise<{ response: EngramAccessRecallResponse; reservation: BudgetReservation | undefined }> {
371
376
  const detach = attachFlightAbort(flight, request.abortSignal, cancelOnAbort);
377
+ // Correlation aid (issue #3499 review): a coalesced follower's response
378
+ // echoes its OWN trace ID, but the daemon's start/timing lines carry the
379
+ // leader's — record the follower->leader association at attach, before the
380
+ // deadline wait, so a follower's timed-out call still maps to this run.
381
+ if (request.traceId !== undefined && request.traceId !== flight.leaderTraceId) {
382
+ log.info(`recall follower [${request.traceId}] joined flight under leader [${flight.leaderTraceId ?? "derived"}]`);
383
+ }
372
384
  try {
373
385
  let result: RecallExecResult;
374
386
  try {
@@ -423,6 +435,10 @@ export async function consumeFlight(
423
435
  // principal id never reaches the response / cache (round 10 #2).
424
436
  response.budgetWarning = toBudgetWarning(ownDecision);
425
437
  }
438
+ // A coalesced caller keeps its OWN caller-known trace ID (issue #3499):
439
+ // the shared pipeline ran under the leader's ID, but the follower's
440
+ // response must echo the ID the follower logged before dispatch.
441
+ if (request.traceId !== undefined) response.traceId = request.traceId;
426
442
  return { response, reservation };
427
443
  } catch (err) {
428
444
  // Clone threw on a successful pipeline — release the admission entry
@@ -527,7 +543,7 @@ async function runRecallDirect(
527
543
  }
528
544
  throw err;
529
545
  }
530
- return response;
546
+ return withCallerTraceId(response, request.traceId);
531
547
  }
532
548
 
533
549
  /** Register a single-flight and start its ONE shared pipeline in the
@@ -573,6 +589,7 @@ export function createAndStartFlight(
573
589
  controller,
574
590
  live: 0,
575
591
  committed: false,
592
+ leaderTraceId: normalizedRequest.traceId,
576
593
  onIdle: () => {
577
594
  const unregister = () => {
578
595
  if (host.recallInFlight.get(flightKey) === flight) {
@@ -777,7 +794,20 @@ export async function leadRecallFlight(
777
794
  }
778
795
  throw err;
779
796
  }
780
- return response;
797
+ return withCallerTraceId(response, request.traceId);
798
+ }
799
+
800
+ /** An idempotent replay returns the ORIGINAL attempt's stored response, so it
801
+ * echoes the original caller's trace ID. Stamp THIS caller's ID on a shallow
802
+ * copy (issue #3499 review): the stored record stays untouched for the next
803
+ * replay, and a caller that logged an ID before dispatch gets it echoed.
804
+ * Same contract as single-flight followers in consumeFlight. */
805
+ function withCallerTraceId(
806
+ response: EngramAccessRecallResponse,
807
+ traceId: string | undefined,
808
+ ): EngramAccessRecallResponse {
809
+ if (traceId === undefined || response.traceId === traceId) return response;
810
+ return { ...response, traceId };
781
811
  }
782
812
 
783
813
  /** The degraded response for a recall whose deadline expired at admission,
@@ -812,6 +842,9 @@ function degradedDeadlineRecallResponse(
812
842
  fallbackUsed: false,
813
843
  sourcesUsed: [],
814
844
  disclosure: request.disclosure ?? DEFAULT_RECALL_DISCLOSURE,
845
+ // Echo the caller's trace ID on the timeout path too — that is exactly
846
+ // the response a client has to correlate when its deadline fires.
847
+ traceId: request.traceId,
815
848
  };
816
849
  }
817
850
 
@@ -354,7 +354,9 @@ export async function assembleRecallResponse(
354
354
  memoryIds: filteredMemoryIds,
355
355
  results,
356
356
  recordedAt: snapshot?.recordedAt,
357
- traceId: snapshot?.traceId,
357
+ // Caller-supplied ID echoes even when no matching snapshot exists —
358
+ // sessionless recalls and timed-out recalls never recorded one (#3499).
359
+ traceId: snapshot?.traceId ?? request.traceId,
358
360
  plannerMode: snapshot?.plannerMode ?? mode,
359
361
  fallbackUsed: snapshot?.fallbackUsed ?? false,
360
362
  sourcesUsed: snapshot?.sourcesUsed ?? [],
@@ -864,6 +864,7 @@ export class AccessRecallSurface {
864
864
  };
865
865
  if (request.searchOptions) recallOptions.searchOptions = request.searchOptions;
866
866
  if (request.deadlineMs !== undefined) recallOptions.deadlineMs = request.deadlineMs;
867
+ if (request.traceId !== undefined) recallOptions.traceId = request.traceId;
867
868
  const startedAt = Date.now();
868
869
  // #1906 atomic budget admission: the peek loop above and this record are
869
870
  // one synchronous JS turn (no await between them), so record()'s own
@@ -188,6 +188,14 @@ export const recallRequestSchema = z.object({
188
188
  * instead of an answer it can no longer use.
189
189
  */
190
190
  deadlineMs: deadlineMsSchema,
191
+ /**
192
+ * Caller-known recall trace ID (issue #3499). When present it becomes
193
+ * the recall's `traceId`, echoed on the response and the daemon's
194
+ * request/timing lines, so a call that times out client-side can still
195
+ * be matched to daemon logs without timestamp correlation. Restricted
196
+ * to word/colon/dot/hyphen characters because it lands in log lines.
197
+ */
198
+ traceId: z.string().min(1, "traceId is required").max(128).regex(/^[\w:.-]+$/, "traceId may only contain word characters, colon, dot and hyphen").optional(),
191
199
  });
192
200
 
193
201
  export const recallExplainRequestSchema = z.object({
@@ -65,6 +65,13 @@ function stubResponse(results: unknown[]): EngramAccessRecallResponse {
65
65
  return { results } as unknown as EngramAccessRecallResponse;
66
66
  }
67
67
 
68
+ // Single trusted cast point for the private seams a stub replaces.
69
+ function asHostSeam<T>(cause: unknown): T {
70
+ // SAFETY: the caller supplies the locally-declared seam contract; the cast
71
+ // re-labels the EngramAccessService prototype instance to that contract.
72
+ return cause as T;
73
+ }
74
+
68
75
  function readResults(response: EngramAccessRecallResponse): unknown[] {
69
76
  assert.ok(response && typeof response === "object" && "results" in response);
70
77
  const { results } = response as { results: unknown[] };
@@ -2230,3 +2237,61 @@ test("a keyed follower does not inherit its leader's queued-deadline rejection (
2230
2237
  assert.equal(pipelineRuns, 2, "holder + the one shared pipeline");
2231
2238
  await holder;
2232
2239
  });
2240
+
2241
+ test("coalesced followers echo their own caller traceId, not the leader's", async () => {
2242
+ const { service } = makeService({
2243
+ limit: 0,
2244
+ singleFlight: true,
2245
+ pipeline: async (request) => ({
2246
+ ...stubResponse([{ id: "m1" }]),
2247
+ traceId: request.traceId,
2248
+ }),
2249
+ });
2250
+
2251
+ const req: EngramAccessRecallRequest = { query: "same", sessionKey: "s1" };
2252
+ const [leader, followerA, followerB] = await Promise.all([
2253
+ service.recall({ ...req, traceId: "leader-tid" }),
2254
+ service.recall({ ...req, traceId: "follower-a" }),
2255
+ service.recall({ ...req }),
2256
+ ]);
2257
+
2258
+ assert.equal(leader.traceId, "leader-tid");
2259
+ assert.equal(followerA.traceId, "follower-a", "a caller-supplied traceId must survive single-flight coalescing");
2260
+ assert.equal(followerB.traceId, "leader-tid", "a caller without traceId keeps the pipeline's value");
2261
+ });
2262
+
2263
+ test("an idempotent replay echoes the REPLAYING caller's traceId, not the original attempt's", async () => {
2264
+ const store = new Map<string, EngramAccessRecallResponse>();
2265
+ const h = makeService({
2266
+ limit: 0,
2267
+ singleFlight: false,
2268
+ crossNamespace: true,
2269
+ pipeline: async (request) => ({
2270
+ ...stubResponse([{ id: "m1" }]),
2271
+ traceId: request.traceId,
2272
+ }),
2273
+ });
2274
+ const host = asHostSeam<{
2275
+ handleIdempotentRead: (options: {
2276
+ idempotencyKey?: string;
2277
+ execute: () => Promise<EngramAccessRecallResponse>;
2278
+ }) => Promise<EngramAccessRecallResponse>;
2279
+ }>(h.service);
2280
+ host.handleIdempotentRead = async (options) => {
2281
+ const key = options.idempotencyKey ?? "";
2282
+ const cached = store.get(key);
2283
+ if (cached) return cached;
2284
+ const response = await options.execute();
2285
+ store.set(key, response);
2286
+ return response;
2287
+ };
2288
+
2289
+ const first = await h.service.recall({ query: "same", idempotencyKey: "k", traceId: "first-tid" });
2290
+ const replay = await h.service.recall({ query: "same", idempotencyKey: "k", traceId: "second-tid" });
2291
+ const replayAgain = await h.service.recall({ query: "same", idempotencyKey: "k", traceId: "third-tid" });
2292
+
2293
+ assert.equal(first.traceId, "first-tid");
2294
+ assert.equal(replay.traceId, "second-tid", "a replay must echo the replaying caller's trace ID");
2295
+ assert.equal(replayAgain.traceId, "third-tid", "an earlier replay's stamp must not corrupt the stored record");
2296
+ assert.equal(store.get("k")!.traceId, "first-tid", "the stored record keeps the original attempt's ID");
2297
+ });
@@ -2640,9 +2640,10 @@ export class EngramAccessService extends SupportPassportAccessServiceBase {
2640
2640
  const deadlineAtMs = resolveClientDeadlineAtMs(request.deadlineMs, Date.now());
2641
2641
  const normalizedRequest = { ...request, query };
2642
2642
  if (deadlineAtMs !== null) normalizedRequest.deadlineMs = deadlineAtMs;
2643
- // `deadlineMs` is per-call QoS, not work identity: two identical recalls
2644
- // carrying different client deadlines must still coalesce (#3514 review).
2645
- const { abortSignal: _abortSignal, deadlineMs: _deadlineMs, ...requestFingerprint } = normalizedRequest;
2643
+ // `deadlineMs`/`traceId` are per-call QoS + correlation, not work
2644
+ // identity: two identical recalls carrying different values must still
2645
+ // coalesce (#3514 review, #3499 trace plumbing).
2646
+ const { abortSignal: _abortSignal, deadlineMs: _deadlineMs, traceId: _traceId, ...requestFingerprint } = normalizedRequest;
2646
2647
  const authenticatedPrincipal = request.authenticatedPrincipal?.trim();
2647
2648
  const principal = this.resolveRequestPrincipal(request.sessionKey, authenticatedPrincipal);
2648
2649
  if (resolveNamespaceCapabilities(this.orchestrator.config).namespaces && !principal) {
package/src/evals.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import path from "node:path";
2
+ import { createHash } from "node:crypto";
2
3
  import { cp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
3
4
  import { listJsonFiles, listNamedFiles, readJsonFile } from "./json-store.js";
4
5
 
@@ -925,17 +926,16 @@ export async function importEvalBenchmarkPack(options: {
925
926
  };
926
927
  }
927
928
 
928
- export async function recordEvalShadowRecall(options: {
929
- memoryDir: string;
930
- evalStoreDir?: string;
931
- record: EvalShadowRecallRecord;
932
- }): Promise<string> {
929
+ export async function recordEvalShadowRecall(
930
+ options: { memoryDir: string; evalStoreDir?: string; record: EvalShadowRecallRecord },
931
+ ): Promise<string> {
933
932
  const rootDir = resolveEvalStoreDir(options.memoryDir, options.evalStoreDir);
934
933
  const validated = validateEvalShadowRecallRecord(options.record);
935
934
  const day = validated.recordedAt.slice(0, 10);
936
935
  const shadowRoot = path.join(rootDir, "shadow");
937
936
  const shadowDir = path.join(shadowRoot, day);
938
- const targetPath = path.join(shadowDir, `${validated.traceId}.json`);
937
+ // Filename is a deterministic hash, not the raw ID: caller-supplied IDs may carry filename-unsafe chars (#3499).
938
+ const targetPath = path.join(shadowDir, `${createHash("sha256").update(validated.traceId).digest("hex").slice(0, 24)}.json`);
939
939
  assertPathWithin(shadowRoot, targetPath, "shadow recall record path");
940
940
  await mkdir(shadowDir, { recursive: true });
941
941
  await writeFile(targetPath, JSON.stringify(validated, null, 2), "utf-8");
@@ -273,6 +273,8 @@ export interface RecallInvocationOptions {
273
273
  * an already-passed deadline behaves like a 0-remaining budget.
274
274
  */
275
275
  deadlineMs?: number;
276
+ /** Caller-known trace ID (issue #3499); replaces the derived snapshot `traceId`. */
277
+ traceId?: string;
276
278
  onContextComposition?: (composition: RecallContextComposition) => void | PromiseLike<void>;
277
279
  }
278
280
 
@@ -58,7 +58,7 @@ export interface RecallEntryDeps {
58
58
  readonly initPromise: Promise<void> | null;
59
59
  lastRecallFailureAtMs: number;
60
60
  lastRecallFailureLogAtMs: number;
61
- logRecallFailure(err: unknown): void;
61
+ logRecallFailure(cause: unknown, traceId?: string): void;
62
62
  readonly profiler: ProfilingCollector;
63
63
  recallInternal(
64
64
  prompt: string,
@@ -162,7 +162,7 @@ export class RecallEntryCoordinator {
162
162
  // A fired client deadline is a timeout, not cancellation — the flow
163
163
  // below then degrades to the missing-note response instead of "".
164
164
  if (gateResult === "aborted" && !clientDeadlineFired) {
165
- this.deps.logRecallFailure(abortRecallError("recall aborted before init"));
165
+ this.deps.logRecallFailure(abortRecallError("recall aborted before init"), options.traceId);
166
166
  if (clientDeadlineHandle) clearTimeout(clientDeadlineHandle);
167
167
  return "";
168
168
  }
@@ -305,7 +305,7 @@ export class RecallEntryCoordinator {
305
305
 
306
306
  return prefixStandingMemoryBlock(recallResult, standingText, standingBudget);
307
307
  } catch (err) {
308
- this.deps.logRecallFailure(err);
308
+ this.deps.logRecallFailure(err, options.traceId);
309
309
  this.deps.profiler.endTrace();
310
310
  // A fired client deadline is a timeout, not caller cancellation: the
311
311
  // caller still expects the degraded response, not "" (issue #3499).
@@ -329,9 +329,9 @@ export class RecallEntryCoordinator {
329
329
  }
330
330
  }
331
331
 
332
- logRecallFailure(err: unknown): void {
332
+ logRecallFailure(cause: unknown, traceId?: string): void {
333
333
  const now = Date.now();
334
- const errorMsg = err instanceof Error ? err.message : String(err);
334
+ const errorMsg = cause instanceof Error ? cause.message : String(cause);
335
335
  const LOG_WINDOW_MS = 60_000;
336
336
  const idleSinceLastFailureMs = now - this.deps.lastRecallFailureAtMs;
337
337
  this.deps.lastRecallFailureAtMs = now;
@@ -344,14 +344,14 @@ export class RecallEntryCoordinator {
344
344
  this.deps.suppressedRecallFailures > 0
345
345
  ? ` (suppressed ${this.deps.suppressedRecallFailures} similar failures in last minute)`
346
346
  : "";
347
- log.warn(`recall timed out or failed: ${errorMsg}${suffix}`);
347
+ log.warn(`recall timed out or failed${traceId ? ` [${traceId}]` : ""}: ${errorMsg}${suffix}`);
348
348
  this.deps.lastRecallFailureLogAtMs = now;
349
349
  this.deps.suppressedRecallFailures = 0;
350
350
  return;
351
351
  }
352
352
 
353
353
  this.deps.suppressedRecallFailures += 1;
354
- log.debug(`recall timed out or failed (suppressed): ${errorMsg}`);
354
+ log.debug(`recall timed out or failed (suppressed)${traceId ? ` [${traceId}]` : ""}: ${errorMsg}`);
355
355
  }
356
356
 
357
357
  queueEvalShadowRecall(
@@ -199,10 +199,18 @@ export class RecallInternalCoordinator {
199
199
  logger: log,
200
200
  });
201
201
  const promptHash = createHash("sha256").update(prompt).digest("hex");
202
- const traceId = createHash("sha256")
202
+ // Caller-supplied traceId (issue #3499) wins: the ID a client logged
203
+ // before dispatch then appears verbatim on response + timing lines.
204
+ const traceId = options.traceId ?? createHash("sha256")
203
205
  .update(`${sessionKey ?? "default"}:${recallStart}:${promptHash}`)
204
206
  .digest("hex")
205
207
  .slice(0, 16);
208
+ // Shadow-eval records are files keyed by this ID; a caller ID reused
209
+ // across runs would overwrite them, so the shadow keeps a per-run key.
210
+ const evalTraceId = `${traceId}-${recallStart}`;
211
+ // Emitted BEFORE the timeout-prone sections so a recall that dies at a
212
+ // deadline still leaves an ID-tagged daemon log line (issue #3499).
213
+ log.info(`recall start [${traceId}]`);
206
214
  const sectionBuckets: RecallSectionBuckets = new Map();
207
215
  // The effective LCM read session_id SET is computed below from
208
216
  // `recallNamespaces` (the SAME read-authorized namespace set normal QMD/file
@@ -601,7 +609,7 @@ export class RecallInternalCoordinator {
601
609
  }
602
610
  if (sessionKey) {
603
611
  this.deps.queueEvalShadowRecall({
604
- traceId,
612
+ traceId: evalTraceId,
605
613
  recordedAt: new Date().toISOString(),
606
614
  sessionKey,
607
615
  promptHash,
@@ -4888,7 +4896,9 @@ export class RecallInternalCoordinator {
4888
4896
  const timingParts = Object.entries(timings)
4889
4897
  .map(([k, v]) => `${k}=${v}`)
4890
4898
  .join(", ");
4891
- log.info(`recall timings: ${timingParts}`);
4899
+ // traceId on the timings line lets a client-side timeout be matched to
4900
+ // this recall by ID, not timestamp proximity (issue #3499).
4901
+ log.info(`recall timings [${traceId}]: ${timingParts}`);
4892
4902
  emitRecallTiming(this.deps.config, {
4893
4903
  ...timings,
4894
4904
  ...phase2Timings,
@@ -5268,7 +5278,7 @@ export class RecallInternalCoordinator {
5268
5278
  }
5269
5279
  if (sessionKey) {
5270
5280
  this.deps.queueEvalShadowRecall({
5271
- traceId,
5281
+ traceId: evalTraceId,
5272
5282
  recordedAt: new Date().toISOString(),
5273
5283
  sessionKey,
5274
5284
  promptHash,
@@ -2508,11 +2508,12 @@ export class Orchestrator {
2508
2508
  );
2509
2509
  }
2510
2510
 
2511
- private logRecallFailure(err: unknown): void {
2511
+ private logRecallFailure(cause: unknown, traceId?: string): void {
2512
2512
  return (this.recallEntryCoordinator ?? new RecallEntryCoordinator(
2513
2513
  selfDeps<ConstructorParameters<typeof RecallEntryCoordinator>[0]>(this),
2514
2514
  )).logRecallFailure(
2515
- err,
2515
+ cause,
2516
+ traceId,
2516
2517
  );
2517
2518
  }
2518
2519
 
@@ -0,0 +1,209 @@
1
+ /**
2
+ * recall-client-deadline-trace.test.ts — issue #3499.
3
+ *
4
+ * Pins the client-visible deadline + trace-ID contract on the explicit
5
+ * `engram.recall` tool route:
6
+ * - tools/list advertises `deadlineMs` and `traceId`, and tools/call
7
+ * forwards both verbatim to the access service (the merged deadline
8
+ * clamp is unreachable while the schema omits the property);
9
+ * - `recallRequestSchema` accepts both fields and rejects a `traceId`
10
+ * that could inject control characters into log lines;
11
+ * - a caller-supplied `traceId` becomes the snapshot's `traceId` so the
12
+ * response echoes the ID the client logged before dispatch, while an
13
+ * unsupplied recall keeps the derived 16-hex ID.
14
+ */
15
+
16
+ import assert from "node:assert/strict";
17
+ import os from "node:os";
18
+ import path from "node:path";
19
+ import { createHash } from "node:crypto";
20
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
21
+ import test from "node:test";
22
+
23
+ import { recallRequestSchema } from "./access-schema.js";
24
+ import { recordEvalShadowRecall } from "./evals.js";
25
+ import { EngramMcpServer } from "./access-mcp.js";
26
+ import type { EngramAccessService } from "./access-service.js";
27
+ import { parseConfig } from "./config.js";
28
+ import { Orchestrator } from "./orchestrator.js";
29
+ import { StorageManager } from "./storage.js";
30
+ import type { PluginConfig } from "./types.js";
31
+
32
+ type ToolArgs = { [key: string]: string | number | boolean };
33
+
34
+ function makeToolRequest(name: string, args: ToolArgs) {
35
+ return {
36
+ jsonrpc: "2.0",
37
+ id: 1,
38
+ method: "tools/call",
39
+ params: { name, arguments: args },
40
+ };
41
+ }
42
+
43
+ type ToolListing = {
44
+ name: string;
45
+ inputSchema: { properties?: { deadlineMs?: unknown; traceId?: unknown } };
46
+ };
47
+
48
+ test("#3499: tools/list advertises deadlineMs and traceId on engram.recall", async () => {
49
+ // SAFETY: tools/list never reaches the service; the empty stub is unreachable.
50
+ const server = new EngramMcpServer(Object.assign({} as EngramAccessService, {}));
51
+ const response = await server.handleRequest({
52
+ jsonrpc: "2.0",
53
+ id: 1,
54
+ method: "tools/list",
55
+ params: {},
56
+ });
57
+ // SAFETY: a tools/list response always resolves to the JSON-RPC result
58
+ // envelope; only the tool name + advertised properties are asserted.
59
+ const tools = (response as { result?: { tools?: ToolListing[] } }).result?.tools ?? [];
60
+ const recall = tools.find((tool) => tool.name === "engram.recall");
61
+ assert.ok(recall, "engram.recall is listed");
62
+ assert.ok(recall.inputSchema.properties?.deadlineMs, "deadlineMs is advertised");
63
+ assert.ok(recall.inputSchema.properties?.traceId, "traceId is advertised");
64
+ });
65
+
66
+ test("#3499: tools/call engram.recall forwards deadlineMs and traceId to the service", async () => {
67
+ let received: ToolArgs | undefined;
68
+ // SAFETY: the stub implements only recall; every other MCP dispatch path
69
+ // is unreachable in this test.
70
+ const service = Object.assign({} as EngramAccessService, {
71
+ recall: async (args: ToolArgs) => {
72
+ received = args;
73
+ return { context: "", results: [], count: 0, memoryIds: [], fallbackUsed: false, sourcesUsed: [], traceId: args.traceId };
74
+ },
75
+ });
76
+ const server = new EngramMcpServer(service);
77
+
78
+ const response = await server.handleRequest(
79
+ makeToolRequest("engram.recall", {
80
+ query: "cold-start recall",
81
+ sessionKey: "pi:session",
82
+ deadlineMs: 55_000,
83
+ traceId: "lane-8z:attempt-2",
84
+ }),
85
+ {},
86
+ );
87
+
88
+ assert.equal(received?.deadlineMs, 55_000);
89
+ assert.equal(received?.traceId, "lane-8z:attempt-2");
90
+ // SAFETY: a tools/call response always resolves to the JSON-RPC result
91
+ // envelope; only structuredContent.traceId is asserted.
92
+ const result = (response as { result?: { structuredContent?: { traceId?: string } } }).result;
93
+ assert.equal(
94
+ result?.structuredContent?.traceId,
95
+ "lane-8z:attempt-2",
96
+ "caller traceId echoes on the response",
97
+ );
98
+ });
99
+
100
+ test("#3499: recallRequestSchema accepts deadline + traceId and rejects injectable traceIds", () => {
101
+ const ok = recallRequestSchema.safeParse({
102
+ query: "q",
103
+ deadlineMs: 42_000,
104
+ traceId: "client:req-7.1",
105
+ });
106
+ assert.equal(ok.success, true);
107
+
108
+ for (const traceId of ["has space", "newline\ninject", "x".repeat(129), ""]) {
109
+ const bad = recallRequestSchema.safeParse({ query: "q", traceId });
110
+ assert.equal(bad.success, false, `traceId ${JSON.stringify(traceId)} rejected`);
111
+ }
112
+ });
113
+
114
+ async function makeOrchestrator(): Promise<{ orchestrator: Orchestrator; memoryDir: string }> {
115
+ const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-3499-trace-"));
116
+ // SAFETY: same minimal-config fixture shape as irc-preference-recall.test.ts;
117
+ // parseConfig fills every unset field with its default.
118
+ const config = parseConfig({
119
+ openaiApiKey: "sk-test",
120
+ memoryDir,
121
+ workspaceDir: path.join(memoryDir, "workspace"),
122
+ qmdEnabled: false,
123
+ embeddingFallbackEnabled: false,
124
+ multiGraphMemoryEnabled: false,
125
+ entityGraphEnabled: false,
126
+ timeGraphEnabled: false,
127
+ causalGraphEnabled: false,
128
+ extractionJudgeEnabled: false,
129
+ contradictionDetectionEnabled: false,
130
+ chunkingEnabled: false,
131
+ extractionMinChars: 0,
132
+ extractionMinImportanceLevel: "trivial",
133
+ inlineSourceAttributionEnabled: false,
134
+ initGateTimeoutMs: 200,
135
+ } as Partial<PluginConfig>);
136
+ return { orchestrator: new Orchestrator(config), memoryDir };
137
+ }
138
+
139
+ test("#3499: a caller-supplied traceId becomes the snapshot traceId", async () => {
140
+ const { orchestrator, memoryDir } = await makeOrchestrator();
141
+ try {
142
+ const storage = new StorageManager(memoryDir);
143
+ await storage.ensureDirectories();
144
+ await storage.writeMemory("preference", "The user prefers vim keybindings.", { source: "test" });
145
+
146
+ await orchestrator.recall("editor preferences", "sess-trace", { traceId: "lane-8z:attempt-2" });
147
+ assert.equal(
148
+ orchestrator.lastRecall.get("sess-trace")?.traceId,
149
+ "lane-8z:attempt-2",
150
+ "caller ID is pinned on the snapshot the response echoes",
151
+ );
152
+
153
+ await orchestrator.recall("editor preferences again", "sess-derived");
154
+ assert.match(
155
+ orchestrator.lastRecall.get("sess-derived")?.traceId ?? "",
156
+ /^[0-9a-f]{16}$/,
157
+ "unsupplied recalls keep the derived 16-hex ID",
158
+ );
159
+ } finally {
160
+ await orchestrator.destroy();
161
+ await rm(memoryDir, { recursive: true, force: true });
162
+ }
163
+ });
164
+
165
+ test("#3499: shadow-eval filenames are hash-derived, safe for special-char caller traceIds", async () => {
166
+ const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-shadow-"));
167
+ try {
168
+ // A caller traceId like "lane-8z:attempt-2" is valid per the request
169
+ // schema but carries ':' — unsafe as a filename on some filesystems.
170
+ const recordTraceId = "lane-8z:attempt.2-1765123456789";
171
+ const targetPath = await recordEvalShadowRecall({
172
+ memoryDir,
173
+ record: {
174
+ schemaVersion: 1,
175
+ traceId: recordTraceId,
176
+ recordedAt: "2026-12-06T17:55:00.000Z",
177
+ sessionKey: "sess-shadow",
178
+ promptHash: "a".repeat(16),
179
+ promptLength: 24,
180
+ retrievalQueryHash: "b".repeat(16),
181
+ retrievalQueryLength: 30,
182
+ recallMode: "full",
183
+ recallResultLimit: 5,
184
+ source: "hot_qmd",
185
+ recalledMemoryCount: 2,
186
+ injected: true,
187
+ contextChars: 400,
188
+ memoryIds: [],
189
+ durationMs: 1234,
190
+ },
191
+ });
192
+
193
+ const fileName = path.basename(targetPath);
194
+ assert.match(fileName, /^[0-9a-f]{24}\.json$/, "filename is a hex hash, not the raw caller ID");
195
+ assert.equal(
196
+ fileName,
197
+ `${createHash("sha256").update(recordTraceId).digest("hex").slice(0, 24)}.json`,
198
+ "the filename deterministically derives from the record traceId",
199
+ );
200
+
201
+ // The raw caller-bearing ID stays in the JSON payload for correlation.
202
+ // SAFETY: recordEvalShadowRecall writes the validated record verbatim;
203
+ // traceId is a required string field of that record.
204
+ const payload = JSON.parse(await readFile(targetPath, "utf-8")) as { traceId: string };
205
+ assert.equal(payload.traceId, recordTraceId);
206
+ } finally {
207
+ await rm(memoryDir, { recursive: true, force: true });
208
+ }
209
+ });