@remnic/core 9.57.4 → 9.57.5

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 (202) hide show
  1. package/dist/access-admin-ops-surface.js +23 -23
  2. package/dist/access-authorization-probe.js +24 -24
  3. package/dist/access-boundary.js +23 -23
  4. package/dist/access-cli.js +57 -57
  5. package/dist/access-extraction-force-flush.js +23 -23
  6. package/dist/access-http-query.js +23 -23
  7. package/dist/access-http.js +34 -34
  8. package/dist/access-identity-continuity-surface.js +23 -23
  9. package/dist/access-lcm-surface.js +23 -23
  10. package/dist/access-mcp.js +30 -30
  11. package/dist/access-memory-search-fanout.js +4 -3
  12. package/dist/access-namespace-preflight.js +23 -23
  13. package/dist/access-observe-write-surface.js +23 -23
  14. package/dist/access-offline-manifest.js +10 -10
  15. package/dist/access-operations-batch.js +26 -26
  16. package/dist/access-operations.js +29 -29
  17. package/dist/access-recall-concurrency.js +23 -23
  18. package/dist/access-recall-response.js +23 -23
  19. package/dist/access-recall-surface.js +23 -23
  20. package/dist/access-service.js +23 -23
  21. package/dist/access-surface-catalog.js +25 -25
  22. package/dist/active-memory-bridge.js +5 -5
  23. package/dist/briefing.js +5 -5
  24. package/dist/buffer.js +6 -5
  25. package/dist/causal-consolidation.js +7 -7
  26. package/dist/{chunk-O54B5YNM.js → chunk-24PNX2GF.js} +3 -3
  27. package/dist/{chunk-ONCWJBWV.js → chunk-3AJOJOFP.js} +2 -2
  28. package/dist/{chunk-QSDPVZPD.js → chunk-4O6R3GPK.js} +8 -8
  29. package/dist/{chunk-IXGQP4RZ.js → chunk-4SGDYYWV.js} +4 -4
  30. package/dist/{chunk-UTDMY476.js → chunk-4UUF2EX3.js} +3 -3
  31. package/dist/{chunk-T6EQPZ6E.js → chunk-4YZCIK5E.js} +16 -14
  32. package/dist/chunk-4YZCIK5E.js.map +1 -0
  33. package/dist/{chunk-S6AH7WSF.js → chunk-5PGYCWA7.js} +5 -5
  34. package/dist/{chunk-7NSC4IVA.js → chunk-6RK2X7BR.js} +3 -3
  35. package/dist/{chunk-VWP5DEHU.js → chunk-6SX4MY5Q.js} +2 -2
  36. package/dist/{chunk-GUNIXT36.js → chunk-7BY7V4YX.js} +2 -2
  37. package/dist/{chunk-R7UHWPYI.js → chunk-7PJARJS4.js} +3 -3
  38. package/dist/{chunk-V3IT3XNG.js → chunk-7VSHDLJQ.js} +6 -6
  39. package/dist/{chunk-SFCJCMZQ.js → chunk-A7266TRJ.js} +2 -2
  40. package/dist/{chunk-4THNU7OF.js → chunk-AW4A4XOP.js} +22 -22
  41. package/dist/{chunk-IFFW25NG.js → chunk-C5B3CIMJ.js} +34 -34
  42. package/dist/{chunk-TF3LMM5E.js → chunk-CSV34HIW.js} +3 -3
  43. package/dist/{chunk-FK7T55BA.js → chunk-CZUHNJHX.js} +19 -19
  44. package/dist/{chunk-NFQB6RJT.js → chunk-D4OCJSLV.js} +3 -3
  45. package/dist/{chunk-JKL53MOY.js → chunk-DLQQU4EG.js} +3 -3
  46. package/dist/{chunk-CME347TM.js → chunk-DNC4A7RS.js} +2 -2
  47. package/dist/{chunk-F2JRDPON.js → chunk-EGBDFJ36.js} +2 -2
  48. package/dist/{chunk-TFXYQNBH.js → chunk-FI3PIOOI.js} +9 -9
  49. package/dist/{chunk-CKSEJD7K.js → chunk-FKTD7IVS.js} +2 -2
  50. package/dist/{chunk-FONW766A.js → chunk-GXIY65UH.js} +2 -2
  51. package/dist/{chunk-2YREVL4T.js → chunk-HZC3OECF.js} +2 -2
  52. package/dist/{chunk-X5OIPQME.js → chunk-HZNYJN77.js} +6 -6
  53. package/dist/{chunk-LYPG7GOO.js → chunk-I2GIYTRU.js} +2 -2
  54. package/dist/{chunk-FR3FNPCJ.js → chunk-IT57AOMC.js} +4 -4
  55. package/dist/{chunk-CMRUIKVA.js → chunk-KCT36JAW.js} +25 -9
  56. package/dist/chunk-KCT36JAW.js.map +1 -0
  57. package/dist/{chunk-KJH6W2I7.js → chunk-L3CHRBHE.js} +4 -4
  58. package/dist/{chunk-PSH3VFZ7.js → chunk-L3LRWDJW.js} +7 -7
  59. package/dist/{chunk-JFPZEWY3.js → chunk-LIF6DO6U.js} +37 -13
  60. package/dist/chunk-LIF6DO6U.js.map +1 -0
  61. package/dist/{chunk-QZR3WT3L.js → chunk-LJJWFV2Q.js} +2 -2
  62. package/dist/{chunk-TLVLJSWS.js → chunk-LRDP2AC2.js} +2 -2
  63. package/dist/{chunk-QV7OEHFN.js → chunk-LTBKKSCX.js} +2 -2
  64. package/dist/{chunk-IGWVMA4Y.js → chunk-MRV7VSQK.js} +20 -10
  65. package/dist/chunk-MRV7VSQK.js.map +1 -0
  66. package/dist/{chunk-6P2NUVM5.js → chunk-NEJQ65NV.js} +2 -2
  67. package/dist/{chunk-7PKNOXYB.js → chunk-NTJ6TY44.js} +2 -2
  68. package/dist/{chunk-HYVBJLEK.js → chunk-O5AFC5KM.js} +2 -2
  69. package/dist/{chunk-U3PN77QT.js → chunk-PCXDUHQH.js} +11 -4
  70. package/dist/chunk-PCXDUHQH.js.map +1 -0
  71. package/dist/{chunk-N655QIA2.js → chunk-PEDYKCJI.js} +3 -3
  72. package/dist/{chunk-TVKWT2CY.js → chunk-Q57GOHLF.js} +11 -9
  73. package/dist/{chunk-TVKWT2CY.js.map → chunk-Q57GOHLF.js.map} +1 -1
  74. package/dist/{chunk-4QFCAKNM.js → chunk-RUZM6Z52.js} +1 -1
  75. package/dist/{chunk-O4TTIMOP.js → chunk-SFR7J2G6.js} +2 -2
  76. package/dist/{chunk-ION47U3Z.js → chunk-SNW3YRO6.js} +2 -2
  77. package/dist/{chunk-XL24QQ63.js → chunk-TBUEE7XF.js} +2 -2
  78. package/dist/{chunk-TAPFJ3ET.js → chunk-U7XLOSG2.js} +3 -3
  79. package/dist/{chunk-T3HC7RJ7.js → chunk-USAUBGBC.js} +2 -2
  80. package/dist/{chunk-TAMY4NKO.js → chunk-USGKHF36.js} +2 -2
  81. package/dist/{chunk-XRPPHIRI.js → chunk-VUDALPI5.js} +2 -2
  82. package/dist/{chunk-EGGE52UU.js → chunk-VUFL7X3H.js} +13 -6
  83. package/dist/chunk-VUFL7X3H.js.map +1 -0
  84. package/dist/{chunk-HC55YCNK.js → chunk-VYIXCMUP.js} +4 -4
  85. package/dist/{chunk-HQ2VGCGP.js → chunk-XBGLEOID.js} +8 -8
  86. package/dist/{chunk-XX4HPFFM.js → chunk-XDL5CYZN.js} +4 -4
  87. package/dist/{chunk-THACANBI.js → chunk-YOKSRIFI.js} +3 -3
  88. package/dist/{chunk-BWJMBJCY.js → chunk-YTZA7U6Q.js} +6 -6
  89. package/dist/{chunk-4KM3V6VS.js → chunk-ZN7SMKAK.js} +2 -2
  90. package/dist/cli.js +45 -45
  91. package/dist/compounding/engine.js +5 -5
  92. package/dist/connectors/codex-materialize-runner.js +6 -6
  93. package/dist/connectors/index.js +6 -6
  94. package/dist/contradiction/index.js +3 -3
  95. package/dist/{contradiction-scan-522AYLQC.js → contradiction-scan-VOTQRRSX.js} +4 -4
  96. package/dist/convergence-refresh.js +7 -7
  97. package/dist/corpus-watermark.js +8 -8
  98. package/dist/entity-retrieval.js +5 -5
  99. package/dist/explicit-capture.js +4 -4
  100. package/dist/external-wiki-access.js +24 -24
  101. package/dist/extraction.js +11 -11
  102. package/dist/{first-start-migration-HZ4VPRFQ.js → first-start-migration-4NETATFF.js} +4 -4
  103. package/dist/{graph-edge-decay-ZXGBXNPW.js → graph-edge-decay-A4SDFMMS.js} +4 -3
  104. package/dist/harmonic-retrieval.js +1 -1
  105. package/dist/index.js +57 -57
  106. package/dist/maintenance/memory-governance.js +5 -5
  107. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +5 -5
  108. package/dist/maintenance/rebuild-memory-projection.js +6 -6
  109. package/dist/namespaces/migrate.js +7 -7
  110. package/dist/namespaces/principal.js +3 -2
  111. package/dist/namespaces/search.js +2 -2
  112. package/dist/namespaces/storage.js +6 -6
  113. package/dist/offline-sync-impression-drain.js +6 -6
  114. package/dist/operator-doctor-corpus.js +9 -9
  115. package/dist/operator-toolkit.js +16 -16
  116. package/dist/orchestration/maintenance.js +14 -14
  117. package/dist/orchestrator.js +57 -57
  118. package/dist/reconcile/manifest.js +3 -3
  119. package/dist/reconcile/plan.js +2 -2
  120. package/dist/routing/engine.js +2 -1
  121. package/dist/routing/store.js +3 -2
  122. package/dist/semantic-consolidation.js +7 -7
  123. package/dist/semantic-rule-promotion.js +5 -5
  124. package/dist/semantic-rule-verifier.js +5 -5
  125. package/dist/source-agent-qualifier.js +10 -10
  126. package/dist/storage.js +4 -4
  127. package/dist/support-passport/index.js +26 -26
  128. package/dist/tier-routing.js +3 -3
  129. package/dist/{tier-stats-7E6OBUSD.js → tier-stats-4B5IJ3NE.js} +4 -4
  130. package/dist/verified-recall.js +5 -5
  131. package/package.json +2 -2
  132. package/src/namespaces/catalog.ts +9 -9
  133. package/src/namespaces/identity.ts +15 -6
  134. package/src/namespaces/principal.test.ts +10 -1
  135. package/src/namespaces/principal.ts +17 -9
  136. package/src/namespaces/scope-profiles.ts +35 -13
  137. package/src/namespaces/storage.ts +63 -13
  138. package/src/namespaces/unicode-routing.test.ts +71 -0
  139. package/src/routing/engine.test.ts +30 -0
  140. package/src/routing/engine.ts +12 -3
  141. package/src/scopes/scope-plan.ts +8 -2
  142. package/src/storage-contract/namespace-routing.test.ts +18 -1
  143. package/dist/chunk-CMRUIKVA.js.map +0 -1
  144. package/dist/chunk-EGGE52UU.js.map +0 -1
  145. package/dist/chunk-IGWVMA4Y.js.map +0 -1
  146. package/dist/chunk-JFPZEWY3.js.map +0 -1
  147. package/dist/chunk-T6EQPZ6E.js.map +0 -1
  148. package/dist/chunk-U3PN77QT.js.map +0 -1
  149. /package/dist/{chunk-O54B5YNM.js.map → chunk-24PNX2GF.js.map} +0 -0
  150. /package/dist/{chunk-ONCWJBWV.js.map → chunk-3AJOJOFP.js.map} +0 -0
  151. /package/dist/{chunk-QSDPVZPD.js.map → chunk-4O6R3GPK.js.map} +0 -0
  152. /package/dist/{chunk-IXGQP4RZ.js.map → chunk-4SGDYYWV.js.map} +0 -0
  153. /package/dist/{chunk-UTDMY476.js.map → chunk-4UUF2EX3.js.map} +0 -0
  154. /package/dist/{chunk-S6AH7WSF.js.map → chunk-5PGYCWA7.js.map} +0 -0
  155. /package/dist/{chunk-7NSC4IVA.js.map → chunk-6RK2X7BR.js.map} +0 -0
  156. /package/dist/{chunk-VWP5DEHU.js.map → chunk-6SX4MY5Q.js.map} +0 -0
  157. /package/dist/{chunk-GUNIXT36.js.map → chunk-7BY7V4YX.js.map} +0 -0
  158. /package/dist/{chunk-R7UHWPYI.js.map → chunk-7PJARJS4.js.map} +0 -0
  159. /package/dist/{chunk-V3IT3XNG.js.map → chunk-7VSHDLJQ.js.map} +0 -0
  160. /package/dist/{chunk-SFCJCMZQ.js.map → chunk-A7266TRJ.js.map} +0 -0
  161. /package/dist/{chunk-4THNU7OF.js.map → chunk-AW4A4XOP.js.map} +0 -0
  162. /package/dist/{chunk-IFFW25NG.js.map → chunk-C5B3CIMJ.js.map} +0 -0
  163. /package/dist/{chunk-TF3LMM5E.js.map → chunk-CSV34HIW.js.map} +0 -0
  164. /package/dist/{chunk-FK7T55BA.js.map → chunk-CZUHNJHX.js.map} +0 -0
  165. /package/dist/{chunk-NFQB6RJT.js.map → chunk-D4OCJSLV.js.map} +0 -0
  166. /package/dist/{chunk-JKL53MOY.js.map → chunk-DLQQU4EG.js.map} +0 -0
  167. /package/dist/{chunk-CME347TM.js.map → chunk-DNC4A7RS.js.map} +0 -0
  168. /package/dist/{chunk-F2JRDPON.js.map → chunk-EGBDFJ36.js.map} +0 -0
  169. /package/dist/{chunk-TFXYQNBH.js.map → chunk-FI3PIOOI.js.map} +0 -0
  170. /package/dist/{chunk-CKSEJD7K.js.map → chunk-FKTD7IVS.js.map} +0 -0
  171. /package/dist/{chunk-FONW766A.js.map → chunk-GXIY65UH.js.map} +0 -0
  172. /package/dist/{chunk-2YREVL4T.js.map → chunk-HZC3OECF.js.map} +0 -0
  173. /package/dist/{chunk-X5OIPQME.js.map → chunk-HZNYJN77.js.map} +0 -0
  174. /package/dist/{chunk-LYPG7GOO.js.map → chunk-I2GIYTRU.js.map} +0 -0
  175. /package/dist/{chunk-FR3FNPCJ.js.map → chunk-IT57AOMC.js.map} +0 -0
  176. /package/dist/{chunk-KJH6W2I7.js.map → chunk-L3CHRBHE.js.map} +0 -0
  177. /package/dist/{chunk-PSH3VFZ7.js.map → chunk-L3LRWDJW.js.map} +0 -0
  178. /package/dist/{chunk-QZR3WT3L.js.map → chunk-LJJWFV2Q.js.map} +0 -0
  179. /package/dist/{chunk-TLVLJSWS.js.map → chunk-LRDP2AC2.js.map} +0 -0
  180. /package/dist/{chunk-QV7OEHFN.js.map → chunk-LTBKKSCX.js.map} +0 -0
  181. /package/dist/{chunk-6P2NUVM5.js.map → chunk-NEJQ65NV.js.map} +0 -0
  182. /package/dist/{chunk-7PKNOXYB.js.map → chunk-NTJ6TY44.js.map} +0 -0
  183. /package/dist/{chunk-HYVBJLEK.js.map → chunk-O5AFC5KM.js.map} +0 -0
  184. /package/dist/{chunk-N655QIA2.js.map → chunk-PEDYKCJI.js.map} +0 -0
  185. /package/dist/{chunk-4QFCAKNM.js.map → chunk-RUZM6Z52.js.map} +0 -0
  186. /package/dist/{chunk-O4TTIMOP.js.map → chunk-SFR7J2G6.js.map} +0 -0
  187. /package/dist/{chunk-ION47U3Z.js.map → chunk-SNW3YRO6.js.map} +0 -0
  188. /package/dist/{chunk-XL24QQ63.js.map → chunk-TBUEE7XF.js.map} +0 -0
  189. /package/dist/{chunk-TAPFJ3ET.js.map → chunk-U7XLOSG2.js.map} +0 -0
  190. /package/dist/{chunk-T3HC7RJ7.js.map → chunk-USAUBGBC.js.map} +0 -0
  191. /package/dist/{chunk-TAMY4NKO.js.map → chunk-USGKHF36.js.map} +0 -0
  192. /package/dist/{chunk-XRPPHIRI.js.map → chunk-VUDALPI5.js.map} +0 -0
  193. /package/dist/{chunk-HC55YCNK.js.map → chunk-VYIXCMUP.js.map} +0 -0
  194. /package/dist/{chunk-HQ2VGCGP.js.map → chunk-XBGLEOID.js.map} +0 -0
  195. /package/dist/{chunk-XX4HPFFM.js.map → chunk-XDL5CYZN.js.map} +0 -0
  196. /package/dist/{chunk-THACANBI.js.map → chunk-YOKSRIFI.js.map} +0 -0
  197. /package/dist/{chunk-BWJMBJCY.js.map → chunk-YTZA7U6Q.js.map} +0 -0
  198. /package/dist/{chunk-4KM3V6VS.js.map → chunk-ZN7SMKAK.js.map} +0 -0
  199. /package/dist/{contradiction-scan-522AYLQC.js.map → contradiction-scan-VOTQRRSX.js.map} +0 -0
  200. /package/dist/{first-start-migration-HZ4VPRFQ.js.map → first-start-migration-4NETATFF.js.map} +0 -0
  201. /package/dist/{graph-edge-decay-ZXGBXNPW.js.map → graph-edge-decay-A4SDFMMS.js.map} +0 -0
  202. /package/dist/{tier-stats-7E6OBUSD.js.map → tier-stats-4B5IJ3NE.js.map} +0 -0
@@ -12,7 +12,12 @@ import type {
12
12
  ScopeProfilePromotionTarget,
13
13
  ScopeTeamConfig,
14
14
  } from "../types.js";
15
- import { canReadNamespace, canWriteNamespace, defaultNamespaceForPrincipal } from "./principal.js";
15
+ import {
16
+ canReadNamespace,
17
+ canWriteNamespace,
18
+ defaultNamespaceForPrincipal,
19
+ } from "./principal.js";
20
+ import { normalizeNamespaceIdentity } from "./identity.js";
16
21
 
17
22
  type ScopeProfileCodingOverlay = Pick<CodingNamespaceOverlay, "namespace" | "readFallbacks">;
18
23
 
@@ -65,19 +70,28 @@ function principalListed(list: string[], principal: string | undefined): boolean
65
70
  }
66
71
 
67
72
  function derivedScopeProfileSelfNamespace(principal: string | undefined, config: PluginConfig): string | null {
68
- if (!principal || principal === config.defaultNamespace || principal === config.sharedNamespace) return null;
73
+ if (
74
+ !principal ||
75
+ normalizeNamespaceIdentity(principal) === normalizeNamespaceIdentity(config.defaultNamespace) ||
76
+ normalizeNamespaceIdentity(principal) === normalizeNamespaceIdentity(config.sharedNamespace)
77
+ ) {
78
+ return null;
79
+ }
69
80
  if (isSafeRouteNamespace(principal)) return principal;
70
81
  return "principal-" + createHash("sha256").update(principal).digest("hex").slice(0, 54);
71
82
  }
72
83
 
73
84
  function scopeProfileSelfNamespace(principal: string | undefined, config: PluginConfig): string {
74
85
  const existing = defaultNamespaceForPrincipal(principal, config);
75
- if (existing !== config.defaultNamespace) return existing;
86
+ if (normalizeNamespaceIdentity(existing) !== normalizeNamespaceIdentity(config.defaultNamespace)) return existing;
76
87
  return derivedScopeProfileSelfNamespace(principal, config) ?? existing;
77
88
  }
78
89
 
79
90
  function hasExplicitNamespacePolicy(namespace: string, config: PluginConfig): boolean {
80
- return (config.namespacePolicies ?? []).some((policy) => policy.name === namespace);
91
+ const identity = normalizeNamespaceIdentity(namespace);
92
+ return (config.namespacePolicies ?? []).some(
93
+ (policy) => normalizeNamespaceIdentity(policy.name) === identity,
94
+ );
81
95
  }
82
96
 
83
97
  function isScopeProfileImplicitSelfNamespace(
@@ -88,9 +102,9 @@ function isScopeProfileImplicitSelfNamespace(
88
102
  const derived = derivedScopeProfileSelfNamespace(principal, config);
89
103
  return Boolean(
90
104
  derived &&
91
- namespace === derived &&
92
- namespace !== config.defaultNamespace &&
93
- namespace !== config.sharedNamespace &&
105
+ normalizeNamespaceIdentity(namespace) === normalizeNamespaceIdentity(derived) &&
106
+ normalizeNamespaceIdentity(namespace) !== normalizeNamespaceIdentity(config.defaultNamespace) &&
107
+ normalizeNamespaceIdentity(namespace) !== normalizeNamespaceIdentity(config.sharedNamespace) &&
94
108
  isSafeRouteNamespace(namespace) &&
95
109
  !hasExplicitNamespacePolicy(namespace, config),
96
110
  );
@@ -297,16 +311,24 @@ function resolveLayer(params: {
297
311
  const userProjectBase = namespace.endsWith(userProjectSuffix)
298
312
  ? namespace.slice(0, -userProjectSuffix.length)
299
313
  : "";
314
+ const userProjectBaseIdentity = normalizeNamespaceIdentity(userProjectBase);
315
+ const defaultIdentity = normalizeNamespaceIdentity(config.defaultNamespace);
316
+ const sharedIdentity = normalizeNamespaceIdentity(config.sharedNamespace);
317
+ const namespaceIdentity = normalizeNamespaceIdentity(namespace);
300
318
  const dynamicUserProjectCollision =
301
319
  userProjectBase.length > 0 &&
302
- (userProjectBase === config.defaultNamespace ||
303
- userProjectBase === config.sharedNamespace ||
304
- (config.namespacePolicies ?? []).some((policy) => policy.name === userProjectBase));
320
+ (userProjectBaseIdentity === defaultIdentity ||
321
+ userProjectBaseIdentity === sharedIdentity ||
322
+ (config.namespacePolicies ?? []).some(
323
+ (policy) => normalizeNamespaceIdentity(policy.name) === userProjectBaseIdentity,
324
+ ));
305
325
  const protectedNamespace =
306
- namespace === config.defaultNamespace ||
307
- namespace === config.sharedNamespace ||
326
+ namespaceIdentity === defaultIdentity ||
327
+ namespaceIdentity === sharedIdentity ||
308
328
  dynamicUserProjectCollision ||
309
- (config.namespacePolicies ?? []).some((policy) => policy.name === namespace);
329
+ (config.namespacePolicies ?? []).some(
330
+ (policy) => normalizeNamespaceIdentity(policy.name) === namespaceIdentity,
331
+ );
310
332
  const policyReadable = !protectedNamespace || canReadNamespace(principal, namespace, config);
311
333
  const policyWritable = !protectedNamespace || canWriteNamespace(principal, namespace, config);
312
334
  const policyBlocked = protectedNamespace && (!policyReadable || !policyWritable);
@@ -6,7 +6,11 @@ import { StorageManager } from "../storage.js";
6
6
  import { keyring, secureStoreDir } from "../secure-store/index.js";
7
7
  import type { PluginConfig } from "../types.js";
8
8
  import { ALL_CATEGORY_DIRS } from "../utils/category-dir.js";
9
- import { namespaceIdentityToken, normalizeNamespaceIdentity } from "./identity.js";
9
+ import {
10
+ namespaceIdentityLegacyToken,
11
+ namespaceIdentityToken,
12
+ normalizeNamespaceIdentity,
13
+ } from "./identity.js";
10
14
  import type { NamespaceCatalog } from "./catalog.js";
11
15
  import { MutationSerializer } from "../utils/serialize-mutations.js";
12
16
 
@@ -153,19 +157,43 @@ export async function resolveDefaultNamespaceRoot(config: PluginConfig): Promise
153
157
  // back to memoryDir/tokenized. `namespaceIdentityToken` already normalizes
154
158
  // internally, so the tokenized path is unaffected.
155
159
  const defaultIdentity = normalizeNamespaceIdentity(config.defaultNamespace);
160
+ const defaultNfdIdentity = defaultIdentity.normalize("NFD");
156
161
  const legacyNsDir = resolveNamespaceDir(config.memoryDir, defaultIdentity);
162
+ const legacyNfdNsDir = resolveNamespaceDir(config.memoryDir, defaultNfdIdentity);
157
163
  const tokenizedNsDir = resolveNamespaceDir(
158
164
  config.memoryDir,
159
- namespaceIdentityToken(config.defaultNamespace),
165
+ namespaceIdentityToken(defaultIdentity),
166
+ );
167
+ const legacyTokenNsDir = resolveNamespaceDir(
168
+ config.memoryDir,
169
+ namespaceIdentityLegacyToken(defaultNfdIdentity),
160
170
  );
161
171
  const tokenizedHasData =
162
172
  (await exists(tokenizedNsDir)) &&
163
173
  (await hasAnyNamespaceStorageMarker(tokenizedNsDir, { includeRuntimeState: true }));
174
+ const legacyTokenHasData =
175
+ (await exists(legacyTokenNsDir)) &&
176
+ (await hasAnyNamespaceStorageMarker(legacyTokenNsDir, { includeRuntimeState: true }));
177
+ const legacyHasData =
178
+ (await exists(legacyNsDir)) &&
179
+ (await hasAnyNamespaceStorageMarker(legacyNsDir, { includeRuntimeState: true }));
180
+ const legacyNfdHasData =
181
+ legacyNfdNsDir !== legacyNsDir &&
182
+ (await exists(legacyNfdNsDir)) &&
183
+ (await hasAnyNamespaceStorageMarker(legacyNfdNsDir, { includeRuntimeState: true }));
164
184
  const nsDir = tokenizedHasData
165
185
  ? tokenizedNsDir
166
- : (await exists(legacyNsDir))
167
- ? legacyNsDir
168
- : tokenizedNsDir;
186
+ : legacyTokenHasData
187
+ ? legacyTokenNsDir
188
+ : legacyHasData
189
+ ? legacyNsDir
190
+ : legacyNfdHasData
191
+ ? legacyNfdNsDir
192
+ : (await exists(legacyNsDir))
193
+ ? legacyNsDir
194
+ : legacyNfdNsDir !== legacyNsDir && (await exists(legacyNfdNsDir))
195
+ ? legacyNfdNsDir
196
+ : tokenizedNsDir;
169
197
  return (await exists(nsDir)) && !(await hasAnyLegacyData(config.memoryDir))
170
198
  ? nsDir
171
199
  : config.memoryDir;
@@ -192,15 +220,37 @@ export async function resolveNamespaceStorageRoot(
192
220
  if (normalizeNamespaceIdentity(namespace) === normalizeNamespaceIdentity(config.defaultNamespace)) {
193
221
  return resolveDefaultNamespaceRoot(config);
194
222
  }
195
- const legacyRoot = resolveNamespaceDir(config.memoryDir, namespace);
196
- const tokenizedRoot = resolveNamespaceDir(config.memoryDir, namespaceIdentityToken(namespace));
197
- if (
198
- (await exists(tokenizedRoot)) &&
199
- (await hasAnyNamespaceStorageMarker(tokenizedRoot, { includeRuntimeState: true }))
200
- ) {
201
- return tokenizedRoot;
223
+ const normalized = normalizeNamespaceIdentity(namespace);
224
+ const legacyExactNamespace = namespace.trim();
225
+ const legacyNfdNamespace = normalized.normalize("NFD");
226
+ const legacyRoot = resolveNamespaceDir(config.memoryDir, normalized);
227
+ const legacyExactRoot =
228
+ legacyExactNamespace !== normalized && isSafeRouteNamespace(legacyExactNamespace)
229
+ ? resolveNamespaceDir(config.memoryDir, legacyExactNamespace)
230
+ : null;
231
+ const legacyNfdRoot =
232
+ legacyNfdNamespace !== normalized
233
+ ? resolveNamespaceDir(config.memoryDir, legacyNfdNamespace)
234
+ : null;
235
+ const tokenizedRoot = resolveNamespaceDir(config.memoryDir, namespaceIdentityToken(normalized));
236
+ const legacyTokenRoots = [
237
+ namespaceIdentityLegacyToken(legacyExactNamespace),
238
+ namespaceIdentityLegacyToken(legacyNfdNamespace),
239
+ ]
240
+ .filter((token, index, tokens) => tokens.indexOf(token) === index)
241
+ .map((token) => resolveNamespaceDir(config.memoryDir, token));
242
+ for (const candidate of [tokenizedRoot, ...legacyTokenRoots]) {
243
+ if (
244
+ (await exists(candidate)) &&
245
+ (await hasAnyNamespaceStorageMarker(candidate, { includeRuntimeState: true }))
246
+ ) {
247
+ return candidate;
248
+ }
249
+ }
250
+ for (const candidate of [legacyRoot, legacyExactRoot, legacyNfdRoot]) {
251
+ if (candidate && (await exists(candidate))) return candidate;
202
252
  }
203
- return (await exists(legacyRoot)) ? legacyRoot : tokenizedRoot;
253
+ return tokenizedRoot;
204
254
  }
205
255
 
206
256
  export class NamespaceStorageRouter {
@@ -0,0 +1,71 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdir, mkdtemp, rm } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+
7
+ import type { PluginConfig } from "../types.js";
8
+ import { NamespaceCatalog } from "./catalog.js";
9
+ import { namespaceIdentityFromToken, namespaceIdentityLegacyToken, namespaceIdentityToken } from "./identity.js";
10
+ import { resolveDefaultNamespaceRoot, resolveNamespaceStorageRoot } from "./storage.js";
11
+
12
+ function makeConfig(memoryDir: string): PluginConfig {
13
+ return {
14
+ memoryDir,
15
+ namespacesEnabled: true,
16
+ namespaceCatalogEnabled: true,
17
+ defaultNamespace: "default",
18
+ sharedNamespace: "shared",
19
+ namespacePolicies: [],
20
+ entitySchemas: {},
21
+ } as unknown as PluginConfig;
22
+ }
23
+
24
+ test("Unicode namespaces decode from disk and list in stable order", async () => {
25
+ const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-unicode-routing-"));
26
+ try {
27
+ const config = makeConfig(memoryDir);
28
+ const catalog = new NamespaceCatalog(config);
29
+ const cjk = "项目";
30
+ const ascii = "alpha";
31
+
32
+ assert.equal(namespaceIdentityFromToken(namespaceIdentityToken(cjk)), cjk);
33
+ assert.equal(namespaceIdentityToken("Cafe\u0301"), namespaceIdentityToken("Café"));
34
+ const nfd = "Café".normalize("NFD");
35
+ const legacyToken = namespaceIdentityLegacyToken(nfd);
36
+ assert.equal(namespaceIdentityFromToken(legacyToken), "Café");
37
+ await mkdir(path.join(memoryDir, "namespaces", legacyToken, "facts"), { recursive: true });
38
+ assert.equal(
39
+ await resolveNamespaceStorageRoot(config, "Café"),
40
+ path.join(memoryDir, "namespaces", legacyToken),
41
+ );
42
+ const rebuilt = await catalog.rebuildFromDisk({ dryRun: true });
43
+ const legacyRecord = rebuilt.records.find((record) => record.namespace === "Café");
44
+ assert.equal(legacyRecord?.storageDir, path.join(memoryDir, "namespaces", legacyToken));
45
+ await catalog.markWrite(cjk, { discoveredBy: "write" });
46
+ await catalog.markWrite(ascii, { discoveredBy: "write" });
47
+
48
+ const first = await catalog.listNamespaces();
49
+ const second = await catalog.listNamespaces();
50
+ assert.deepEqual(
51
+ first.map((record) => record.namespace),
52
+ second.map((record) => record.namespace)
53
+ );
54
+ assert.ok(first.some((record) => record.namespace === cjk));
55
+ } finally {
56
+ await rm(memoryDir, { recursive: true, force: true });
57
+ }
58
+ });
59
+
60
+ test("default Unicode namespace resolves legacy NFD roots", async () => {
61
+ const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-unicode-default-"));
62
+ try {
63
+ const config = { ...makeConfig(memoryDir), defaultNamespace: "Café" };
64
+ const nfd = config.defaultNamespace.normalize("NFD");
65
+ const nfdRoot = path.join(memoryDir, "namespaces", nfd);
66
+ await mkdir(path.join(nfdRoot, "facts"), { recursive: true });
67
+ assert.equal(await resolveDefaultNamespaceRoot(config), nfdRoot);
68
+ } finally {
69
+ await rm(memoryDir, { recursive: true, force: true });
70
+ }
71
+ });
@@ -0,0 +1,30 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ import { isSafeRouteNamespace, validateRouteTarget } from "./engine.js";
5
+
6
+ test("isSafeRouteNamespace accepts Unicode letters and NFC-normalizes before validation", () => {
7
+ assert.equal(isSafeRouteNamespace("项目"), true);
8
+ assert.equal(isSafeRouteNamespace("Cafe\u0301"), true);
9
+ assert.equal(isSafeRouteNamespace("a1._-"), true);
10
+ assert.equal(isSafeRouteNamespace("a".repeat(64)), true);
11
+ assert.equal(isSafeRouteNamespace("a".repeat(65)), false);
12
+ assert.equal(isSafeRouteNamespace("界".repeat(42)), true);
13
+ assert.equal(isSafeRouteNamespace("界".repeat(43)), false);
14
+
15
+ const target = validateRouteTarget({ namespace: "Cafe\u0301" }, { allowedNamespaces: ["Café"] });
16
+ assert.deepEqual(target, {
17
+ ok: true,
18
+ target: { namespace: "Café" },
19
+ });
20
+ assert.equal(
21
+ validateRouteTarget({ namespace: "Café" }, { allowedNamespaces: [" Café "] }).ok,
22
+ true,
23
+ );
24
+ });
25
+
26
+ test("isSafeRouteNamespace rejects traversal, controls, bidi overrides, and edge whitespace", () => {
27
+ for (const unsafe of ["../escape", "a/b", "a\\b", "a\u0000b", "a\u202Eb", " name", "name ", ".."]) {
28
+ assert.equal(isSafeRouteNamespace(unsafe), false, JSON.stringify(unsafe));
29
+ }
30
+ });
@@ -1,3 +1,4 @@
1
+ import { namespaceIdentityToken } from "../namespaces/identity.js";
1
2
  import type { MemoryCategory } from "../types.js";
2
3
 
3
4
  export type RoutePatternType = "regex" | "keyword";
@@ -43,9 +44,11 @@ const DEFAULT_CATEGORIES: readonly MemoryCategory[] = [
43
44
  ] as const;
44
45
 
45
46
  function normalizeNamespace(namespace: string): string {
46
- return namespace.trim();
47
+ return namespace.normalize("NFC");
47
48
  }
48
49
 
50
+ const SAFE_ROUTE_NAMESPACE_CHARS = /^[\p{L}\p{M}\p{N}._-]+$/u;
51
+
49
52
  export function isLikelyUnsafeRegex(pattern: string): boolean {
50
53
  const value = pattern.trim();
51
54
  if (value.length === 0) return true;
@@ -65,11 +68,17 @@ export function isLikelyUnsafeRegex(pattern: string): boolean {
65
68
 
66
69
  export function isSafeRouteNamespace(namespace: string): boolean {
67
70
  const value = normalizeNamespace(namespace);
71
+ // The route limit is 64 Unicode code points. On-disk identity tokens may
72
+ // exceed 64 characters because namespaceIdentityToken hex-encodes UTF-8.
73
+ // A route can use at most 64 code points, but the reversible on-disk token
74
+ // must also fit one filesystem component (255 characters).
68
75
  if (value.length === 0) return false;
76
+ if (Array.from(value).length > 64) return false;
77
+ if (namespaceIdentityToken(value).length > 255) return false;
69
78
  if (value === ".") return false;
70
79
  if (value.includes("/") || value.includes("\\")) return false;
71
80
  if (value.includes("..")) return false;
72
- return /^[A-Za-z0-9._-]{1,64}$/.test(value);
81
+ return SAFE_ROUTE_NAMESPACE_CHARS.test(value);
73
82
  }
74
83
 
75
84
  export function validateRouteTarget(target: RouteTarget | null | undefined, options?: RoutingEngineOptions): {
@@ -83,7 +92,7 @@ export function validateRouteTarget(target: RouteTarget | null | undefined, opti
83
92
 
84
93
  const allowedCategories = new Set(options?.allowedCategories ?? DEFAULT_CATEGORIES);
85
94
  const allowedNamespaces = options?.allowedNamespaces
86
- ? new Set(options.allowedNamespaces.map((v) => v.trim()).filter((v) => v.length > 0))
95
+ ? new Set(options.allowedNamespaces.map((v) => normalizeNamespace(v.trim())).filter((v) => v.length > 0))
87
96
  : null;
88
97
 
89
98
  const normalized: RouteTarget = {};
@@ -41,7 +41,9 @@ import {
41
41
  } from "../namespaces/principal.js";
42
42
  import {
43
43
  namespaceIdentityFromToken,
44
+ namespaceIdentityLegacyToken,
44
45
  namespaceIdentityToken,
46
+ normalizeNamespaceIdentity,
45
47
  } from "../namespaces/identity.js";
46
48
  import path from "node:path";
47
49
  import {
@@ -359,7 +361,7 @@ export function getConfiguredNamespaces(config: PluginConfig): string[] {
359
361
  config.sharedNamespace,
360
362
  ...config.namespacePolicies.map((policy) => policy.name),
361
363
  ]
362
- .map((value) => value.trim())
364
+ .map((value) => normalizeNamespaceIdentity(value))
363
365
  .filter(Boolean),
364
366
  ),
365
367
  );
@@ -430,7 +432,11 @@ export function resolveNamespaceFromStorageDir(
430
432
  if (hintedNamespace) return hintedNamespace;
431
433
  }
432
434
  const decoded = namespaceIdentityFromToken(dirName);
433
- if (decoded && namespaceIdentityToken(decoded) === dirName) {
435
+ if (
436
+ decoded &&
437
+ (namespaceIdentityToken(decoded) === dirName ||
438
+ namespaceIdentityLegacyToken(decoded.normalize("NFD")) === dirName)
439
+ ) {
434
440
  return decoded;
435
441
  }
436
442
  return dirName;
@@ -19,7 +19,7 @@ import path from "node:path";
19
19
  import test from "node:test";
20
20
 
21
21
  import { makeStorage, makeNamespaceRouter, resetStaticCaches } from "./harness.js";
22
- import { resolveNamespaceStorageRoot } from "../namespaces/storage.js";
22
+ import { NamespaceStorageRouter, resolveNamespaceStorageRoot } from "../namespaces/storage.js";
23
23
  import { namespaceIdentityToken } from "../namespaces/identity.js";
24
24
  import { getCachedMemories } from "../memory-cache.js";
25
25
 
@@ -158,3 +158,20 @@ test("namespace-routing: hotMemoriesCacheEnabled=false propagates to namespace c
158
158
  await cleanup();
159
159
  }
160
160
  });
161
+
162
+ test("namespace-routing: CJK namespace round-trips through storage", async () => {
163
+ const { router, memoryDir, config, cleanup } = await makeNamespaceRouter();
164
+ try {
165
+ const namespace = "项目";
166
+ const token = namespaceIdentityToken(namespace);
167
+ const writer = await router.storageFor(namespace);
168
+ const written = await writer.writeMemory("fact", "CJK namespace fact");
169
+ assert.equal(writer.dir, path.join(memoryDir, "namespaces", token));
170
+
171
+ const reader = await new NamespaceStorageRouter(config).storageFor(namespace);
172
+ assert.equal(reader.dir, writer.dir);
173
+ assert.equal((await reader.getMemoryById(written.id))?.content, "CJK namespace fact");
174
+ } finally {
175
+ await cleanup();
176
+ }
177
+ });
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/namespaces/scope-profiles.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport { createHash } from \"node:crypto\";\n\nimport { combineNamespaces, type CodingNamespaceOverlay } from \"../coding/coding-namespace.js\";\nimport { stableHash } from \"../coding/git-context.js\";\nimport { isSafeRouteNamespace } from \"../routing/engine.js\";\nimport type {\n CodingContext,\n PluginConfig,\n ScopeProfileConfig,\n ScopeProfileLayerId,\n ScopeProfilePromotionTarget,\n ScopeTeamConfig,\n} from \"../types.js\";\nimport { canReadNamespace, canWriteNamespace, defaultNamespaceForPrincipal } from \"./principal.js\";\n\ntype ScopeProfileCodingOverlay = Pick<CodingNamespaceOverlay, \"namespace\" | \"readFallbacks\">;\n\nexport interface ScopeProfileLayerResolution {\n id: ScopeProfileLayerId;\n kind: \"user-project\" | \"team-project\" | \"user-global\" | \"server-shared\";\n namespace?: string;\n readable: boolean;\n writable: boolean;\n promotable: boolean;\n reason: string;\n}\n\nexport interface ScopeProfilePromotionResolution {\n target: ScopeProfilePromotionTarget;\n namespace?: string;\n authorized: boolean;\n reason: string;\n}\n\nexport interface ResolvedScopeProfilePlan {\n profileId: string;\n profile: ScopeProfileConfig;\n baseNamespace: string;\n writeLayer: ScopeProfileLayerId;\n writeNamespace: string;\n readNamespaces: string[];\n layers: ScopeProfileLayerResolution[];\n promotionTargets: ScopeProfilePromotionResolution[];\n warnings: string[];\n}\n\nexport interface ResolveScopeProfilePlanOptions {\n config: PluginConfig;\n principal?: string;\n codingContext?: CodingContext | null;\n codingOverlay?: ScopeProfileCodingOverlay | null;\n}\n\nfunction activeScopeProfile(config: PluginConfig): { profileId: string; profile: ScopeProfileConfig } | null {\n const profileId = config.defaultScopeProfile;\n if (!profileId) return null;\n const profile = (config.scopeProfiles ?? {})[profileId];\n return profile ? { profileId, profile } : null;\n}\n\nfunction principalListed(list: string[], principal: string | undefined): boolean {\n if (!principal) return false;\n return list.includes(principal) || list.includes(\"*\");\n}\n\nfunction derivedScopeProfileSelfNamespace(principal: string | undefined, config: PluginConfig): string | null {\n if (!principal || principal === config.defaultNamespace || principal === config.sharedNamespace) return null;\n if (isSafeRouteNamespace(principal)) return principal;\n return \"principal-\" + createHash(\"sha256\").update(principal).digest(\"hex\").slice(0, 54);\n}\n\nfunction scopeProfileSelfNamespace(principal: string | undefined, config: PluginConfig): string {\n const existing = defaultNamespaceForPrincipal(principal, config);\n if (existing !== config.defaultNamespace) return existing;\n return derivedScopeProfileSelfNamespace(principal, config) ?? existing;\n}\n\nfunction hasExplicitNamespacePolicy(namespace: string, config: PluginConfig): boolean {\n return (config.namespacePolicies ?? []).some((policy) => policy.name === namespace);\n}\n\nfunction isScopeProfileImplicitSelfNamespace(\n principal: string | undefined,\n namespace: string,\n config: PluginConfig,\n): boolean {\n const derived = derivedScopeProfileSelfNamespace(principal, config);\n return Boolean(\n derived &&\n namespace === derived &&\n namespace !== config.defaultNamespace &&\n namespace !== config.sharedNamespace &&\n isSafeRouteNamespace(namespace) &&\n !hasExplicitNamespacePolicy(namespace, config),\n );\n}\n\nfunction canReadScopeProfileNamespace(\n principal: string | undefined,\n namespace: string,\n config: PluginConfig,\n): boolean {\n return isScopeProfileImplicitSelfNamespace(principal, namespace, config) || canReadNamespace(principal, namespace, config);\n}\n\nfunction canWriteScopeProfileNamespace(\n principal: string | undefined,\n namespace: string,\n config: PluginConfig,\n): boolean {\n return isScopeProfileImplicitSelfNamespace(principal, namespace, config) || canWriteNamespace(principal, namespace, config);\n}\n\nfunction resolveTeam(\n config: PluginConfig,\n profile: ScopeProfileConfig,\n principal: string | undefined,\n): { teamId: string; team: ScopeTeamConfig } | null {\n const configuredTeamId = profile.teamProject?.teamId;\n if (configuredTeamId) {\n const configured = (config.teams ?? {})[configuredTeamId];\n return configured ? { teamId: configuredTeamId, team: configured } : null;\n }\n const readableTeams = Object.entries(config.teams ?? {}).filter(([, team]) =>\n principalListed(team.principals, principal) || principalListed(team.read, principal),\n );\n const needsWritableTeam = profile.writeDefault === \"teamProject\" || profile.readOrder.includes(\"teamProject\");\n if (needsWritableTeam) {\n const writableTeam = readableTeams.find(([, team]) => principalListed(team.write, principal));\n if (writableTeam) return { teamId: writableTeam[0], team: writableTeam[1] };\n }\n const needsPromotableTeam =\n profile.promotionTargets.includes(\"teamProject\") || profile.autoPromote.targets.includes(\"teamProject\");\n if (needsPromotableTeam) {\n const promotableTeam = readableTeams.find(\n ([, team]) => principalListed(team.promote, principal) || principalListed(team.write, principal),\n );\n if (promotableTeam) return { teamId: promotableTeam[0], team: promotableTeam[1] };\n }\n const firstReadableTeam = readableTeams[0];\n return firstReadableTeam\n ? { teamId: firstReadableTeam[0], team: firstReadableTeam[1] }\n : null;\n}\n\nfunction renderTeamProjectNamespace(params: {\n template: string;\n teamId: string;\n principal: string | undefined;\n codingContext: CodingContext;\n codingOverlay: ScopeProfileCodingOverlay;\n}): { namespace: string; unknownPlaceholders: string[] } {\n const replacements: Record<string, string> = {\n teamId: params.teamId,\n principal: params.principal ?? \"anonymous\",\n projectId: params.codingContext.projectId,\n projectHash: stableHash(params.codingContext.projectId),\n projectNamespace: params.codingOverlay.namespace,\n };\n const unknownPlaceholders: string[] = [];\n const namespace = params.template.replace(/\\{([A-Za-z][A-Za-z0-9]*)\\}/g, (match, key: string) => {\n const replacement = replacements[key];\n if (replacement !== undefined) return replacement;\n if (!unknownPlaceholders.includes(key)) unknownPlaceholders.push(key);\n return match;\n });\n return { namespace, unknownPlaceholders };\n}\n\nfunction resolveLayer(params: {\n id: ScopeProfileLayerId;\n config: PluginConfig;\n profile: ScopeProfileConfig;\n principal: string | undefined;\n baseNamespace: string;\n codingContext: CodingContext | null | undefined;\n codingOverlay: ScopeProfileCodingOverlay | null | undefined;\n}): ScopeProfileLayerResolution {\n const { id, config, profile, principal, baseNamespace, codingContext, codingOverlay } = params;\n if (id === \"userGlobal\") {\n return {\n id,\n kind: \"user-global\",\n namespace: baseNamespace,\n readable: canReadScopeProfileNamespace(principal, baseNamespace, config),\n writable: canWriteScopeProfileNamespace(principal, baseNamespace, config),\n promotable: canWriteScopeProfileNamespace(principal, baseNamespace, config),\n reason: \"principal self/global namespace\",\n };\n }\n if (id === \"serverShared\") {\n return {\n id,\n kind: \"server-shared\",\n namespace: config.sharedNamespace,\n readable: canReadNamespace(principal, config.sharedNamespace, config),\n writable: canWriteNamespace(principal, config.sharedNamespace, config),\n promotable: canWriteNamespace(principal, config.sharedNamespace, config),\n reason: \"configured shared namespace\",\n };\n }\n if (id === \"userProject\") {\n if (!codingContext || !codingOverlay) {\n return {\n id,\n kind: \"user-project\",\n readable: false,\n writable: false,\n promotable: false,\n reason: \"missing project context\",\n };\n }\n const namespace = combineNamespaces(baseNamespace, codingOverlay.namespace);\n const explicitProjectPolicy = hasExplicitNamespacePolicy(namespace, config);\n const baseReadable = canReadScopeProfileNamespace(principal, baseNamespace, config);\n const baseWritable = canWriteScopeProfileNamespace(principal, baseNamespace, config);\n const projectReadable = explicitProjectPolicy\n ? canReadNamespace(principal, namespace, config)\n : baseReadable;\n const projectWritable = explicitProjectPolicy\n ? canWriteNamespace(principal, namespace, config)\n : baseWritable;\n return {\n id,\n kind: \"user-project\",\n namespace,\n readable: projectReadable,\n writable: projectWritable,\n promotable: projectWritable,\n reason: explicitProjectPolicy\n ? \"explicit user-project namespace policy\"\n : baseReadable || baseWritable\n ? \"principal project namespace derived from coding context\"\n : \"principal base namespace is not authorized\",\n };\n }\n const team = resolveTeam(config, profile, principal);\n if (!team) {\n return {\n id,\n kind: \"team-project\",\n readable: false,\n writable: false,\n promotable: false,\n reason: \"no authorized team mapping\",\n };\n }\n if (!codingContext || !codingOverlay) {\n return {\n id,\n kind: \"team-project\",\n readable: false,\n writable: false,\n promotable: false,\n reason: \"missing project context\",\n };\n }\n const template =\n profile.teamProject?.namespaceTemplate ??\n team.team.projectNamespaceTemplate ??\n \"team-{teamId}-project-{projectHash}\";\n const renderedNamespace = renderTeamProjectNamespace({\n template,\n teamId: team.teamId,\n principal,\n codingContext,\n codingOverlay,\n });\n const namespace = renderedNamespace.namespace.trim();\n if (renderedNamespace.unknownPlaceholders.length > 0) {\n return {\n id,\n kind: \"team-project\",\n namespace,\n readable: false,\n writable: false,\n promotable: false,\n reason: `unknown team-project namespace template placeholder(s): ${renderedNamespace.unknownPlaceholders.join(\", \")}`,\n };\n }\n if (!namespace || !isSafeRouteNamespace(namespace)) {\n return {\n id,\n kind: \"team-project\",\n namespace,\n readable: false,\n writable: false,\n promotable: false,\n reason: \"team-project namespace template resolved to an unsafe namespace\",\n };\n }\n const teamReadable = principalListed(team.team.read, principal) || principalListed(team.team.principals, principal);\n const teamWritable = principalListed(team.team.write, principal);\n const teamPromotable = principalListed(team.team.promote, principal) || principalListed(team.team.write, principal);\n const userProjectSuffix = `-${codingOverlay.namespace}`;\n const userProjectBase = namespace.endsWith(userProjectSuffix)\n ? namespace.slice(0, -userProjectSuffix.length)\n : \"\";\n const dynamicUserProjectCollision =\n userProjectBase.length > 0 &&\n (userProjectBase === config.defaultNamespace ||\n userProjectBase === config.sharedNamespace ||\n (config.namespacePolicies ?? []).some((policy) => policy.name === userProjectBase));\n const protectedNamespace =\n namespace === config.defaultNamespace ||\n namespace === config.sharedNamespace ||\n dynamicUserProjectCollision ||\n (config.namespacePolicies ?? []).some((policy) => policy.name === namespace);\n const policyReadable = !protectedNamespace || canReadNamespace(principal, namespace, config);\n const policyWritable = !protectedNamespace || canWriteNamespace(principal, namespace, config);\n const policyBlocked = protectedNamespace && (!policyReadable || !policyWritable);\n return {\n id,\n kind: \"team-project\",\n namespace,\n readable: teamReadable && policyReadable,\n writable: teamWritable && policyWritable,\n promotable: teamPromotable && policyWritable,\n reason: policyBlocked\n ? \"team-project namespace collides with a protected namespace policy\"\n : \"trusted team-project namespace derived from team and project config\",\n };\n}\n\nexport function resolveScopeProfilePlan(\n options: ResolveScopeProfilePlanOptions,\n): ResolvedScopeProfilePlan | null {\n const active = activeScopeProfile(options.config);\n if (!active || !resolveNamespaceCapabilities(options.config).namespaces) return null;\n\n const baseNamespace = scopeProfileSelfNamespace(options.principal, options.config);\n const layerIds = Array.from(\n new Set<ScopeProfileLayerId>([\n ...active.profile.readOrder,\n active.profile.writeDefault,\n \"userGlobal\",\n ...active.profile.promotionTargets.filter((target): target is ScopeProfileLayerId =>\n [\"userProject\", \"teamProject\", \"userGlobal\", \"serverShared\"].includes(target),\n ),\n ]),\n );\n const layerMap = new Map<ScopeProfileLayerId, ScopeProfileLayerResolution>();\n for (const id of layerIds) {\n layerMap.set(\n id,\n resolveLayer({\n id,\n config: options.config,\n profile: active.profile,\n principal: options.principal,\n baseNamespace,\n codingContext: options.codingContext,\n codingOverlay: options.codingOverlay,\n }),\n );\n }\n\n const readNamespaces: string[] = [];\n for (const id of active.profile.readOrder) {\n const layer = layerMap.get(id);\n if (layer?.readable && layer.namespace && !readNamespaces.includes(layer.namespace)) {\n readNamespaces.push(layer.namespace);\n }\n }\n\n const preferredWriteLayer = layerMap.get(active.profile.writeDefault);\n const readableWriteLayers = active.profile.readOrder\n .map((id) => layerMap.get(id))\n .filter(\n (layer): layer is ScopeProfileLayerResolution =>\n Boolean(layer?.writable && layer.namespace && readNamespaces.includes(layer.namespace)),\n );\n const fallbackWriteLayer =\n preferredWriteLayer?.writable &&\n preferredWriteLayer.namespace &&\n readNamespaces.includes(preferredWriteLayer.namespace)\n ? preferredWriteLayer\n : readableWriteLayers[0];\n const warnings: string[] = [];\n if (!fallbackWriteLayer?.namespace) {\n warnings.push(`scope profile ${active.profileId} has no writable layer inside the profile read stack; writes disabled`);\n } else if (fallbackWriteLayer.id !== active.profile.writeDefault) {\n warnings.push(\n `scope profile ${active.profileId} writeDefault ${active.profile.writeDefault} unavailable: ${preferredWriteLayer?.reason ?? \"not resolved\"}`,\n );\n }\n\n const promotionTargets = active.profile.promotionTargets.map((target) => {\n const layer = layerMap.get(target as ScopeProfileLayerId);\n if (!layer) {\n return {\n target,\n authorized: false,\n reason: \"promotion target did not resolve to a profile layer\",\n };\n }\n return {\n target,\n namespace: layer.namespace,\n authorized: layer.promotable && Boolean(layer.namespace),\n reason: layer.reason,\n };\n });\n\n return {\n profileId: active.profileId,\n profile: active.profile,\n baseNamespace,\n writeLayer: fallbackWriteLayer?.id ?? active.profile.writeDefault,\n writeNamespace: fallbackWriteLayer?.namespace ?? \"\",\n readNamespaces,\n layers: [...layerMap.values()],\n promotionTargets,\n warnings,\n };\n}\n\nexport function expandScopeProfileReadNamespaces(options: {\n profilePlan: ResolvedScopeProfilePlan;\n principalSelfNamespace: string;\n config: PluginConfig;\n principal?: string;\n codingOverlay?: ScopeProfileCodingOverlay | null;\n legacyRecallNamespaces?: string[];\n}): string[] {\n if (options.profilePlan.readNamespaces.length === 0) {\n return [];\n }\n const out = [...options.profilePlan.readNamespaces];\n const add = (namespace: string | undefined): void => {\n if (namespace && !out.includes(namespace)) out.push(namespace);\n };\n const userProjectReadable =\n options.profilePlan.profile.readOrder.includes(\"userProject\") &&\n options.profilePlan.layers.some(\n (layer) => layer.id === \"userProject\" && layer.readable && layer.namespace,\n );\n const userGlobalReadable =\n options.profilePlan.profile.readOrder.includes(\"userGlobal\") &&\n options.profilePlan.layers.some(\n (layer) => layer.id === \"userGlobal\" && layer.readable && layer.namespace,\n );\n if (userProjectReadable) {\n for (const fallback of options.codingOverlay?.readFallbacks ?? []) {\n if (fallback === \"\" && !userGlobalReadable) continue;\n const fallbackNamespace = combineNamespaces(options.principalSelfNamespace, fallback);\n if (\n !hasExplicitNamespacePolicy(fallbackNamespace, options.config) ||\n canReadScopeProfileNamespace(options.principal, fallbackNamespace, options.config)\n ) {\n add(fallbackNamespace);\n }\n }\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AACA,SAAS,kBAAkB;AAqD3B,SAAS,mBAAmB,QAAiF;AAC3G,QAAM,YAAY,OAAO;AACzB,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,WAAW,OAAO,iBAAiB,CAAC,GAAG,SAAS;AACtD,SAAO,UAAU,EAAE,WAAW,QAAQ,IAAI;AAC5C;AAEA,SAAS,gBAAgB,MAAgB,WAAwC;AAC/E,MAAI,CAAC,UAAW,QAAO;AACvB,SAAO,KAAK,SAAS,SAAS,KAAK,KAAK,SAAS,GAAG;AACtD;AAEA,SAAS,iCAAiC,WAA+B,QAAqC;AAC5G,MAAI,CAAC,aAAa,cAAc,OAAO,oBAAoB,cAAc,OAAO,gBAAiB,QAAO;AACxG,MAAI,qBAAqB,SAAS,EAAG,QAAO;AAC5C,SAAO,eAAe,WAAW,QAAQ,EAAE,OAAO,SAAS,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE;AACxF;AAEA,SAAS,0BAA0B,WAA+B,QAA8B;AAC9F,QAAM,WAAW,6BAA6B,W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AA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":["namespace"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/namespaces/identity.ts"],"sourcesContent":["export function normalizeNamespaceIdentity(namespace: string | null | undefined): string {\n return namespace?.trim() ?? \"\";\n}\n\nexport function namespaceIdentityToken(namespace: string): string {\n const normalized = normalizeNamespaceIdentity(namespace);\n const bytes = new TextEncoder().encode(normalized);\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n return `ns-${hex || \"default\"}`;\n}\n\nexport function namespaceIdentityFromToken(token: string): string | null {\n if (!token.startsWith(\"ns-\")) return null;\n const hex = token.slice(3);\n if (hex === \"default\") return \"\";\n if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(hex)) {\n return null;\n }\n const decoded = Buffer.from(hex, \"hex\").toString(\"utf8\");\n return namespaceIdentityToken(decoded).toLowerCase() === token.toLowerCase()\n ? decoded\n : null;\n}\n"],"mappings":";AAAO,SAAS,2BAA2B,WAA8C;AACvF,SAAO,WAAW,KAAK,KAAK;AAC9B;AAEO,SAAS,uBAAuB,WAA2B;AAChE,QAAM,aAAa,2BAA2B,SAAS;AACvD,QAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,UAAU;AACjD,QAAM,MAAM,MAAM,KAAK,OAAO,CAAC,SAAS,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AACnF,SAAO,MAAM,OAAO,SAAS;AAC/B;AAEO,SAAS,2BAA2B,OAA8B;AACvE,MAAI,CAAC,MAAM,WAAW,KAAK,EAAG,QAAO;AACrC,QAAM,MAAM,MAAM,MAAM,CAAC;AACzB,MAAI,QAAQ,UAAW,QAAO;AAC9B,MAAI,IAAI,WAAW,KAAK,IAAI,SAAS,MAAM,KAAK,CAAC,eAAe,KAAK,GAAG,GAAG;AACzE,WAAO;AAAA,EACT;AACA,QAAM,UAAU,OAAO,KAAK,KAAK,KAAK,EAAE,SAAS,MAAM;AACvD,SAAO,uBAAuB,OAAO,EAAE,YAAY,MAAM,MAAM,YAAY,IACvE,UACA;AACN;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/namespaces/principal.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport { isLikelyUnsafeRegex } from \"../routing/engine.js\";\n\nconst MAX_REGEX_SESSION_KEY_LENGTH = 512;\n\nfunction compileSafePrincipalRegex(pattern: string): RegExp | null {\n if (isLikelyUnsafeRegex(pattern)) return null;\n try {\n return new RegExp(pattern);\n } catch {\n return null;\n }\n}\n\nexport function resolvePrincipal(sessionKey: string | undefined, config: PluginConfig): string | undefined {\n if (!resolveNamespaceCapabilities(config).namespaces) return \"default\";\n const sk = typeof sessionKey === \"string\" && sessionKey.trim().length > 0\n ? sessionKey\n : \"\";\n const mode = config.principalFromSessionKeyMode;\n const rules = config.principalFromSessionKeyRules ?? [];\n\n if (!sk) return undefined;\n\n if (mode === \"prefix\") {\n for (const r of rules) {\n if (sk.startsWith(r.match)) return r.principal;\n }\n } else if (mode === \"map\") {\n for (const r of rules) {\n if (sk === r.match) return r.principal;\n }\n } else if (mode === \"regex\") {\n if (sk.length <= MAX_REGEX_SESSION_KEY_LENGTH) {\n for (const r of rules) {\n const re = compileSafePrincipalRegex(r.match);\n if (re?.test(sk)) {\n return r.principal;\n }\n }\n }\n }\n\n // Fallback heuristic: \"agent:<agentId>:<channelType>:...\"\n const parts = sk.split(\":\");\n if (parts.length >= 2 && parts[0] === \"agent\") {\n const agentId = parts[1];\n if (agentId && agentId.length > 0) return agentId;\n }\n return \"default\";\n}\n\nexport function canReadNamespace(principal: string | undefined, namespace: string, config: PluginConfig): boolean {\n if (!resolveNamespaceCapabilities(config).namespaces) return true;\n if (!principal) return false;\n const policy = config.namespacePolicies.find((p) => p.name === namespace);\n if (!policy) return namespace === config.defaultNamespace || namespace === config.sharedNamespace;\n return policy.readPrincipals.includes(principal) || policy.readPrincipals.includes(\"*\");\n}\n\nexport function canWriteNamespace(principal: string | undefined, namespace: string, config: PluginConfig): boolean {\n if (!resolveNamespaceCapabilities(config).namespaces) return true;\n if (!principal) return false;\n const policy = config.namespacePolicies.find((p) => p.name === namespace);\n if (!policy) return namespace === config.defaultNamespace;\n return policy.writePrincipals.includes(principal) || policy.writePrincipals.includes(\"*\");\n}\n\n/**\n * Config-time namespace-policy lint (issue #1888 improvement 3). Principal-\n * agnostic mirror of {@link canWriteNamespace}: true when the namespace is\n * writable by AT LEAST ONE principal. When namespace enforcement is off every\n * write is allowed. Otherwise an explicit `namespacePolicies` entry takes\n * precedence (exactly as `canWriteNamespace`): with a matching policy the\n * namespace is covered only if that policy grants at least one non-blank\n * writer — even when the name equals `defaultNamespace`; without a policy it\n * is covered only if it IS the `defaultNamespace`. The `sharedNamespace` is\n * NOT implicitly writable (matching\n * `canWriteNamespace`), and a policy entry with no `writePrincipals` grants\n * nobody. A configured namespace that is NOT covered is writable for no one,\n * so every write to it is rejected by the ACL and dead-lettered — `remnic\n * doctor` warns on that before a session silently loses memory.\n */\nexport function isNamespacePolicyCovered(namespace: string, config: PluginConfig): boolean {\n if (!resolveNamespaceCapabilities(config).namespaces) return true;\n // An explicit policy wins over the default fallback (exactly as\n // canWriteNamespace), so a policy naming the default with no writers is NOT\n // covered. Only fall back to defaultNamespace when no policy matches.\n const policy = config.namespacePolicies.find((p) => p.name === namespace);\n if (!policy) return namespace === config.defaultNamespace;\n return policy.writePrincipals.some((w) => w.trim().length > 0);\n}\n\n/**\n * Default \"self\" namespace for a principal.\n *\n * Heuristic:\n * - If there's a namespace policy with the same name as the principal, use it.\n * - Otherwise use config.defaultNamespace.\n */\nexport function defaultNamespaceForPrincipal(principal: string | undefined, config: PluginConfig): string {\n if (!resolveNamespaceCapabilities(config).namespaces) return config.defaultNamespace;\n if (!principal) return config.defaultNamespace;\n const exists = config.namespacePolicies.some((p) => p.name === principal);\n return exists ? principal : config.defaultNamespace;\n}\n\nexport function recallNamespacesForPrincipal(principal: string | undefined, config: PluginConfig): string[] {\n const out: string[] = [];\n if (!resolveNamespaceCapabilities(config).namespaces) return [config.defaultNamespace];\n if (!principal) return out;\n\n const selfNs = defaultNamespaceForPrincipal(principal, config);\n if (config.defaultRecallNamespaces.includes(\"self\") && canReadNamespace(principal, selfNs, config)) {\n out.push(selfNs);\n }\n if (config.defaultRecallNamespaces.includes(\"shared\") && canReadNamespace(principal, config.sharedNamespace, config)) {\n out.push(config.sharedNamespace);\n }\n\n for (const p of config.namespacePolicies) {\n if (p.includeInRecallByDefault && canReadNamespace(principal, p.name, config)) {\n if (!out.includes(p.name)) out.push(p.name);\n }\n }\n\n return out;\n}\n\n/**\n * Namespaces a principal may attribute a citation to: the default-recall\n * namespaces, every readable policy namespace, and the readable built-in\n * default/shared namespaces — which `defaultRecallNamespaces` can omit even\n * though `canReadNamespace` grants access (#2020).\n */\nexport function citationAuthorizedNamespaces(\n principal: string | undefined,\n config: PluginConfig,\n): string[] {\n return Array.from(\n new Set([\n ...recallNamespacesForPrincipal(principal, config),\n ...config.namespacePolicies\n .filter((p) => canReadNamespace(principal, p.name, config))\n .map((p) => p.name),\n ...[config.defaultNamespace, config.sharedNamespace].filter((ns) =>\n canReadNamespace(principal, ns, config),\n ),\n ]),\n );\n}\n"],"mappings":";;;;;;;;AAIA,IAAM,+BAA+B;AAErC,SAAS,0BAA0B,SAAgC;AACjE,MAAI,oBAAoB,OAAO,EAAG,QAAO;AACzC,MAAI;AACF,WAAO,IAAI,OAAO,OAAO;AAAA,EAC3B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,iBAAiB,YAAgC,QAA0C;AACzG,MAAI,CAAC,6BAA6B,MAAM,EAAE,WAAY,QAAO;AAC7D,QAAM,KAAK,OAAO,eAAe,YAAY,WAAW,KAAK,EAAE,SAAS,IACpE,aACA;AACJ,QAAM,OAAO,OAAO;AACpB,QAAM,QAAQ,OAAO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I;AAAA,IAC5C;AAAA,EACF;AAEA,SAAO;AACT;AAQO,SAAS,6BACd,WACA,QACU;AACV,SAAO,MAAM;AAAA,IACX,oBAAI,IAAI;AAAA,MACN,GAAG,6BAA6B,WAAW,MAAM;AAAA,MACjD,GAAG,OAAO,kBACP,OAAO,CAAC,MAAM,iBAAiB,WAAW,EAAE,MAAM,MAAM,CAAC,EACzD,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,MACpB,GAAG,CAAC,OAAO,kBAAkB,OAAO,eAAe,EAAE;AAAA,QAAO,CAAC,OAC3D,iBAAiB,WAAW,IAAI,MAAM;AAAA,MACxC;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/namespaces/storage.ts"],"sourcesContent":["import { resolveNamespaceCapabilities, resolveRecallAuxiliaryCapabilities } from \"../capabilities.js\";\nimport path from \"node:path\";\nimport { access, lstat, readdir } from \"node:fs/promises\";\nimport { isSafeRouteNamespace } from \"../routing/engine.js\";\nimport { StorageManager } from \"../storage.js\";\nimport { keyring, secureStoreDir } from \"../secure-store/index.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport { ALL_CATEGORY_DIRS } from \"../utils/category-dir.js\";\nimport { namespaceIdentityToken, normalizeNamespaceIdentity } from \"./identity.js\";\nimport type { NamespaceCatalog } from \"./catalog.js\";\nimport { MutationSerializer } from \"../utils/serialize-mutations.js\";\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function hasStoredEntries(p: string): Promise<boolean> {\n try {\n const entry = await lstat(p);\n if (entry.isSymbolicLink()) return true;\n if (!entry.isDirectory()) return true;\n const children = await readdir(p, { withFileTypes: true });\n for (const child of children) {\n const childPath = path.join(p, child.name);\n if (child.isSymbolicLink() || child.isFile()) return true;\n if (child.isDirectory() && (await hasStoredEntries(childPath))) return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n\n// Build a per-namespace directory under `<memoryDir>/namespaces` and assert the\n// resolved path stays inside that base. Namespace identifiers can originate from\n// operator config (config.defaultNamespace) and request-derived routing, so this\n// containment check prevents directory traversal (CodeQL js/path-injection).\n// For safe segments this returns exactly `path.join(base, segment)`, so there is\n// no behavioral change for valid namespaces.\nfunction resolveNamespaceDir(memoryDir: string, segment: string): string {\n // Mirror isSafeRouteNamespace's separator/parent-ref rejection (without its\n // 64-char cap, so identity tokens still pass). Rejecting separators and \"..\"\n // up front keeps the value a single contained child of <memoryDir>/namespaces.\n if (\n segment.length === 0 ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\") ||\n segment.includes(\"..\") ||\n path.isAbsolute(segment)\n ) {\n throw new Error(`unsafe namespace path segment: ${segment}`);\n }\n return path.join(memoryDir, \"namespaces\", segment);\n}\n\nconst LEGACY_NAMESPACE_CONTENT_CHILDREN = [\n ...ALL_CATEGORY_DIRS,\n \"entities\",\n \"artifacts\",\n \"identity\",\n \"config\",\n \"summaries\",\n \"profile.md\",\n] as const;\n\nconst LEGACY_NAMESPACE_RUNTIME_CHILDREN = [\"state\"] as const;\n\nasync function hasAnyLegacyData(\n rootDir: string,\n options: { includeRuntimeState?: boolean } = {},\n): Promise<boolean> {\n const children = options.includeRuntimeState === true\n ? [...LEGACY_NAMESPACE_CONTENT_CHILDREN, ...LEGACY_NAMESPACE_RUNTIME_CHILDREN]\n : LEGACY_NAMESPACE_CONTENT_CHILDREN;\n for (const child of children) {\n if (await hasStoredEntries(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\nasync function hasAnyNamespaceStorageMarker(\n rootDir: string,\n options: { includeRuntimeState?: boolean } = {},\n): Promise<boolean> {\n const children = options.includeRuntimeState === true\n ? [...LEGACY_NAMESPACE_CONTENT_CHILDREN, ...LEGACY_NAMESPACE_RUNTIME_CHILDREN]\n : LEGACY_NAMESPACE_CONTENT_CHILDREN;\n for (const child of children) {\n if (await exists(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\n/**\n * Storage routing for namespaces.\n *\n * Compatibility note:\n * - When namespaces are enabled, existing raw namespace roots are preserved.\n * New namespace roots use tokenized names under `memoryDir/namespaces/<token>`.\n * - The default namespace continues to use the legacy `memoryDir` root unless the caller\n * has created `memoryDir/namespaces/<defaultNamespace>` (in which case we use that).\n *\n * This avoids surprising \"lost memories\" when an install flips namespaces on without\n * migrating existing data.\n */\n/**\n * Optional hooks for the storage router. `onResolve` fires whenever a namespace's\n * storage is resolved/created, so a downstream consumer (e.g. the namespace\n * catalog, issue #1499) can register the namespace. The hook MUST NOT throw into\n * the router; the router invokes it defensively and a hook failure never affects\n * storage resolution.\n *\n * The hook MAY return (or resolve to) a boolean indicating whether the\n * registration actually PERSISTED (round 6, codex P2 — NEFoX). When it resolves\n * to `false` (a dropped/no-op registration), the router does NOT mark the\n * (namespace, storageDir) pair as notified, so the next resolve RETRIES it\n * instead of suppressing it forever. A `void`/`undefined` result is treated as\n * success (legacy hooks).\n */\nexport interface NamespaceStorageRouterHooks {\n onResolve?: (\n namespace: string,\n storageDir: string,\n ) => void | boolean | Promise<void | boolean>;\n}\n\n/**\n * Resolve the runtime storage root for the configured DEFAULT namespace.\n *\n * Shared between the live router (`NamespaceStorageRouter.defaultNamespaceRoot`)\n * and the rebuildable catalog (`NamespaceCatalog.rebuildFromDisk`) so the two\n * can never diverge (CLAUDE.md rule #22/#42 — read & write paths resolve through\n * the same logic). The contract is: while legacy memory data still lives\n * directly under `memoryDir`, the default root stays `memoryDir`; only once the\n * legacy root is empty and a `namespaces/<default|token>` dir holds data does\n * the default migrate into that tokenized/legacy-named dir.\n */\nexport async function resolveDefaultNamespaceRoot(config: PluginConfig): Promise<string> {\n if (!resolveNamespaceCapabilities(config).namespaces) {\n return config.memoryDir;\n }\n\n // Build the legacy default root from the NORMALIZED (trimmed) name so a\n // whitespace-padded `defaultNamespace` still finds the live `namespaces/default`\n // root (NIabe). `storageFor()` classifies the trimmed value as the default, and\n // the on-disk legacy dir is created under the trimmed name; using the raw spaced\n // name here would look for `namespaces/<spaced>` and miss the real root, falling\n // back to memoryDir/tokenized. `namespaceIdentityToken` already normalizes\n // internally, so the tokenized path is unaffected.\n const defaultIdentity = normalizeNamespaceIdentity(config.defaultNamespace);\n const legacyNsDir = resolveNamespaceDir(config.memoryDir, defaultIdentity);\n const tokenizedNsDir = resolveNamespaceDir(\n config.memoryDir,\n namespaceIdentityToken(config.defaultNamespace),\n );\n const tokenizedHasData =\n (await exists(tokenizedNsDir)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedNsDir, { includeRuntimeState: true }));\n const nsDir = tokenizedHasData\n ? tokenizedNsDir\n : (await exists(legacyNsDir))\n ? legacyNsDir\n : tokenizedNsDir;\n return (await exists(nsDir)) && !(await hasAnyLegacyData(config.memoryDir))\n ? nsDir\n : config.memoryDir;\n}\n\n/**\n * Resolve the runtime storage root for ANY namespace exactly as the live router\n * would (`NamespaceStorageRouter.namespaceRoot`). Shared so the rebuildable\n * catalog records the SAME on-disk root the router routes to — a recall/read\n * touch must not guess `namespaces/<token>` when the router actually serves a\n * legacy raw-name dir or a migrated default root (CLAUDE.md rule #22/#42; round\n * 4, cursor Medium). The default namespace delegates to `resolveDefaultNamespaceRoot`;\n * every other namespace prefers the tokenized root when it has a storage marker,\n * else a legacy raw-name dir when present, else the tokenized root.\n */\nexport async function resolveNamespaceStorageRoot(\n config: PluginConfig,\n namespace: string,\n): Promise<string> {\n if (!resolveNamespaceCapabilities(config).namespaces) return config.memoryDir;\n // Compare on NORMALIZED identity so a whitespace-padded configured default name\n // still routes to the default root rather than a tokenized non-default dir\n // (NH-FH). The catalog keys records by the same normalized identity.\n if (normalizeNamespaceIdentity(namespace) === normalizeNamespaceIdentity(config.defaultNamespace)) {\n return resolveDefaultNamespaceRoot(config);\n }\n const legacyRoot = resolveNamespaceDir(config.memoryDir, namespace);\n const tokenizedRoot = resolveNamespaceDir(config.memoryDir, namespaceIdentityToken(namespace));\n if (\n (await exists(tokenizedRoot)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedRoot, { includeRuntimeState: true }))\n ) {\n return tokenizedRoot;\n }\n return (await exists(legacyRoot)) ? legacyRoot : tokenizedRoot;\n}\n\nexport class NamespaceStorageRouter {\n private readonly cache = new Map<string, StorageManager>();\n private defaultNsRootResolved: string | null = null;\n // Dedup the resolve hook (round 6, cursor Medium — NCNL2). Recall/extraction\n // call `storageFor` repeatedly; firing `onResolve` (→ catalog loadCompacted +\n // append) on every cache hit grows `namespaces.jsonl` without bound between\n // rebuilds. We fire the hook only when the (namespace, storageDir) pair is new\n // or its dir changed, so a steady-state cache hit is a no-op for the catalog.\n private readonly notifiedResolved = new Map<string, string>();\n // Instance-scoped serializer for the resolve hook (issue #1524 adoption).\n // Replaces the bespoke `inFlightResolved` marker-then-clear pattern: the\n // serializer's per-key chain strictly orders concurrent notifications for the\n // SAME namespace, and the task re-checks `notifiedResolved` once it runs, so a\n // burst of cache hits before the first hook settles collapses to a single\n // hook invocation (the once-per-namespace intent). Recovery is preserved —\n // one rejected hook never poisons subsequent notifications for that key.\n private readonly resolveSerializer = new MutationSerializer();\n // (namespace, storageDir) pairs whose resolve hook is currently pending. Set SYNCHRONOUSLY in\n // notifyResolved (before queueing) so a burst of concurrent storageFor()\n // cache hits collapses onto the one in-flight hook instead of each enqueuing\n // its own task. Cleared when the queued hook settles. Without this, a dropped\n // hook (returns false on a rebuild-lock timeout) leaves notifiedResolved\n // unset, so every queued sibling task would re-run the hook — N serial lock\n // waits (cursor Medium 06f58a7c, codex P2).\n private readonly inFlightResolveHooks = new Set<string>();\n // Tracks every in-flight resolve-hook promise so callers can deterministically\n // await the fire-and-forget registrations that `storageFor()` kicks off (see\n // `whenResolveHooksSettled`). Entries are removed as each hook settles, so the\n // set holds at most one promise per concurrently-resolving namespace.\n private readonly pendingResolveHooks = new Set<Promise<unknown>>();\n // Pending post-write catalog touch promises (#1522). Like pendingResolveHooks,\n // lets tests await fire-and-forget write touches deterministically.\n private readonly pendingWriteTouches = new Set<Promise<unknown>>();\n\n // Normalized (trimmed) default namespace identity (NH-FH). `storageFor`\n // normalizes its input, so default-namespace branches must compare against the\n // normalized config default too — otherwise a whitespace-padded configured\n // default name routes the default namespace to a tokenized non-default root.\n private readonly defaultNamespaceIdentity: string;\n\n /** #2019: hook fired when a new namespace storage is created via storageFor. */\n onStorageCreated?: (storage: StorageManager, namespace: string) => void;\n\n constructor(\n private readonly config: PluginConfig,\n private readonly hooks: NamespaceStorageRouterHooks = {},\n /** Catalog reference for post-write/read touches (issue #1522 chokepoint). */\n private readonly catalog?: NamespaceCatalog,\n ) {\n this.defaultNamespaceIdentity = normalizeNamespaceIdentity(config.defaultNamespace);\n }\n\n private async defaultNamespaceRoot(): Promise<string> {\n this.defaultNsRootResolved = await resolveDefaultNamespaceRoot(this.config);\n return this.defaultNsRootResolved;\n }\n\n private async namespaceRoot(namespace: string): Promise<string> {\n // NOTE: only used after defaultNamespaceRoot() resolution.\n if (!resolveNamespaceCapabilities(this.config).namespaces) return this.config.memoryDir;\n if (normalizeNamespaceIdentity(namespace) === this.defaultNamespaceIdentity) {\n return this.defaultNsRootResolved ?? this.config.memoryDir;\n }\n return resolveNamespaceStorageRoot(this.config, namespace);\n }\n\n async storageFor(namespace: string): Promise<StorageManager> {\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n if (ns !== this.defaultNamespaceIdentity && !isSafeRouteNamespace(ns)) {\n throw new Error(`unsafe namespace: ${ns}`);\n }\n // Even when the default namespace is exempt from the check above, every\n // on-disk path is built through resolveNamespaceDir(), which rejects\n // traversal segments — so an unsafe configured default still cannot escape\n // <memoryDir>/namespaces (CodeQL js/path-injection).\n\n let root: string;\n if (ns === this.defaultNamespaceIdentity) {\n root = await this.defaultNamespaceRoot();\n const cached = this.cache.get(ns);\n if (cached && cached.dir === root) {\n await this.applySecureStoreConfig(cached);\n this.notifyResolved(ns, root);\n return cached;\n }\n } else {\n const cached = this.cache.get(ns);\n root = await this.namespaceRoot(ns);\n if (cached && cached.dir === root) {\n await this.applySecureStoreConfig(cached);\n this.notifyResolved(ns, root);\n return cached;\n }\n }\n\n // Pass the hot-memories cache gate explicitly (issue #1902, Codex P2): a\n // per-namespace child root is never registered in the per-dir default map,\n // so without this it would fall back to the process-wide default and ignore\n // THIS daemon's hotMemoriesCacheEnabled config. Threading it from config\n // keeps every namespace storage aligned with its owning orchestrator.\n const sm = new StorageManager(\n root,\n this.config.entitySchemas,\n this.config.hotMemoriesCacheEnabled,\n );\n // Register this child root's gate AND TTL in the per-dir maps (issue #1902,\n // Codex P2). The constructor override above fixes the child's own gate, but\n // its TTL is resolved via the per-dir map (hotCacheTtlMs); an unregistered\n // child root would fall back to the last process-wide TTL and could inherit\n // another daemon's value. Registering keyed by root keeps both per-dir.\n StorageManager.setHotMemoriesCacheDefault(\n root,\n this.config.hotMemoriesCacheEnabled,\n this.config.hotMemoriesCacheTtlMs,\n );\n const { scopedCacheInvalidationEnabled } = this.config;\n StorageManager.setScopedCacheInvalidationDefault(root, scopedCacheInvalidationEnabled);\n // Propagate the inline-attribution template so that router-created storages\n // (used by extraction and shared-promotion paths) strip citations consistently,\n // matching the behaviour of the primary this.storage instance in the orchestrator.\n sm.citationTemplate = this.config.inlineSourceAttributionFormat;\n // #1522: install the post-write catalog touch at the chokepoint — every\n // successful write on this StorageManager records the namespace touch.\n this.bindCatalogWriteHook(sm, ns);\n // #1579: apply the tombstone non-resurrection config so every namespace\n // storage enforces the invariant at its own writeMemory chokepoint.\n this.applyTombstonesConfig(sm, ns);\n // #2033: install the secure-store context on router-created stores. The\n // orchestrator keys ONLY its primary default-namespace storage; without\n // this, a store resolved through the router reads isSecureStoreUnlocked()\n // === false even after the operator unlocked the keyring, so secure-store\n // recovery paths (e.g. the CLI lifecycle-ledger rebuild) refuse an encrypted\n // ledger they could actually rewrite, and namespace writes could silently\n // fall back to plaintext. Mirror the orchestrator's setup exactly.\n await this.applySecureStoreConfig(sm);\n this.cache.set(ns, sm);\n // #2019: let the orchestrator wire write-triggered prioritized embedding on\n // every router-created namespace storage, not just the primary default store.\n this.onStorageCreated?.(sm, ns);\n this.notifyResolved(ns, root);\n return sm;\n }\n\n /**\n * Fire the resolve hook defensively. A hook failure (e.g. a catalog write\n * error) MUST NOT crash storage resolution — see CLAUDE.md gotcha #13.\n *\n * Issue #1524 adoption: hook invocations for the SAME namespace are now\n * strictly ordered through the shared `MutationSerializer` rather than the\n * bespoke `inFlightResolved` marker-then-clear pattern. The serializer\n * guarantees one in-flight hook per namespace; a concurrent burst of\n * `storageFor()` cache hits collapses to a single hook invocation because\n * each queued task re-checks `notifiedResolved` before invoking the hook. A\n * dropped (`false`) or rejected hook leaves `notifiedResolved` unset so the\n * next `storageFor()` retries — the serializer recovers from the rejection,\n * so a failed hook never poisons later notifications.\n */\n private notifyResolved(namespace: string, storageDir: string): void {\n const hook = this.hooks.onResolve;\n if (!hook) return;\n // Permanent dedup: skip once we've SUCCESSFULLY notified this exact\n // (namespace, storageDir). A changed dir (rare: migration/realignment)\n // still re-fires once. The mark is set ONLY AFTER the hook succeeds, so a\n // dropped registration (e.g. rebuild-lock timeout) is RETRIED on the next\n // cache hit instead of being suppressed forever (round 6, cursor Medium —\n // ND3EJ).\n if (this.notifiedResolved.get(namespace) === storageDir) return;\n // In-flight dedup (cursor Medium 06f58a7c, codex P2): if a hook for THIS\n // namespace is already pending, collapse this call onto it instead of\n // enqueueing another task. The serializer strictly orders queued tasks, but\n // ordering alone is not enough — when the first hook returns `false`\n // (dropped touch, e.g. rebuild-lock timeout), `notifiedResolved` stays\n // unset, so each queued sibling task would pass its re-check and re-run the\n // hook. With the real catalog hook each retry can spend the full lock wait,\n // so N cache hits during a rebuild leave N serial background lock attempts.\n // Collapsing here means at most ONE hook runs per in-flight registration;\n // its result (set `notifiedResolved` on success, leave unset on drop)\n // decides whether a LATER `storageFor()` retries — collapsing loses\n // nothing because the drop is already retried on the next cache hit.\n // Keyed by the composite (namespace, storageDir) so a CHANGED dir\n // (migration/realignment) for the same namespace still gets its own hook —\n // it is NOT collapsed onto the old dir's pending registration (cursor\n // Medium, codex P2).\n const inFlightKey = namespace + \"\\u0000\" + storageDir;\n if (this.inFlightResolveHooks.has(inFlightKey)) return;\n this.inFlightResolveHooks.add(inFlightKey);\n // Queue through the serializer. Concurrent calls for the same namespace\n // strictly order here; the 2nd call's task runs only after the 1st's hook\n // settles, by which point `notifiedResolved` is either set (no-op) or still\n // unset (retry). The returned promise is tracked for\n // `whenResolveHooksSettled()`. Rejections from the task body are caught so\n // they never reach the caller (best-effort hook contract); the serializer's\n // recovered tail still lets subsequent notifications run.\n const task = async (): Promise<void> => {\n // Re-check after queueing: a prior task in this same chain may have just\n // marked the pair as notified.\n if (this.notifiedResolved.get(namespace) === storageDir) return;\n try {\n // Hook may be sync or async; Promise.resolve normalizes both. A result\n // of `false` means the registration was dropped/no-op (e.g. rebuild-lock\n // timeout) — leave notifiedResolved UNSET so the next storageFor retries\n // (round 6, codex P2 — NEFoX). `void`/`undefined` is success for legacy\n // hooks. A rejection leaves notifiedResolved unset for the same reason.\n const persisted = await Promise.resolve(hook(namespace, storageDir));\n if (persisted !== false) {\n this.notifiedResolved.set(namespace, storageDir);\n }\n } catch {\n // Best-effort: a hook failure MUST NOT crash storage resolution. Leave\n // notifiedResolved unset so a later storageFor retries the registration.\n }\n };\n const queued = this.resolveSerializer.serialize(namespace, task);\n this.pendingResolveHooks.add(queued);\n // Clear the in-flight marker when the hook settles so a subsequent\n // storageFor() can retry after a drop, or short-circuit via notifiedResolved\n // after a success.\n const cleanup = (): void => {\n this.inFlightResolveHooks.delete(inFlightKey);\n this.pendingResolveHooks.delete(queued);\n };\n void queued.then(cleanup, cleanup);\n }\n\n /**\n * Install the post-write catalog touch hook on an externally-constructed\n * StorageManager (issue #1522). Used by the orchestrator for the legacy\n * default-namespace storage (`this.storage`) that bypasses the router.\n */\n bindCatalogWriteHook(sm: StorageManager, namespace: string): void {\n // Issue #1903: pure state-file writes only touch the catalog when explicitly\n // opted in. Router-created storages (storageFor) and the legacy default\n // storage both flow through here, so this is the single wiring point.\n sm.touchStateWrites = this.config.namespacesCatalogTouchStateWrites === true;\n sm.onCatalogWrite = () => this.touchCatalogWrite(namespace, sm.dir);\n }\n\n /**\n * Install the tombstone config on an externally-constructed StorageManager\n * (issue #1579). Mirrors `bindCatalogWriteHook` — used for the legacy\n * default-namespace storage that bypasses the router. Router-created\n * storages are wired inline in `storageFor()` via `applyTombstonesConfig`.\n */\n bindTombstonesConfig(\n sm: StorageManager,\n namespace: string,\n config: { enabled: boolean; semanticMatch: boolean; semanticThreshold: number },\n ): void {\n this.tombstonesGlobalConfig = { ...config };\n sm.setTombstonesConfig({ ...config, namespace });\n }\n\n private tombstonesGlobalConfig: {\n enabled: boolean;\n semanticMatch: boolean;\n semanticThreshold: number;\n } = { enabled: false, semanticMatch: false, semanticThreshold: 0.9 };\n\n /**\n * Apply the tombstone config to a router-created StorageManager. Called\n * inline in `storageFor()` so every namespace storage enforces the\n * non-resurrection invariant, namespace-scoped (rule 42).\n */\n private applyTombstonesConfig(sm: StorageManager, namespace: string): void {\n sm.setTombstonesConfig({ ...this.tombstonesGlobalConfig, namespace });\n }\n\n /**\n * Install the at-rest secure-store context on a router-created StorageManager\n * (#2033). Mirrors the orchestrator's primary-storage setup: mark the store\n * required so a locked store throws instead of silently writing plaintext, and\n * install the master key when the process-local keyring already holds it (the\n * operator unlocked). The secure store is one key per memory ROOT (single\n * header + per-file path-bound AAD), so every namespace store keys off the\n * root keyring id — exactly the id the orchestrator and `secure-store unlock`\n * register under. No-op when secure-store is disabled.\n */\n private async applySecureStoreConfig(sm: StorageManager): Promise<void> {\n if (!resolveRecallAuxiliaryCapabilities(this.config).secureStore) return;\n sm.setSecureStoreRequired(true);\n const existingKey = keyring.getKey(secureStoreDir(this.config.memoryDir));\n if (existingKey) {\n await sm.setSecureStoreKeyAndWait(existingKey, this.config.secureStoreEncryptOnWrite);\n }\n }\n\n /**\n * Post-write catalog touch (issue #1522 chokepoint). Called by every\n * StorageManager's post-write hook AFTER a successful write. Best-effort\n * and failure-tolerant — a catalog error MUST NOT affect the primary write\n * (gotcha #13, rule #40). Fire-and-forget by design.\n */\n private touchCatalogWrite(namespace: string, storageDir: string): void {\n if (!this.catalog) return;\n const touch = this.catalog\n .markWrite(namespace, { discoveredBy: \"write\", storageDir })\n .catch(() => undefined);\n this.pendingWriteTouches.add(touch);\n void touch.then(\n () => { this.pendingWriteTouches.delete(touch); },\n () => { this.pendingWriteTouches.delete(touch); },\n );\n }\n\n /**\n * Record a namespace read in the catalog (issue #1522 chokepoint move).\n * Best-effort and failure-tolerant. Used by recall paths so the read touch\n * lives in the storage layer, not at the caller.\n */\n recordRead(namespace: string, storageDir?: string): void {\n if (!this.catalog) return;\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n void this.catalog\n .markRead(ns, { discoveredBy: \"read\", storageDir })\n .catch(() => undefined);\n }\n /**\n * Record a namespace write touch in the catalog (issue #1522). Best-effort\n * and failure-tolerant. Used by consolidation/cleanup passes that may mutate\n * the store via delete-only paths (e.g. entity-file merges, TTL cleanup) so\n * the namespace's lastWriteAt stays fresh even when no explicit write went\n * through the storage chokepoint. This is NOT a substitute for the chokepoint\n * — it's a belt-and-suspenders for paths the chokepoint doesn't cover.\n */\n recordWrite(namespace: string, storageDir?: string): void {\n if (!this.catalog) return;\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n const touch = this.catalog\n .markWrite(ns, { discoveredBy: \"write\", storageDir })\n .catch(() => undefined);\n this.pendingWriteTouches.add(touch);\n void touch.then(\n () => { this.pendingWriteTouches.delete(touch); },\n () => { this.pendingWriteTouches.delete(touch); },\n );\n }\n\n /**\n * Resolve once every in-flight post-write catalog touch has settled (#1522).\n * Mirrors `whenResolveHooksSettled()`: the StorageManager's post-write hook\n * fires the catalog touch fire-and-forget, so tests asserting lastWriteAt\n * moved should await this instead of racing a timer.\n */\n async whenWriteTouchesSettled(): Promise<void> {\n // Flush any coalesced (buffered) touches first so their appends join the\n // pending set below — otherwise this could resolve while a buffered touch's\n // lastWriteAt is still unwritten on disk (#1903, Cursor). No-op when\n // coalescing is disabled (window 0) or the catalog is inert.\n await this.catalog?.flushPendingTouches().catch(() => undefined);\n while (this.pendingWriteTouches.size > 0) {\n await Promise.allSettled([...this.pendingWriteTouches]);\n }\n }\n\n /**\n * Resolve once every in-flight `onResolve` registration has settled.\n *\n * `storageFor()` fires the resolve hook fire-and-forget, so its catalog side\n * effect (e.g. `registerResolved(...)`) is not observable the moment\n * `storageFor()` returns. Callers that must act on that side effect — notably\n * tests asserting the catalog was updated — should await this instead of\n * racing a timer. Resolves immediately when no hook is registered or nothing\n * is in flight. The loop re-checks because a settling hook could, in\n * principle, trigger a follow-on resolution.\n */\n async whenResolveHooksSettled(): Promise<void> {\n while (this.pendingResolveHooks.size > 0) {\n await Promise.allSettled([...this.pendingResolveHooks]);\n }\n }\n\n /**\n * #2019: iterate the currently cached router storages with their namespace so\n * callers can wire hooks on stores resolved before the hook was installed.\n */\n forEachCachedStorage(fn: (storage: StorageManager, namespace: string) => void): void {\n for (const [namespace, storage] of this.cache) fn(storage, namespace);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,QAAQ,OAAO,eAAe;AAUvC,eAAe,OAAO,GAA6B;AACjD,MAAI;AACF,UAAM,OAAO,CAAC;AACd,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,eAAe,iBAAiB,GAA6B;AAC3D,MAAI;AACF,UAAM,QAAQ,MAAM,MAAM,CAAC;AAC3B,QAAI,MAAM,eAAe,EAAG,QAAO;AACnC,QAAI,CAAC,MAAM,YAAY,EAAG,QAAO;AACjC,UAAM,WAAW,MAAM,QAAQ,GAAG,EAAE,eAAe,KAAK,CAAC;AACzD,eAAW,SAAS,UAAU;AAC5B,YAAM,YAAY,KAAK,KAAK,GAAG,MAAM,IAAI;AACzC,UAAI,MAAM,eAAe,KAAK,MA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