@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
@@ -10,8 +10,11 @@ import {
10
10
  } from "./chunk-6KH5NLQS.js";
11
11
 
12
12
  // src/coding/git-context.ts
13
+ import { lstat, readFile, stat } from "fs/promises";
13
14
  import path from "path";
14
15
  var DEFAULT_GIT_TIMEOUT_MS = 2e3;
16
+ var GIT_TIMEOUT_EXIT_CODE = 124;
17
+ var GIT_SPAWN_ERROR_EXIT_CODE = 127;
15
18
  function defaultGitInvokerSync() {
16
19
  return (cwd, args) => {
17
20
  const result = launchProcessSync("git", args, {
@@ -20,7 +23,7 @@ function defaultGitInvokerSync() {
20
23
  timeout: DEFAULT_GIT_TIMEOUT_MS,
21
24
  shell: false
22
25
  });
23
- if (result.error) return { stdout: "", exitCode: 127 };
26
+ if (result.error) return { stdout: "", exitCode: GIT_SPAWN_ERROR_EXIT_CODE };
24
27
  return {
25
28
  stdout: typeof result.stdout === "string" ? result.stdout : "",
26
29
  exitCode: typeof result.status === "number" ? result.status : 1
@@ -68,7 +71,7 @@ function defaultGitInvoker() {
68
71
  child.stdout?.on("data", (chunk) => {
69
72
  stdout += chunk.toString();
70
73
  });
71
- child.once("error", () => finish({ stdout: "", exitCode: 127 }));
74
+ child.once("error", () => finish({ stdout: "", exitCode: GIT_SPAWN_ERROR_EXIT_CODE }));
72
75
  child.once("close", (exitCode) => {
73
76
  finish({ stdout, exitCode: typeof exitCode === "number" ? exitCode : 1 });
74
77
  });
@@ -79,7 +82,7 @@ function defaultGitInvoker() {
79
82
  );
80
83
  timer = setTimeout(() => {
81
84
  child.kill("SIGTERM");
82
- finish({ stdout: "", exitCode: 124 });
85
+ finish({ stdout: "", exitCode: GIT_TIMEOUT_EXIT_CODE });
83
86
  }, timeoutMs);
84
87
  if (options.abortSignal?.aborted) onAbort();
85
88
  return promise;
@@ -123,7 +126,95 @@ function normalizeOriginUrl(rawUrl) {
123
126
  }
124
127
  return url.toLowerCase();
125
128
  }
129
+ var GitContextCache = class {
130
+ entries = /* @__PURE__ */ new Map();
131
+ ttlMs;
132
+ maxEntries;
133
+ now;
134
+ cacheRepos;
135
+ constructor(options = {}) {
136
+ this.cacheRepos = options.cacheRepos ?? true;
137
+ this.ttlMs = options.ttlMs ?? 3e4;
138
+ this.maxEntries = options.maxEntries ?? 256;
139
+ this.now = options.now ?? Date.now;
140
+ }
141
+ has(key) {
142
+ return this.get(key) !== void 0;
143
+ }
144
+ /** `undefined` = miss; `value: null` = cached "not a repo". */
145
+ get(key) {
146
+ const hit = this.entries.get(key);
147
+ if (!hit) return void 0;
148
+ if (this.now() - hit.at >= this.ttlMs) {
149
+ this.entries.delete(key);
150
+ return void 0;
151
+ }
152
+ return hit;
153
+ }
154
+ set(key, value, head) {
155
+ if (value !== null && !this.cacheRepos) return;
156
+ this.entries.delete(key);
157
+ this.entries.set(key, { value, head, at: this.now() });
158
+ if (this.entries.size > this.maxEntries) {
159
+ const oldest = this.entries.keys().next();
160
+ if (!oldest.done) this.entries.delete(oldest.value);
161
+ }
162
+ }
163
+ };
126
164
  async function resolveGitContext(cwd, options = {}) {
165
+ const { cache } = options;
166
+ if (!cache) return resolveGitContextUncached(cwd, options);
167
+ throwIfInterrupted(options);
168
+ const hit = cache.get(cwd);
169
+ if (hit?.value === null) return null;
170
+ if (hit?.value && hit.head !== void 0 && await readHeadFile(hit.value.rootPath) === hit.head) {
171
+ return { ...hit.value };
172
+ }
173
+ let inconclusive = false;
174
+ let head;
175
+ const inner = options.invoker ?? defaultGitInvoker();
176
+ const invoker = async (probeCwd, args, invokeOptions) => {
177
+ let result;
178
+ try {
179
+ result = await inner(probeCwd, args, invokeOptions);
180
+ } catch (err) {
181
+ inconclusive = true;
182
+ throw err;
183
+ }
184
+ if (result.exitCode === GIT_TIMEOUT_EXIT_CODE || result.exitCode === GIT_SPAWN_ERROR_EXIT_CODE) inconclusive = true;
185
+ if (args[1] === "--show-toplevel" && result.exitCode === 0) head = await readHeadFile(result.stdout.trim());
186
+ return result;
187
+ };
188
+ const value = await resolveGitContextUncached(cwd, { ...options, invoker });
189
+ if (inconclusive || options.abortSignal?.aborted) return value;
190
+ if (value === null || head !== void 0) cache.set(cwd, value && { ...value }, head);
191
+ return value;
192
+ }
193
+ async function readHeadFile(rootPath) {
194
+ try {
195
+ let gitDir = path.join(rootPath, ".git");
196
+ if ((await stat(gitDir)).isFile()) {
197
+ const pointer = /^gitdir:\s*(.+)$/m.exec(await readFile(gitDir, "utf-8"));
198
+ if (!pointer?.[1]) return void 0;
199
+ gitDir = path.resolve(rootPath, pointer[1].trim());
200
+ }
201
+ const headPath = path.join(gitDir, "HEAD");
202
+ if ((await lstat(headPath)).isSymbolicLink()) return void 0;
203
+ const head = await readFile(headPath, "utf-8");
204
+ return head.includes("refs/heads/.invalid") ? void 0 : head;
205
+ } catch {
206
+ return void 0;
207
+ }
208
+ }
209
+ function throwIfInterrupted(options) {
210
+ if (options.abortSignal?.aborted) {
211
+ throw options.abortSignal.reason instanceof Error ? options.abortSignal.reason : abortError("git context resolution aborted");
212
+ }
213
+ if (options.deadlineMs !== void 0 && (options.now ?? Date.now)() >= options.deadlineMs) {
214
+ throw abortError("git context resolution deadline exceeded");
215
+ }
216
+ }
217
+ async function resolveGitContextUncached(cwd, options) {
127
218
  try {
128
219
  if (typeof cwd !== "string" || cwd.length === 0) return null;
129
220
  const expanded = expandTildePath(cwd);
@@ -195,6 +286,8 @@ async function resolveGitContext(cwd, options = {}) {
195
286
  return null;
196
287
  }
197
288
  }
289
+ var sharedGitContextCache = new GitContextCache();
290
+ var sharedNonRepoGitContextCache = new GitContextCache({ cacheRepos: false });
198
291
 
199
292
  // src/coding/coding-namespace.ts
200
293
  function sanitizeFragment(input) {
@@ -383,6 +476,8 @@ export {
383
476
  stableHash,
384
477
  normalizeOriginUrl,
385
478
  resolveGitContext,
479
+ sharedGitContextCache,
480
+ sharedNonRepoGitContextCache,
386
481
  sanitizeFragment,
387
482
  projectNamespaceName,
388
483
  projectTagProjectId,
@@ -393,4 +488,4 @@ export {
393
488
  lcmSessionKeyForNamespace,
394
489
  lcmReadSessionIdsForNamespaces
395
490
  };
396
- //# sourceMappingURL=chunk-4RAJT5L2.js.map
491
+ //# sourceMappingURL=chunk-5HFCXTGY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/coding/git-context.ts","../src/coding/coding-namespace.ts"],"sourcesContent":["/**\n * GitContextResolver — pure module for detecting the git project + branch\n * a session is operating in.\n *\n * Introduced by issue #569 (coding-agent project/branch-scoped namespaces).\n *\n * This module is deliberately pure:\n * - no orchestrator references\n * - no config side-effects\n * - no namespace wiring\n *\n * Downstream slices (PR 2+ of #569) wire `resolveGitContext` into the\n * `NamespaceResolver` / `Orchestrator` so that memories are scoped to a\n * detected project / branch without leaking across repos.\n *\n * CLAUDE.md rule 17 (expand `~`): the `rootPath` returned here is always an\n * absolute, tilde-expanded path. Callers must not re-expand.\n *\n * CLAUDE.md rule 51 (reject invalid input): `cwd` must be an absolute path\n * and must exist. `resolveGitContext` returns `null` — rather than throwing —\n * when the directory is not inside a git worktree, because being outside a\n * repo is a normal runtime state (e.g. agent opened in a scratch dir).\n */\nimport { lstat, readFile, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { abortError } from \"../abort-error.js\";\nimport { launchProcess, launchProcessSync } from \"../runtime/child-process.js\";\nimport { expandTildePath } from \"../utils/path.js\";\n\n// Re-export so existing callers / tests that imported `expandTildePath` from\n// this module keep working. CLAUDE.md #17 requires consistent `~` expansion\n// across every user-facing path input; the canonical implementation now\n// lives in `utils/path.ts`.\nexport { expandTildePath };\n\n// ──────────────────────────────────────────────────────────────────────────\n// Public types\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface GitContext {\n /**\n * Stable identifier for the project. Derived from `git remote get-url origin`\n * when an origin remote is configured, otherwise from the repo root path.\n *\n * Formatted as `origin:<hex>` or `root:<hex>` so that the source is visible\n * to operators (see `remnic doctor`, issue #569 acceptance criteria).\n */\n projectId: string;\n /**\n * Current branch, e.g. `main`, `feat/foo`. `null` only in detached-HEAD\n * state (e.g. rebase in progress). Callers should treat `null` as \"no\n * branch-scope overlay applies\" without erroring.\n */\n branch: string | null;\n /**\n * Absolute path to the repository root (the directory containing `.git`).\n * Tilde-expanded per CLAUDE.md #17.\n */\n rootPath: string;\n /**\n * Best-effort default branch (usually `main` or `master`). Derived from the\n * `refs/remotes/origin/HEAD` symbolic ref. `null` when not available (e.g.\n * fresh clone without a default branch symref, or no origin remote).\n */\n defaultBranch: string | null;\n}\n\nexport interface GitInvokeOptions {\n abortSignal?: AbortSignal;\n timeoutMs?: number;\n}\n\nexport interface GitInvokeResult {\n stdout: string;\n exitCode: number;\n}\n\n/**\n * Run `git <args>` with `cwd` as the working directory. Implementations\n * should return non-zero exit codes rather than throwing for command failure.\n */\nexport interface GitInvoker {\n (\n cwd: string,\n args: string[],\n options?: GitInvokeOptions,\n ): GitInvokeResult | Promise<GitInvokeResult>;\n}\n\nexport interface SyncGitInvoker {\n (cwd: string, args: string[]): GitInvokeResult;\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Default git invoker — spawns real `git` via the shared child-process helper\n// ──────────────────────────────────────────────────────────────────────────\n\nconst DEFAULT_GIT_TIMEOUT_MS = 2_000;\nconst GIT_TIMEOUT_EXIT_CODE = 124;\nconst GIT_SPAWN_ERROR_EXIT_CODE = 127;\n\nexport function defaultGitInvokerSync(): SyncGitInvoker {\n return (cwd: string, args: string[]) => {\n const result = launchProcessSync(\"git\", args, {\n cwd,\n encoding: \"utf-8\",\n timeout: DEFAULT_GIT_TIMEOUT_MS,\n shell: false,\n });\n if (result.error) return { stdout: \"\", exitCode: GIT_SPAWN_ERROR_EXIT_CODE };\n return {\n stdout: typeof result.stdout === \"string\" ? result.stdout : \"\",\n exitCode: typeof result.status === \"number\" ? result.status : 1,\n };\n };\n}\n\nexport function defaultGitInvoker(): GitInvoker {\n return (cwd, args, options = {}) => {\n if (options.abortSignal?.aborted) {\n throw options.abortSignal.reason instanceof Error\n ? options.abortSignal.reason\n : abortError(\"git context resolution aborted\");\n }\n\n const child = launchProcess(\"git\", args, {\n cwd,\n encoding: \"utf-8\",\n shell: false,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n const { promise, resolve, reject } = Promise.withResolvers<GitInvokeResult>();\n let stdout = \"\";\n let settled = false;\n let timer: NodeJS.Timeout | undefined;\n\n const cleanup = (): void => {\n clearTimeout(timer);\n options.abortSignal?.removeEventListener(\"abort\", onAbort);\n };\n const finish = (result: GitInvokeResult): void => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve(result);\n };\n const fail = (error: Error): void => {\n if (settled) return;\n settled = true;\n cleanup();\n reject(error);\n };\n const onAbort = (): void => {\n child.kill(\"SIGTERM\");\n fail(\n options.abortSignal?.reason instanceof Error\n ? options.abortSignal.reason\n : abortError(\"git context resolution aborted\"),\n );\n };\n\n child.stdout?.setEncoding(\"utf-8\");\n child.stdout?.on(\"data\", (chunk: string | Buffer) => {\n stdout += chunk.toString();\n });\n child.once(\"error\", () => finish({ stdout: \"\", exitCode: GIT_SPAWN_ERROR_EXIT_CODE }));\n child.once(\"close\", (exitCode: number | null) => {\n finish({ stdout, exitCode: typeof exitCode === \"number\" ? exitCode : 1 });\n });\n options.abortSignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n const timeoutMs = Math.max(\n 1,\n Math.min(DEFAULT_GIT_TIMEOUT_MS, options.timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS),\n );\n timer = setTimeout(() => {\n child.kill(\"SIGTERM\");\n finish({ stdout: \"\", exitCode: GIT_TIMEOUT_EXIT_CODE });\n }, timeoutMs);\n if (options.abortSignal?.aborted) onAbort();\n return promise;\n };\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Stable hashing\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Non-cryptographic stable hash. Used only to derive a deterministic\n * `projectId` from either the origin URL or the root path. The hash does not\n * need to be collision-resistant against adversarial input — it is purely a\n * namespace discriminator.\n *\n * Uses FNV-1a 32-bit so we don't pull in `node:crypto` for a simple bucket\n * key. Output is lowercase hex, zero-padded to 8 characters.\n */\nexport function stableHash(input: string): string {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Origin URL normalization\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Normalize a git remote URL so that equivalent SSH / HTTPS forms of the\n * same repo produce the same `projectId`. Handles:\n * - `git@github.com:foo/bar.git` → `github.com/foo/bar`\n * - `https://github.com/foo/bar` → `github.com/foo/bar`\n * - `https://github.com/foo/bar.git` → `github.com/foo/bar`\n * - `ssh://git@github.com/foo/bar` → `github.com/foo/bar`\n * - `ssh://git@github.com:2222/foo/bar` → `github.com/foo/bar` (port stripped)\n *\n * Case-insensitive (remote hostnames and most repo paths on major forges are\n * case-insensitive in practice).\n */\nexport function normalizeOriginUrl(rawUrl: string): string {\n let url = rawUrl.trim();\n if (!url) return \"\";\n\n // Strip trailing `.git` case-insensitively — the whole result is\n // lowercased at the end, so `.GIT` / `.Git` must be treated the same as\n // `.git`. Previously the `.endsWith(\".git\")` check let `.GIT` leak\n // through and appear in the output.\n if (/\\.git$/i.test(url)) url = url.slice(0, -4);\n\n // Windows drive-letter local path (e.g. `C:/repos/app`): detect here\n // so the scp matcher below can accept single-character SSH host aliases\n // (`h:foo/bar` from `.ssh/config`). A drive letter is exactly one ASCII\n // letter followed by `:/` or `:\\`; SSH aliases never have a slash\n // immediately after the colon.\n if (/^[A-Za-z]:[\\\\/]/.test(url)) {\n return url.toLowerCase();\n }\n\n // Protocol-prefixed: ssh://, https://, http://, git://, file://\n // Must be tried FIRST so that scp-style detection below doesn't\n // incorrectly swallow an ssh:// URL that happens to contain `:port/`.\n //\n // Matches:\n // 1: host — bracketed IPv6 `[2001:db8::1]`, plain host with no `:` / `/`,\n // OR empty (for `file:///path` which has no host component).\n // 2: port (optional) — preserved in the output so two repos on the same\n // host under different ports get distinct project namespaces.\n // Losing the port risked false-coalescing separate repos on custom\n // SSH mesh setups.\n // 3: path (optional)\n const protoMatch =\n /^[a-z][a-z0-9+.-]*:\\/\\/(?:[^@/]+@)?(\\[[^\\]]+\\]|[^/:]*)(?::(\\d+))?(\\/.*)?$/i.exec(url);\n if (protoMatch) {\n let host = protoMatch[1] ?? \"\";\n // Detect IPv6 via the bracketed input form BEFORE stripping brackets,\n // so that when we later re-attach a port we can preserve the\n // `[host]:port` boundary. Without the brackets, `host:2222` is\n // ambiguous with a longer bare IPv6 address like `2001:db8::1:2222`.\n const wasBracketed =\n host.startsWith(\"[\") && host.endsWith(\"]\");\n if (wasBracketed) host = host.slice(1, -1);\n const port = protoMatch[2];\n const repoPath = (protoMatch[3] ?? \"\").replace(/^\\/+/, \"\");\n const hostPort = port\n ? wasBracketed\n ? `[${host}]:${port}`\n : `${host}:${port}`\n : host;\n // For protocols without a host component (file:///path), fall back to\n // a stable prefix so distinct local paths don't collapse to \"/path\".\n const prefix = hostPort.length > 0 ? hostPort : \"localhost\";\n return `${prefix}/${repoPath}`.toLowerCase();\n }\n\n // scp-like syntax: [user@]host:path. Protocol-prefixed URLs (`scheme://`)\n // are handled above, so the scp branch below guards against them: a\n // matched `host` of `scheme` followed by a path starting with `//` is\n // a protocol URL that fell through and must NOT be parsed here.\n // `user@` is optional — git also accepts userless scp forms like\n // `host:org/repo`. Valid scp paths may start with digits (e.g.\n // `git@host:123/repo.git`), so no numeric guard is needed: port-bearing\n // URLs have the `://` prefix and match the protocol branch above before\n // reaching here.\n //\n // Windows drive letters were filtered above, so single-character SSH\n // host aliases (`h:foo/bar`) are accepted here.\n //\n // Bracketed IPv6 (`[2001:db8::1]`) is supported: the host alternative\n // matches the bracketed literal up to `]` without splitting on internal\n // `:`. Brackets are stripped in the normalised form so the scp and\n // `ssh://` forms of the same IPv6 remote produce identical projectIds.\n const scpMatch =\n /^(?:([^@\\s/]+)@)?(\\[[^\\]]+\\]|[^:@\\s/]+):(.+)$/.exec(url);\n if (scpMatch) {\n let host = scpMatch[2] ?? \"\";\n if (host.startsWith(\"[\") && host.endsWith(\"]\")) host = host.slice(1, -1);\n const repoPath = scpMatch[3] ?? \"\";\n // Reject protocol-like leftovers (e.g. `file:///path` where the scp\n // regex greedily matched `file` as host and `///path` as path).\n if (repoPath.startsWith(\"//\")) {\n return url.toLowerCase();\n }\n return `${host}/${repoPath.replace(/^\\/+/, \"\")}`.toLowerCase();\n }\n\n // Fallback: use raw lowercased\n return url.toLowerCase();\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Resolver\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface ResolveGitContextOptions {\n /** Inject a git invoker (tests). Defaults to spawning real `git`. */\n invoker?: GitInvoker;\n abortSignal?: AbortSignal;\n /** Absolute epoch deadline shared with the extraction lifecycle. */\n deadlineMs?: number;\n /** Injectable clock for deadline tests. */\n now?: () => number;\n /**\n * Share results across calls. Each miss costs up to five `git` spawns on the\n * event loop, so per-request callers (recall, memory_store) pass one.\n */\n cache?: GitContextCache;\n}\n\n/** Short-lived, bounded memo of git resolution per cwd (COS-666). */\nexport class GitContextCache {\n private readonly entries = new Map<string, { value: GitContext | null; head?: string; at: number }>();\n private readonly ttlMs: number;\n private readonly maxEntries: number;\n private readonly now: () => number;\n\n private readonly cacheRepos: boolean;\n\n constructor(options: { ttlMs?: number; maxEntries?: number; now?: () => number; cacheRepos?: boolean } = {}) {\n this.cacheRepos = options.cacheRepos ?? true;\n this.ttlMs = options.ttlMs ?? 30_000;\n this.maxEntries = options.maxEntries ?? 256;\n this.now = options.now ?? Date.now;\n }\n\n has(key: string): boolean {\n return this.get(key) !== undefined;\n }\n\n /** `undefined` = miss; `value: null` = cached \"not a repo\". */\n get(key: string): { value: GitContext | null; head?: string } | undefined {\n const hit = this.entries.get(key);\n if (!hit) return undefined;\n if (this.now() - hit.at >= this.ttlMs) {\n this.entries.delete(key);\n return undefined;\n }\n return hit;\n }\n\n set(key: string, value: GitContext | null, head?: string): void {\n // Negative-only caches never hold a branch, so a session snapshot taken\n // from them cannot carry a stale one.\n if (value !== null && !this.cacheRepos) return;\n this.entries.delete(key);\n this.entries.set(key, { value, head, at: this.now() });\n if (this.entries.size > this.maxEntries) {\n const oldest = this.entries.keys().next();\n if (!oldest.done) this.entries.delete(oldest.value);\n }\n }\n}\n\n/**\n * Detect the git project + branch for `cwd`.\n *\n * Returns `null` when `cwd` is invalid, outside a worktree, or git is\n * unavailable. Unexpected command failures also resolve to `null`.\n *\n * Caller cancellation and an exhausted deadline reject so lifecycle callers\n * can stop promptly instead of treating an interrupted probe as \"not a repo\".\n */\nexport async function resolveGitContext(\n cwd: string,\n options: ResolveGitContextOptions = {},\n): Promise<GitContext | null> {\n const { cache } = options;\n if (!cache) return resolveGitContextUncached(cwd, options);\n // A cache hit must not mask cancellation or an exhausted deadline.\n throwIfInterrupted(options);\n const hit = cache.get(cwd);\n if (hit?.value === null) return null;\n // The branch picks the write/recall namespace and git alone decides it, so a\n // hit is served only while HEAD is byte-identical to what git answered for.\n if (hit?.value && hit.head !== undefined && (await readHeadFile(hit.value.rootPath)) === hit.head) {\n return { ...hit.value };\n }\n // Timeouts and spawn failures are not answers about the repo, so a lookup\n // that hit one (even partially) is never cached.\n let inconclusive = false;\n // HEAD is snapshotted once git names the root and BEFORE the branch probe: a\n // checkout racing the probe then leaves the entry older than HEAD, so the\n // next hit mismatches and re-resolves (never a stale branch pinned to a new HEAD).\n let head: string | undefined;\n const inner = options.invoker ?? defaultGitInvoker();\n const invoker: GitInvoker = async (probeCwd, args, invokeOptions) => {\n let result: GitInvokeResult;\n try {\n result = await inner(probeCwd, args, invokeOptions);\n } catch (err) {\n inconclusive = true;\n throw err;\n }\n if (result.exitCode === GIT_TIMEOUT_EXIT_CODE || result.exitCode === GIT_SPAWN_ERROR_EXIT_CODE) inconclusive = true;\n if (args[1] === \"--show-toplevel\" && result.exitCode === 0) head = await readHeadFile(result.stdout.trim());\n return result;\n };\n const value = await resolveGitContextUncached(cwd, { ...options, invoker });\n if (inconclusive || options.abortSignal?.aborted) return value;\n if (value === null || head !== undefined) cache.set(cwd, value && { ...value }, head);\n return value;\n}\n\n/**\n * Raw `HEAD` contents without spawning git, or `undefined` when they cannot\n * vouch for the branch: unreadable, a symlinked HEAD (old\n * `core.preferSymlinkRefs`), or reftable's constant `refs/heads/.invalid`\n * placeholder (HEAD never changes on checkout there). Callers then re-resolve.\n */\nasync function readHeadFile(rootPath: string): Promise<string | undefined> {\n try {\n let gitDir = path.join(rootPath, \".git\");\n if ((await stat(gitDir)).isFile()) {\n // Linked worktree: `.git` is a file pointing at the real git dir.\n const pointer = /^gitdir:\\s*(.+)$/m.exec(await readFile(gitDir, \"utf-8\"));\n if (!pointer?.[1]) return undefined;\n gitDir = path.resolve(rootPath, pointer[1].trim());\n }\n const headPath = path.join(gitDir, \"HEAD\");\n if ((await lstat(headPath)).isSymbolicLink()) return undefined;\n const head = await readFile(headPath, \"utf-8\");\n return head.includes(\"refs/heads/.invalid\") ? undefined : head;\n } catch {\n return undefined;\n }\n}\n\nfunction throwIfInterrupted(options: ResolveGitContextOptions): void {\n if (options.abortSignal?.aborted) {\n throw options.abortSignal.reason instanceof Error\n ? options.abortSignal.reason\n : abortError(\"git context resolution aborted\");\n }\n if (options.deadlineMs !== undefined && (options.now ?? Date.now)() >= options.deadlineMs) {\n throw abortError(\"git context resolution deadline exceeded\");\n }\n}\n\nasync function resolveGitContextUncached(\n cwd: string,\n options: ResolveGitContextOptions,\n): Promise<GitContext | null> {\n // Wrap the whole body so the documented \"Never throws\" contract is\n // enforced. Possible throw sites include:\n // - `expandTildePath` → `resolveHomeDir()` → `os.homedir()` when HOME\n // is unset (e.g. minimal containers)\n // - a custom `options.invoker` that raises instead of returning a\n // non-zero exitCode\n // - any future helper added to this chain\n // All of those map to \"not in a repo\" / `null`.\n try {\n // Validate input: must be a non-empty string.\n if (typeof cwd !== \"string\" || cwd.length === 0) return null;\n\n // Expand `~` per CLAUDE.md #17, then require absolute path.\n const expanded = expandTildePath(cwd);\n if (!path.isAbsolute(expanded)) return null;\n\n const invoker = options.invoker ?? defaultGitInvoker();\n const now = options.now ?? Date.now;\n const invoke = async (probeCwd: string, args: string[]): Promise<GitInvokeResult> => {\n if (options.abortSignal?.aborted) {\n throw options.abortSignal.reason instanceof Error\n ? options.abortSignal.reason\n : abortError(\"git context resolution aborted\");\n }\n const remainingMs =\n options.deadlineMs === undefined ? DEFAULT_GIT_TIMEOUT_MS : options.deadlineMs - now();\n if (remainingMs <= 0) throw abortError(\"git context resolution deadline exceeded\");\n return invoker(probeCwd, args, {\n abortSignal: options.abortSignal,\n timeoutMs: Math.min(DEFAULT_GIT_TIMEOUT_MS, remainingMs),\n });\n };\n\n // 1. Locate the repo root.\n const topLevel = await invoke(expanded, [\"rev-parse\", \"--show-toplevel\"]);\n if (topLevel.exitCode !== 0) return null;\n const rootPath = topLevel.stdout.trim();\n if (!rootPath) return null;\n\n // 2. Current branch. `--abbrev-ref HEAD` returns `HEAD` in detached\n // state, which we normalize to `null`. On a fresh `git init` the\n // HEAD ref is unborn and `--abbrev-ref HEAD` fails, but\n // `symbolic-ref HEAD` still returns the target branch. Fall back\n // so newly-initialized repos get a sensible branch name.\n const branchResult = await invoke(rootPath, [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n let branch: string | null = null;\n if (branchResult.exitCode === 0) {\n const raw = branchResult.stdout.trim();\n branch = raw && raw !== \"HEAD\" ? raw : null;\n } else {\n const unbornRef = await invoke(rootPath, [\"symbolic-ref\", \"--quiet\", \"HEAD\"]);\n if (unbornRef.exitCode === 0) {\n const raw = unbornRef.stdout.trim();\n const prefix = \"refs/heads/\";\n if (raw.startsWith(prefix)) {\n const candidate = raw.slice(prefix.length);\n if (candidate) branch = candidate;\n }\n }\n }\n\n // 3. Origin URL — optional. Used to derive a stable `projectId`.\n const originResult = await invoke(rootPath, [\"remote\", \"get-url\", \"origin\"]);\n let projectId: string;\n if (originResult.exitCode === 0) {\n const normalized = normalizeOriginUrl(originResult.stdout);\n projectId = normalized ? `origin:${stableHash(normalized)}` : `root:${stableHash(rootPath)}`;\n } else {\n projectId = `root:${stableHash(rootPath)}`;\n }\n\n // 4. Default branch — best effort.\n const headRef = await invoke(rootPath, [\"symbolic-ref\", \"--quiet\", \"refs/remotes/origin/HEAD\"]);\n let defaultBranch: string | null = null;\n if (headRef.exitCode === 0) {\n const raw = headRef.stdout.trim();\n const prefix = \"refs/remotes/origin/\";\n if (raw.startsWith(prefix)) {\n const candidate = raw.slice(prefix.length);\n if (candidate) defaultBranch = candidate;\n }\n }\n\n return {\n projectId,\n branch,\n rootPath,\n defaultBranch,\n };\n } catch {\n if (options.abortSignal?.aborted) {\n throw options.abortSignal.reason instanceof Error\n ? options.abortSignal.reason\n : abortError(\"git context resolution aborted\");\n }\n if (options.deadlineMs !== undefined && (options.now ?? Date.now)() >= options.deadlineMs) {\n throw abortError(\"git context resolution deadline exceeded\");\n }\n return null;\n }\n}\n\n/** Process-wide cache for per-request callers (recall scope). */\nexport const sharedGitContextCache = new GitContextCache();\n\n/**\n * Session-attach callers snapshot the branch once per session, so they must\n * read a repo fresh; they only skip repeat probes of non-repo directories.\n */\nexport const sharedNonRepoGitContextCache = new GitContextCache({ cacheRepos: false });\n","/**\n * Coding-agent namespace overlay (issue #569 PR 2 + PR 3).\n *\n * Given a `CodingContext` (from `resolveGitContext`) and a `CodingModeConfig`,\n * returns the namespace that recall + write paths should use — or `null` when\n * no overlay should apply (coding mode disabled, no context supplied, or\n * feature flags off).\n *\n * PR 2 ships the project overlay. PR 3 will add the branch overlay; the\n * function here already handles both flags so the schema / types / plumbing\n * don't have to change a second time when branch-scope lands.\n *\n * Pure function — no orchestrator, no config side-effects. Callers keep rule\n * 42 (read + write through same namespace layer) by consulting the same\n * function on both paths.\n */\n\nimport type { CodingContext, CodingModeConfig } from \"../types.js\";\nimport { stableHash } from \"./git-context.js\";\n\nexport interface CodingNamespaceOverlay {\n /**\n * Effective namespace to use for this session's memory operations. When\n * `branchScope` is on, takes the form `project:<id>/branch:<b>`; otherwise\n * `project:<id>`.\n */\n namespace: string;\n /**\n * Read fallbacks — additional namespaces a caller should include in recall\n * so that, for example, a branch-scoped session still sees project-level\n * memories that were written before the branch scope was enabled.\n *\n * Writes MUST go to `namespace` only; these are read-side only.\n *\n * Introduced to carry PR 3's branch→project fallback; PR 2 returns an empty\n * array here.\n */\n readFallbacks: string[];\n /**\n * `\"project\"` when only project scope applies, `\"branch\"` when branch scope\n * is also layered on. Used for diagnostics (`remnic doctor`) and logging.\n */\n scope: \"project\" | \"branch\";\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Sanitization\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Normalize a projectId / branch fragment so the resulting namespace passes\n * the router's `isSafeRouteNamespace` check (`[A-Za-z0-9._-]{1,64}`).\n *\n * Namespaces are used as filesystem directory names and must not contain\n * path separators (`/`, `\\`) or colons — so both `:` and `/` collapse to `-`.\n * The project-id format `origin:<8hex>` and branch names like `feat/x` both\n * flow through this helper before hitting the storage layer.\n *\n * NOT a security boundary — projectIds come from `resolveGitContext` (known\n * hex), and branch names come from local git. This defends against corrupt\n * input only.\n */\n/**\n * Single-pass sanitization — each input character is visited exactly once.\n * Rewriting as an explicit loop (instead of chained `replace()` calls with\n * greedy quantifiers) closes the polynomial-backtracking surface that\n * CodeQL flagged on patterns like `-+` and `^-+|-+$`.\n */\nexport function sanitizeFragment(input: string): string {\n if (typeof input !== \"string\") return \"\";\n const trimmed = input.trim().toLowerCase();\n let out = \"\";\n let prevIsDash = true; // suppress leading dashes\n for (let i = 0; i < trimmed.length; i += 1) {\n const c = trimmed[i]!;\n const cc = trimmed.charCodeAt(i);\n const isSafe =\n (cc >= 48 && cc <= 57) /* 0-9 */ ||\n (cc >= 97 && cc <= 122) /* a-z */ ||\n cc === 46 /* . */ ||\n cc === 95 /* _ */;\n if (isSafe) {\n out += c;\n prevIsDash = false;\n } else if (!prevIsDash) {\n out += \"-\";\n prevIsDash = true;\n }\n }\n // Strip a single trailing dash introduced by the final run of unsafe chars.\n if (out.endsWith(\"-\")) out = out.slice(0, -1);\n return out;\n}\n\n/**\n * Cap to the router's per-namespace upper bound.\n *\n * Raw truncation alone would collapse distinct long inputs that differ near\n * the end (e.g. two `feat/...` branches with different suffixes) into the\n * same namespace — silently mixing recall/write state across branches or\n * projects. When truncation is needed, we append a short deterministic\n * hash suffix (`-<8hex>`) derived from the FULL pre-truncated value so\n * collisions only happen under true hash collisions, not simple prefix\n * overlap.\n *\n * The tail is trimmed to leave room for the separator and 8-char hash and\n * any trailing `-` introduced by the slice is stripped so the final\n * character before `-<hash>` is always alphanumeric or `.`/`_`.\n */\nconst MAX_NAMESPACE_LEN = 64;\nconst HASH_SUFFIX_LEN = 9; // \"-\" + 8 hex chars\n\nfunction capLength(value: string): string {\n if (value.length <= MAX_NAMESPACE_LEN) return value;\n // Reuse the FNV-1a 32-bit hash from git-context — one canonical\n // implementation, one set of edge-case fixes. Uses Math.imul for\n // correct 32-bit wrap-around, which plain `*` would not guarantee\n // for the largest intermediate products.\n const hash = stableHash(value);\n // Trim trailing '-' with a linear, non-backtracking loop. A regex\n // like `-+$` is linear too, but an explicit loop keeps CodeQL happy\n // about polynomial backtracking warnings when several `\\-+` patterns\n // appear in the same module.\n let end = MAX_NAMESPACE_LEN - HASH_SUFFIX_LEN;\n while (end > 0 && value.charCodeAt(end - 1) === 45 /* '-' */) end -= 1;\n return `${value.slice(0, end)}-${hash}`;\n}\n\n/**\n * Produce the project-scope namespace name. Exported for tests and for\n * `remnic doctor` to render. Guaranteed to satisfy `isSafeRouteNamespace`:\n * no `/`, no `:`, lowercase only, length-capped to 64 chars.\n */\nexport function projectNamespaceName(projectId: string): string {\n const frag = sanitizeFragment(projectId);\n return capLength(`project-${frag || \"unknown\"}`);\n}\n\nexport function projectTagProjectId(projectTag: string): string {\n const trimmed = projectTag.trim();\n const frag = sanitizeFragment(trimmed);\n const disambig = trimmed.length > 0 && frag !== trimmed;\n const suffix = disambig ? `-${stableHash(trimmed)}` : \"\";\n return `tag:${frag || \"unknown\"}${suffix}`;\n}\n\n/**\n * Preserve case when sanitizing a principal-derived base namespace. The\n * router's `isSafeRouteNamespace` check accepts `[A-Za-z0-9._-]{1,64}`, so\n * upper-case characters in the principal name are safe and MUST be kept to\n * avoid colliding two otherwise-distinct principals (e.g. `Alice` vs\n * `alice`) into the same combined namespace.\n *\n * Otherwise identical to `sanitizeFragment`: single-pass, linear, no\n * polynomial-backtracking quantifiers, unsafe chars collapse to `-` with\n * leading/trailing dashes suppressed.\n */\nfunction sanitizeBaseFragment(input: string): string {\n if (typeof input !== \"string\") return \"\";\n const trimmed = input.trim();\n let out = \"\";\n let prevIsDash = true;\n for (let i = 0; i < trimmed.length; i += 1) {\n const c = trimmed[i]!;\n const cc = trimmed.charCodeAt(i);\n const isSafe =\n (cc >= 48 && cc <= 57) /* 0-9 */ ||\n (cc >= 65 && cc <= 90) /* A-Z */ ||\n (cc >= 97 && cc <= 122) /* a-z */ ||\n cc === 46 /* . */ ||\n cc === 95 /* _ */;\n if (isSafe) {\n out += c;\n prevIsDash = false;\n } else if (!prevIsDash) {\n out += \"-\";\n prevIsDash = true;\n }\n }\n if (out.endsWith(\"-\")) out = out.slice(0, -1);\n return out;\n}\n\n/**\n * Combine a principal-derived base namespace (e.g. `default`, `alice`) with a\n * coding-agent overlay namespace (e.g. `project-origin-abcd1234`). The result\n * is a single safe-route token that preserves principal isolation (CLAUDE.md\n * rule 42: read + write must resolve through the same namespace layer — and\n * here, through the same principal-scoped prefix) while layering project or\n * project/branch scope on top.\n *\n * Multiple principals working in the same repo thus get distinct namespaces:\n *\n * alice + project-origin-ab12 → alice-project-origin-ab12\n * bob + project-origin-ab12 → bob-project-origin-ab12\n * Alice + project-origin-ab12 → Alice-project-origin-ab12 (distinct)\n *\n * The base fragment preserves case so `Alice` and `alice` remain distinct;\n * the overlay fragment is still lowercase-sanitized because it derives from\n * deterministic, pre-lowercased git hashes.\n *\n * Output is re-capped through `capLength` so a very long base + overlay\n * combination still fits inside `isSafeRouteNamespace` (≤ 64 chars). The\n * deterministic hash suffix on truncation keeps distinct inputs distinct.\n */\nexport function combineNamespaces(base: string, overlay: string): string {\n const baseFrag = sanitizeBaseFragment(base);\n const overlayFrag = sanitizeFragment(overlay);\n if (!baseFrag) return capLength(overlayFrag || \"unknown\");\n if (!overlayFrag) return capLength(baseFrag);\n return capLength(`${baseFrag}-${overlayFrag}`);\n}\n\n/**\n * Produce the branch-scope namespace name. Format:\n * `project-<id>-branch-<name>[-<hash>]`. Uses `-` as the structural separator\n * rather than `/` or `:` so the result is a single safe route-namespace\n * token that can be used directly as a filesystem directory.\n *\n * Two failure modes must not collapse distinct branches to one namespace:\n *\n * 1. Sanitization is lossy (`feat/x` and `feat-x` both sanitize to\n * `feat-x`; `Feature` and `feature` both sanitize to `feature`). When\n * sanitization rewrote any character, we append a short hash of the\n * RAW branch so distinct inputs stay distinct.\n * 2. Truncation is applied when the total exceeds 64 chars. In that\n * mode `capLength` appends its own hash of the full pre-truncated\n * value.\n *\n * Long branches that also sanitize may receive both kinds of hashes — that\n * is acceptable: the router only requires the result be unique and\n * deterministic, and the two hashes derive from different domains so they\n * don't conflict.\n */\nexport function branchNamespaceName(projectId: string, branch: string): string {\n const projectFrag = sanitizeFragment(projectId);\n const trimmedBranch = branch.trim();\n const branchFrag = sanitizeFragment(trimmedBranch);\n // Lossy-sanitization disambiguator: append hash of the raw (trimmed)\n // branch when sanitization actually changed the string. Preserves\n // distinctness across `feat/x` vs `feat-x` and `Feature` vs `feature`.\n // The comparison uses the raw trimmed value (NOT `.toLowerCase()`) so\n // case-only variants are treated as lossy and receive their own hash.\n // Empty / already-safe-lowercase inputs get no hash so the common case\n // stays readable.\n const disambig = trimmedBranch.length > 0 && branchFrag !== trimmedBranch;\n const base = `project-${projectFrag || \"unknown\"}-branch-${branchFrag || \"unknown\"}`;\n const suffixed = disambig ? `${base}-${stableHash(trimmedBranch)}` : base;\n return capLength(suffixed);\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Overlay resolver\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Compute the namespace overlay for a session.\n *\n * Returns `null` when no overlay applies — callers should then use their\n * existing `defaultNamespaceForPrincipal(...)` result unchanged. This keeps\n * CLAUDE.md #30 (escape hatch): setting `codingMode.projectScope: false`\n * exactly restores pre-#569 behaviour at every call site.\n *\n * @param codingContext — git context from the connector\n * @param config — coding mode flags (projectScope, branchScope, globalFallback)\n * @param defaultNamespace — retained for call-site compatibility; no longer\n * used. The global fallback is expressed as an empty-string sentinel in\n * `readFallbacks`, which `combineNamespaces(principal, \"\")` resolves to the\n * principal's own namespace at the call site.\n */\nexport function resolveCodingNamespaceOverlay(\n codingContext: CodingContext | null | undefined,\n config: Pick<CodingModeConfig, \"projectScope\" | \"branchScope\" | \"globalFallback\">,\n defaultNamespace?: string,\n): CodingNamespaceOverlay | null {\n // No context supplied (session isn't in a git repo, or connector didn't\n // attach one) → no overlay.\n if (!codingContext) return null;\n\n // Project scope disabled → no overlay at all. Branch scope depends on\n // project scope being on; there is no branch-only mode.\n if (!config.projectScope) return null;\n\n // Require a non-empty projectId — defensive.\n const projectId = typeof codingContext.projectId === \"string\" ? codingContext.projectId.trim() : \"\";\n if (!projectId) return null;\n\n const projectNs = projectNamespaceName(projectId);\n\n // Root/global namespace fallback: when `globalFallback` is true, include\n // the principal's self namespace in readFallbacks so cross-project knowledge\n // remains visible. CLAUDE.md #30: the gate is `globalFallback` — set to\n // false for strict project isolation.\n //\n // The fallback value is \"\" (empty string), NOT the defaultNamespace name.\n // The orchestrator passes each fallback through combineNamespaces(principal, fallback),\n // and combineNamespaces(base, \"\") returns base unchanged — yielding the\n // principal's own namespace. Using the actual namespace name (e.g., \"default\")\n // would produce \"default-default\" after combination, missing the target.\n const includeRoot = config.globalFallback === true;\n\n // Branch-scope layering (PR 3):\n // - only when config.branchScope is explicitly true\n // - only when we actually have a branch (null in detached HEAD)\n // - project namespace becomes a read fallback so project-level memories\n // remain visible from any branch (deliberate asymmetry — branch writes\n // don't leak up, but project reads leak down).\n // - when globalFallback is on, the root namespace is also appended so\n // globally useful memories surface in every branch.\n if (config.branchScope && typeof codingContext.branch === \"string\" && codingContext.branch.length > 0) {\n const branchNs = branchNamespaceName(projectId, codingContext.branch);\n const fallbacks = [projectNs];\n if (includeRoot) fallbacks.push(\"\");\n return {\n namespace: branchNs,\n readFallbacks: fallbacks,\n scope: \"branch\",\n };\n }\n\n return {\n namespace: projectNs,\n readFallbacks: includeRoot ? [\"\"] : [],\n scope: \"project\",\n };\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Diagnostics (issue #569 PR 3 + PR 8)\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface CodingScopeDescription {\n /** \"none\" when no overlay is active; otherwise the resolved scope level. */\n scope: \"none\" | \"project\" | \"branch\";\n /** Project id (raw, not sanitized) when a context is attached. */\n projectId: string | null;\n /** Branch name (raw, not sanitized) when available. */\n branch: string | null;\n /** Effective namespace writes route to. `null` when no overlay applies. */\n effectiveNamespace: string | null;\n /** Read fallbacks included in recall (non-empty only when branch-scope is on). */\n readFallbacks: string[];\n /**\n * Why no overlay applies, when `scope === \"none\"`. One of:\n * - `\"no-context\"` — connector didn't attach a CodingContext\n * - `\"disabled\"` — codingMode.projectScope is false\n * - `\"empty-project\"` — codingContext.projectId was empty/whitespace\n */\n disabledReason: \"no-context\" | \"disabled\" | \"empty-project\" | null;\n}\n\n/**\n * Human-readable description of the coding-agent scope that currently applies\n * for a session. Consumed by `remnic doctor` (PR 8) and by logs to surface\n * why recall routes where it does.\n *\n * Pure — callers pass the coding context + config they already have.\n */\nexport function describeCodingScope(\n codingContext: CodingContext | null | undefined,\n config: Pick<CodingModeConfig, \"projectScope\" | \"branchScope\" | \"globalFallback\">,\n defaultNamespace?: string,\n): CodingScopeDescription {\n const projectId = codingContext?.projectId ?? null;\n const branch = codingContext?.branch ?? null;\n\n if (!codingContext) {\n return {\n scope: \"none\",\n projectId: null,\n branch: null,\n effectiveNamespace: null,\n readFallbacks: [],\n disabledReason: \"no-context\",\n };\n }\n if (!config.projectScope) {\n return {\n scope: \"none\",\n projectId,\n branch,\n effectiveNamespace: null,\n readFallbacks: [],\n disabledReason: \"disabled\",\n };\n }\n const trimmedId = typeof projectId === \"string\" ? projectId.trim() : \"\";\n if (!trimmedId) {\n return {\n scope: \"none\",\n projectId,\n branch,\n effectiveNamespace: null,\n readFallbacks: [],\n disabledReason: \"empty-project\",\n };\n }\n\n const overlay = resolveCodingNamespaceOverlay(codingContext, config, defaultNamespace);\n // Unreachable in practice given the guards above, but keep the return\n // shape consistent if the resolver grows new null branches later.\n if (!overlay) {\n return {\n scope: \"none\",\n projectId,\n branch,\n effectiveNamespace: null,\n readFallbacks: [],\n disabledReason: \"disabled\",\n };\n }\n return {\n scope: overlay.scope,\n projectId,\n branch,\n effectiveNamespace: overlay.namespace,\n readFallbacks: overlay.readFallbacks,\n disabledReason: null,\n };\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// LCM session-key namespacing (#1495)\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Reserved structural sentinel for the namespaced LCM `session_id` encoding\n * (#1495 P1). U+001F (UNIT SEPARATOR) is a C0 control character that CANNOT\n * occur in a route namespace (`isSafeRouteNamespace` ⇒ `[A-Za-z0-9._-]{1,64}`,\n * see routing/engine.ts) and does not occur in any legitimate session key, so\n * it is an unforgeable structural marker for the namespace boundary.\n *\n * SECURITY — why this is unforgeable (the #1495 P1 fix):\n * The LCM archive is keyed by the `session_id` STRING (exact `session_id = ?`\n * and prefix `session_id LIKE '<prefix>%'`), NOT physically partitioned by\n * namespace. The previous encoding `${namespace}:${sessionKey}` shared the SAME\n * string space as a raw default-store key, so a caller authorized for the\n * `default` store could pass a raw `sessionKey` equal to another namespace's\n * encoded key (`\"<overlay-ns>:<victim-session>\"`) and exact-match the victim's\n * rows — a cross-tenant read leak.\n *\n * The new encoding makes the namespaced and default key-spaces PROVABLY\n * DISJOINT:\n * - Overlay key = `\\x1f<namespace>\\x1f<sessionKey>` — always begins with\n * `\\x1f` followed by a NON-`\\x1f` character (the namespace is non-empty and\n * `\\x1f`-free). The leading `\\x1f<namespace>\\x1f` is an unambiguous,\n * injective frame: the namespace cannot contain `\\x1f`, so the second `\\x1f`\n * terminates it without any escaping of the (raw) session key.\n * - Default key = the raw `sessionKey`, UNLESS it already begins with the\n * sentinel, in which case it is escaped to begin with `\\x1f\\x1f` (see\n * `escapeDefaultLcmKey`). A default key therefore NEVER matches the overlay\n * frame `\\x1f<non-\\x1f>…`.\n * Hence no caller-controlled raw `sessionKey` (default path) can reproduce an\n * overlay key, closing the forgery for BOTH the exact-`session_id` match and the\n * `sessionPrefix` LIKE match (an overlay prefix `\\x1f<ns>\\x1f<rawPrefix>` stays a\n * valid LIKE-prefix of the overlay full keys, and a default prefix can only\n * LIKE-match default keys).\n *\n * Existing default-store rows need NO migration: legitimate session keys never\n * contain `\\x1f`, so `escapeDefaultLcmKey` is a no-op for them and they remain\n * byte-for-byte their raw form. The namespaced encoding is NEW in this\n * unreleased PR, so changing its shape costs nothing.\n */\nconst LCM_NS_SENTINEL = \"\\u001f\";\n\n/**\n * Make a default-store (raw) LCM key disjoint from the namespaced key-space.\n *\n * Namespaced overlay keys always begin with `\\x1f` followed by a non-`\\x1f`\n * namespace character. A raw default key collides with that frame ONLY if it\n * begins with `\\x1f`. Legitimate session keys never contain `\\x1f`, so this is a\n * pure no-op for them; a forged key that begins with `\\x1f` is escaped to begin\n * with `\\x1f\\x1f`, which can never equal an overlay key (whose second character\n * is a `[A-Za-z0-9._-]` namespace char, never `\\x1f`).\n */\nfunction escapeDefaultLcmKey(sessionKey: string): string {\n return sessionKey.startsWith(LCM_NS_SENTINEL)\n ? `${LCM_NS_SENTINEL}${sessionKey}`\n : sessionKey;\n}\n\n/**\n * Build the LCM/structured-history `session_id` that a write-producing surface\n * archives under, and that a same-session reader must search under, so reads\n * and writes never drift (#1495, CLAUDE.md rule 42).\n *\n * The LCM archive filters strictly by the `session_id` string, so the writer's\n * archival key and the reader's lookup key MUST agree byte-for-byte. The\n * encoding frames the namespace with the reserved {@link LCM_NS_SENTINEL}\n * (`\\x1f<namespace>\\x1f<sessionKey>`) whenever that namespace diverges from the\n * single-store default; otherwise it passes the (escaped) raw `sessionKey` so\n * single-user / no-overlay deployments keep pre-#1495 behavior exactly. The two\n * key-spaces are provably disjoint, so a caller-controlled raw `sessionKey`\n * cannot forge another namespace's encoded id (see the {@link LCM_NS_SENTINEL}\n * doc comment for the full security rationale).\n *\n * `observe`, compaction flush/record, and the orchestrator recall readers all\n * route through this one helper so a project-scoped (cwd/projectTag) or\n * explicit-namespace session reads its own compressed-history / structured /\n * targeted-fact evidence instead of missing it.\n */\nexport function lcmSessionKeyForNamespace(\n namespace: string | undefined,\n sessionKey: string | undefined,\n defaultNamespace: string,\n): string | undefined {\n if (typeof sessionKey !== \"string\" || sessionKey.length === 0) return sessionKey;\n if (\n typeof namespace === \"string\" &&\n namespace.length > 0 &&\n namespace !== defaultNamespace\n ) {\n // Namespaced (overlay / explicit) key: frame the namespace with the reserved\n // sentinel so the boundary is unambiguous AND unforgeable from the default\n // key-space. The namespace is guaranteed `\\x1f`-free by `isSafeRouteNamespace`.\n return `${LCM_NS_SENTINEL}${namespace}${LCM_NS_SENTINEL}${sessionKey}`;\n }\n // Default store: raw sessionKey, escaped only if it would otherwise intrude on\n // the namespaced key-space (no-op for every legitimate key).\n return escapeDefaultLcmKey(sessionKey);\n}\n\n/**\n * Map an ORDERED, read-authorized namespace set (the SAME set normal QMD/file\n * recall searches) to the ordered set of LCM `session_id`s a same-session reader\n * must query (#1505 thread \"Include coding fallback namespaces in LCM reads\").\n *\n * The LCM archive filters strictly by `session_id`, and `observe` archives each\n * turn under `${effectiveNamespace}:${sessionKey}` for the namespace that was\n * effective when it was written. A branch-scoped session that overlays\n * `${base-project-*-branch-*}` only sees rows written under THAT namespace if it\n * reads a single overlay key — but normal recall ALSO searches the\n * `codingOverlay.readFallbacks` (project / root) namespaces, so rows archived at\n * project/root scope are surfaced by QMD/file recall yet MISSED by a single-key\n * LCM read. Deriving the LCM read keys from the SAME `recallNamespaces` set keeps\n * the LCM read path from diverging: every namespace recall is authorized to read\n * (read-auth gate already applied upstream in `recallNamespaces`) contributes one\n * LCM key, ordered primary-overlay-first then fallbacks. Unreadable namespaces\n * are never in `recallNamespaces`, so they are never searched here either (no\n * cross-tenant read leak).\n *\n * Single-user / no-overlay recall passes a single-namespace set that collapses to\n * the raw `sessionKey`, so the result is `[sessionKey]` — byte-for-byte the\n * pre-#1505 single-key behavior.\n *\n * SESSIONLESS recall (`sessionKey === undefined`): returns `[undefined]` so the\n * caller issues ONE archive-wide LCM read with no exact `session_id` filter —\n * byte-for-byte the pre-#1505 sessionless behavior. It must NOT substitute the\n * literal `\"default\"` session id (codex P2 \"Preserve unscoped LCM searches\n * without a session key\"): that would filter to a session literally named\n * `default`, silently dropping the explicit-cue / targeted / focused / response /\n * event LCM sections for every recall that omits a session key.\n *\n * The result is deduped while preserving first-seen order so the caller can query\n * keys in priority order and short-circuit on the first hit without re-querying an\n * identical key (e.g. when two namespaces both collapse to the default store).\n */\nexport function lcmReadSessionIdsForNamespaces(\n namespaces: readonly string[],\n sessionKey: string | undefined,\n defaultNamespace: string,\n): Array<string | undefined> {\n // Sessionless ⇒ a single archive-wide read (no `session_id` filter). NEVER the\n // literal \"default\" session id (codex P2).\n if (typeof sessionKey !== \"string\" || sessionKey.length === 0) {\n return [undefined];\n }\n const out: string[] = [];\n const seen = new Set<string>();\n for (const namespace of namespaces) {\n const key =\n lcmSessionKeyForNamespace(namespace, sessionKey, defaultNamespace) ??\n sessionKey;\n if (!seen.has(key)) {\n seen.add(key);\n out.push(key);\n }\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,SAAS,OAAO,UAAU,YAAY;AACtC,OAAO,UAAU;AA0EjB,IAAM,yBAAyB;AAC/B,IAAM,wBAAwB;AAC9B,IAAM,4BAA4B;AAE3B,SAAS,wBAAwC;AACtD,SAAO,CAAC,KAAa,SAAmB;AACtC,UAAM,SAAS,kBAAkB,OAAO,MAAM;AAAA,MAC5C;AAAA,MACA,UAAU;AAAA,MACV,SAAS;AAAA,MACT,OAAO;AAAA,IACT,CAAC;AACD,QAAI,OAAO,MAAO,QAAO,EAAE,QAAQ,IAAI,UAAU,0BAA0B;AAC3E,WAAO;AAAA,MACL,QAAQ,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA,MAC5D,UAAU,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA,IAChE;AAAA,EACF;AACF;AAEO,SAAS,oBAAgC;AAC9C,SAAO,CAAC,KAAK,MAAM,UAAU,CAAC,MAAM;AAClC,QAAI,QAAQ,aAAa,SAAS;AAChC,YAAM,QAAQ,YAAY,kBAAkB,QACxC,QAAQ,YAAY,SACpB,WAAW,gCAAgC;AAAA,IACjD;AAEA,UAAM,QAAQ,cAAc,OAAO,MAAM;AAAA,MACvC;AAAA,MACA,UAAU;AAAA,MACV,OAAO;AAAA,MACP,OAAO,CAAC,UAAU,QAAQ,QAAQ;AAAA,IACpC,CAAC;AACD,UAAM,EAAE,SAAS,SAAS,OAAO,IAAI,QAAQ,cAA+B;AAC5E,QAAI,SAAS;AACb,QAAI,UAAU;AACd,QAAI;AAEJ,UAAM,UAAU,MAAY;AAC1B,mBAAa,KAAK;AAClB,cAAQ,aA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,KAAK,GAAG;AAAA,IACd;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -2,18 +2,18 @@ import {
2
2
  ExtractionDrain,
3
3
  TurnIngestionCoordinator,
4
4
  shouldSkipImplicitExtraction
5
- } from "./chunk-CCFGLUSC.js";
5
+ } from "./chunk-WDAIXMEU.js";
6
6
  import {
7
7
  headerConnector,
8
8
  renderExtractionConversation,
9
9
  resolveSourceConnector
10
- } from "./chunk-4IJFJQPD.js";
10
+ } from "./chunk-MYXJCR3E.js";
11
11
  import {
12
12
  SmartBuffer
13
- } from "./chunk-5NFF2TSD.js";
13
+ } from "./chunk-KBUFYKUN.js";
14
14
  import {
15
15
  selfDeps
16
- } from "./chunk-OIOKDTZU.js";
16
+ } from "./chunk-SZXDGB32.js";
17
17
  import {
18
18
  describeError,
19
19
  groupTurnsByExtractionScope
@@ -447,4 +447,4 @@ export {
447
447
  ClaimBufferStorage,
448
448
  BufferDrainRunner
449
449
  };
450
- //# sourceMappingURL=chunk-QZPXXABV.js.map
450
+ //# sourceMappingURL=chunk-6DUBULUV.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  rebuildMemoryProjection,
3
3
  watchProjectionRebuildParent
4
- } from "./chunk-LYR57GEF.js";
4
+ } from "./chunk-I5PCMNN5.js";
5
5
  import {
6
6
  initLogger,
7
7
  log
@@ -77,4 +77,4 @@ if (invokedAsRunner) {
77
77
  export {
78
78
  PROJECTION_REBUILD_RUNNER_FLAG
79
79
  };
80
- //# sourceMappingURL=chunk-63OWJXGW.js.map
80
+ //# sourceMappingURL=chunk-6YXIL26Y.js.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  NamespaceStorageRouter
3
- } from "./chunk-FV2B6XE6.js";
3
+ } from "./chunk-R3LYKUZH.js";
4
4
  import {
5
5
  namespaceCollectionName
6
- } from "./chunk-BUOP3DOK.js";
6
+ } from "./chunk-TR4HFZBD.js";
7
7
  import {
8
8
  isSafeRouteNamespace
9
9
  } from "./chunk-PCXDUHQH.js";
@@ -213,4 +213,4 @@ export {
213
213
  verifyNamespaces,
214
214
  runNamespaceMigration
215
215
  };
216
- //# sourceMappingURL=chunk-GT2TH7FZ.js.map
216
+ //# sourceMappingURL=chunk-AAF7RX22.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  StorageManager
3
- } from "./chunk-OIOKDTZU.js";
3
+ } from "./chunk-SZXDGB32.js";
4
4
  import {
5
5
  countRecallTokenOverlap,
6
6
  normalizeRecallTokens
@@ -119,4 +119,4 @@ export {
119
119
  compareVerifiedSemanticRuleResults,
120
120
  searchVerifiedSemanticRules
121
121
  };
122
- //# sourceMappingURL=chunk-B3LGXOM5.js.map
122
+ //# sourceMappingURL=chunk-AJCXPMDA.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  parseFrontmatter
3
- } from "./chunk-OIOKDTZU.js";
3
+ } from "./chunk-SZXDGB32.js";
4
4
  import {
5
5
  activityDigestPath,
6
6
  isValidActivityDate
@@ -199,4 +199,4 @@ export {
199
199
  buildStandup,
200
200
  standupHelp
201
201
  };
202
- //# sourceMappingURL=chunk-5VWN3FJS.js.map
202
+ //# sourceMappingURL=chunk-BFRNDOHO.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  rebuildMemoryProjection
3
- } from "./chunk-LYR57GEF.js";
3
+ } from "./chunk-I5PCMNN5.js";
4
4
 
5
5
  // src/convergence-refresh.ts
6
6
  async function refreshConvergedNamespaces(namespaces, namespaceSearchRouter, getStorage, searchEnabled) {
@@ -32,4 +32,4 @@ async function refreshConvergedNamespaces(namespaces, namespaceSearchRouter, get
32
32
  export {
33
33
  refreshConvergedNamespaces
34
34
  };
35
- //# sourceMappingURL=chunk-K32VAS5B.js.map
35
+ //# sourceMappingURL=chunk-BGM7O5TD.js.map
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-B2NXOVZN.js";
5
5
  import {
6
6
  TranscriptManager
7
- } from "./chunk-WQ4XKIOX.js";
7
+ } from "./chunk-F32RH72R.js";
8
8
  import {
9
9
  resolveCommitmentLedgerDir,
10
10
  validateCommitmentLedgerEntry
@@ -268,4 +268,4 @@ export {
268
268
  recordResumeBundle,
269
269
  getResumeBundleStatus
270
270
  };
271
- //# sourceMappingURL=chunk-FQACH7MC.js.map
271
+ //# sourceMappingURL=chunk-BZAI3ETM.js.map
@@ -14,7 +14,7 @@ import {
14
14
  } from "./chunk-3UXOZBHV.js";
15
15
  import {
16
16
  StorageManager
17
- } from "./chunk-OIOKDTZU.js";
17
+ } from "./chunk-SZXDGB32.js";
18
18
  import {
19
19
  OKF_PROFILE_TYPE,
20
20
  okfTypeForMemory
@@ -272,4 +272,4 @@ export {
272
272
  exportOkfBundle,
273
273
  firstHeading
274
274
  };
275
- //# sourceMappingURL=chunk-UOIVXBNS.js.map
275
+ //# sourceMappingURL=chunk-E5DYZM56.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  lcmSessionKeyForNamespace
3
- } from "./chunk-4RAJT5L2.js";
3
+ } from "./chunk-5HFCXTGY.js";
4
4
  import {
5
5
  log
6
6
  } from "./chunk-3WCASNQZ.js";
@@ -77,4 +77,4 @@ export {
77
77
  observeTranscriptSessionKey,
78
78
  ObserveTranscriptPersister
79
79
  };
80
- //# sourceMappingURL=chunk-GCZJ7XRI.js.map
80
+ //# sourceMappingURL=chunk-EAHNSQ7H.js.map
@@ -1,6 +1,12 @@
1
1
  import {
2
2
  JsonlOwnershipDigestCache
3
3
  } from "./chunk-ADJXJKU6.js";
4
+ import {
5
+ RECENT_SKEW_MS,
6
+ mapLimited,
7
+ readLinesSince,
8
+ readNewestFromFiles
9
+ } from "./chunk-GE5J2T67.js";
4
10
  import {
5
11
  sessionStoragePaths
6
12
  } from "./chunk-5Y43VGYB.js";
@@ -427,41 +433,26 @@ var TranscriptManager = class _TranscriptManager {
427
433
  /**
428
434
  * Get all transcript files from the hierarchical directory structure.
429
435
  * Recursively finds all .jsonl files in transcripts/{channelType}/{channelId}/ subdirectories.
436
+ * Directories are listed concurrently: a large store has ~17k channel directories and a
437
+ * sequential walk spent ~1.5 s on round trips alone. Results keep readdir order.
430
438
  */
431
439
  async getAllTranscriptFiles() {
432
- const files = [];
433
- try {
434
- const entries = await readdir(this.transcriptsDir, { withFileTypes: true });
435
- for (const entry of entries) {
436
- if (entry.isDirectory()) {
437
- const channelTypeDir = path.join(this.transcriptsDir, entry.name);
438
- try {
439
- const channelTypeEntries = await readdir(channelTypeDir, { withFileTypes: true });
440
- for (const channelTypeEntry of channelTypeEntries) {
441
- if (channelTypeEntry.isDirectory()) {
442
- const channelDir = path.join(channelTypeDir, channelTypeEntry.name);
443
- try {
444
- const channelFiles = await readdir(channelDir);
445
- for (const file of channelFiles) {
446
- if (file.endsWith(".jsonl") && !isMacOsReplicationJunkBasename(file)) {
447
- files.push(path.join(entry.name, channelTypeEntry.name, file));
448
- }
449
- }
450
- } catch {
451
- }
452
- } else if (channelTypeEntry.isFile() && channelTypeEntry.name.endsWith(".jsonl") && !isMacOsReplicationJunkBasename(channelTypeEntry.name)) {
453
- files.push(path.join(entry.name, channelTypeEntry.name));
454
- }
455
- }
456
- } catch {
457
- }
458
- } else if (entry.isFile() && entry.name.endsWith(".jsonl") && !isMacOsReplicationJunkBasename(entry.name)) {
459
- files.push(entry.name);
440
+ const isJsonl = (name) => name.endsWith(".jsonl") && !isMacOsReplicationJunkBasename(name);
441
+ const top = await readdir(this.transcriptsDir, { withFileTypes: true }).catch(() => []);
442
+ const perTop = await Promise.all(top.map(async (entry) => {
443
+ if (!entry.isDirectory()) return entry.isFile() && isJsonl(entry.name) ? [entry.name] : [];
444
+ const channelTypeDir = path.join(this.transcriptsDir, entry.name);
445
+ const children = await readdir(channelTypeDir, { withFileTypes: true }).catch(() => []);
446
+ const perChild = await mapLimited(children, async (child) => {
447
+ if (child.isDirectory()) {
448
+ const channelFiles = await readdir(path.join(channelTypeDir, child.name)).catch(() => []);
449
+ return channelFiles.filter(isJsonl).map((file) => path.join(entry.name, child.name, file));
460
450
  }
461
- }
462
- } catch {
463
- }
464
- return files;
451
+ return child.isFile() && isJsonl(child.name) ? [path.join(entry.name, child.name)] : [];
452
+ });
453
+ return perChild.flat();
454
+ }));
455
+ return perTop.flat();
465
456
  }
466
457
  /**
467
458
  * Read transcript entries for a date range.
@@ -484,8 +475,7 @@ var TranscriptManager = class _TranscriptManager {
484
475
  for (const relativePath of transcriptFiles) {
485
476
  const filePath = path.join(this.transcriptsDir, relativePath);
486
477
  try {
487
- const content = await readFile(filePath, "utf-8");
488
- const lines = content.trim().split("\n").filter(Boolean);
478
+ const lines = skipFilesDatedBefore !== void 0 ? await readLinesSince(filePath, start.getTime() - RECENT_SKEW_MS) : (await readFile(filePath, "utf-8")).trim().split("\n").filter(Boolean);
489
479
  for (const line of lines) {
490
480
  try {
491
481
  const entry = JSON.parse(line);
@@ -515,17 +505,35 @@ var TranscriptManager = class _TranscriptManager {
515
505
  * Read the last N hours of transcript.
516
506
  *
517
507
  * Fast path: when sessionKey is given, reads only the 1-2 daily files for that channel. Without one,
518
- * every channel is scanned but daily files older than the window (less a day of clock skew) are skipped.
508
+ * every channel is scanned but daily files older than the window (less a day of clock skew) are skipped,
509
+ * and each file is read from its tail. With `maxEntries` and no sessionKey, only the newest `maxEntries`
510
+ * entries are returned (what a caller that keeps `slice(-maxEntries)` would see) and files are visited
511
+ * newest-modified first, stopping once no remaining file can hold a newer entry. The per-file read cap of
512
+ * 48 applies per channel-type directory, not globally.
519
513
  */
520
- async readRecent(hours, sessionKey) {
514
+ async readRecent(hours, sessionKey, maxEntries) {
521
515
  const now = /* @__PURE__ */ new Date();
522
516
  const end = new Date(now.getTime() + 1);
523
517
  const start = new Date(now.getTime() - hours * 60 * 60 * 1e3);
524
518
  if (sessionKey) {
525
519
  return this.readRecentForSession(start, end, sessionKey);
526
520
  }
521
+ if (maxEntries !== void 0 && Number.isInteger(maxEntries) && maxEntries >= 1) {
522
+ return this.readNewestEntries(start, end, maxEntries);
523
+ }
527
524
  return this.readRange(start.toISOString(), end.toISOString(), void 0, new Date(start.getTime() - 864e5).toISOString().slice(0, 10));
528
525
  }
526
+ /** Newest `limit` entries in `[start, end)` across every channel; see {@link readRecent}. */
527
+ async readNewestEntries(start, end, limit) {
528
+ const minDate = new Date(start.getTime() - 864e5).toISOString().slice(0, 10);
529
+ try {
530
+ const files = (await this.getAllTranscriptFiles()).filter((f) => !isDailyFileDatedBefore(f, minDate));
531
+ return await readNewestFromFiles(this.transcriptsDir, files, start, end, limit);
532
+ } catch (err) {
533
+ log.error("failed to read newest transcript entries:", err);
534
+ return [];
535
+ }
536
+ }
529
537
  /**
530
538
  * Optimized read for a specific session: only looks in that session's channel
531
539
  * directory and only reads files whose date falls within the lookback window.
@@ -910,4 +918,4 @@ export {
910
918
  utcDayRange,
911
919
  TranscriptManager
912
920
  };
913
- //# sourceMappingURL=chunk-WQ4XKIOX.js.map
921
+ //# sourceMappingURL=chunk-F32RH72R.js.map