@remnic/core 10.0.109 → 10.0.111

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 (213) hide show
  1. package/dist/access-admin-ops-surface.js +62 -61
  2. package/dist/access-cli.js +62 -61
  3. package/dist/access-cli.js.map +1 -1
  4. package/dist/access-coding-context-resolution.d.ts.map +1 -1
  5. package/dist/access-coding-context-resolution.js +2 -2
  6. package/dist/access-extraction-force-flush.js +62 -61
  7. package/dist/access-http-briefing.js +62 -61
  8. package/dist/access-http-query.js +62 -61
  9. package/dist/access-http.js +62 -61
  10. package/dist/access-identity-continuity-surface.js +62 -61
  11. package/dist/access-lcm-surface.js +62 -61
  12. package/dist/access-mcp.js +62 -61
  13. package/dist/access-observe-transcript.js +2 -2
  14. package/dist/access-observe-write-surface.js +62 -61
  15. package/dist/access-offline-manifest.js +5 -5
  16. package/dist/access-operations-batch.js +62 -61
  17. package/dist/access-operations.js +62 -61
  18. package/dist/access-recall-concurrency.js +62 -61
  19. package/dist/access-recall-response.js +62 -61
  20. package/dist/access-recall-surface.js +62 -61
  21. package/dist/access-service.js +62 -61
  22. package/dist/active-recall.js +9 -9
  23. package/dist/adapters/index.js +4 -4
  24. package/dist/adapters/registry.js +2 -2
  25. package/dist/briefing.js +10 -10
  26. package/dist/buffer.js +4 -4
  27. package/dist/causal-consolidation.js +11 -11
  28. package/dist/{chunk-7HNQR5MV.js → chunk-25JBIXAV.js} +3 -3
  29. package/dist/{chunk-7SW6EBEF.js → chunk-27YNNLRB.js} +2 -2
  30. package/dist/{chunk-NUQEREIP.js → chunk-3QNFHI6T.js} +6 -4
  31. package/dist/chunk-3QNFHI6T.js.map +1 -0
  32. package/dist/{chunk-E55J2NFL.js → chunk-477SVZUZ.js} +2 -2
  33. package/dist/{chunk-4RAJT5L2.js → chunk-5HFCXTGY.js} +99 -4
  34. package/dist/chunk-5HFCXTGY.js.map +1 -0
  35. package/dist/{chunk-QZPXXABV.js → chunk-6DUBULUV.js} +5 -5
  36. package/dist/{chunk-63OWJXGW.js → chunk-6YXIL26Y.js} +2 -2
  37. package/dist/{chunk-GT2TH7FZ.js → chunk-AAF7RX22.js} +3 -3
  38. package/dist/{chunk-B3LGXOM5.js → chunk-AJCXPMDA.js} +2 -2
  39. package/dist/{chunk-5VWN3FJS.js → chunk-BFRNDOHO.js} +2 -2
  40. package/dist/{chunk-K32VAS5B.js → chunk-BGM7O5TD.js} +2 -2
  41. package/dist/{chunk-FQACH7MC.js → chunk-BZAI3ETM.js} +2 -2
  42. package/dist/{chunk-UOIVXBNS.js → chunk-E5DYZM56.js} +2 -2
  43. package/dist/{chunk-GCZJ7XRI.js → chunk-EAHNSQ7H.js} +2 -2
  44. package/dist/{chunk-WQ4XKIOX.js → chunk-F32RH72R.js} +45 -37
  45. package/dist/chunk-F32RH72R.js.map +1 -0
  46. package/dist/{chunk-WCKLRFGF.js → chunk-F6GNH5UY.js} +2 -2
  47. package/dist/{chunk-DLZGSZVC.js → chunk-FYQUUIPI.js} +4 -4
  48. package/dist/{chunk-XTN54NML.js → chunk-G3T6YMBO.js} +4 -4
  49. package/dist/{chunk-AY535ZIM.js → chunk-G7QANNRD.js} +2 -2
  50. package/dist/chunk-GE5J2T67.js +100 -0
  51. package/dist/chunk-GE5J2T67.js.map +1 -0
  52. package/dist/{chunk-H4XPEXWA.js → chunk-GG3QMQEG.js} +2 -2
  53. package/dist/{chunk-LGEHAQHK.js → chunk-HRWZEP5O.js} +2 -2
  54. package/dist/{chunk-FVMEZ57K.js → chunk-HWMIXG3J.js} +10 -10
  55. package/dist/{chunk-LYR57GEF.js → chunk-I5PCMNN5.js} +3 -3
  56. package/dist/{chunk-QIGEWFXE.js → chunk-INXS64LQ.js} +2 -2
  57. package/dist/{chunk-BP7LNNWG.js → chunk-IOTMEQUC.js} +2 -2
  58. package/dist/{chunk-PZJQ46DH.js → chunk-JCAMHTS2.js} +2 -2
  59. package/dist/{chunk-5NFF2TSD.js → chunk-KBUFYKUN.js} +2 -2
  60. package/dist/{chunk-S2HLHAZ4.js → chunk-L76BQSWB.js} +10 -2
  61. package/dist/chunk-L76BQSWB.js.map +1 -0
  62. package/dist/{chunk-7QIRIF3Z.js → chunk-LFPGCYXE.js} +2 -2
  63. package/dist/{chunk-YD4D4EVO.js → chunk-MPIMRX3I.js} +2 -2
  64. package/dist/{chunk-4IJFJQPD.js → chunk-MYXJCR3E.js} +2 -2
  65. package/dist/{chunk-PFUXPTBT.js → chunk-P3AQ2YSX.js} +4 -4
  66. package/dist/{chunk-ZG4GNPRE.js → chunk-PBE7NFB5.js} +5 -5
  67. package/dist/{chunk-FV2B6XE6.js → chunk-R3LYKUZH.js} +2 -2
  68. package/dist/{chunk-OIOKDTZU.js → chunk-SZXDGB32.js} +17 -6
  69. package/dist/chunk-SZXDGB32.js.map +1 -0
  70. package/dist/{chunk-BUOP3DOK.js → chunk-TR4HFZBD.js} +2 -2
  71. package/dist/{chunk-V2QSNFCT.js → chunk-U5I2G4VU.js} +2 -2
  72. package/dist/{chunk-2R3ACFYN.js → chunk-U7LMXR2W.js} +2 -2
  73. package/dist/{chunk-QRMG4HK4.js → chunk-UPWOMMVU.js} +3 -3
  74. package/dist/{chunk-JODSN3V5.js → chunk-UY3JSQ7H.js} +2 -2
  75. package/dist/{chunk-CCFGLUSC.js → chunk-WDAIXMEU.js} +87 -73
  76. package/dist/chunk-WDAIXMEU.js.map +1 -0
  77. package/dist/{chunk-HCCRWSP7.js → chunk-WOXO4HE6.js} +3 -3
  78. package/dist/{chunk-2BXPAOOR.js → chunk-X3HLHS5E.js} +7 -7
  79. package/dist/{chunk-YU3TOAXV.js → chunk-XSFDRM2P.js} +3 -3
  80. package/dist/{chunk-DOJBV6WR.js → chunk-YK6SFDP2.js} +4 -4
  81. package/dist/{chunk-4ANH42MO.js → chunk-YQ7H7P4Y.js} +7 -7
  82. package/dist/{chunk-IOGYSADY.js → chunk-YTNLLRHQ.js} +2 -2
  83. package/dist/{chunk-EDVVW655.js → chunk-Z4NOA733.js} +2 -2
  84. package/dist/{chunk-AZYUG2HW.js → chunk-Z64ANMII.js} +2 -2
  85. package/dist/{chunk-OEVJH66T.js → chunk-ZAMVB4JK.js} +3 -3
  86. package/dist/cli.js +62 -61
  87. package/dist/coding/export-okf-codegraph.js +10 -10
  88. package/dist/coding/git-context.d.ts +33 -0
  89. package/dist/coding/git-context.d.ts.map +1 -1
  90. package/dist/compounding/engine.js +11 -11
  91. package/dist/config.js +9 -9
  92. package/dist/connectors/codex-materialize-runner.js +10 -10
  93. package/dist/connectors/index.js +10 -10
  94. package/dist/convergence-refresh.js +12 -12
  95. package/dist/corpus-watermark.js +12 -12
  96. package/dist/entity-retrieval.js +10 -10
  97. package/dist/explicit-capture.js +62 -61
  98. package/dist/extraction.js +15 -15
  99. package/dist/harmonic-retrieval.js +10 -10
  100. package/dist/index.js +83 -82
  101. package/dist/lcm/engine.js +2 -2
  102. package/dist/lcm/index.js +5 -5
  103. package/dist/location/index.js +11 -11
  104. package/dist/maintenance/memory-governance.js +10 -10
  105. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +10 -10
  106. package/dist/maintenance/rebuild-memory-projection-runner.js +12 -12
  107. package/dist/maintenance/rebuild-memory-projection.js +11 -11
  108. package/dist/memory-snapshot.d.ts +7 -1
  109. package/dist/memory-snapshot.d.ts.map +1 -1
  110. package/dist/memory-snapshot.js +5 -3
  111. package/dist/namespaces/migrate.js +11 -11
  112. package/dist/namespaces/search.js +7 -7
  113. package/dist/namespaces/storage.js +10 -10
  114. package/dist/offline-sync-impression-drain.js +4 -4
  115. package/dist/operator-doctor-corpus.js +13 -13
  116. package/dist/operator-toolkit.js +19 -19
  117. package/dist/orchestration/backlog-scheduler.js +63 -62
  118. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  119. package/dist/orchestration/buffer-drain-runner.js +63 -62
  120. package/dist/orchestration/maintenance.js +21 -21
  121. package/dist/orchestration/recall-internal.d.ts.map +1 -1
  122. package/dist/orchestration/workspace-ops.d.ts.map +1 -1
  123. package/dist/orchestrator.js +62 -61
  124. package/dist/recall-navigation.js +62 -61
  125. package/dist/resume-bundles.js +12 -11
  126. package/dist/search/factory.js +6 -6
  127. package/dist/search/index.js +11 -11
  128. package/dist/search/lancedb-backend.js +2 -2
  129. package/dist/search/meilisearch-backend.js +2 -2
  130. package/dist/search/orama-backend.js +2 -2
  131. package/dist/semantic-consolidation.js +11 -11
  132. package/dist/semantic-rule-promotion.js +10 -10
  133. package/dist/semantic-rule-verifier.js +10 -10
  134. package/dist/source-agent-qualifier.js +14 -14
  135. package/dist/standup/build.js +10 -10
  136. package/dist/storage.d.ts +3 -0
  137. package/dist/storage.d.ts.map +1 -1
  138. package/dist/storage.js +9 -9
  139. package/dist/transcript-recent.d.ts +22 -0
  140. package/dist/transcript-recent.d.ts.map +1 -0
  141. package/dist/transcript-recent.js +15 -0
  142. package/dist/transcript-recent.js.map +1 -0
  143. package/dist/transcript.d.ts +11 -3
  144. package/dist/transcript.d.ts.map +1 -1
  145. package/dist/transcript.js +2 -1
  146. package/dist/transfer/export-okf.js +10 -10
  147. package/dist/verified-recall.js +10 -10
  148. package/dist/who-knows-cli.js +11 -11
  149. package/dist/who-knows.js +10 -10
  150. package/package.json +2 -2
  151. package/src/access-coding-context-resolution.ts +2 -1
  152. package/src/access-service.ts +2 -2
  153. package/src/coding/git-context.test.ts +270 -0
  154. package/src/coding/git-context.ts +140 -3
  155. package/src/memory-snapshot.ts +14 -1
  156. package/src/orchestration/recall-internal.ts +1 -4
  157. package/src/orchestration/workspace-ops.test.ts +113 -0
  158. package/src/orchestration/workspace-ops.ts +38 -12
  159. package/src/storage-contract/lazy-memory-snapshot.test.ts +194 -0
  160. package/src/storage.ts +15 -4
  161. package/src/transcript-recent-tail.test.ts +355 -0
  162. package/src/transcript-recent.ts +129 -0
  163. package/src/transcript.ts +47 -47
  164. package/dist/chunk-4RAJT5L2.js.map +0 -1
  165. package/dist/chunk-CCFGLUSC.js.map +0 -1
  166. package/dist/chunk-NUQEREIP.js.map +0 -1
  167. package/dist/chunk-OIOKDTZU.js.map +0 -1
  168. package/dist/chunk-S2HLHAZ4.js.map +0 -1
  169. package/dist/chunk-WQ4XKIOX.js.map +0 -1
  170. /package/dist/{chunk-7HNQR5MV.js.map → chunk-25JBIXAV.js.map} +0 -0
  171. /package/dist/{chunk-7SW6EBEF.js.map → chunk-27YNNLRB.js.map} +0 -0
  172. /package/dist/{chunk-E55J2NFL.js.map → chunk-477SVZUZ.js.map} +0 -0
  173. /package/dist/{chunk-QZPXXABV.js.map → chunk-6DUBULUV.js.map} +0 -0
  174. /package/dist/{chunk-63OWJXGW.js.map → chunk-6YXIL26Y.js.map} +0 -0
  175. /package/dist/{chunk-GT2TH7FZ.js.map → chunk-AAF7RX22.js.map} +0 -0
  176. /package/dist/{chunk-B3LGXOM5.js.map → chunk-AJCXPMDA.js.map} +0 -0
  177. /package/dist/{chunk-5VWN3FJS.js.map → chunk-BFRNDOHO.js.map} +0 -0
  178. /package/dist/{chunk-K32VAS5B.js.map → chunk-BGM7O5TD.js.map} +0 -0
  179. /package/dist/{chunk-FQACH7MC.js.map → chunk-BZAI3ETM.js.map} +0 -0
  180. /package/dist/{chunk-UOIVXBNS.js.map → chunk-E5DYZM56.js.map} +0 -0
  181. /package/dist/{chunk-GCZJ7XRI.js.map → chunk-EAHNSQ7H.js.map} +0 -0
  182. /package/dist/{chunk-WCKLRFGF.js.map → chunk-F6GNH5UY.js.map} +0 -0
  183. /package/dist/{chunk-DLZGSZVC.js.map → chunk-FYQUUIPI.js.map} +0 -0
  184. /package/dist/{chunk-XTN54NML.js.map → chunk-G3T6YMBO.js.map} +0 -0
  185. /package/dist/{chunk-AY535ZIM.js.map → chunk-G7QANNRD.js.map} +0 -0
  186. /package/dist/{chunk-H4XPEXWA.js.map → chunk-GG3QMQEG.js.map} +0 -0
  187. /package/dist/{chunk-LGEHAQHK.js.map → chunk-HRWZEP5O.js.map} +0 -0
  188. /package/dist/{chunk-FVMEZ57K.js.map → chunk-HWMIXG3J.js.map} +0 -0
  189. /package/dist/{chunk-LYR57GEF.js.map → chunk-I5PCMNN5.js.map} +0 -0
  190. /package/dist/{chunk-QIGEWFXE.js.map → chunk-INXS64LQ.js.map} +0 -0
  191. /package/dist/{chunk-BP7LNNWG.js.map → chunk-IOTMEQUC.js.map} +0 -0
  192. /package/dist/{chunk-PZJQ46DH.js.map → chunk-JCAMHTS2.js.map} +0 -0
  193. /package/dist/{chunk-5NFF2TSD.js.map → chunk-KBUFYKUN.js.map} +0 -0
  194. /package/dist/{chunk-7QIRIF3Z.js.map → chunk-LFPGCYXE.js.map} +0 -0
  195. /package/dist/{chunk-YD4D4EVO.js.map → chunk-MPIMRX3I.js.map} +0 -0
  196. /package/dist/{chunk-4IJFJQPD.js.map → chunk-MYXJCR3E.js.map} +0 -0
  197. /package/dist/{chunk-PFUXPTBT.js.map → chunk-P3AQ2YSX.js.map} +0 -0
  198. /package/dist/{chunk-ZG4GNPRE.js.map → chunk-PBE7NFB5.js.map} +0 -0
  199. /package/dist/{chunk-FV2B6XE6.js.map → chunk-R3LYKUZH.js.map} +0 -0
  200. /package/dist/{chunk-BUOP3DOK.js.map → chunk-TR4HFZBD.js.map} +0 -0
  201. /package/dist/{chunk-V2QSNFCT.js.map → chunk-U5I2G4VU.js.map} +0 -0
  202. /package/dist/{chunk-2R3ACFYN.js.map → chunk-U7LMXR2W.js.map} +0 -0
  203. /package/dist/{chunk-QRMG4HK4.js.map → chunk-UPWOMMVU.js.map} +0 -0
  204. /package/dist/{chunk-JODSN3V5.js.map → chunk-UY3JSQ7H.js.map} +0 -0
  205. /package/dist/{chunk-HCCRWSP7.js.map → chunk-WOXO4HE6.js.map} +0 -0
  206. /package/dist/{chunk-2BXPAOOR.js.map → chunk-X3HLHS5E.js.map} +0 -0
  207. /package/dist/{chunk-YU3TOAXV.js.map → chunk-XSFDRM2P.js.map} +0 -0
  208. /package/dist/{chunk-DOJBV6WR.js.map → chunk-YK6SFDP2.js.map} +0 -0
  209. /package/dist/{chunk-4ANH42MO.js.map → chunk-YQ7H7P4Y.js.map} +0 -0
  210. /package/dist/{chunk-IOGYSADY.js.map → chunk-YTNLLRHQ.js.map} +0 -0
  211. /package/dist/{chunk-EDVVW655.js.map → chunk-Z4NOA733.js.map} +0 -0
  212. /package/dist/{chunk-AZYUG2HW.js.map → chunk-Z64ANMII.js.map} +0 -0
  213. /package/dist/{chunk-OEVJH66T.js.map → chunk-ZAMVB4JK.js.map} +0 -0
@@ -21,6 +21,7 @@
21
21
  * when the directory is not inside a git worktree, because being outside a
22
22
  * repo is a normal runtime state (e.g. agent opened in a scratch dir).
23
23
  */
24
+ import { lstat, readFile, stat } from "node:fs/promises";
24
25
  import path from "node:path";
25
26
 
26
27
  import { abortError } from "../abort-error.js";
@@ -96,6 +97,8 @@ export interface SyncGitInvoker {
96
97
  // ──────────────────────────────────────────────────────────────────────────
97
98
 
98
99
  const DEFAULT_GIT_TIMEOUT_MS = 2_000;
100
+ const GIT_TIMEOUT_EXIT_CODE = 124;
101
+ const GIT_SPAWN_ERROR_EXIT_CODE = 127;
99
102
 
100
103
  export function defaultGitInvokerSync(): SyncGitInvoker {
101
104
  return (cwd: string, args: string[]) => {
@@ -105,7 +108,7 @@ export function defaultGitInvokerSync(): SyncGitInvoker {
105
108
  timeout: DEFAULT_GIT_TIMEOUT_MS,
106
109
  shell: false,
107
110
  });
108
- if (result.error) return { stdout: "", exitCode: 127 };
111
+ if (result.error) return { stdout: "", exitCode: GIT_SPAWN_ERROR_EXIT_CODE };
109
112
  return {
110
113
  stdout: typeof result.stdout === "string" ? result.stdout : "",
111
114
  exitCode: typeof result.status === "number" ? result.status : 1,
@@ -161,7 +164,7 @@ export function defaultGitInvoker(): GitInvoker {
161
164
  child.stdout?.on("data", (chunk: string | Buffer) => {
162
165
  stdout += chunk.toString();
163
166
  });
164
- child.once("error", () => finish({ stdout: "", exitCode: 127 }));
167
+ child.once("error", () => finish({ stdout: "", exitCode: GIT_SPAWN_ERROR_EXIT_CODE }));
165
168
  child.once("close", (exitCode: number | null) => {
166
169
  finish({ stdout, exitCode: typeof exitCode === "number" ? exitCode : 1 });
167
170
  });
@@ -173,7 +176,7 @@ export function defaultGitInvoker(): GitInvoker {
173
176
  );
174
177
  timer = setTimeout(() => {
175
178
  child.kill("SIGTERM");
176
- finish({ stdout: "", exitCode: 124 });
179
+ finish({ stdout: "", exitCode: GIT_TIMEOUT_EXIT_CODE });
177
180
  }, timeoutMs);
178
181
  if (options.abortSignal?.aborted) onAbort();
179
182
  return promise;
@@ -320,6 +323,55 @@ export interface ResolveGitContextOptions {
320
323
  deadlineMs?: number;
321
324
  /** Injectable clock for deadline tests. */
322
325
  now?: () => number;
326
+ /**
327
+ * Share results across calls. Each miss costs up to five `git` spawns on the
328
+ * event loop, so per-request callers (recall, memory_store) pass one.
329
+ */
330
+ cache?: GitContextCache;
331
+ }
332
+
333
+ /** Short-lived, bounded memo of git resolution per cwd (COS-666). */
334
+ export class GitContextCache {
335
+ private readonly entries = new Map<string, { value: GitContext | null; head?: string; at: number }>();
336
+ private readonly ttlMs: number;
337
+ private readonly maxEntries: number;
338
+ private readonly now: () => number;
339
+
340
+ private readonly cacheRepos: boolean;
341
+
342
+ constructor(options: { ttlMs?: number; maxEntries?: number; now?: () => number; cacheRepos?: boolean } = {}) {
343
+ this.cacheRepos = options.cacheRepos ?? true;
344
+ this.ttlMs = options.ttlMs ?? 30_000;
345
+ this.maxEntries = options.maxEntries ?? 256;
346
+ this.now = options.now ?? Date.now;
347
+ }
348
+
349
+ has(key: string): boolean {
350
+ return this.get(key) !== undefined;
351
+ }
352
+
353
+ /** `undefined` = miss; `value: null` = cached "not a repo". */
354
+ get(key: string): { value: GitContext | null; head?: string } | undefined {
355
+ const hit = this.entries.get(key);
356
+ if (!hit) return undefined;
357
+ if (this.now() - hit.at >= this.ttlMs) {
358
+ this.entries.delete(key);
359
+ return undefined;
360
+ }
361
+ return hit;
362
+ }
363
+
364
+ set(key: string, value: GitContext | null, head?: string): void {
365
+ // Negative-only caches never hold a branch, so a session snapshot taken
366
+ // from them cannot carry a stale one.
367
+ if (value !== null && !this.cacheRepos) return;
368
+ this.entries.delete(key);
369
+ this.entries.set(key, { value, head, at: this.now() });
370
+ if (this.entries.size > this.maxEntries) {
371
+ const oldest = this.entries.keys().next();
372
+ if (!oldest.done) this.entries.delete(oldest.value);
373
+ }
374
+ }
323
375
  }
324
376
 
325
377
  /**
@@ -334,6 +386,82 @@ export interface ResolveGitContextOptions {
334
386
  export async function resolveGitContext(
335
387
  cwd: string,
336
388
  options: ResolveGitContextOptions = {},
389
+ ): Promise<GitContext | null> {
390
+ const { cache } = options;
391
+ if (!cache) return resolveGitContextUncached(cwd, options);
392
+ // A cache hit must not mask cancellation or an exhausted deadline.
393
+ throwIfInterrupted(options);
394
+ const hit = cache.get(cwd);
395
+ if (hit?.value === null) return null;
396
+ // The branch picks the write/recall namespace and git alone decides it, so a
397
+ // hit is served only while HEAD is byte-identical to what git answered for.
398
+ if (hit?.value && hit.head !== undefined && (await readHeadFile(hit.value.rootPath)) === hit.head) {
399
+ return { ...hit.value };
400
+ }
401
+ // Timeouts and spawn failures are not answers about the repo, so a lookup
402
+ // that hit one (even partially) is never cached.
403
+ let inconclusive = false;
404
+ // HEAD is snapshotted once git names the root and BEFORE the branch probe: a
405
+ // checkout racing the probe then leaves the entry older than HEAD, so the
406
+ // next hit mismatches and re-resolves (never a stale branch pinned to a new HEAD).
407
+ let head: string | undefined;
408
+ const inner = options.invoker ?? defaultGitInvoker();
409
+ const invoker: GitInvoker = async (probeCwd, args, invokeOptions) => {
410
+ let result: GitInvokeResult;
411
+ try {
412
+ result = await inner(probeCwd, args, invokeOptions);
413
+ } catch (err) {
414
+ inconclusive = true;
415
+ throw err;
416
+ }
417
+ if (result.exitCode === GIT_TIMEOUT_EXIT_CODE || result.exitCode === GIT_SPAWN_ERROR_EXIT_CODE) inconclusive = true;
418
+ if (args[1] === "--show-toplevel" && result.exitCode === 0) head = await readHeadFile(result.stdout.trim());
419
+ return result;
420
+ };
421
+ const value = await resolveGitContextUncached(cwd, { ...options, invoker });
422
+ if (inconclusive || options.abortSignal?.aborted) return value;
423
+ if (value === null || head !== undefined) cache.set(cwd, value && { ...value }, head);
424
+ return value;
425
+ }
426
+
427
+ /**
428
+ * Raw `HEAD` contents without spawning git, or `undefined` when they cannot
429
+ * vouch for the branch: unreadable, a symlinked HEAD (old
430
+ * `core.preferSymlinkRefs`), or reftable's constant `refs/heads/.invalid`
431
+ * placeholder (HEAD never changes on checkout there). Callers then re-resolve.
432
+ */
433
+ async function readHeadFile(rootPath: string): Promise<string | undefined> {
434
+ try {
435
+ let gitDir = path.join(rootPath, ".git");
436
+ if ((await stat(gitDir)).isFile()) {
437
+ // Linked worktree: `.git` is a file pointing at the real git dir.
438
+ const pointer = /^gitdir:\s*(.+)$/m.exec(await readFile(gitDir, "utf-8"));
439
+ if (!pointer?.[1]) return undefined;
440
+ gitDir = path.resolve(rootPath, pointer[1].trim());
441
+ }
442
+ const headPath = path.join(gitDir, "HEAD");
443
+ if ((await lstat(headPath)).isSymbolicLink()) return undefined;
444
+ const head = await readFile(headPath, "utf-8");
445
+ return head.includes("refs/heads/.invalid") ? undefined : head;
446
+ } catch {
447
+ return undefined;
448
+ }
449
+ }
450
+
451
+ function throwIfInterrupted(options: ResolveGitContextOptions): void {
452
+ if (options.abortSignal?.aborted) {
453
+ throw options.abortSignal.reason instanceof Error
454
+ ? options.abortSignal.reason
455
+ : abortError("git context resolution aborted");
456
+ }
457
+ if (options.deadlineMs !== undefined && (options.now ?? Date.now)() >= options.deadlineMs) {
458
+ throw abortError("git context resolution deadline exceeded");
459
+ }
460
+ }
461
+
462
+ async function resolveGitContextUncached(
463
+ cwd: string,
464
+ options: ResolveGitContextOptions,
337
465
  ): Promise<GitContext | null> {
338
466
  // Wrap the whole body so the documented "Never throws" contract is
339
467
  // enforced. Possible throw sites include:
@@ -436,3 +564,12 @@ export async function resolveGitContext(
436
564
  return null;
437
565
  }
438
566
  }
567
+
568
+ /** Process-wide cache for per-request callers (recall scope). */
569
+ export const sharedGitContextCache = new GitContextCache();
570
+
571
+ /**
572
+ * Session-attach callers snapshot the branch once per session, so they must
573
+ * read a repo fresh; they only skip repeat probes of non-repo directories.
574
+ */
575
+ export const sharedNonRepoGitContextCache = new GitContextCache({ cacheRepos: false });
@@ -1,4 +1,4 @@
1
- import type { MemoryFile } from "./types.js";
1
+ import type { MemoryFile, MemoryFrontmatter } from "./types.js";
2
2
 
3
3
  function sortSnapshotObject(_key: string, candidate: unknown): unknown {
4
4
  if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) return candidate;
@@ -13,3 +13,16 @@ function sortSnapshotObject(_key: string, candidate: unknown): unknown {
13
13
  export function createMemorySnapshot(memory: MemoryFile): string {
14
14
  return JSON.stringify([memory.frontmatter, memory.content], sortSnapshotObject);
15
15
  }
16
+
17
+ /**
18
+ * created/updated for a snapshot rebuilt from a file's text. parseFrontmatter stamps a missing key with "now", so take
19
+ * the loaded memory's own stamp instead, as the old eager snapshot did: a file with no timestamps then never matches a
20
+ * later read of itself (refused every time, not by clock tick). Key presence follows the parser, which trims the key.
21
+ */
22
+ export function loadTimeStamps(raw: string, parsed: MemoryFrontmatter, loaded: MemoryFrontmatter): Pick<MemoryFrontmatter, "created" | "updated"> {
23
+ const front = raw.slice(0, raw.indexOf("\n---", 3)); // the block parseFrontmatter reads, without a lazy regex
24
+ return {
25
+ created: /^[ \t]*created[ \t]*:/m.test(front) ? parsed.created : loaded.created,
26
+ updated: /^[ \t]*updated[ \t]*:/m.test(front) ? parsed.updated : loaded.updated,
27
+ };
28
+ }
@@ -2361,10 +2361,7 @@ export class RecallInternalCoordinator {
2361
2361
  }
2362
2362
 
2363
2363
  if (!checkpointInjected) {
2364
- const entries = await this.deps.transcript.readRecent(
2365
- transcriptLookbackHours,
2366
- sessionKey,
2367
- );
2364
+ const entries = await this.deps.transcript.readRecent(transcriptLookbackHours, sessionKey, transcriptMaxTurns);
2368
2365
  log.debug(
2369
2366
  `recall: read ${entries.length} transcript entries for sessionKey=${sessionKey}`,
2370
2367
  );
@@ -383,3 +383,116 @@ test("trackMemoryAccess preserves namespaces for relative paths", () => {
383
383
  ],
384
384
  );
385
385
  });
386
+
387
+ // COS-666e: flushAccessTracking scanned the whole corpus for every buffered update and resolved paths on each
388
+ // comparison: 100 updates x 130k memories x 2-3 resolves was a 40 s main-thread stall in production.
389
+ type FlushMemory = { path: string; frontmatter: { id: string; accessCount: number } };
390
+ type FlushBuffer = WorkspaceOpsDeps["accessTrackingBuffer"];
391
+
392
+ interface FlushOut {
393
+ flushed: AccessTrackingEntry[];
394
+ }
395
+
396
+
397
+ function flushHarness(memories: FlushMemory[], buffered: FlushBuffer) {
398
+ const out: FlushOut = { flushed: [] };
399
+ const deps = {
400
+ config: {
401
+ namespacesEnabled: false,
402
+ defaultNamespace: "default",
403
+ sharedNamespace: "shared",
404
+ namespacePolicies: [],
405
+ memoryDir: "/memory",
406
+ },
407
+ accessTrackingBuffer: buffered,
408
+ readAllMemoriesForNamespaces: async () => memories,
409
+ namespaceFromPath: () => "default",
410
+ storageRouter: {
411
+ storageFor: async () => ({
412
+ flushAccessTracking: async (entries: AccessTrackingEntry[]) => {
413
+ out.flushed = entries;
414
+ },
415
+ }),
416
+ },
417
+ };
418
+ // SAFETY: flushAccessTracking reads only the fields stubbed above; the full deps object is not worth building.
419
+ // oxlint-disable-next-line anti-slop/no-chained-type-assertions
420
+ return { out, coordinator: new WorkspaceOpsCoordinator(deps as unknown as WorkspaceOpsDeps) };
421
+ }
422
+
423
+ const stamp = "2026-07-19T00:00:00.000Z";
424
+
425
+ test("flushAccessTracking picks the first memory in corpus order when several match a buffered path or id", async () => {
426
+ const first = path.join("/memory", "facts", "dup.md");
427
+ const memories = [
428
+ { path: first, frontmatter: { id: "dup-a", accessCount: 10 } },
429
+ { path: path.join("/memory", "facts", "..", "facts", "dup.md"), frontmatter: { id: "dup-b", accessCount: 20 } }, // same resolved path
430
+ { path: path.join("/memory", "facts", "other.md"), frontmatter: { id: "same-id", accessCount: 30 } },
431
+ { path: path.join("/memory", "facts", "other2.md"), frontmatter: { id: "same-id", accessCount: 40 } },
432
+ ];
433
+ const buffered: FlushBuffer = new Map([
434
+ ["default:dup", { memoryId: "x", memoryPath: path.join("facts", "dup.md"), count: 1, lastAccessed: stamp }],
435
+ ["default:same-id", { memoryId: "same-id", count: 1, lastAccessed: stamp }],
436
+ ]);
437
+ const { out, coordinator } = flushHarness(memories, buffered);
438
+ await coordinator.flushAccessTracking();
439
+ const byPath = new Map(out.flushed.map((e) => [e.memoryPath, e.newCount]));
440
+ assert.equal(byPath.get(first), 11);
441
+ assert.equal(byPath.get(memories[2].path), 31);
442
+ assert.equal(out.flushed.length, 2);
443
+ });
444
+
445
+ test("flushAccessTracking looks buffered paths up in an index, not by scanning the corpus per update", async (t) => {
446
+ const corpus = 3000;
447
+ const memories = Array.from({ length: corpus }, (_, i) => ({
448
+ path: path.join("/memory", "facts", `m${i}.md`),
449
+ frontmatter: { id: `m${i}`, accessCount: i },
450
+ }));
451
+ const buffered: FlushBuffer = new Map();
452
+ for (let i = 0; i < 100; i++) {
453
+ const at = 2900 - i * 20; // late in the corpus: a scan walks almost all of it
454
+ buffered.set(`default:m${at}`, {
455
+ memoryId: `m${at}`,
456
+ memoryPath: i % 2 === 0 ? memories[at].path : path.join("facts", `m${at}.md`), // absolute, or relative to the memory dir
457
+ count: 1,
458
+ lastAccessed: stamp,
459
+ });
460
+ }
461
+ const { out, coordinator } = flushHarness(memories, buffered);
462
+ const resolve = t.mock.method(path, "resolve");
463
+ await coordinator.flushAccessTracking();
464
+ assert.equal(out.flushed.length, 100);
465
+ assert.equal(out.flushed.find((e) => e.memoryId === "m2900")?.newCount, 2901);
466
+ assert.equal(out.flushed.find((e) => e.memoryId === "m1000")?.newCount, 1001);
467
+ assert.ok(resolve.mock.callCount() < corpus * 4, `${resolve.mock.callCount()} path.resolve calls for ${corpus} memories and 100 updates`);
468
+ });
469
+
470
+ test("flushAccessTracking with 100 updates over 20,000 memories finishes in well under a second", async () => {
471
+ const memories = Array.from({ length: 20_000 }, (_, i) => ({
472
+ path: path.join("/memory", "facts", `m${i}.md`),
473
+ frontmatter: { id: `m${i}`, accessCount: 0 },
474
+ }));
475
+ const buffered: FlushBuffer = new Map();
476
+ for (let i = 0; i < 100; i++) {
477
+ const at = 19_999 - i * 7;
478
+ buffered.set(`default:m${at}`, { memoryId: `m${at}`, memoryPath: memories[at].path, count: 1, lastAccessed: stamp });
479
+ }
480
+ const { out, coordinator } = flushHarness(memories, buffered);
481
+ const started = performance.now();
482
+ await coordinator.flushAccessTracking();
483
+ const elapsed = performance.now() - started;
484
+ assert.equal(out.flushed.length, 100);
485
+ assert.ok(elapsed < 1000, `flush took ${Math.round(elapsed)} ms`); // the per-update corpus scan took several seconds here
486
+ });
487
+
488
+ test("flushAccessTracking takes the earlier memory when a relative path matches one as given and another under the memory dir", async () => {
489
+ const underMemoryDir = path.join("/memory", "facts", "x.md");
490
+ const memories = [
491
+ { path: underMemoryDir, frontmatter: { id: "under-dir", accessCount: 5 } },
492
+ { path: path.resolve("facts", "x.md"), frontmatter: { id: "as-given", accessCount: 50 } },
493
+ ];
494
+ const buffered: FlushBuffer = new Map([["default:x", { memoryId: "x", memoryPath: path.join("facts", "x.md"), count: 1, lastAccessed: stamp }]]);
495
+ const { out, coordinator } = flushHarness(memories, buffered);
496
+ await coordinator.flushAccessTracking();
497
+ assert.deepEqual(out.flushed.map((e) => [e.memoryPath, e.newCount]), [[underMemoryDir, 6]]);
498
+ });
@@ -120,9 +120,35 @@ export interface WorkspaceOpsDeps {
120
120
  readonly meetingsServiceByNamespace: Map<string, MeetingsService>;
121
121
  }
122
122
 
123
- function matchesMemoryPath(candidatePath: string, requestedPath: string, memoryDir: string): boolean {
124
- const normalizedCandidate = path.resolve(candidatePath);
125
- return normalizedCandidate === path.resolve(requestedPath) || normalizedCandidate === path.resolve(memoryDir, requestedPath);
123
+ /** A namespace's memories keyed for lookup: first index per resolved path, first memory per id (corpus order wins). */
124
+ interface MemoryIndex {
125
+ readonly list: MemoryFile[];
126
+ readonly byPath: Map<string, number>;
127
+ readonly byId: Map<string, MemoryFile>;
128
+ }
129
+
130
+ // COS-666e: the old per-update `find` over the corpus resolved paths on every comparison (a 40 s stall at 130k memories).
131
+ function indexMemories(list: MemoryFile[]): MemoryIndex {
132
+ const byPath = new Map<string, number>();
133
+ const byId = new Map<string, MemoryFile>();
134
+ list.forEach((memory, i) => {
135
+ const resolved = path.resolve(memory.path);
136
+ if (!byPath.has(resolved)) byPath.set(resolved, i);
137
+ if (!byId.has(memory.frontmatter.id)) byId.set(memory.frontmatter.id, memory);
138
+ });
139
+ return { list, byPath, byId };
140
+ }
141
+
142
+ /** The first memory, in corpus order, whose path is a requested path as given or relative to the memory dir. */
143
+ function findByRequestedPaths(index: MemoryIndex, requestedPaths: string[], memoryDir: string): MemoryFile | undefined {
144
+ let best: number | undefined;
145
+ for (const requested of requestedPaths) {
146
+ for (const key of [path.resolve(requested), path.resolve(memoryDir, requested)]) {
147
+ const i = index.byPath.get(key);
148
+ if (i !== undefined && (best === undefined || i < best)) best = i;
149
+ }
150
+ }
151
+ return best === undefined ? undefined : index.list[best];
126
152
  }
127
153
 
128
154
  function accessTrackingPathCandidates(storageDir: string, memoryPath: string): string[] {
@@ -1016,6 +1042,7 @@ export class WorkspaceOpsCoordinator {
1016
1042
  const entriesByNamespace = new Map<string, AccessTrackingEntry[]>();
1017
1043
  const mergedEntriesByNamespace = new Map<string, Map<string, AccessTrackingEntry>>();
1018
1044
  const storageDirByNamespace = new Map<string, string | null>();
1045
+ const indexByNamespace = new Map<string, MemoryIndex>();
1019
1046
  for (const [, update] of this.deps.accessTrackingBuffer) {
1020
1047
  const memoryPath = update.memoryPath;
1021
1048
  const namespace =
@@ -1036,16 +1063,15 @@ export class WorkspaceOpsCoordinator {
1036
1063
  ...(storageDir ? accessTrackingPathCandidates(storageDir, memoryPath) : []),
1037
1064
  ]
1038
1065
  : [];
1066
+ let index = indexByNamespace.get(namespace);
1067
+ if (index === undefined && namespaceMemories) {
1068
+ index = indexMemories(namespaceMemories);
1069
+ indexByNamespace.set(namespace, index);
1070
+ }
1039
1071
  const memory = memoryPath
1040
- ? namespaceMemories?.find((candidate) =>
1041
- matchesMemoryPath(candidate.path, memoryPath, this.deps.config.memoryDir),
1042
- ) ??
1043
- namespaceMemories?.find((candidate) =>
1044
- requestedPaths.some((requestedPath) =>
1045
- matchesMemoryPath(candidate.path, requestedPath, this.deps.config.memoryDir),
1046
- ),
1047
- )
1048
- : namespaceMemories?.find((candidate) => candidate.frontmatter.id === update.memoryId);
1072
+ ? (index && (findByRequestedPaths(index, [memoryPath], this.deps.config.memoryDir) ??
1073
+ findByRequestedPaths(index, requestedPaths, this.deps.config.memoryDir)))
1074
+ : index?.byId.get(update.memoryId);
1049
1075
  if (!memory) continue;
1050
1076
 
1051
1077
  const namespaceEntries = mergedEntriesByNamespace.get(namespace) ?? new Map();
@@ -0,0 +1,194 @@
1
+ /**
2
+ * COS-666d: loading the corpus built a key-sorted JSON snapshot of every memory
3
+ * (`createMemorySnapshot`), 5-6.6 s of synchronous main-thread work at ~120k
4
+ * facts on every cache rebuild, for a value only `moveMemoryToPath` reads. The
5
+ * snapshot is now derived from the raw file text the loader already keeps, at
6
+ * the moment a tier move needs it, and means the same thing: the memory as it
7
+ * was loaded.
8
+ */
9
+
10
+ import assert from "node:assert/strict";
11
+ import test, { mock } from "node:test";
12
+ import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+
16
+ import { StorageManager } from "../storage.js";
17
+ import type { MemoryFile } from "../types.js";
18
+ import { resetStaticCaches } from "./harness.js";
19
+
20
+ /** Calls to the snapshot serializer: the only JSON.stringify here that is given a replacer function. */
21
+ async function countSnapshotCalls<T>(fn: () => Promise<T>): Promise<{ result: T; calls: number }> {
22
+ const spy = mock.method(JSON, "stringify");
23
+ try {
24
+ const result = await fn();
25
+ return { result, calls: spy.mock.calls.filter((call) => call.arguments[1] instanceof Function).length };
26
+ } finally {
27
+ spy.mock.restore();
28
+ }
29
+ }
30
+
31
+ async function withStorage(run: (storage: StorageManager, dir: string) => Promise<void>): Promise<void> {
32
+ const dir = await mkdtemp(path.join(os.tmpdir(), "remnic-lazy-snapshot-"));
33
+ try {
34
+ resetStaticCaches();
35
+ const storage = new StorageManager(dir);
36
+ await storage.ensureDirectories();
37
+ await run(storage, dir);
38
+ } finally {
39
+ resetStaticCaches();
40
+ await rm(dir, { recursive: true, force: true });
41
+ }
42
+ }
43
+
44
+ test("reading the corpus builds no snapshots", async () => {
45
+ await withStorage(async (storage) => {
46
+ for (let i = 0; i < 12; i++) await storage.writeMemory("fact", `lazy snapshot fact ${i}`);
47
+ resetStaticCaches();
48
+ const { result, calls } = await countSnapshotCalls(() => storage.readAllMemories());
49
+ assert.equal(result.length, 12);
50
+ assert.equal(calls, 0, "no snapshot may be built while loading the corpus");
51
+ const byPath = await countSnapshotCalls(() => storage.readMemoryByPath(result[0].path));
52
+ assert.ok(byPath.result);
53
+ assert.equal(byPath.calls, 0);
54
+ });
55
+ });
56
+
57
+ test("a tier move still succeeds for a loaded memory the caller mutated, and builds the snapshot only then", async () => {
58
+ await withStorage(async (storage) => {
59
+ const { id } = await storage.writeMemory("fact", "original disk content");
60
+ const memory = (await storage.readAllMemories()).find((m) => m.frontmatter.id === id);
61
+ assert.ok(memory);
62
+ memory.content = "caller mutated unpersisted content";
63
+ const targetPath = storage.buildTierMemoryPath(memory, "cold");
64
+ const { result, calls } = await countSnapshotCalls(() => storage.moveMemoryToPath(memory, targetPath));
65
+ assert.equal(result, true);
66
+ assert.ok(calls > 0, "the move compares snapshots");
67
+ assert.ok((await readFile(targetPath, "utf8")).includes("original disk content"));
68
+ });
69
+ });
70
+
71
+ test("a tier move refuses when the file changed on disk since it was loaded", async () => {
72
+ await withStorage(async (storage) => {
73
+ const { id } = await storage.writeMemory("fact", "unmodified content");
74
+ const memory = (await storage.readAllMemories()).find((m) => m.frontmatter.id === id);
75
+ assert.ok(memory);
76
+ const disk = await readFile(memory.path, "utf8");
77
+ await writeFile(memory.path, disk.replace("unmodified content", "external edit on disk"));
78
+ await assert.rejects(
79
+ () => storage.moveMemoryToPath(memory, storage.buildTierMemoryPath(memory, "cold")),
80
+ /changed before its tier move/,
81
+ );
82
+ });
83
+ });
84
+
85
+ test("a tier move ignores a rewrite that only reorders frontmatter keys (the snapshot is key-order independent)", async () => {
86
+ await withStorage(async (storage) => {
87
+ const { id } = await storage.writeMemory("fact", "reordered frontmatter");
88
+ const memory = (await storage.readAllMemories()).find((m) => m.frontmatter.id === id);
89
+ assert.ok(memory);
90
+ const disk = await readFile(memory.path, "utf8");
91
+ const closing = disk.indexOf("\n---\n", 4);
92
+ assert.ok(disk.startsWith("---\n") && closing > 0, "memory file has frontmatter");
93
+ const front = disk.slice(4, closing);
94
+ const body = disk.slice(closing + 5);
95
+ await writeFile(memory.path, `---\n${front.split("\n").reverse().join("\n")}\n---\n${body}`);
96
+ assert.equal(await storage.moveMemoryToPath(memory, storage.buildTierMemoryPath(memory, "cold")), true);
97
+ });
98
+ });
99
+
100
+ test("a memory with no retained file text falls back to an eager snapshot", async () => {
101
+ await withStorage(async (storage) => {
102
+ const { id } = await storage.writeMemory("fact", "no raw text");
103
+ const loaded = (await storage.readAllMemories()).find((m) => m.frontmatter.id === id);
104
+ assert.ok(loaded);
105
+ // A handcrafted object has no retained raw document and was never loaded: the old fallback
106
+ // compares `frontmatter.updated` only, so the same state moves and a changed one is refused.
107
+ const copy: MemoryFile = { path: loaded.path, frontmatter: { ...loaded.frontmatter }, content: loaded.content };
108
+ assert.equal(await storage.moveMemoryToPath(copy, storage.buildTierMemoryPath(copy, "cold")), true);
109
+ });
110
+ });
111
+
112
+ test("a loaded archive-path memory whose file has no status still moves (loaded status is archived)", async () => {
113
+ await withStorage(async (storage, dir) => {
114
+ const { id } = await storage.writeMemory("fact", "archived without status");
115
+ const source = (await storage.readAllMemories()).find((m) => m.frontmatter.id === id);
116
+ assert.ok(source);
117
+ const archivedPath = path.join(dir, "archive", "2026-01-01", `${id}.md`);
118
+ await mkdir(path.dirname(archivedPath), { recursive: true });
119
+ await rename(source.path, archivedPath);
120
+ resetStaticCaches();
121
+ const memory = (await storage.readArchivedMemories()).find((m) => m.frontmatter.id === id);
122
+ assert.ok(memory);
123
+ assert.equal(memory.frontmatter.status, "archived");
124
+ assert.equal(await storage.moveMemoryToPath(memory, storage.buildTierMemoryPath(memory, "cold")), true);
125
+ });
126
+ });
127
+
128
+ test("a tier move ignores caller edits to a loaded memory's frontmatter, not just its content", async () => {
129
+ await withStorage(async (storage) => {
130
+ const { id } = await storage.writeMemory("fact", "frontmatter edited by caller", { tags: ["kept"] });
131
+ const memory = (await storage.readAllMemories()).find((m) => m.frontmatter.id === id);
132
+ assert.ok(memory);
133
+ memory.frontmatter.tags = [...memory.frontmatter.tags, "caller-only"];
134
+ memory.frontmatter.confidence = 0.01;
135
+ memory.frontmatter.created = "2000-01-01T00:00:00.000Z";
136
+ memory.frontmatter.updated = "2000-01-02T00:00:00.000Z";
137
+ assert.equal(await storage.moveMemoryToPath(memory, storage.buildTierMemoryPath(memory, "cold")), true);
138
+ });
139
+ });
140
+
141
+ test("a file with no created or updated is refused on every move, not only when the clock ticks", async () => {
142
+ await withStorage(async (storage) => {
143
+ const memories: MemoryFile[] = [];
144
+ for (let i = 0; i < 12; i++) {
145
+ const { id } = await storage.writeMemory("fact", `no timestamps ${i}`);
146
+ const file = (await storage.readAllMemories()).find((m) => m.frontmatter.id === id);
147
+ assert.ok(file);
148
+ const disk = await readFile(file.path, "utf8");
149
+ await writeFile(file.path, disk.replace(/^(created|updated): .*\n/gm, ""));
150
+ }
151
+ resetStaticCaches();
152
+ for (const m of await storage.readAllMemories()) if (m.content.startsWith("no timestamps")) memories.push(m);
153
+ assert.equal(memories.length, 12);
154
+ await new Promise((resolve) => setTimeout(resolve, 5)); // a fresh parse now stamps a later millisecond
155
+ for (const memory of memories) {
156
+ await assert.rejects(
157
+ () => storage.moveMemoryToPath(memory, storage.buildTierMemoryPath(memory, "cold")),
158
+ /changed before its tier move/,
159
+ );
160
+ }
161
+ });
162
+ });
163
+
164
+ test("a loaded memory under an entities path moves: the snapshot normalizes with the file's content", async () => {
165
+ await withStorage(async (storage, dir) => {
166
+ const { id } = await storage.writeMemory("fact", "**Type:** vendor\n\nan entity-like note");
167
+ const source = (await storage.readAllMemories()).find((m) => m.frontmatter.id === id);
168
+ assert.ok(source);
169
+ const entityPath = path.join(dir, "facts", "entities", `${id}.md`);
170
+ await mkdir(path.dirname(entityPath), { recursive: true });
171
+ await rename(source.path, entityPath);
172
+ resetStaticCaches();
173
+ const memory = (await storage.readAllMemories()).find((m) => m.frontmatter.id === id);
174
+ assert.ok(memory);
175
+ assert.ok(memory.frontmatter.tags.includes("vendor"), "loaded tags carry the type read from the content");
176
+ assert.equal(await storage.moveMemoryToPath(memory, storage.buildTierMemoryPath(memory, "cold")), true);
177
+ });
178
+ });
179
+
180
+ test("an indented created or updated key counts as present: caller edits to it do not refuse the move", async () => {
181
+ await withStorage(async (storage) => {
182
+ const { id } = await storage.writeMemory("fact", "indented timestamp keys");
183
+ const file = (await storage.readAllMemories()).find((m) => m.frontmatter.id === id);
184
+ assert.ok(file);
185
+ const disk = await readFile(file.path, "utf8");
186
+ await writeFile(file.path, disk.replace(/^(created|updated):/gm, " $1:"));
187
+ resetStaticCaches();
188
+ const memory = (await storage.readAllMemories()).find((m) => m.frontmatter.id === id);
189
+ assert.ok(memory);
190
+ memory.frontmatter.created = "2000-01-01T00:00:00.000Z";
191
+ memory.frontmatter.updated = "2000-01-02T00:00:00.000Z";
192
+ assert.equal(await storage.moveMemoryToPath(memory, storage.buildTierMemoryPath(memory, "cold")), true);
193
+ });
194
+ });
package/src/storage.ts CHANGED
@@ -22,7 +22,7 @@ import { selectArtifactMatches, type ArtifactSearchOptions } from "./artifact-se
22
22
  import path from "node:path";
23
23
  import { resolveSafeStoragePath } from "./storage-paths.js";
24
24
  import { log } from "./logger.js";
25
- import { createMemorySnapshot } from "./memory-snapshot.js";
25
+ import { createMemorySnapshot, loadTimeStamps } from "./memory-snapshot.js";
26
26
  import { assertMemoryFrontmatterId, warnProjectionFallback } from "./storage-guards.js";
27
27
  import { createTombstoneMigrationSourceContents } from "./storage/tombstone-migration-sources.js";
28
28
  import { MemoryReadStore, readWindowedMemories, type WindowedMemoryReadOptions, type WindowedMemoryReadResult } from "./storage/memory-read-store.js";
@@ -62,7 +62,7 @@ import {
62
62
  type EntityCanonicalIdMigrationHost,
63
63
  } from "./storage/entity-canonical-id-migration-adapter.js";
64
64
  import { EntityCanonicalIdMigrationRunner } from "./storage/entity-canonical-id-migration-runner.js";
65
- import { rememberRawFrontmatter } from "./storage/memory-frontmatter-metadata.js";
65
+ import { readRawMemoryDocument, rememberRawFrontmatter } from "./storage/memory-frontmatter-metadata.js";
66
66
  import { createMemoryEntityRefSerializer } from "./storage/memory-migration-serialization.js";
67
67
  import { readEntityAliasConfigSync } from "./storage/entity-alias-config.js";
68
68
  import { assertSafeEntityId } from "./storage/entity-id-safety.js";
@@ -4343,13 +4343,24 @@ export class StorageManager extends TombstoneBlockedCaptureIndexHost {
4343
4343
  return lineCount > threshold;
4344
4344
  }
4345
4345
 
4346
+ /** Loaded memories keep their file text, so the load-time snapshot is derived from it when a tier move needs it, not built per memory on every corpus read (COS-666d). */
4346
4347
  private rememberMemorySnapshot<T extends MemoryFile | null>(memory: T): T {
4347
- if (memory !== null && !StorageManager.loadedMemorySnapshots.has(memory)) {
4348
+ if (memory !== null && readRawMemoryDocument(memory) === undefined && !StorageManager.loadedMemorySnapshots.has(memory)) {
4348
4349
  StorageManager.loadedMemorySnapshots.set(memory, createMemorySnapshot(memory));
4349
4350
  }
4350
4351
  return memory;
4351
4352
  }
4352
4353
 
4354
+ /** The snapshot of `memory` as loaded, rebuilt from its retained file text; undefined when none was retained. */
4355
+ private snapshotFromLoadedDocument(memory: MemoryFile): string | undefined {
4356
+ const raw = readRawMemoryDocument(memory);
4357
+ const parsed = raw === undefined ? null : parseFrontmatter(raw);
4358
+ if (raw === undefined || !parsed) return undefined;
4359
+ const frontmatter = { ...parsed.frontmatter, ...loadTimeStamps(raw, parsed.frontmatter, memory.frontmatter) };
4360
+ const normalized = normalizeFrontmatterForPath(frontmatter, toMemoryPathRel(this.baseDir, memory.path), parsed.content);
4361
+ return createMemorySnapshot({ path: memory.path, frontmatter: normalized, content: parsed.content });
4362
+ }
4363
+
4353
4364
  private rememberMemorySnapshots(memories: MemoryFile[]): MemoryFile[] {
4354
4365
  for (const memory of memories) this.rememberMemorySnapshot(memory);
4355
4366
  return memories;
@@ -5015,7 +5026,7 @@ export class StorageManager extends TombstoneBlockedCaptureIndexHost {
5015
5026
  if (current === null && destination?.frontmatter.id === memory.frontmatter.id) return false;
5016
5027
  throw new Error(`memory ${memory.frontmatter.id} changed before its tier move`);
5017
5028
  }
5018
- const callerSnapshot = StorageManager.loadedMemorySnapshots.get(memory);
5029
+ const callerSnapshot = StorageManager.loadedMemorySnapshots.get(memory) ?? this.snapshotFromLoadedDocument(memory);
5019
5030
  const currentSnapshot = createMemorySnapshot(current);
5020
5031
  if (
5021
5032
  callerSnapshot === undefined