@remnic/core 10.0.164 → 10.0.166

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 (418) hide show
  1. package/dist/access-admin-ops-surface.js +128 -127
  2. package/dist/access-authorization-probe.js +4 -4
  3. package/dist/access-boundary.js +3 -3
  4. package/dist/access-cli.d.ts.map +1 -1
  5. package/dist/access-cli.js +144 -137
  6. package/dist/access-cli.js.map +1 -1
  7. package/dist/access-coding-context-resolution.d.ts +37 -0
  8. package/dist/access-coding-context-resolution.d.ts.map +1 -1
  9. package/dist/access-coding-context-resolution.js +48 -4
  10. package/dist/access-errors.d.ts +5 -0
  11. package/dist/access-errors.d.ts.map +1 -1
  12. package/dist/access-errors.js +3 -1
  13. package/dist/access-extraction-force-flush-preempt.js +128 -127
  14. package/dist/access-extraction-force-flush.js +128 -127
  15. package/dist/access-http-briefing.js +128 -127
  16. package/dist/access-http-query.js +128 -127
  17. package/dist/access-http.d.ts.map +1 -1
  18. package/dist/access-http.js +128 -127
  19. package/dist/access-identity-continuity-surface.js +128 -127
  20. package/dist/access-lcm-surface.js +128 -127
  21. package/dist/access-mcp.js +128 -127
  22. package/dist/access-memory-search-fanout.js +2 -2
  23. package/dist/access-namespace-preflight.js +4 -4
  24. package/dist/access-observe-transcript.js +3 -2
  25. package/dist/access-observe-write-category.js +9 -9
  26. package/dist/access-observe-write-surface.d.ts +1 -0
  27. package/dist/access-observe-write-surface.d.ts.map +1 -1
  28. package/dist/access-observe-write-surface.js +128 -127
  29. package/dist/access-offline-manifest.js +9 -8
  30. package/dist/access-operations-batch.js +128 -127
  31. package/dist/access-operations.d.ts +1 -1
  32. package/dist/access-operations.js +128 -127
  33. package/dist/access-recall-concurrency.d.ts +3 -16
  34. package/dist/access-recall-concurrency.d.ts.map +1 -1
  35. package/dist/access-recall-concurrency.js +128 -127
  36. package/dist/access-recall-corpus-versions.d.ts +4 -1
  37. package/dist/access-recall-corpus-versions.d.ts.map +1 -1
  38. package/dist/access-recall-corpus-versions.js +4 -1
  39. package/dist/access-recall-diagnostics.js +3 -3
  40. package/dist/access-recall-response.d.ts.map +1 -1
  41. package/dist/access-recall-response.js +128 -127
  42. package/dist/access-recall-surface.d.ts +1 -0
  43. package/dist/access-recall-surface.d.ts.map +1 -1
  44. package/dist/access-recall-surface.js +128 -127
  45. package/dist/access-schema.d.ts +1 -0
  46. package/dist/access-schema.d.ts.map +1 -1
  47. package/dist/access-schema.js +2 -2
  48. package/dist/access-service.d.ts +3 -15
  49. package/dist/access-service.d.ts.map +1 -1
  50. package/dist/access-service.js +130 -127
  51. package/dist/access-surface-catalog.js +5 -5
  52. package/dist/access-token-capabilities.js +2 -2
  53. package/dist/active-recall.js +21 -21
  54. package/dist/artifact-search.js +2 -2
  55. package/dist/auto-sync-L3M4RKJD.js +1 -1
  56. package/dist/briefing.js +19 -19
  57. package/dist/buffer-add-turns-bounded.js +2 -2
  58. package/dist/buffer-turn-helpers.d.ts.map +1 -1
  59. package/dist/buffer-turn-helpers.js +1 -1
  60. package/dist/buffer.js +11 -10
  61. package/dist/calibration.js +2 -2
  62. package/dist/capsule-import-gate.js +2 -2
  63. package/dist/causal-consolidation.js +20 -20
  64. package/dist/{chunk-5V3IBSVB.js → chunk-22V3CMIW.js} +4 -4
  65. package/dist/{chunk-IHOKB3L3.js → chunk-2FCZIWRI.js} +785 -515
  66. package/dist/chunk-2FCZIWRI.js.map +1 -0
  67. package/dist/{chunk-7IWRLYFJ.js → chunk-2TJSGIKT.js} +2 -2
  68. package/dist/{chunk-V6M6N3EE.js → chunk-333SBFXB.js} +2 -2
  69. package/dist/{chunk-XBW7U7GM.js → chunk-3PNJZTDV.js} +5 -2
  70. package/dist/chunk-3PNJZTDV.js.map +1 -0
  71. package/dist/{chunk-XE4UYWW3.js → chunk-3YOX2BQD.js} +3 -3
  72. package/dist/{chunk-V4ASAWRP.js → chunk-47LDDGAL.js} +3 -3
  73. package/dist/{chunk-XEBNSY7N.js → chunk-4D2EY4WM.js} +2 -2
  74. package/dist/{chunk-5HFCXTGY.js → chunk-4D77BI3J.js} +29 -189
  75. package/dist/chunk-4D77BI3J.js.map +1 -0
  76. package/dist/{chunk-LPV72KRQ.js → chunk-4IMOGAFF.js} +3 -3
  77. package/dist/{chunk-QBREZ4QL.js → chunk-4L25GAYL.js} +2 -2
  78. package/dist/{chunk-HADD45AR.js → chunk-4WCLZBM2.js} +2 -2
  79. package/dist/{chunk-B3GKQ6DU.js → chunk-5MA6ZQ4Z.js} +2 -2
  80. package/dist/{chunk-3QLAOYBL.js → chunk-5QDTZIGH.js} +3 -3
  81. package/dist/{chunk-WXDTOE6F.js → chunk-5VMRM2X3.js} +2 -2
  82. package/dist/{chunk-VE23DIBH.js → chunk-6QWFZ3X5.js} +2 -2
  83. package/dist/{chunk-SDGD6MYV.js → chunk-7F7HRJI2.js} +2 -2
  84. package/dist/{chunk-QFPNWSVH.js → chunk-7OCKK5M5.js} +6 -6
  85. package/dist/{chunk-YAVIBVCU.js → chunk-7QF26EWO.js} +5 -5
  86. package/dist/{chunk-WAJL65KW.js → chunk-7VIJUZYW.js} +3 -3
  87. package/dist/{chunk-EI2M2CFJ.js → chunk-A5UOREWD.js} +3 -3
  88. package/dist/{chunk-32CA7B6L.js → chunk-AQZL7JBZ.js} +2 -2
  89. package/dist/{chunk-EDA6CDBT.js → chunk-AVWOULJH.js} +2 -2
  90. package/dist/{chunk-4HKK5HUI.js → chunk-B3M56D2A.js} +2 -2
  91. package/dist/{chunk-SRN5M4LQ.js → chunk-BKTCVXMK.js} +4 -4
  92. package/dist/{chunk-TXVTNDQT.js → chunk-BPCR5DZP.js} +2 -2
  93. package/dist/chunk-CKELO7Q6.js +113 -0
  94. package/dist/chunk-CKELO7Q6.js.map +1 -0
  95. package/dist/{chunk-IEB6XYW6.js → chunk-CKZWLAHN.js} +2 -2
  96. package/dist/{chunk-JVIWVJ2A.js → chunk-CUPILBIP.js} +3 -3
  97. package/dist/{chunk-274UY54Z.js → chunk-DFZYZOLH.js} +3 -3
  98. package/dist/{chunk-6S4DM53Y.js → chunk-E6EESRJ6.js} +6 -6
  99. package/dist/{chunk-FSI45NUK.js → chunk-EZG54YDS.js} +2 -2
  100. package/dist/{chunk-7ZFB4VZS.js → chunk-FFWFFAP3.js} +2 -2
  101. package/dist/{chunk-22VXXA67.js → chunk-FGT7CUYZ.js} +2 -2
  102. package/dist/{chunk-Z3SXC3MP.js → chunk-FOTFLHBN.js} +2 -2
  103. package/dist/{chunk-RH6XWXMA.js → chunk-FRYCXXTB.js} +3 -3
  104. package/dist/{chunk-B377OKUP.js → chunk-G64WYD2S.js} +4 -4
  105. package/dist/{chunk-JJEQRSYU.js → chunk-GBSXTTLP.js} +2 -2
  106. package/dist/{chunk-2YODOG2O.js → chunk-GIL2M2OI.js} +3 -3
  107. package/dist/{chunk-YVRQ5JRA.js → chunk-GYOKVJPB.js} +14 -8
  108. package/dist/chunk-GYOKVJPB.js.map +1 -0
  109. package/dist/{chunk-ARJ3KCX4.js → chunk-HDLNSDLK.js} +2 -2
  110. package/dist/{chunk-VXUO5JZC.js → chunk-HDWISXFH.js} +6 -6
  111. package/dist/{chunk-RNFMFC37.js → chunk-IDYYGOOQ.js} +28 -1
  112. package/dist/chunk-IDYYGOOQ.js.map +1 -0
  113. package/dist/{chunk-EZ47HOJ6.js → chunk-IXI6S2VJ.js} +4 -4
  114. package/dist/{chunk-VXMWTRQX.js → chunk-J74YOBB3.js} +4 -4
  115. package/dist/{chunk-AMW3IDCO.js → chunk-JFMMEHVG.js} +2 -2
  116. package/dist/{chunk-6TPWIPE3.js → chunk-JFZZDMEZ.js} +3 -3
  117. package/dist/{chunk-JTSSSR4L.js → chunk-KIUFT2WZ.js} +3 -3
  118. package/dist/{chunk-L6BLTV4D.js → chunk-L7SEYUHS.js} +2 -2
  119. package/dist/{chunk-WRAK5LLB.js → chunk-LPUEBFX2.js} +3 -3
  120. package/dist/{chunk-DBVSU3HE.js → chunk-LVGTH6IQ.js} +9 -9
  121. package/dist/{chunk-33VVVP57.js → chunk-MEVBSF6T.js} +4 -1
  122. package/dist/chunk-MEVBSF6T.js.map +1 -0
  123. package/dist/{chunk-CJCTKL6Y.js → chunk-MGKCKY7X.js} +4 -1
  124. package/dist/chunk-MGKCKY7X.js.map +1 -0
  125. package/dist/{chunk-SOGOHLWN.js → chunk-N7AIFTSH.js} +1 -1
  126. package/dist/chunk-N7AIFTSH.js.map +1 -0
  127. package/dist/chunk-O3XGASU5.js +197 -0
  128. package/dist/chunk-O3XGASU5.js.map +1 -0
  129. package/dist/{chunk-OGBQMY46.js → chunk-O544TUJO.js} +2 -2
  130. package/dist/{chunk-TFNZXOXK.js → chunk-OAQRZ4SV.js} +2 -2
  131. package/dist/{chunk-IEEV27BC.js → chunk-OO2HEUZ4.js} +2 -2
  132. package/dist/{chunk-YMC4AYJK.js → chunk-OWM2VWNX.js} +10 -10
  133. package/dist/{chunk-4LPTSB5V.js → chunk-PFLN6TTW.js} +2 -2
  134. package/dist/{chunk-YOR5QBEU.js → chunk-QFTK6EDM.js} +4 -4
  135. package/dist/{chunk-A2WFUMUN.js → chunk-QKDXO4FD.js} +4 -4
  136. package/dist/{chunk-Y7HLGKKU.js → chunk-QLQUAVVP.js} +4 -4
  137. package/dist/{chunk-MUMQWCE2.js → chunk-QPFM6DHY.js} +2 -2
  138. package/dist/{chunk-YWPCDR3I.js → chunk-QVXEXGIM.js} +3 -3
  139. package/dist/{chunk-UPE7TJWN.js → chunk-QWWHYBPT.js} +2 -2
  140. package/dist/{chunk-NZHZQGLB.js → chunk-QXTKN25V.js} +2 -2
  141. package/dist/{chunk-OAGTKS73.js → chunk-RFLC6PKQ.js} +2 -2
  142. package/dist/{chunk-ZRLTQ2Y7.js → chunk-RO5EGRAI.js} +2 -2
  143. package/dist/{chunk-5D4NBANY.js → chunk-SIONKXLU.js} +2 -2
  144. package/dist/{chunk-6XTUZKCZ.js → chunk-SMDZTJ2D.js} +2 -2
  145. package/dist/{chunk-OFSAKEZB.js → chunk-T4BT4FQN.js} +2 -2
  146. package/dist/{chunk-IC35ZYLM.js → chunk-TAD6QMMD.js} +4 -4
  147. package/dist/{chunk-EAHNSQ7H.js → chunk-TB6VFEHQ.js} +2 -2
  148. package/dist/{chunk-6ARSFTLD.js → chunk-TNRGWJYT.js} +2 -2
  149. package/dist/{chunk-JCAMHTS2.js → chunk-UBG65KEY.js} +7 -5
  150. package/dist/{chunk-JCAMHTS2.js.map → chunk-UBG65KEY.js.map} +1 -1
  151. package/dist/{chunk-CGOPDXLK.js → chunk-UMEUU66X.js} +2 -2
  152. package/dist/{chunk-5LTXYM7D.js → chunk-UYIBNDQE.js} +2 -2
  153. package/dist/{chunk-UGQEJWR3.js → chunk-VHXRLD6S.js} +2 -2
  154. package/dist/{chunk-WJ6S54ES.js → chunk-VOLTQNAP.js} +2 -2
  155. package/dist/{chunk-SBU5GDOT.js → chunk-VRHY7Y5A.js} +7 -7
  156. package/dist/{chunk-E5RJPLNL.js → chunk-W7N7NWG5.js} +3 -3
  157. package/dist/{chunk-UPWOMMVU.js → chunk-WECKZ3KT.js} +7 -7
  158. package/dist/{chunk-PCUDFWX5.js → chunk-WEFFO2MJ.js} +2 -2
  159. package/dist/{chunk-QCP75JGO.js → chunk-WQUGCOKF.js} +5 -5
  160. package/dist/{chunk-FKBGK3NC.js → chunk-WWUQ6CP3.js} +2 -2
  161. package/dist/{chunk-KR6PEAM4.js → chunk-X67XNZ64.js} +8 -8
  162. package/dist/{chunk-UYHDMCY2.js → chunk-XUVCQ4YZ.js} +2 -2
  163. package/dist/{chunk-7IJ2H43M.js → chunk-YY57TRKN.js} +2 -2
  164. package/dist/{chunk-AU6AEUFD.js → chunk-YYXYZM2I.js} +2 -2
  165. package/dist/{chunk-3FBAEPCU.js → chunk-ZDUE44CC.js} +2 -2
  166. package/dist/{chunk-PRE7R3RQ.js → chunk-ZQUOUPP3.js} +12 -3
  167. package/dist/chunk-ZQUOUPP3.js.map +1 -0
  168. package/dist/{chunk-RDO6AMDL.js → chunk-ZWDDY4WF.js} +2 -2
  169. package/dist/{chunk-QASTQVGK.js → chunk-ZX546Y3Y.js} +2 -2
  170. package/dist/chunk-ZX546Y3Y.js.map +1 -0
  171. package/dist/cli.js +128 -127
  172. package/dist/coding/architecture-surfaces.d.ts +0 -24
  173. package/dist/coding/architecture-surfaces.d.ts.map +1 -1
  174. package/dist/coding/codegraph-surfaces.d.ts.map +1 -1
  175. package/dist/coding/export-okf-codegraph.js +51 -24
  176. package/dist/coding/export-okf-codegraph.js.map +1 -1
  177. package/dist/coding/git-context.d.ts +23 -0
  178. package/dist/coding/git-context.d.ts.map +1 -1
  179. package/dist/coding/git-context.js +31 -0
  180. package/dist/coding/git-context.js.map +1 -0
  181. package/dist/coding/session-delta-surfaces.d.ts +0 -23
  182. package/dist/coding/session-delta-surfaces.d.ts.map +1 -1
  183. package/dist/compounding/engine.js +20 -20
  184. package/dist/config.js +21 -21
  185. package/dist/connectors/codex-materialize-runner.js +19 -19
  186. package/dist/connectors/index.js +23 -23
  187. package/dist/convergence-refresh.js +21 -21
  188. package/dist/conversation-index/backend.js +2 -2
  189. package/dist/corpus-watermark.js +23 -23
  190. package/dist/deep-recall-config.js +2 -2
  191. package/dist/deep-recall-http-glue.js +4 -4
  192. package/dist/entity-recall-cancellation.js +2 -2
  193. package/dist/entity-recall-reads.js +3 -3
  194. package/dist/entity-retrieval.js +21 -21
  195. package/dist/explicit-capture.js +128 -127
  196. package/dist/external-wiki-access.js +4 -4
  197. package/dist/extraction-judge.js +1 -1
  198. package/dist/extraction.js +31 -30
  199. package/dist/harmonic-retrieval.js +19 -19
  200. package/dist/index.js +207 -205
  201. package/dist/local-llm.js +2 -2
  202. package/dist/location/index.js +21 -21
  203. package/dist/maintenance/memory-governance.js +19 -19
  204. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +19 -19
  205. package/dist/maintenance/rebuild-memory-projection-runner.js +21 -21
  206. package/dist/maintenance/rebuild-memory-projection.js +20 -20
  207. package/dist/memory-browse-http-glue.js +2 -2
  208. package/dist/memory-browse-operations.js +4 -4
  209. package/dist/memory-browse.js +6 -6
  210. package/dist/namespaces/migrate.js +20 -20
  211. package/dist/namespaces/search.js +8 -8
  212. package/dist/namespaces/storage.js +19 -19
  213. package/dist/offline-sync-impression-drain.js +8 -7
  214. package/dist/operator-doctor-corpus.js +26 -26
  215. package/dist/operator-doctor-replica.js +4 -4
  216. package/dist/operator-toolkit.js +35 -34
  217. package/dist/orchestration/backlog-scheduler.js +129 -128
  218. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  219. package/dist/orchestration/buffer-drain-runner.js +129 -128
  220. package/dist/orchestration/episodic-context-section.d.ts +3 -2
  221. package/dist/orchestration/episodic-context-section.d.ts.map +1 -1
  222. package/dist/orchestration/maintenance.js +34 -33
  223. package/dist/orchestration/orchestrator-helpers.d.ts +10 -0
  224. package/dist/orchestration/orchestrator-helpers.d.ts.map +1 -1
  225. package/dist/orchestration/orchestrator-init.d.ts +12 -13
  226. package/dist/orchestration/orchestrator-init.d.ts.map +1 -1
  227. package/dist/orchestration/recall-entry.d.ts.map +1 -1
  228. package/dist/orchestration/recall-internal.d.ts.map +1 -1
  229. package/dist/orchestration/session-context.d.ts +5 -1
  230. package/dist/orchestration/session-context.d.ts.map +1 -1
  231. package/dist/orchestration/startup-search-sync.d.ts +73 -0
  232. package/dist/orchestration/startup-search-sync.d.ts.map +1 -0
  233. package/dist/orchestration/turn-ingestion.d.ts.map +1 -1
  234. package/dist/orchestrator.d.ts +4 -1
  235. package/dist/orchestrator.d.ts.map +1 -1
  236. package/dist/orchestrator.js +128 -127
  237. package/dist/qmd-daemon-session.js +2 -2
  238. package/dist/qmd.js +3 -3
  239. package/dist/recall-explain-renderer.js +3 -3
  240. package/dist/recall-navigate-access.js +2 -2
  241. package/dist/recall-navigate-disclosure.js +2 -2
  242. package/dist/recall-navigate.js +2 -2
  243. package/dist/recall-navigation-http-glue.js +2 -2
  244. package/dist/recall-navigation-operations.js +4 -4
  245. package/dist/recall-navigation.js +128 -127
  246. package/dist/recall-qos.d.ts +26 -0
  247. package/dist/recall-qos.d.ts.map +1 -1
  248. package/dist/recall-qos.js +9 -1
  249. package/dist/recall-state-view-admission.js +6 -6
  250. package/dist/recall-why-service.js +6 -6
  251. package/dist/recall-xray-cli.js +4 -4
  252. package/dist/recall-xray-renderer.js +3 -3
  253. package/dist/recall-xray.js +2 -2
  254. package/dist/relay/mission.d.ts +3 -3
  255. package/dist/replica-divergence.js +3 -3
  256. package/dist/resume-bundles.js +23 -23
  257. package/dist/search/factory.js +7 -7
  258. package/dist/search/index.js +9 -9
  259. package/dist/semantic-consolidation.js +20 -20
  260. package/dist/semantic-rule-promotion.js +19 -19
  261. package/dist/semantic-rule-verifier.js +19 -19
  262. package/dist/source-agent-qualifier.js +29 -28
  263. package/dist/standup/build.js +20 -20
  264. package/dist/storage/buffer-drain-claims.js +2 -2
  265. package/dist/storage/buffer-session-files.js +2 -2
  266. package/dist/storage.js +18 -18
  267. package/dist/summarizer.js +3 -3
  268. package/dist/support-passport/index.js +7 -7
  269. package/dist/tokens.js +3 -3
  270. package/dist/transfer/export-okf.js +19 -19
  271. package/dist/types.d.ts +1 -0
  272. package/dist/types.d.ts.map +1 -1
  273. package/dist/types.js +1 -1
  274. package/dist/verified-recall.js +19 -19
  275. package/dist/who-knows-cli.js +21 -21
  276. package/dist/who-knows.js +20 -20
  277. package/package.json +12 -2
  278. package/src/access-cli.ts +18 -9
  279. package/src/access-coding-context-resolution.ts +138 -0
  280. package/src/access-errors.ts +5 -0
  281. package/src/access-http-admission.test.ts +76 -0
  282. package/src/access-http.test.ts +2 -0
  283. package/src/access-http.ts +4 -0
  284. package/src/access-observe-write-surface.ts +2 -1
  285. package/src/access-operations-batch.ts +2 -2
  286. package/src/access-recall-concurrency.ts +179 -22
  287. package/src/access-recall-corpus-versions.ts +12 -7
  288. package/src/access-recall-response.ts +25 -2
  289. package/src/access-recall-surface.ts +6 -4
  290. package/src/access-schema.ts +9 -0
  291. package/src/access-service-raw-excerpt-read-gate.test.ts +7 -2
  292. package/src/access-service-recall-concurrency.test.ts +242 -0
  293. package/src/access-service-set-coding-context.test.ts +210 -0
  294. package/src/access-service.ts +43 -58
  295. package/src/buffer-turn-helpers.ts +3 -0
  296. package/src/capsule-import-gate.test.ts +106 -0
  297. package/src/coding/access-coding-context.test.ts +3 -0
  298. package/src/coding/architecture-surfaces.ts +2 -1
  299. package/src/coding/codegraph-surfaces.test.ts +34 -0
  300. package/src/coding/codegraph-surfaces.ts +3 -2
  301. package/src/coding/git-context.test.ts +29 -0
  302. package/src/coding/git-context.ts +63 -2
  303. package/src/coding/session-delta-surfaces.ts +2 -1
  304. package/src/harmonic-graph-version.test.ts +63 -0
  305. package/src/orchestration/episodic-context-section.ts +6 -7
  306. package/src/orchestration/orchestrator-helpers.ts +10 -0
  307. package/src/orchestration/orchestrator-init.ts +57 -303
  308. package/src/orchestration/recall-entry.ts +59 -4
  309. package/src/orchestration/recall-internal.ts +10 -10
  310. package/src/orchestration/session-context.ts +11 -1
  311. package/src/orchestration/startup-search-sync.ts +492 -0
  312. package/src/orchestration/task-exit.test.ts +45 -0
  313. package/src/orchestration/turn-ingestion-buffered.test.ts +224 -0
  314. package/src/orchestration/turn-ingestion.ts +28 -35
  315. package/src/orchestrator-flush.test.ts +7 -7
  316. package/src/orchestrator-init.test.ts +364 -12
  317. package/src/orchestrator-source-attribution.test.ts +100 -0
  318. package/src/orchestrator-startup-ready-path.test.ts +133 -10
  319. package/src/orchestrator.ts +16 -1
  320. package/src/recall-qos.test.ts +62 -0
  321. package/src/recall-qos.ts +75 -0
  322. package/src/recall-retrieval-failure.test.ts +282 -18
  323. package/src/recall-search-options.test.ts +13 -1
  324. package/src/storage/buffer-drain-handin-memo.test.ts +140 -0
  325. package/src/types.ts +1 -1
  326. package/dist/chunk-33VVVP57.js.map +0 -1
  327. package/dist/chunk-3QNFHI6T.js +0 -38
  328. package/dist/chunk-3QNFHI6T.js.map +0 -1
  329. package/dist/chunk-5HFCXTGY.js.map +0 -1
  330. package/dist/chunk-CJCTKL6Y.js.map +0 -1
  331. package/dist/chunk-IHOKB3L3.js.map +0 -1
  332. package/dist/chunk-PRE7R3RQ.js.map +0 -1
  333. package/dist/chunk-QASTQVGK.js.map +0 -1
  334. package/dist/chunk-RNFMFC37.js.map +0 -1
  335. package/dist/chunk-SOGOHLWN.js.map +0 -1
  336. package/dist/chunk-XBW7U7GM.js.map +0 -1
  337. package/dist/chunk-YVRQ5JRA.js.map +0 -1
  338. /package/dist/{chunk-5V3IBSVB.js.map → chunk-22V3CMIW.js.map} +0 -0
  339. /package/dist/{chunk-7IWRLYFJ.js.map → chunk-2TJSGIKT.js.map} +0 -0
  340. /package/dist/{chunk-V6M6N3EE.js.map → chunk-333SBFXB.js.map} +0 -0
  341. /package/dist/{chunk-XE4UYWW3.js.map → chunk-3YOX2BQD.js.map} +0 -0
  342. /package/dist/{chunk-V4ASAWRP.js.map → chunk-47LDDGAL.js.map} +0 -0
  343. /package/dist/{chunk-XEBNSY7N.js.map → chunk-4D2EY4WM.js.map} +0 -0
  344. /package/dist/{chunk-LPV72KRQ.js.map → chunk-4IMOGAFF.js.map} +0 -0
  345. /package/dist/{chunk-QBREZ4QL.js.map → chunk-4L25GAYL.js.map} +0 -0
  346. /package/dist/{chunk-HADD45AR.js.map → chunk-4WCLZBM2.js.map} +0 -0
  347. /package/dist/{chunk-B3GKQ6DU.js.map → chunk-5MA6ZQ4Z.js.map} +0 -0
  348. /package/dist/{chunk-3QLAOYBL.js.map → chunk-5QDTZIGH.js.map} +0 -0
  349. /package/dist/{chunk-WXDTOE6F.js.map → chunk-5VMRM2X3.js.map} +0 -0
  350. /package/dist/{chunk-VE23DIBH.js.map → chunk-6QWFZ3X5.js.map} +0 -0
  351. /package/dist/{chunk-SDGD6MYV.js.map → chunk-7F7HRJI2.js.map} +0 -0
  352. /package/dist/{chunk-QFPNWSVH.js.map → chunk-7OCKK5M5.js.map} +0 -0
  353. /package/dist/{chunk-YAVIBVCU.js.map → chunk-7QF26EWO.js.map} +0 -0
  354. /package/dist/{chunk-WAJL65KW.js.map → chunk-7VIJUZYW.js.map} +0 -0
  355. /package/dist/{chunk-EI2M2CFJ.js.map → chunk-A5UOREWD.js.map} +0 -0
  356. /package/dist/{chunk-32CA7B6L.js.map → chunk-AQZL7JBZ.js.map} +0 -0
  357. /package/dist/{chunk-EDA6CDBT.js.map → chunk-AVWOULJH.js.map} +0 -0
  358. /package/dist/{chunk-4HKK5HUI.js.map → chunk-B3M56D2A.js.map} +0 -0
  359. /package/dist/{chunk-SRN5M4LQ.js.map → chunk-BKTCVXMK.js.map} +0 -0
  360. /package/dist/{chunk-TXVTNDQT.js.map → chunk-BPCR5DZP.js.map} +0 -0
  361. /package/dist/{chunk-IEB6XYW6.js.map → chunk-CKZWLAHN.js.map} +0 -0
  362. /package/dist/{chunk-JVIWVJ2A.js.map → chunk-CUPILBIP.js.map} +0 -0
  363. /package/dist/{chunk-274UY54Z.js.map → chunk-DFZYZOLH.js.map} +0 -0
  364. /package/dist/{chunk-6S4DM53Y.js.map → chunk-E6EESRJ6.js.map} +0 -0
  365. /package/dist/{chunk-FSI45NUK.js.map → chunk-EZG54YDS.js.map} +0 -0
  366. /package/dist/{chunk-7ZFB4VZS.js.map → chunk-FFWFFAP3.js.map} +0 -0
  367. /package/dist/{chunk-22VXXA67.js.map → chunk-FGT7CUYZ.js.map} +0 -0
  368. /package/dist/{chunk-Z3SXC3MP.js.map → chunk-FOTFLHBN.js.map} +0 -0
  369. /package/dist/{chunk-RH6XWXMA.js.map → chunk-FRYCXXTB.js.map} +0 -0
  370. /package/dist/{chunk-B377OKUP.js.map → chunk-G64WYD2S.js.map} +0 -0
  371. /package/dist/{chunk-JJEQRSYU.js.map → chunk-GBSXTTLP.js.map} +0 -0
  372. /package/dist/{chunk-2YODOG2O.js.map → chunk-GIL2M2OI.js.map} +0 -0
  373. /package/dist/{chunk-ARJ3KCX4.js.map → chunk-HDLNSDLK.js.map} +0 -0
  374. /package/dist/{chunk-VXUO5JZC.js.map → chunk-HDWISXFH.js.map} +0 -0
  375. /package/dist/{chunk-EZ47HOJ6.js.map → chunk-IXI6S2VJ.js.map} +0 -0
  376. /package/dist/{chunk-VXMWTRQX.js.map → chunk-J74YOBB3.js.map} +0 -0
  377. /package/dist/{chunk-AMW3IDCO.js.map → chunk-JFMMEHVG.js.map} +0 -0
  378. /package/dist/{chunk-6TPWIPE3.js.map → chunk-JFZZDMEZ.js.map} +0 -0
  379. /package/dist/{chunk-JTSSSR4L.js.map → chunk-KIUFT2WZ.js.map} +0 -0
  380. /package/dist/{chunk-L6BLTV4D.js.map → chunk-L7SEYUHS.js.map} +0 -0
  381. /package/dist/{chunk-WRAK5LLB.js.map → chunk-LPUEBFX2.js.map} +0 -0
  382. /package/dist/{chunk-DBVSU3HE.js.map → chunk-LVGTH6IQ.js.map} +0 -0
  383. /package/dist/{chunk-OGBQMY46.js.map → chunk-O544TUJO.js.map} +0 -0
  384. /package/dist/{chunk-TFNZXOXK.js.map → chunk-OAQRZ4SV.js.map} +0 -0
  385. /package/dist/{chunk-IEEV27BC.js.map → chunk-OO2HEUZ4.js.map} +0 -0
  386. /package/dist/{chunk-YMC4AYJK.js.map → chunk-OWM2VWNX.js.map} +0 -0
  387. /package/dist/{chunk-4LPTSB5V.js.map → chunk-PFLN6TTW.js.map} +0 -0
  388. /package/dist/{chunk-YOR5QBEU.js.map → chunk-QFTK6EDM.js.map} +0 -0
  389. /package/dist/{chunk-A2WFUMUN.js.map → chunk-QKDXO4FD.js.map} +0 -0
  390. /package/dist/{chunk-Y7HLGKKU.js.map → chunk-QLQUAVVP.js.map} +0 -0
  391. /package/dist/{chunk-MUMQWCE2.js.map → chunk-QPFM6DHY.js.map} +0 -0
  392. /package/dist/{chunk-YWPCDR3I.js.map → chunk-QVXEXGIM.js.map} +0 -0
  393. /package/dist/{chunk-UPE7TJWN.js.map → chunk-QWWHYBPT.js.map} +0 -0
  394. /package/dist/{chunk-NZHZQGLB.js.map → chunk-QXTKN25V.js.map} +0 -0
  395. /package/dist/{chunk-OAGTKS73.js.map → chunk-RFLC6PKQ.js.map} +0 -0
  396. /package/dist/{chunk-ZRLTQ2Y7.js.map → chunk-RO5EGRAI.js.map} +0 -0
  397. /package/dist/{chunk-5D4NBANY.js.map → chunk-SIONKXLU.js.map} +0 -0
  398. /package/dist/{chunk-6XTUZKCZ.js.map → chunk-SMDZTJ2D.js.map} +0 -0
  399. /package/dist/{chunk-OFSAKEZB.js.map → chunk-T4BT4FQN.js.map} +0 -0
  400. /package/dist/{chunk-IC35ZYLM.js.map → chunk-TAD6QMMD.js.map} +0 -0
  401. /package/dist/{chunk-EAHNSQ7H.js.map → chunk-TB6VFEHQ.js.map} +0 -0
  402. /package/dist/{chunk-6ARSFTLD.js.map → chunk-TNRGWJYT.js.map} +0 -0
  403. /package/dist/{chunk-CGOPDXLK.js.map → chunk-UMEUU66X.js.map} +0 -0
  404. /package/dist/{chunk-5LTXYM7D.js.map → chunk-UYIBNDQE.js.map} +0 -0
  405. /package/dist/{chunk-UGQEJWR3.js.map → chunk-VHXRLD6S.js.map} +0 -0
  406. /package/dist/{chunk-WJ6S54ES.js.map → chunk-VOLTQNAP.js.map} +0 -0
  407. /package/dist/{chunk-SBU5GDOT.js.map → chunk-VRHY7Y5A.js.map} +0 -0
  408. /package/dist/{chunk-E5RJPLNL.js.map → chunk-W7N7NWG5.js.map} +0 -0
  409. /package/dist/{chunk-UPWOMMVU.js.map → chunk-WECKZ3KT.js.map} +0 -0
  410. /package/dist/{chunk-PCUDFWX5.js.map → chunk-WEFFO2MJ.js.map} +0 -0
  411. /package/dist/{chunk-QCP75JGO.js.map → chunk-WQUGCOKF.js.map} +0 -0
  412. /package/dist/{chunk-FKBGK3NC.js.map → chunk-WWUQ6CP3.js.map} +0 -0
  413. /package/dist/{chunk-KR6PEAM4.js.map → chunk-X67XNZ64.js.map} +0 -0
  414. /package/dist/{chunk-UYHDMCY2.js.map → chunk-XUVCQ4YZ.js.map} +0 -0
  415. /package/dist/{chunk-7IJ2H43M.js.map → chunk-YY57TRKN.js.map} +0 -0
  416. /package/dist/{chunk-AU6AEUFD.js.map → chunk-YYXYZM2I.js.map} +0 -0
  417. /package/dist/{chunk-3FBAEPCU.js.map → chunk-ZDUE44CC.js.map} +0 -0
  418. /package/dist/{chunk-RDO6AMDL.js.map → chunk-ZWDDY4WF.js.map} +0 -0
@@ -1 +0,0 @@
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, defaultNamesp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AAA,IAClB;AAAA,EACF;AAEA,QAAM,UAAU,8BAA8B,eAAe,QAAQ,gBAAgB;AAGrF,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,MACL,OAAO;AAAA,MACP;AAAA,MACA;AAAA,MACA,oBAAoB;AAAA,MACpB,eAAe,CAAC;AAAA,MAChB,gBAAgB;AAAA,IAClB;AAAA,EACF;AACA,SAAO;AAAA,IACL,OAAO,QAAQ;AAAA,IACf;AAAA,IACA;AAAA,IACA,oBAAoB,QAAQ;AAAA,IAC5B,eAAe,QAAQ;AAAA,IACvB,gBAAgB;AAAA,EAClB;AACF;AA4CA,IAAM,kBAAkB;AAYxB,SAAS,oBAAoB,YAA4B;AACvD,SAAO,WAAW,WAAW,eAAe,IACxC,GAAG,eAAe,GAAG,UAAU,KAC/B;AACN;AAsBO,SAAS,0BACd,WACA,YACA,kBACoB;AACpB,MAAI,OAAO,eAAe,YAAY,WAAW,WAAW,EAAG,QAAO;AACtE,MACE,OAAO,cAAc,YACrB,UAAU,SAAS,KACnB,cAAc,kBACd;AAIA,WAAO,GAAG,eAAe,GAAG,SAAS,GAAG,eAAe,GAAG,UAAU;AAAA,EACtE;AAGA,SAAO,oBAAoB,UAAU;AACvC;AAqCO,SAAS,+BACd,YACA,YACA,kBAC2B;AAG3B,MAAI,OAAO,eAAe,YAAY,WAAW,WAAW,GAAG;AAC7D,WAAO,CAAC,MAAS;AAAA,EACnB;AACA,QAAM,MAAgB,CAAC;AACvB,QAAM,OAAO,oBAAI,IAAY;AAC7B,aAAW,aAAa,YAAY;AAClC,UAAM,MACJ,0BAA0B,WAAW,YAAY,gBAAgB,KACjE;AACF,QAAI,CAAC,KAAK,IAAI,GAAG,GAAG;AAClB,WAAK,IAAI,GAAG;AACZ,UAAI,KAAK,GAAG;AAAA,IACd;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/access-errors.ts"],"sourcesContent":["/**\n * Tool-surface error enrichment: nearest-tool suggestions and arg-shape hints.\n *\n * Each function is a pure message builder — it returns a better error string\n * without changing semantics, status codes, or rejection behavior.\n *\n * @module access-errors\n */\n\nimport type { ZodError } from \"zod\";\n\n// ─── Existing error classes (restored from pre-#3042) ─────────────────────\n\n/** Authenticated caller lacks the required authorization (HTTP 403). */\nexport class EngramAccessForbiddenError extends Error {}\n\n/** Invalid caller input (HTTP 400). */\nexport class EngramAccessInputError extends Error {}\n\n/**\n * A write rejected by the namespace write-ACL (issue #1888). Subclasses\n * EngramAccessInputError so every existing catch/HTTP-400 mapping still\n * applies, but carries the attempted namespace + principal so the observe/\n * write surfaces can dead-letter the payload before re-throwing (fail-closed\n * placement is unchanged; only the destroyed-payload behavior is fixed).\n */\nexport class NamespaceNotWritableError extends EngramAccessInputError {\n constructor(\n readonly attemptedNamespace: string,\n readonly principal: string | undefined,\n message?: string,\n ) {\n super(message ?? `namespace is not writable: ${attemptedNamespace}`);\n this.name = \"NamespaceNotWritableError\";\n }\n}\n\n// ─── Reserved argument keys (issue #3225 B1) ──────────────────────────────\n\n/**\n * Dictionary keys that change object shape or prototype resolution. A JSON\n * body can carry them as own members; the request preprocessors reject them\n * before copying, so a decoded `__proto__` member cannot become an inherited\n * schema field. Lives in this lowest module so the boundary and wire schema\n * layers share one implementation without an import cycle.\n */\nexport const RESERVED_PROTO_KEYS: readonly string[] = [\"__proto__\", \"constructor\", \"prototype\"];\n\n/**\n * Reject the reserved keys with the input-error type, so a client that\n * submits a magic dictionary key gets a validation error instead of a\n * silently reshaped request object.\n */\nexport function rejectReservedArgumentKey(key: string): void {\n if (RESERVED_PROTO_KEYS.includes(key)) {\n throw new EngramAccessInputError(`${key} is not a permitted argument key`);\n }\n}\n\n// ─── Levenshtein distance ─────────────────────────────────────────────────\n\n/**\n * Standard Levenshtein edit distance. O(n*m) over bounded inputs.\n * Exported so the test can verify it without importing private helpers.\n */\nexport function levenshtein(a: string, b: string): number {\n const an = a.length;\n const bn = b.length;\n // Fast paths for empty strings.\n if (an === 0) return bn;\n if (bn === 0) return an;\n\n // Use two rows to keep memory O(min(n,m)).\n let prev: number[] = [];\n let curr: number[] = [];\n\n // Align loops to the shorter string.\n const [shorter, longer, sn, ln] =\n an < bn ? [a, b, an, bn] : [b, a, bn, an];\n\n for (let i = 0; i <= sn; i++) prev[i] = i;\n\n for (let j = 1; j <= ln; j++) {\n curr[0] = j;\n for (let i = 1; i <= sn; i++) {\n const cost = shorter[i - 1] === longer[j - 1] ? 0 : 1;\n curr[i] = Math.min(\n prev[i] + 1, // deletion\n curr[i - 1] + 1, // insertion\n prev[i - 1] + cost, // substitution\n );\n }\n [prev, curr] = [curr, prev];\n }\n return prev[sn];\n}\n\n// ─── Similar-name helpers ─────────────────────────────────────────────────\n\nconst SUGGESTION_DISTANCE_CAP = 3;\n/**\n * Upper bound on the requested tool name. Anything longer is rejected before\n * the O(n*m) Levenshtein pass (#3042 review, P2): a 128 KB request over ~30\n * tools would otherwise run hundreds of millions of comparisons and block\n * the server event loop. The repo documents 64 chars as the tool-name shape;\n * this matches the limit enforced by every published surface.\n */\nexport const SUGGESTION_REQUEST_MAX_LEN = 64;\n\nexport interface SuggestionCandidate {\n name: string;\n distance: number;\n}\n\n/**\n * Find the nearest registered tool names by Levenshtein distance.\n * Results are sorted by distance ascending then name ascending (deterministic).\n * Only names with distance <= {@link SUGGESTION_DISTANCE_CAP} are returned;\n * when no name is that close the caller falls back to listing the full set.\n */\nexport function nearestSuggestions(\n requested: string,\n registeredNames: readonly string[],\n): SuggestionCandidate[] {\n // Defense in depth: the entry point already caps; this guards any direct\n // caller of the helper from an unbounded Levenshtein pass (issue #3042).\n if (requested.length > SUGGESTION_REQUEST_MAX_LEN) return [];\n const candidates: SuggestionCandidate[] = [];\n for (const name of registeredNames) {\n const distance = levenshtein(requested.toLowerCase(), name.toLowerCase());\n if (distance <= SUGGESTION_DISTANCE_CAP) {\n candidates.push({ name, distance });\n }\n }\n // Total comparator: distance asc, then name asc.\n candidates.sort((a, b) => {\n if (a.distance !== b.distance) return a.distance < b.distance ? -1 : 1;\n return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;\n });\n return candidates;\n}\n\n/**\n * Build a human-readable \"did you mean?\" suggestion string.\n * When no close match is found, returns a fallback listing.\n */\nfunction buildSuggestion(\n requested: string,\n registeredNames: readonly string[],\n): string {\n const suggestions = nearestSuggestions(requested, registeredNames);\n if (suggestions.length === 0) {\n return `Registered tools: ${registeredNames.join(\", \")}`;\n }\n return `Did you mean ${suggestions.map((s) => s.name).join(\", \")}?`;\n}\n\n/**\n * Read a Zod type tag without asserting a shape.\n *\n * Zod keeps its discriminant at `_def.typeName`. Both hops are narrowed with\n * `in`/`typeof` rather than an inline cast, so a non-Zod object yields\n * `undefined` instead of a fabricated read.\n */\nfunction zodTypeName(schema: unknown): string | undefined {\n // zod 4: schema internals live on `_zod.def.type` (v3 read `_def.typeName`).\n if (!(schema instanceof Object) || !(\"_zod\" in schema)) return undefined;\n // SAFETY: the guard above established `_zod` exists; its `.def` carries the\n // discriminator string under `type`.\n const def = (schema as { _zod?: { def?: { type?: unknown } } })._zod?.def;\n // SAFETY: zod's `_zod.def.type` discriminator is always a string literal.\n const discriminator = def?.type;\n return discriminator === undefined ? undefined : String(discriminator);\n}\n\n/**\n * A zod schema node this module reflects over — any object the library\n * exposes as a schema (v4 marks them with `_zod`).\n */\n/** Structural marker: every zod schema carries `_zod`. */\ntype ZodSchemaLike = { _zod?: unknown };\n\n/**\n * A synthetic example value derived from a schema: a placeholder the SAME\n * schema accepts, so the error message can show a valid argument shape.\n */\ntype SchemaExample = string | number | boolean | null | readonly SchemaExample[] | { [key: string]: SchemaExample };\n\n/**\n * Reverse-engineer ONE synthetic example value from a Zod schema type.\n * Returns a deterministic placeholder intended to round-trip through parse().\n */\nfunction exampleFromSchema(schema: ZodSchemaLike): SchemaExample | undefined {\n switch (zodTypeName(schema)) {\n case \"string\":\n return \"<string>\";\n case \"number\":\n return 42;\n case \"boolean\":\n return true;\n case \"nullable\":\n return null;\n case \"array\":\n return [];\n case \"optional\":\n // Optional fields are omitted from the example rather than sent as null.\n return undefined;\n case \"enum\": {\n // v4 exposes accepted values as the public `.enum` record.\n if (!(schema instanceof Object) || !(\"enum\" in schema)) return \"<value>\";\n // SAFETY: the guard established `.enum`; zod types it as a value record.\n const values = Object.values((schema as { enum: Record<string, string> }).enum);\n return values.length > 0 ? values[0] : \"<value>\";\n }\n case \"object\": {\n // v4 exposes `.shape` as a plain property on the object schema.\n if (!(schema instanceof Object) || !(\"shape\" in schema)) return {};\n // SAFETY: object schemas expose their field schemas keyed by name.\n const fieldsByName = (schema as { shape: { [field: string]: ZodSchemaLike } }).shape;\n if (!(fieldsByName instanceof Object)) return {};\n const result: { [key: string]: SchemaExample } = {};\n for (const field of Object.getOwnPropertyNames(fieldsByName)) {\n if (!Object.hasOwn(fieldsByName, field)) continue;\n const schemaNode = fieldsByName[field];\n const value = exampleFromSchema(schemaNode);\n if (value !== undefined) result[field] = value;\n }\n return result;\n }\n default:\n return undefined;\n }\n}\n/**\n * Build an enriched \"unknown tool\" error message.\n *\n * @param requested - the tool name the caller used\n * @param registeredNames - ALL registered tool names (including aliases)\n */\nexport function unknownToolError(\n requested: string,\n registeredNames: readonly string[],\n): string {\n // Cap the request before the suggestion pass: a 128 KB name would otherwise\n // pay O(n*m) per registered tool (issue #3042 review, P2). The cap matches\n // the documented tool-name shape; an over-long request is rejected with a\n // teaching message rather than a silent truncate.\n if (requested.length > SUGGESTION_REQUEST_MAX_LEN) {\n return `Unknown tool: name exceeds ${SUGGESTION_REQUEST_MAX_LEN} characters (got ${requested.length}).`;\n }\n const suggestion = buildSuggestion(requested, registeredNames);\n return `Unknown tool: ${requested}. ${suggestion}`;\n}\n\n/**\n * Build an enriched \"invalid arguments\" error message.\n *\n * The example is generated from the schema (never hand-written, so it cannot\n * drift) and is shown ONLY when it round-trips through that same schema. It\n * carries schema-derived fields only: injecting the tool name would add an\n * unrecognized property and fail a `.strict()` object (#3035 review finding).\n *\n * @param tool - the tool name that received the invalid args\n * @param zodError - the ZodError from parse()\n * @param schema - the original Zod schema, used to generate the example\n */\nexport function invalidArgsError(\n tool: string,\n zodError: ZodError,\n schema?: unknown,\n): string {\n const issues = zodError.issues.map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join(\".\") : \"(root)\";\n // `expected` exists only on the invalid_type / invalid_literal variants of\n // ZodIssue, so it is read through a presence check rather than assumed.\n const expected = \"expected\" in issue ? issue.expected : undefined;\n return expected === undefined\n ? `${path}: ${issue.message}`\n : `${path}: ${issue.message} (expected ${String(expected)})`;\n });\n let message = `Invalid arguments for \"${tool}\": ${issues.join(\"; \")}`;\n if (!schema) return message;\n\n const example = exampleFromSchema(schema);\n if (!example || typeof example !== \"object\" || Object.keys(example).length === 0) {\n return message;\n }\n\n // Withhold an example that cannot parse against its own schema: a\n // non-round-tripping example is misinformation, worse than none. Narrowed\n // with `in`/`typeof` rather than an inline cast so the shape is checked.\n let roundTrips = false;\n if (typeof schema === \"object\" && \"safeParse\" in schema) {\n const parser = schema.safeParse;\n if (typeof parser === \"function\") {\n try {\n const parsed: unknown = parser.call(schema, example);\n roundTrips =\n typeof parsed === \"object\"\n && parsed !== null\n && \"success\" in parsed\n && parsed.success === true;\n } catch {\n roundTrips = false;\n }\n }\n }\n\n return roundTrips ? `${message}. Example arguments: ${JSON.stringify(example)}` : message;\n}\n"],"mappings":";AAcO,IAAM,6BAAN,cAAyC,MAAM;AAAC;AAGhD,IAAM,yBAAN,cAAqC,MAAM;AAAC;AAS5C,IAAM,4BAAN,cAAwC,uBAAuB;AAAA,EACpE,YACW,oBACA,WACT,SACA;AACA,UAAM,WAAW,8BAA8B,kBAAkB,EAAE;AAJ1D;AACA;AAIT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAAA,EACA;AAMb;AAWO,IAAM,sBAAyC,CAAC,aAAa,eAAe,WAAW;AAOvF,SAAS,0BAA0B,KAAmB;AAC3D,MAAI,oBAAoB,SAAS,GAAG,GAAG;AACrC,U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