@fgv/ts-agent-memory 5.1.0-37 → 5.1.0-39

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 (197) hide show
  1. package/.rush/temp/{6dfc331ddf74dc2db0d4483d0c96ea971f351c83.tar.log → b82cf6bdece20481260e6bab946179eeec9d7b46.tar.log} +116 -2
  2. package/.rush/temp/chunked-rush-logs/ts-agent-memory.build.chunks.jsonl +4 -4
  3. package/.rush/temp/operation/build/all.log +4 -4
  4. package/.rush/temp/operation/build/log-chunks.jsonl +4 -4
  5. package/.rush/temp/operation/build/state.json +1 -1
  6. package/.rush/temp/shrinkwrap-deps.json +222 -221
  7. package/config/jest.config.json +1 -1
  8. package/dist/index.js +2 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/packlets/ingest/cycleGuard.js +111 -0
  11. package/dist/packlets/ingest/cycleGuard.js.map +1 -0
  12. package/dist/packlets/ingest/hostStages.js +6 -0
  13. package/dist/packlets/ingest/hostStages.js.map +1 -0
  14. package/dist/packlets/ingest/index.js +9 -0
  15. package/dist/packlets/ingest/index.js.map +1 -0
  16. package/dist/packlets/ingest/model.js +6 -0
  17. package/dist/packlets/ingest/model.js.map +1 -0
  18. package/dist/packlets/ingest/orchestrator.js +438 -0
  19. package/dist/packlets/ingest/orchestrator.js.map +1 -0
  20. package/dist/packlets/retrieve/index.js +1 -0
  21. package/dist/packlets/retrieve/index.js.map +1 -1
  22. package/dist/packlets/retrieve/temporalRetrievers.js +172 -0
  23. package/dist/packlets/retrieve/temporalRetrievers.js.map +1 -0
  24. package/dist/packlets/store/fileTreeMemoryStore.js +323 -41
  25. package/dist/packlets/store/fileTreeMemoryStore.js.map +1 -1
  26. package/dist/packlets/tools/index.js +6 -0
  27. package/dist/packlets/tools/index.js.map +1 -0
  28. package/dist/packlets/tools/memoryTools.js +337 -0
  29. package/dist/packlets/tools/memoryTools.js.map +1 -0
  30. package/dist/packlets/types/identityCodec.js +115 -0
  31. package/dist/packlets/types/identityCodec.js.map +1 -1
  32. package/dist/packlets/types/index.js +1 -0
  33. package/dist/packlets/types/index.js.map +1 -1
  34. package/dist/packlets/types/temporal.js +85 -0
  35. package/dist/packlets/types/temporal.js.map +1 -0
  36. package/dist/packlets/types/writePolicy.js +96 -0
  37. package/dist/packlets/types/writePolicy.js.map +1 -1
  38. package/dist/test/unit/converters/antagonistRoundTrip.test.js +95 -0
  39. package/dist/test/unit/converters/antagonistRoundTrip.test.js.map +1 -0
  40. package/dist/test/unit/ingest/antagonistCycleAndParity.test.js +273 -0
  41. package/dist/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -0
  42. package/dist/test/unit/ingest/cycleGuard.test.js +54 -0
  43. package/dist/test/unit/ingest/cycleGuard.test.js.map +1 -0
  44. package/dist/test/unit/ingest/orchestrator.test.js +913 -0
  45. package/dist/test/unit/ingest/orchestrator.test.js.map +1 -0
  46. package/dist/test/unit/retrieve/temporalRetrievers.test.js +182 -0
  47. package/dist/test/unit/retrieve/temporalRetrievers.test.js.map +1 -0
  48. package/dist/test/unit/store/antagonistTemporalBoundary.test.js +120 -0
  49. package/dist/test/unit/store/antagonistTemporalBoundary.test.js.map +1 -0
  50. package/dist/test/unit/store/fileTreeMemoryStore.test.js +74 -7
  51. package/dist/test/unit/store/fileTreeMemoryStore.test.js.map +1 -1
  52. package/dist/test/unit/store/temporalStore.test.js +398 -0
  53. package/dist/test/unit/store/temporalStore.test.js.map +1 -0
  54. package/dist/test/unit/tools/memoryTools.test.js +572 -0
  55. package/dist/test/unit/tools/memoryTools.test.js.map +1 -0
  56. package/dist/test/unit/types/temporalCodec.test.js +203 -0
  57. package/dist/test/unit/types/temporalCodec.test.js.map +1 -0
  58. package/dist/test/unit/types/temporalPolicy.test.js +62 -0
  59. package/dist/test/unit/types/temporalPolicy.test.js.map +1 -0
  60. package/dist/ts-agent-memory.d.ts +1042 -10
  61. package/dist/tsdoc-metadata.json +1 -1
  62. package/etc/ts-agent-memory.api.md +284 -0
  63. package/lib/index.d.ts +2 -0
  64. package/lib/index.d.ts.map +1 -1
  65. package/lib/index.js +2 -0
  66. package/lib/index.js.map +1 -1
  67. package/lib/packlets/ingest/cycleGuard.d.ts +41 -0
  68. package/lib/packlets/ingest/cycleGuard.d.ts.map +1 -0
  69. package/lib/packlets/ingest/cycleGuard.js +115 -0
  70. package/lib/packlets/ingest/cycleGuard.js.map +1 -0
  71. package/lib/packlets/ingest/hostStages.d.ts +88 -0
  72. package/lib/packlets/ingest/hostStages.d.ts.map +1 -0
  73. package/lib/packlets/ingest/hostStages.js +7 -0
  74. package/lib/packlets/ingest/hostStages.js.map +1 -0
  75. package/lib/packlets/ingest/index.d.ts +5 -0
  76. package/lib/packlets/ingest/index.d.ts.map +1 -0
  77. package/lib/packlets/ingest/index.js +25 -0
  78. package/lib/packlets/ingest/index.js.map +1 -0
  79. package/lib/packlets/ingest/model.d.ts +177 -0
  80. package/lib/packlets/ingest/model.d.ts.map +1 -0
  81. package/lib/packlets/ingest/model.js +7 -0
  82. package/lib/packlets/ingest/model.js.map +1 -0
  83. package/lib/packlets/ingest/orchestrator.d.ts +206 -0
  84. package/lib/packlets/ingest/orchestrator.d.ts.map +1 -0
  85. package/lib/packlets/ingest/orchestrator.js +442 -0
  86. package/lib/packlets/ingest/orchestrator.js.map +1 -0
  87. package/lib/packlets/retrieve/index.d.ts +1 -0
  88. package/lib/packlets/retrieve/index.d.ts.map +1 -1
  89. package/lib/packlets/retrieve/index.js +1 -0
  90. package/lib/packlets/retrieve/index.js.map +1 -1
  91. package/lib/packlets/retrieve/temporalRetrievers.d.ts +78 -0
  92. package/lib/packlets/retrieve/temporalRetrievers.d.ts.map +1 -0
  93. package/lib/packlets/retrieve/temporalRetrievers.js +178 -0
  94. package/lib/packlets/retrieve/temporalRetrievers.js.map +1 -0
  95. package/lib/packlets/store/fileTreeMemoryStore.d.ts +118 -9
  96. package/lib/packlets/store/fileTreeMemoryStore.d.ts.map +1 -1
  97. package/lib/packlets/store/fileTreeMemoryStore.js +322 -40
  98. package/lib/packlets/store/fileTreeMemoryStore.js.map +1 -1
  99. package/lib/packlets/tools/index.d.ts +2 -0
  100. package/lib/packlets/tools/index.d.ts.map +1 -0
  101. package/lib/packlets/tools/index.js +22 -0
  102. package/lib/packlets/tools/index.js.map +1 -0
  103. package/lib/packlets/tools/memoryTools.d.ts +139 -0
  104. package/lib/packlets/tools/memoryTools.d.ts.map +1 -0
  105. package/lib/packlets/tools/memoryTools.js +341 -0
  106. package/lib/packlets/tools/memoryTools.js.map +1 -0
  107. package/lib/packlets/types/identityCodec.d.ts +86 -0
  108. package/lib/packlets/types/identityCodec.d.ts.map +1 -1
  109. package/lib/packlets/types/identityCodec.js +118 -1
  110. package/lib/packlets/types/identityCodec.js.map +1 -1
  111. package/lib/packlets/types/index.d.ts +1 -0
  112. package/lib/packlets/types/index.d.ts.map +1 -1
  113. package/lib/packlets/types/index.js +1 -0
  114. package/lib/packlets/types/index.js.map +1 -1
  115. package/lib/packlets/types/temporal.d.ts +40 -0
  116. package/lib/packlets/types/temporal.d.ts.map +1 -0
  117. package/lib/packlets/types/temporal.js +92 -0
  118. package/lib/packlets/types/temporal.js.map +1 -0
  119. package/lib/packlets/types/writePolicy.d.ts +49 -0
  120. package/lib/packlets/types/writePolicy.d.ts.map +1 -1
  121. package/lib/packlets/types/writePolicy.js +98 -1
  122. package/lib/packlets/types/writePolicy.js.map +1 -1
  123. package/lib/test/unit/converters/antagonistRoundTrip.test.d.ts +10 -0
  124. package/lib/test/unit/converters/antagonistRoundTrip.test.d.ts.map +1 -0
  125. package/lib/test/unit/converters/antagonistRoundTrip.test.js +97 -0
  126. package/lib/test/unit/converters/antagonistRoundTrip.test.js.map +1 -0
  127. package/lib/test/unit/ingest/antagonistCycleAndParity.test.d.ts +9 -0
  128. package/lib/test/unit/ingest/antagonistCycleAndParity.test.d.ts.map +1 -0
  129. package/lib/test/unit/ingest/antagonistCycleAndParity.test.js +275 -0
  130. package/lib/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -0
  131. package/lib/test/unit/ingest/cycleGuard.test.d.ts +2 -0
  132. package/lib/test/unit/ingest/cycleGuard.test.d.ts.map +1 -0
  133. package/lib/test/unit/ingest/cycleGuard.test.js +56 -0
  134. package/lib/test/unit/ingest/cycleGuard.test.js.map +1 -0
  135. package/lib/test/unit/ingest/orchestrator.test.d.ts +2 -0
  136. package/lib/test/unit/ingest/orchestrator.test.d.ts.map +1 -0
  137. package/lib/test/unit/ingest/orchestrator.test.js +915 -0
  138. package/lib/test/unit/ingest/orchestrator.test.js.map +1 -0
  139. package/lib/test/unit/retrieve/temporalRetrievers.test.d.ts +2 -0
  140. package/lib/test/unit/retrieve/temporalRetrievers.test.d.ts.map +1 -0
  141. package/lib/test/unit/retrieve/temporalRetrievers.test.js +184 -0
  142. package/lib/test/unit/retrieve/temporalRetrievers.test.js.map +1 -0
  143. package/lib/test/unit/store/antagonistTemporalBoundary.test.d.ts +9 -0
  144. package/lib/test/unit/store/antagonistTemporalBoundary.test.d.ts.map +1 -0
  145. package/lib/test/unit/store/antagonistTemporalBoundary.test.js +122 -0
  146. package/lib/test/unit/store/antagonistTemporalBoundary.test.js.map +1 -0
  147. package/lib/test/unit/store/fileTreeMemoryStore.test.js +74 -7
  148. package/lib/test/unit/store/fileTreeMemoryStore.test.js.map +1 -1
  149. package/lib/test/unit/store/temporalStore.test.d.ts +2 -0
  150. package/lib/test/unit/store/temporalStore.test.d.ts.map +1 -0
  151. package/lib/test/unit/store/temporalStore.test.js +400 -0
  152. package/lib/test/unit/store/temporalStore.test.js.map +1 -0
  153. package/lib/test/unit/tools/memoryTools.test.d.ts +2 -0
  154. package/lib/test/unit/tools/memoryTools.test.d.ts.map +1 -0
  155. package/lib/test/unit/tools/memoryTools.test.js +574 -0
  156. package/lib/test/unit/tools/memoryTools.test.js.map +1 -0
  157. package/lib/test/unit/types/temporalCodec.test.d.ts +2 -0
  158. package/lib/test/unit/types/temporalCodec.test.d.ts.map +1 -0
  159. package/lib/test/unit/types/temporalCodec.test.js +205 -0
  160. package/lib/test/unit/types/temporalCodec.test.js.map +1 -0
  161. package/lib/test/unit/types/temporalPolicy.test.d.ts +2 -0
  162. package/lib/test/unit/types/temporalPolicy.test.d.ts.map +1 -0
  163. package/lib/test/unit/types/temporalPolicy.test.js +64 -0
  164. package/lib/test/unit/types/temporalPolicy.test.js.map +1 -0
  165. package/package.json +7 -7
  166. package/rush-logs/ts-agent-memory.build.cache.log +1 -1
  167. package/rush-logs/ts-agent-memory.build.log +4 -4
  168. package/src/index.ts +2 -0
  169. package/src/packlets/ingest/cycleGuard.ts +142 -0
  170. package/src/packlets/ingest/hostStages.ts +111 -0
  171. package/src/packlets/ingest/index.ts +9 -0
  172. package/src/packlets/ingest/model.ts +184 -0
  173. package/src/packlets/ingest/orchestrator.ts +797 -0
  174. package/src/packlets/retrieve/index.ts +1 -0
  175. package/src/packlets/retrieve/temporalRetrievers.ts +210 -0
  176. package/src/packlets/store/fileTreeMemoryStore.ts +460 -66
  177. package/src/packlets/tools/index.ts +6 -0
  178. package/src/packlets/tools/memoryTools.ts +579 -0
  179. package/src/packlets/types/identityCodec.ts +184 -0
  180. package/src/packlets/types/index.ts +1 -0
  181. package/src/packlets/types/temporal.ts +96 -0
  182. package/src/packlets/types/writePolicy.ts +127 -0
  183. package/src/test/unit/converters/antagonistRoundTrip.test.ts +110 -0
  184. package/src/test/unit/ingest/antagonistCycleAndParity.test.ts +362 -0
  185. package/src/test/unit/ingest/cycleGuard.test.ts +68 -0
  186. package/src/test/unit/ingest/orchestrator.test.ts +1158 -0
  187. package/src/test/unit/retrieve/temporalRetrievers.test.ts +226 -0
  188. package/src/test/unit/store/antagonistTemporalBoundary.test.ts +158 -0
  189. package/src/test/unit/store/fileTreeMemoryStore.test.ts +98 -7
  190. package/src/test/unit/store/temporalStore.test.ts +469 -0
  191. package/src/test/unit/tools/memoryTools.test.ts +771 -0
  192. package/src/test/unit/types/temporalCodec.test.ts +259 -0
  193. package/src/test/unit/types/temporalPolicy.test.ts +96 -0
  194. package/temp/build/lint/_eslint-5eVG3S6w.json +85 -9
  195. package/temp/build/typescript/ts_8nwakTlr.json +1 -1
  196. package/temp/ts-agent-memory.api.json +11984 -6314
  197. package/temp/ts-agent-memory.api.md +284 -0
@@ -1 +1 @@
1
- {"version":3,"file":"writePolicy.js","sourceRoot":"","sources":["../../../src/packlets/types/writePolicy.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,4CAAsD;AAEtD,0CAA8D;AAoB9D;;;;;GAKG;AACU,QAAA,mBAAmB,GAAe,QAAQ,CAAC;AAuExD;;;;;;;;;GASG;AACH,MAAM,mBAAmB,GAAgC;IACvD,KAAK,EAAE;QACL,YAAY,EAAE,IAAI;QAClB,kBAAkB,EAAE,SAAS;KAC9B;CACF,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,kBAAkB;IA0B7B,YAAoB,WAAuB,EAAE,WAAuB;QAzBpE;;;WAGG;QACa,kBAAa,GAA0B;YACrD,MAAM;YACN,MAAM;YACN,OAAO;YACP,YAAY;YACZ,cAAc;SACf,CAAC;QAEF;;;;;WAKG;QACa,eAAU,GAAe,SAAS,CAAC;QAQjD,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;QAChC,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;IAClC,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,MAAM;QAClB,OAAO,oBAAU,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,WAAW,EAAE,EAAE,CACzD,oBAAU,CAAC,MAAM,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,WAAW,EAAE,EAAE,CACnE,IAAA,kBAAO,EAAC,IAAI,kBAAkB,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,CAC1D,CACF,CAAC;IACJ,CAAC;IAED,uCAAuC;IAChC,KAAK,CACV,UAAkC,EAClC,UAA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,MAAM,CAAC,CAAC,CAAE,MAAM,CAAC,UAAqC,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,UAAU,EACvG,YAAY,EAAE,mBAAmB;gBAC/B,CAAC,CAAC,cAAc,IAAI,MAAM;oBACxB,CAAC,CAAE,MAAM,CAAC,YAA8B;oBACxC,CAAC,CAAC,SAAS;gBACb,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,YAAY,GACnC,CAAC;QACF,OAAO,IAAA,kBAAO,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,IAAI,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;IACrF,CAAC;CACF;AA/HD,kDA+HC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result, fail, succeed } from '@fgv/ts-utils';\nimport { JsonObject } from '@fgv/ts-json-base';\nimport { IJsonEditorOptions, JsonEditor } from '@fgv/ts-json';\nimport { IEdge, IMemoryEnvelope, IMemoryRecord, IProvenance } from './envelope';\nimport { MemoryId, Tag } from './ids';\n\n/**\n * The granularity at which the store deduplicates an incoming write against the\n * existing vault, declared per kind via {@link IWritePolicy.dedupScope}.\n *\n * - `'content'`: scope-wide cross-id content dedup. An identical\n * `{ kind, body, links }` triple ANYWHERE in the scope — even under a\n * different id — is a no-op that returns the existing record. The knowledge\n * kind family uses this.\n * - `'entity'`: same-id content dedup only. An identical re-put of the SAME\n * entity is a no-op, but two DISTINCT entities with identical content never\n * collapse. The experience (memory) kind families use this so that, e.g.,\n * two turns whose summaries happen to be byte-identical both persist.\n * @public\n */\nexport type DedupScope = 'content' | 'entity';\n\n/**\n * The default {@link DedupScope} applied when a policy does not declare one.\n * Entity-scoped dedup is the safe default — it never silently collapses two\n * distinct entities with coincidentally-identical content.\n * @public\n */\nexport const DEFAULT_DEDUP_SCOPE: DedupScope = 'entity';\n\n/**\n * The admission decision returned by {@link IWritePolicy.admit}.\n * @public\n */\nexport type AdmissionDecision =\n | { readonly decision: 'accept' }\n | { readonly decision: 'reject'; readonly reason: string }\n | {\n readonly decision: 'cull-oldest';\n /** {@link MemoryId}s to evict before writing the incoming record. */\n readonly evict: ReadonlyArray<MemoryId>;\n };\n\n/**\n * A per-kind write policy, injected at store construction. Invoked AFTER\n * content-hash dedup (dedup is always pre-policy). The policy decides\n * admission and, on update, applies a JSON Merge Patch (RFC-7386) restricted\n * to the declared mutable fields.\n * @public\n */\nexport interface IWritePolicy {\n /**\n * Names of the fields a merge-patch update may touch. Fields outside this\n * list are immutable; a change to one constitutes a new entity (its\n * `contentHash` differs). Used by {@link IWritePolicy.applyUpdate} to\n * restrict which fields the patch applies.\n */\n readonly mutableFields: ReadonlyArray<string>;\n\n /**\n * The granularity at which the store deduplicates an incoming write for this\n * kind. Optional; when absent the store applies {@link DEFAULT_DEDUP_SCOPE}\n * (`'entity'`). See {@link DedupScope}.\n */\n readonly dedupScope?: DedupScope;\n\n /**\n * Determine whether the incoming record is admitted.\n * @param incoming - The record about to be written.\n * @param existing - The admission cohort the kind's cap applies to: the\n * records in the same scope of the same kind, EXCLUDING the record at\n * `incoming`'s target id. Empty on a first write into an empty cohort.\n * Excluding the target id makes the post-write count uniform\n * (`existing.length + 1`) across first-writes and same-id updates. A\n * last-write-wins policy that has no cap ignores this argument.\n * @returns A {@link AdmissionDecision}.\n */\n admit(\n incoming: IMemoryRecord<unknown>,\n existing: ReadonlyArray<IMemoryRecord<unknown>>\n ): Result<AdmissionDecision>;\n\n /**\n * Apply a JSON Merge Patch (RFC-7386) to the mutable fields of an existing\n * record. Called when admission is `accept` AND a record with the same\n * `entityId` already exists (an update, not a first write).\n *\n * @param existing - The current persisted record.\n * @param patch - A partial JSON object in Merge Patch format. `null`\n * deletes the corresponding key; arrays replace wholesale; nested objects\n * deep-merge. Only keys in {@link IWritePolicy.mutableFields} are applied.\n * @returns The updated record (envelope + body).\n */\n applyUpdate(\n existing: IMemoryRecord<unknown>,\n patch: Record<string, unknown>\n ): Result<IMemoryRecord<unknown>>;\n}\n\n/**\n * RFC-7386-compliant merge options for {@link IWritePolicy.applyUpdate}.\n *\n * @remarks\n * Phase-A verification (design-lock §5.1) confirmed `@fgv/ts-json`'s\n * `JsonEditor` diverges from RFC-7386 under its defaults on two axes —\n * `nullAsDelete` defaults `false` and `arrayMergeBehavior` defaults\n * `'append'`. Both are corrected here via the existing option surface, so the\n * primitive is composed (not extended, not hand-rolled).\n */\nconst MERGE_PATCH_OPTIONS: Partial<IJsonEditorOptions> = {\n merge: {\n nullAsDelete: true,\n arrayMergeBehavior: 'replace'\n }\n};\n\n/**\n * Last-write-wins write policy for the knowledge kind family. Admission\n * always accepts (no cap, no cull); updates apply an RFC-7386 merge patch\n * restricted to the knowledge mutable surface.\n *\n * @remarks\n * **Merge-surface pin (resolves design-lock §5.3's body-vs-envelope muddle).**\n * The declared `mutableFields` span both axes of a record: `body` is the\n * per-kind body, while `tags` / `links` / `provenance` / `embeddingRef` live\n * on the {@link IMemoryEnvelope}. `applyUpdate` projects exactly those fields\n * — each read from its canonical location — into a single record-level JSON\n * view, runs the merge over that view, then rebuilds a coherent record. The\n * identity and transaction-time envelope fields (`id`, `entityId`, `kind`,\n * `created`, `updated`, `seq`, `contentHash`) are NOT mutable and are\n * preserved verbatim; the store stamps `updated` / `seq` on write.\n * @public\n */\nexport class KnowledgeLwwPolicy implements IWritePolicy {\n /**\n * The knowledge mutable surface: the body plus the envelope metadata a\n * consumer may revise without minting a new entity.\n */\n public readonly mutableFields: ReadonlyArray<string> = [\n 'body',\n 'tags',\n 'links',\n 'provenance',\n 'embeddingRef'\n ];\n\n /**\n * Knowledge dedups scope-wide: an identical `{ kind, body, links }` triple\n * anywhere in the `knowledge` scope — even under a different `docId` — is a\n * no-op. Declared explicitly so the B1 content-dedup behavior (and its tests)\n * are unchanged by the {@link DedupScope} amendment.\n */\n public readonly dedupScope: DedupScope = 'content';\n\n /** Deep-clones the mutable view without RFC-7386 null-deletion semantics. */\n private readonly _cloneEditor: JsonEditor;\n /** Applies the RFC-7386 merge patch. */\n private readonly _mergeEditor: JsonEditor;\n\n private constructor(cloneEditor: JsonEditor, mergeEditor: JsonEditor) {\n this._cloneEditor = cloneEditor;\n this._mergeEditor = mergeEditor;\n }\n\n /**\n * Family-convention factory. Constructs the shared `JsonEditor` instances\n * (one for cloning, one for the RFC-7386 merge), both with the template /\n * conditional / multivalue / reference rules disabled (empty rules array).\n */\n public static create(): Result<KnowledgeLwwPolicy> {\n return JsonEditor.create({}, []).onSuccess((cloneEditor) =>\n JsonEditor.create(MERGE_PATCH_OPTIONS, []).onSuccess((mergeEditor) =>\n succeed(new KnowledgeLwwPolicy(cloneEditor, mergeEditor))\n )\n );\n }\n\n /** {@inheritDoc IWritePolicy.admit} */\n public admit(\n __incoming: IMemoryRecord<unknown>,\n __existing: ReadonlyArray<IMemoryRecord<unknown>>\n ): Result<AdmissionDecision> {\n // Last-write-wins: always accept. No cap, no cull.\n return succeed({ decision: 'accept' });\n }\n\n /** {@inheritDoc IWritePolicy.applyUpdate} */\n public applyUpdate(\n existing: IMemoryRecord<unknown>,\n patch: Record<string, unknown>\n ): Result<IMemoryRecord<unknown>> {\n // Project the mutable fields into a single record-level view, each sourced\n // from its canonical location. `embeddingRef` is omitted when `undefined`\n // (the editor rejects undefined property values).\n const view: Record<string, unknown> = {\n body: existing.body,\n tags: existing.envelope.tags,\n links: existing.envelope.links,\n provenance: existing.envelope.provenance\n };\n if (existing.envelope.embeddingRef !== undefined) {\n view.embeddingRef = existing.envelope.embeddingRef;\n }\n\n // Restrict the incoming patch to the declared mutable fields; out-of-scope\n // keys are never applied (the store enforces the same constraint).\n const scopedPatch: Record<string, unknown> = {};\n for (const field of this.mutableFields) {\n if (field in patch) {\n scopedPatch[field] = patch[field];\n }\n }\n\n // Clone the view (no null-deletion), then apply the RFC-7386 merge patch\n // onto the clone so the persisted record is never mutated in place.\n return this._cloneEditor\n .mergeObjectInPlace({}, view as JsonObject)\n .onSuccess((clone) => this._mergeEditor.mergeObjectInPlace(clone, scopedPatch as JsonObject))\n .onSuccess((merged) => this._rebuild(existing, merged));\n }\n\n /**\n * Reassemble a record from the merged mutable view. `body` / `tags` /\n * `links` / `provenance` are required and may not be deleted by a patch.\n * `embeddingRef` is optional: when it is absent from the merged view —\n * because the existing record never carried it OR a `null` patch deleted it\n * (RFC-7386) — it is restored as `undefined` (absent), NOT `null`. This keeps\n * an originally-absent `embeddingRef` from silently flipping to `null` on an\n * unrelated update, so the field round-trips hash-stably through the store's\n * content-hash recomputation.\n */\n private _rebuild(existing: IMemoryRecord<unknown>, merged: JsonObject): Result<IMemoryRecord<unknown>> {\n const required: ReadonlyArray<string> = ['body', 'tags', 'links', 'provenance'];\n const missing: ReadonlyArray<string> = required.filter((field) => !(field in merged));\n if (missing.length > 0) {\n return fail(`knowledge LWW: merge patch may not delete required field(s): ${missing.join(', ')}`);\n }\n\n // The merged values are JSON projections of the already-validated typed\n // record; restore the domain types. (The types packlet cannot import the\n // converters packlet without a cycle, so these are structural restorations\n // of fields the merge preserved, not fresh untrusted input.)\n const envelope: IMemoryEnvelope = {\n ...existing.envelope,\n tags: merged.tags as unknown as ReadonlyArray<Tag>,\n links: merged.links as unknown as ReadonlyArray<IEdge>,\n provenance: merged.provenance as unknown as IProvenance,\n embeddingRef: 'embeddingRef' in merged ? (merged.embeddingRef as string | null) : undefined\n };\n return succeed({ envelope, body: merged.body });\n }\n}\n\n/**\n * Parameters for {@link MemoryCapCullPolicy.create}.\n * @public\n */\nexport interface IMemoryCapCullPolicyParams {\n /**\n * Maximum number of records the policy admits before culling the oldest.\n * Counted over the `existing` cohort passed to {@link IWritePolicy.admit}.\n * Absent = no cap (admission always accepts).\n */\n readonly maxRecords?: number;\n /**\n * The fields a merge-patch update may touch (drawn from the record-level\n * mutable vocabulary: `body` / `tags` / `links` / `provenance` /\n * `embeddingRef`). Fields outside this list are immutable.\n */\n readonly mutableFields: ReadonlyArray<string>;\n}\n\n/**\n * The record-level fields a {@link MemoryCapCullPolicy} merge-patch may project,\n * mapped to their canonical location on a record. Mirrors the store's\n * mutable-field accessor vocabulary; a declared mutable field outside this set\n * is inert (the store cannot project it either).\n */\nconst CAP_CULL_FIELD_READERS: ReadonlyMap<string, (record: IMemoryRecord<unknown>) => unknown> = new Map<\n string,\n (record: IMemoryRecord<unknown>) => unknown\n>([\n ['body', (r) => r.body],\n ['tags', (r) => r.envelope.tags],\n ['links', (r) => r.envelope.links],\n ['provenance', (r) => r.envelope.provenance],\n ['embeddingRef', (r) => r.envelope.embeddingRef]\n]);\n\n/** The record-level mutable fields that may never be deleted by a merge patch. */\nconst CAP_CULL_REQUIRED_FIELDS: ReadonlySet<string> = new Set<string>([\n 'body',\n 'tags',\n 'links',\n 'provenance'\n]);\n\n/**\n * Bounded-ring write policy for the experience (memory) kind families.\n * Admission accepts until `maxRecords` is reached, then evicts the oldest\n * record(s) by `created` ascending (design-lock §5.3); updates apply the same\n * RFC-7386 merge patch as {@link KnowledgeLwwPolicy}, restricted to the declared\n * {@link IMemoryCapCullPolicyParams.mutableFields | mutableFields}.\n *\n * @remarks\n * - **Dedup scope.** Declares `dedupScope: 'entity'` — two distinct memory\n * entities (e.g. `turn-5` / `turn-9`) with identical `{ kind, body, links }`\n * never collapse; only an identical re-put of the SAME entity is a no-op.\n * - **Eviction boundary.** `admit` only DECIDES (returns the `MemoryId`s to\n * evict); the store executes the file deletions and index patches. The\n * `existing` cohort the cap counts against is whatever the store supplies to\n * `admit`.\n * @public\n */\nexport class MemoryCapCullPolicy implements IWritePolicy {\n /** {@inheritDoc IWritePolicy.mutableFields} */\n public readonly mutableFields: ReadonlyArray<string>;\n\n /** Experience kinds dedup per-entity (see the class remarks). */\n public readonly dedupScope: DedupScope = 'entity';\n\n /** The admission cap; `undefined` = no cap. */\n private readonly _maxRecords: number | undefined;\n /** Deep-clones the mutable view without RFC-7386 null-deletion semantics. */\n private readonly _cloneEditor: JsonEditor;\n /** Applies the RFC-7386 merge patch. */\n private readonly _mergeEditor: JsonEditor;\n\n private constructor(params: IMemoryCapCullPolicyParams, cloneEditor: JsonEditor, mergeEditor: JsonEditor) {\n this.mutableFields = params.mutableFields;\n this._maxRecords = params.maxRecords;\n this._cloneEditor = cloneEditor;\n this._mergeEditor = mergeEditor;\n }\n\n /**\n * Family-convention factory. Constructs the shared `JsonEditor` instances\n * (one for cloning, one for the RFC-7386 merge) with the same merge config as\n * {@link KnowledgeLwwPolicy} (`nullAsDelete` true, `arrayMergeBehavior`\n * `'replace'`, rules disabled).\n */\n public static create(params: IMemoryCapCullPolicyParams): Result<MemoryCapCullPolicy> {\n return JsonEditor.create({}, []).onSuccess((cloneEditor) =>\n JsonEditor.create(MERGE_PATCH_OPTIONS, []).onSuccess((mergeEditor) =>\n succeed(new MemoryCapCullPolicy(params, cloneEditor, mergeEditor))\n )\n );\n }\n\n /** {@inheritDoc IWritePolicy.admit} */\n public admit(\n __incoming: IMemoryRecord<unknown>,\n existing: ReadonlyArray<IMemoryRecord<unknown>>\n ): Result<AdmissionDecision> {\n if (this._maxRecords === undefined || existing.length < this._maxRecords) {\n return succeed({ decision: 'accept' });\n }\n // Cap reached: evict the oldest by `created` ascending so the post-write\n // count is exactly `maxRecords` (existing.length - maxRecords + 1 victims).\n const evict: ReadonlyArray<MemoryId> = [...existing]\n .sort((a, b) => a.envelope.created - b.envelope.created)\n .slice(0, existing.length - this._maxRecords + 1)\n .map((record) => record.envelope.id);\n return succeed({ decision: 'cull-oldest', evict });\n }\n\n /** {@inheritDoc IWritePolicy.applyUpdate} */\n public applyUpdate(\n existing: IMemoryRecord<unknown>,\n patch: Record<string, unknown>\n ): Result<IMemoryRecord<unknown>> {\n // Project the declared mutable fields (restricted to the known record-level\n // vocabulary) into a single record-level view from their canonical\n // locations. An `undefined` value is omitted (the editor rejects undefined\n // property values).\n const view: Record<string, unknown> = {};\n for (const field of this.mutableFields) {\n const reader: ((record: IMemoryRecord<unknown>) => unknown) | undefined =\n CAP_CULL_FIELD_READERS.get(field);\n if (reader !== undefined) {\n const value: unknown = reader(existing);\n if (value !== undefined) {\n view[field] = value;\n }\n }\n }\n\n // Restrict the incoming patch to the declared mutable fields.\n const scopedPatch: Record<string, unknown> = {};\n for (const field of this.mutableFields) {\n if (field in patch) {\n scopedPatch[field] = patch[field];\n }\n }\n\n // Clone the view (no null-deletion), then apply the RFC-7386 merge patch\n // onto the clone so the persisted record is never mutated in place.\n return this._cloneEditor\n .mergeObjectInPlace({}, view as JsonObject)\n .onSuccess((clone) => this._mergeEditor.mergeObjectInPlace(clone, scopedPatch as JsonObject))\n .onSuccess((merged) => this._rebuild(existing, merged));\n }\n\n /**\n * Reassemble a record from the merged mutable view. Only the declared mutable\n * fields are taken from the merge; undeclared fields are preserved verbatim\n * from `existing`. A `null` patch that deletes a *declared mutable* required\n * field (`body` / `tags` / `links` / `provenance`) is an error — a required\n * field that is NOT declared mutable simply falls through to its `existing.*`\n * value and is never at risk. `embeddingRef`, when mutable, is restored as\n * `undefined` (absent) if the merge dropped it — same hash-stable semantics as\n * {@link KnowledgeLwwPolicy}.\n */\n private _rebuild(existing: IMemoryRecord<unknown>, merged: JsonObject): Result<IMemoryRecord<unknown>> {\n const deleted: ReadonlyArray<string> = this.mutableFields.filter(\n (field) => CAP_CULL_REQUIRED_FIELDS.has(field) && !(field in merged)\n );\n if (deleted.length > 0) {\n return fail(`memory cap-cull: merge patch may not delete required field(s): ${deleted.join(', ')}`);\n }\n\n // The merged values are JSON projections of the already-validated typed\n // record; restore the domain types. (The types packlet cannot import the\n // converters packlet without a cycle, so these are structural restorations\n // of fields the merge preserved, not fresh untrusted input — mirrors\n // KnowledgeLwwPolicy._rebuild.)\n const embeddingRefMutable: boolean = this.mutableFields.includes('embeddingRef');\n const envelope: IMemoryEnvelope = {\n ...existing.envelope,\n tags: 'tags' in merged ? (merged.tags as unknown as ReadonlyArray<Tag>) : existing.envelope.tags,\n links: 'links' in merged ? (merged.links as unknown as ReadonlyArray<IEdge>) : existing.envelope.links,\n provenance:\n 'provenance' in merged ? (merged.provenance as unknown as IProvenance) : existing.envelope.provenance,\n embeddingRef: embeddingRefMutable\n ? 'embeddingRef' in merged\n ? (merged.embeddingRef as string | null)\n : undefined\n : existing.envelope.embeddingRef\n };\n return succeed({ envelope, body: 'body' in merged ? merged.body : existing.body });\n }\n}\n"]}
1
+ {"version":3,"file":"writePolicy.js","sourceRoot":"","sources":["../../../src/packlets/types/writePolicy.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,4CAAsD;AAEtD,0CAA8D;AAoB9D;;;;;GAKG;AACU,QAAA,mBAAmB,GAAe,QAAQ,CAAC;AAuExD;;;;;;;;;GASG;AACH,MAAM,mBAAmB,GAAgC;IACvD,KAAK,EAAE;QACL,YAAY,EAAE,IAAI;QAClB,kBAAkB,EAAE,SAAS;KAC9B;CACF,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,kBAAkB;IA0B7B,YAAoB,WAAuB,EAAE,WAAuB;QAzBpE;;;WAGG;QACa,kBAAa,GAA0B;YACrD,MAAM;YACN,MAAM;YACN,OAAO;YACP,YAAY;YACZ,cAAc;SACf,CAAC;QAEF;;;;;WAKG;QACa,eAAU,GAAe,SAAS,CAAC;QAQjD,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;QAChC,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;IAClC,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,MAAM;QAClB,OAAO,oBAAU,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,WAAW,EAAE,EAAE,CACzD,oBAAU,CAAC,MAAM,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,WAAW,EAAE,EAAE,CACnE,IAAA,kBAAO,EAAC,IAAI,kBAAkB,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,CAC1D,CACF,CAA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AED;;;;;OAKG;IACK,QAAQ,CAAC,QAAgC,EAAE,MAAkB;QACnE,MAAM,QAAQ,GAA0B,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC;QAChF,MAAM,OAAO,GAA0B,QAAQ,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,IAAI,MAAM,CAAC,CAAC,CAAC;QACtF,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACvB,OAAO,IAAA,eAAI,EAAC,qEAAqE,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACzG,CAAC;QAED,wEAAwE;QACxE,uEAAuE;QACvE,0DAA0D;QAC1D,MAAM,QAAQ,mCACT,QAAQ,CAAC,QAAQ,KACpB,IAAI,EAAE,MAAM,CAAC,IAAqC,EAClD,KAAK,EAAE,MAAM,CAAC,KAAwC,EACtD,UAAU,EAAE,MAAM,CAAC,UAAoC,EACvD,YAAY,EAAE,cAAc,IAAI,MAAM,CAAC,CAAC,CAAE,MAAM,CAAC,YAA8B,CAAC,CAAC,CAAC,SAAS,GAC5F,CAAC;QACF,OAAO,IAAA,kBAAO,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;IAClD,CAAC;CACF;AAxGD,0DAwGC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result, fail, succeed } from '@fgv/ts-utils';\nimport { JsonObject } from '@fgv/ts-json-base';\nimport { IJsonEditorOptions, JsonEditor } from '@fgv/ts-json';\nimport { IEdge, IMemoryEnvelope, IMemoryRecord, IProvenance } from './envelope';\nimport { MemoryId, Tag } from './ids';\n\n/**\n * The granularity at which the store deduplicates an incoming write against the\n * existing vault, declared per kind via {@link IWritePolicy.dedupScope}.\n *\n * - `'content'`: scope-wide cross-id content dedup. An identical\n * `{ kind, body, links }` triple ANYWHERE in the scope — even under a\n * different id — is a no-op that returns the existing record. The knowledge\n * kind family uses this.\n * - `'entity'`: same-id content dedup only. An identical re-put of the SAME\n * entity is a no-op, but two DISTINCT entities with identical content never\n * collapse. The experience (memory) kind families use this so that, e.g.,\n * two turns whose summaries happen to be byte-identical both persist.\n * @public\n */\nexport type DedupScope = 'content' | 'entity';\n\n/**\n * The default {@link DedupScope} applied when a policy does not declare one.\n * Entity-scoped dedup is the safe default — it never silently collapses two\n * distinct entities with coincidentally-identical content.\n * @public\n */\nexport const DEFAULT_DEDUP_SCOPE: DedupScope = 'entity';\n\n/**\n * The admission decision returned by {@link IWritePolicy.admit}.\n * @public\n */\nexport type AdmissionDecision =\n | { readonly decision: 'accept' }\n | { readonly decision: 'reject'; readonly reason: string }\n | {\n readonly decision: 'cull-oldest';\n /** {@link MemoryId}s to evict before writing the incoming record. */\n readonly evict: ReadonlyArray<MemoryId>;\n };\n\n/**\n * A per-kind write policy, injected at store construction. Invoked AFTER\n * content-hash dedup (dedup is always pre-policy). The policy decides\n * admission and, on update, applies a JSON Merge Patch (RFC-7386) restricted\n * to the declared mutable fields.\n * @public\n */\nexport interface IWritePolicy {\n /**\n * Names of the fields a merge-patch update may touch. Fields outside this\n * list are immutable; a change to one constitutes a new entity (its\n * `contentHash` differs). Used by {@link IWritePolicy.applyUpdate} to\n * restrict which fields the patch applies.\n */\n readonly mutableFields: ReadonlyArray<string>;\n\n /**\n * The granularity at which the store deduplicates an incoming write for this\n * kind. Optional; when absent the store applies {@link DEFAULT_DEDUP_SCOPE}\n * (`'entity'`). See {@link DedupScope}.\n */\n readonly dedupScope?: DedupScope;\n\n /**\n * Determine whether the incoming record is admitted.\n * @param incoming - The record about to be written.\n * @param existing - The admission cohort the kind's cap applies to: the\n * records in the same scope of the same kind, EXCLUDING the record at\n * `incoming`'s target id. Empty on a first write into an empty cohort.\n * Excluding the target id makes the post-write count uniform\n * (`existing.length + 1`) across first-writes and same-id updates. A\n * last-write-wins policy that has no cap ignores this argument.\n * @returns A {@link AdmissionDecision}.\n */\n admit(\n incoming: IMemoryRecord<unknown>,\n existing: ReadonlyArray<IMemoryRecord<unknown>>\n ): Result<AdmissionDecision>;\n\n /**\n * Apply a JSON Merge Patch (RFC-7386) to the mutable fields of an existing\n * record. Called when admission is `accept` AND a record with the same\n * `entityId` already exists (an update, not a first write).\n *\n * @param existing - The current persisted record.\n * @param patch - A partial JSON object in Merge Patch format. `null`\n * deletes the corresponding key; arrays replace wholesale; nested objects\n * deep-merge. Only keys in {@link IWritePolicy.mutableFields} are applied.\n * @returns The updated record (envelope + body).\n */\n applyUpdate(\n existing: IMemoryRecord<unknown>,\n patch: Record<string, unknown>\n ): Result<IMemoryRecord<unknown>>;\n}\n\n/**\n * RFC-7386-compliant merge options for {@link IWritePolicy.applyUpdate}.\n *\n * @remarks\n * Phase-A verification (design-lock §5.1) confirmed `@fgv/ts-json`'s\n * `JsonEditor` diverges from RFC-7386 under its defaults on two axes —\n * `nullAsDelete` defaults `false` and `arrayMergeBehavior` defaults\n * `'append'`. Both are corrected here via the existing option surface, so the\n * primitive is composed (not extended, not hand-rolled).\n */\nconst MERGE_PATCH_OPTIONS: Partial<IJsonEditorOptions> = {\n merge: {\n nullAsDelete: true,\n arrayMergeBehavior: 'replace'\n }\n};\n\n/**\n * Last-write-wins write policy for the knowledge kind family. Admission\n * always accepts (no cap, no cull); updates apply an RFC-7386 merge patch\n * restricted to the knowledge mutable surface.\n *\n * @remarks\n * **Merge-surface pin (resolves design-lock §5.3's body-vs-envelope muddle).**\n * The declared `mutableFields` span both axes of a record: `body` is the\n * per-kind body, while `tags` / `links` / `provenance` / `embeddingRef` live\n * on the {@link IMemoryEnvelope}. `applyUpdate` projects exactly those fields\n * — each read from its canonical location — into a single record-level JSON\n * view, runs the merge over that view, then rebuilds a coherent record. The\n * identity and transaction-time envelope fields (`id`, `entityId`, `kind`,\n * `created`, `updated`, `seq`, `contentHash`) are NOT mutable and are\n * preserved verbatim; the store stamps `updated` / `seq` on write.\n * @public\n */\nexport class KnowledgeLwwPolicy implements IWritePolicy {\n /**\n * The knowledge mutable surface: the body plus the envelope metadata a\n * consumer may revise without minting a new entity.\n */\n public readonly mutableFields: ReadonlyArray<string> = [\n 'body',\n 'tags',\n 'links',\n 'provenance',\n 'embeddingRef'\n ];\n\n /**\n * Knowledge dedups scope-wide: an identical `{ kind, body, links }` triple\n * anywhere in the `knowledge` scope — even under a different `docId` — is a\n * no-op. Declared explicitly so the B1 content-dedup behavior (and its tests)\n * are unchanged by the {@link DedupScope} amendment.\n */\n public readonly dedupScope: DedupScope = 'content';\n\n /** Deep-clones the mutable view without RFC-7386 null-deletion semantics. */\n private readonly _cloneEditor: JsonEditor;\n /** Applies the RFC-7386 merge patch. */\n private readonly _mergeEditor: JsonEditor;\n\n private constructor(cloneEditor: JsonEditor, mergeEditor: JsonEditor) {\n this._cloneEditor = cloneEditor;\n this._mergeEditor = mergeEditor;\n }\n\n /**\n * Family-convention factory. Constructs the shared `JsonEditor` instances\n * (one for cloning, one for the RFC-7386 merge), both with the template /\n * conditional / multivalue / reference rules disabled (empty rules array).\n */\n public static create(): Result<KnowledgeLwwPolicy> {\n return JsonEditor.create({}, []).onSuccess((cloneEditor) =>\n JsonEditor.create(MERGE_PATCH_OPTIONS, []).onSuccess((mergeEditor) =>\n succeed(new KnowledgeLwwPolicy(cloneEditor, mergeEditor))\n )\n );\n }\n\n /** {@inheritDoc IWritePolicy.admit} */\n public admit(\n __incoming: IMemoryRecord<unknown>,\n __existing: ReadonlyArray<IMemoryRecord<unknown>>\n ): Result<AdmissionDecision> {\n // Last-write-wins: always accept. No cap, no cull.\n return succeed({ decision: 'accept' });\n }\n\n /** {@inheritDoc IWritePolicy.applyUpdate} */\n public applyUpdate(\n existing: IMemoryRecord<unknown>,\n patch: Record<string, unknown>\n ): Result<IMemoryRecord<unknown>> {\n // Project the mutable fields into a single record-level view, each sourced\n // from its canonical location. `embeddingRef` is omitted when `undefined`\n // (the editor rejects undefined property values).\n const view: Record<string, unknown> = {\n body: existing.body,\n tags: existing.envelope.tags,\n links: existing.envelope.links,\n provenance: existing.envelope.provenance\n };\n if (existing.envelope.embeddingRef !== undefined) {\n view.embeddingRef = existing.envelope.embeddingRef;\n }\n\n // Restrict the incoming patch to the declared mutable fields; out-of-scope\n // keys are never applied (the store enforces the same constraint).\n const scopedPatch: Record<string, unknown> = {};\n for (const field of this.mutableFields) {\n if (field in patch) {\n scopedPatch[field] = patch[field];\n }\n }\n\n // Clone the view (no null-deletion), then apply the RFC-7386 merge patch\n // onto the clone so the persisted record is never mutated in place.\n return this._cloneEditor\n .mergeObjectInPlace({}, view as JsonObject)\n .onSuccess((clone) => this._mergeEditor.mergeObjectInPlace(clone, scopedPatch as JsonObject))\n .onSuccess((merged) => this._rebuild(existing, merged));\n }\n\n /**\n * Reassemble a record from the merged mutable view. `body` / `tags` /\n * `links` / `provenance` are required and may not be deleted by a patch.\n * `embeddingRef` is optional: when it is absent from the merged view —\n * because the existing record never carried it OR a `null` patch deleted it\n * (RFC-7386) — it is restored as `undefined` (absent), NOT `null`. This keeps\n * an originally-absent `embeddingRef` from silently flipping to `null` on an\n * unrelated update, so the field round-trips hash-stably through the store's\n * content-hash recomputation.\n */\n private _rebuild(existing: IMemoryRecord<unknown>, merged: JsonObject): Result<IMemoryRecord<unknown>> {\n const required: ReadonlyArray<string> = ['body', 'tags', 'links', 'provenance'];\n const missing: ReadonlyArray<string> = required.filter((field) => !(field in merged));\n if (missing.length > 0) {\n return fail(`knowledge LWW: merge patch may not delete required field(s): ${missing.join(', ')}`);\n }\n\n // The merged values are JSON projections of the already-validated typed\n // record; restore the domain types. (The types packlet cannot import the\n // converters packlet without a cycle, so these are structural restorations\n // of fields the merge preserved, not fresh untrusted input.)\n const envelope: IMemoryEnvelope = {\n ...existing.envelope,\n tags: merged.tags as unknown as ReadonlyArray<Tag>,\n links: merged.links as unknown as ReadonlyArray<IEdge>,\n provenance: merged.provenance as unknown as IProvenance,\n embeddingRef: 'embeddingRef' in merged ? (merged.embeddingRef as string | null) : undefined\n };\n return succeed({ envelope, body: merged.body });\n }\n}\n\n/**\n * Parameters for {@link MemoryCapCullPolicy.create}.\n * @public\n */\nexport interface IMemoryCapCullPolicyParams {\n /**\n * Maximum number of records the policy admits before culling the oldest.\n * Counted over the `existing` cohort passed to {@link IWritePolicy.admit}.\n * Absent = no cap (admission always accepts).\n */\n readonly maxRecords?: number;\n /**\n * The fields a merge-patch update may touch (drawn from the record-level\n * mutable vocabulary: `body` / `tags` / `links` / `provenance` /\n * `embeddingRef`). Fields outside this list are immutable.\n */\n readonly mutableFields: ReadonlyArray<string>;\n}\n\n/**\n * The record-level fields a {@link MemoryCapCullPolicy} merge-patch may project,\n * mapped to their canonical location on a record. Mirrors the store's\n * mutable-field accessor vocabulary; a declared mutable field outside this set\n * is inert (the store cannot project it either).\n */\nconst CAP_CULL_FIELD_READERS: ReadonlyMap<string, (record: IMemoryRecord<unknown>) => unknown> = new Map<\n string,\n (record: IMemoryRecord<unknown>) => unknown\n>([\n ['body', (r) => r.body],\n ['tags', (r) => r.envelope.tags],\n ['links', (r) => r.envelope.links],\n ['provenance', (r) => r.envelope.provenance],\n ['embeddingRef', (r) => r.envelope.embeddingRef]\n]);\n\n/** The record-level mutable fields that may never be deleted by a merge patch. */\nconst CAP_CULL_REQUIRED_FIELDS: ReadonlySet<string> = new Set<string>([\n 'body',\n 'tags',\n 'links',\n 'provenance'\n]);\n\n/**\n * Bounded-ring write policy for the experience (memory) kind families.\n * Admission accepts until `maxRecords` is reached, then evicts the oldest\n * record(s) by `created` ascending (design-lock §5.3); updates apply the same\n * RFC-7386 merge patch as {@link KnowledgeLwwPolicy}, restricted to the declared\n * {@link IMemoryCapCullPolicyParams.mutableFields | mutableFields}.\n *\n * @remarks\n * - **Dedup scope.** Declares `dedupScope: 'entity'` — two distinct memory\n * entities (e.g. `turn-5` / `turn-9`) with identical `{ kind, body, links }`\n * never collapse; only an identical re-put of the SAME entity is a no-op.\n * - **Eviction boundary.** `admit` only DECIDES (returns the `MemoryId`s to\n * evict); the store executes the file deletions and index patches. The\n * `existing` cohort the cap counts against is whatever the store supplies to\n * `admit`.\n * @public\n */\nexport class MemoryCapCullPolicy implements IWritePolicy {\n /** {@inheritDoc IWritePolicy.mutableFields} */\n public readonly mutableFields: ReadonlyArray<string>;\n\n /** Experience kinds dedup per-entity (see the class remarks). */\n public readonly dedupScope: DedupScope = 'entity';\n\n /** The admission cap; `undefined` = no cap. */\n private readonly _maxRecords: number | undefined;\n /** Deep-clones the mutable view without RFC-7386 null-deletion semantics. */\n private readonly _cloneEditor: JsonEditor;\n /** Applies the RFC-7386 merge patch. */\n private readonly _mergeEditor: JsonEditor;\n\n private constructor(params: IMemoryCapCullPolicyParams, cloneEditor: JsonEditor, mergeEditor: JsonEditor) {\n this.mutableFields = params.mutableFields;\n this._maxRecords = params.maxRecords;\n this._cloneEditor = cloneEditor;\n this._mergeEditor = mergeEditor;\n }\n\n /**\n * Family-convention factory. Constructs the shared `JsonEditor` instances\n * (one for cloning, one for the RFC-7386 merge) with the same merge config as\n * {@link KnowledgeLwwPolicy} (`nullAsDelete` true, `arrayMergeBehavior`\n * `'replace'`, rules disabled).\n */\n public static create(params: IMemoryCapCullPolicyParams): Result<MemoryCapCullPolicy> {\n return JsonEditor.create({}, []).onSuccess((cloneEditor) =>\n JsonEditor.create(MERGE_PATCH_OPTIONS, []).onSuccess((mergeEditor) =>\n succeed(new MemoryCapCullPolicy(params, cloneEditor, mergeEditor))\n )\n );\n }\n\n /** {@inheritDoc IWritePolicy.admit} */\n public admit(\n __incoming: IMemoryRecord<unknown>,\n existing: ReadonlyArray<IMemoryRecord<unknown>>\n ): Result<AdmissionDecision> {\n if (this._maxRecords === undefined || existing.length < this._maxRecords) {\n return succeed({ decision: 'accept' });\n }\n // Cap reached: evict the oldest by `created` ascending so the post-write\n // count is exactly `maxRecords` (existing.length - maxRecords + 1 victims).\n const evict: ReadonlyArray<MemoryId> = [...existing]\n .sort((a, b) => a.envelope.created - b.envelope.created)\n .slice(0, existing.length - this._maxRecords + 1)\n .map((record) => record.envelope.id);\n return succeed({ decision: 'cull-oldest', evict });\n }\n\n /** {@inheritDoc IWritePolicy.applyUpdate} */\n public applyUpdate(\n existing: IMemoryRecord<unknown>,\n patch: Record<string, unknown>\n ): Result<IMemoryRecord<unknown>> {\n // Project the declared mutable fields (restricted to the known record-level\n // vocabulary) into a single record-level view from their canonical\n // locations. An `undefined` value is omitted (the editor rejects undefined\n // property values).\n const view: Record<string, unknown> = {};\n for (const field of this.mutableFields) {\n const reader: ((record: IMemoryRecord<unknown>) => unknown) | undefined =\n CAP_CULL_FIELD_READERS.get(field);\n if (reader !== undefined) {\n const value: unknown = reader(existing);\n if (value !== undefined) {\n view[field] = value;\n }\n }\n }\n\n // Restrict the incoming patch to the declared mutable fields.\n const scopedPatch: Record<string, unknown> = {};\n for (const field of this.mutableFields) {\n if (field in patch) {\n scopedPatch[field] = patch[field];\n }\n }\n\n // Clone the view (no null-deletion), then apply the RFC-7386 merge patch\n // onto the clone so the persisted record is never mutated in place.\n return this._cloneEditor\n .mergeObjectInPlace({}, view as JsonObject)\n .onSuccess((clone) => this._mergeEditor.mergeObjectInPlace(clone, scopedPatch as JsonObject))\n .onSuccess((merged) => this._rebuild(existing, merged));\n }\n\n /**\n * Reassemble a record from the merged mutable view. Only the declared mutable\n * fields are taken from the merge; undeclared fields are preserved verbatim\n * from `existing`. A `null` patch that deletes a *declared mutable* required\n * field (`body` / `tags` / `links` / `provenance`) is an error — a required\n * field that is NOT declared mutable simply falls through to its `existing.*`\n * value and is never at risk. `embeddingRef`, when mutable, is restored as\n * `undefined` (absent) if the merge dropped it — same hash-stable semantics as\n * {@link KnowledgeLwwPolicy}.\n */\n private _rebuild(existing: IMemoryRecord<unknown>, merged: JsonObject): Result<IMemoryRecord<unknown>> {\n const deleted: ReadonlyArray<string> = this.mutableFields.filter(\n (field) => CAP_CULL_REQUIRED_FIELDS.has(field) && !(field in merged)\n );\n if (deleted.length > 0) {\n return fail(`memory cap-cull: merge patch may not delete required field(s): ${deleted.join(', ')}`);\n }\n\n // The merged values are JSON projections of the already-validated typed\n // record; restore the domain types. (The types packlet cannot import the\n // converters packlet without a cycle, so these are structural restorations\n // of fields the merge preserved, not fresh untrusted input — mirrors\n // KnowledgeLwwPolicy._rebuild.)\n const embeddingRefMutable: boolean = this.mutableFields.includes('embeddingRef');\n const envelope: IMemoryEnvelope = {\n ...existing.envelope,\n tags: 'tags' in merged ? (merged.tags as unknown as ReadonlyArray<Tag>) : existing.envelope.tags,\n links: 'links' in merged ? (merged.links as unknown as ReadonlyArray<IEdge>) : existing.envelope.links,\n provenance:\n 'provenance' in merged ? (merged.provenance as unknown as IProvenance) : existing.envelope.provenance,\n embeddingRef: embeddingRefMutable\n ? 'embeddingRef' in merged\n ? (merged.embeddingRef as string | null)\n : undefined\n : existing.envelope.embeddingRef\n };\n return succeed({ envelope, body: 'body' in merged ? merged.body : existing.body });\n }\n}\n\n/**\n * Write policy for a versioned (temporal) kind family, implementing\n * invalidate-don't-delete. Admission always accepts — history is retained, never\n * culled — and updates apply the same RFC-7386 merge patch as\n * {@link KnowledgeLwwPolicy}, restricted to the temporal mutable surface.\n *\n * @remarks\n * The policy does NOT perform the version file writes or set `invalid_at` — that\n * is the store's versioned write branch, driven by the kind's\n * {@link ITemporalIdentityCodec}. The policy's role is limited to admission and\n * the merge that forms the **new version's** content from the **current**\n * version plus the incoming patch (the merge-patch-under-versioning contract).\n *\n * - **Dedup scope.** `'entity'` — an identical re-put of the current content is a\n * no-op (the store compares the incoming content hash against the current\n * version), so identical writes do not spawn redundant versions.\n * - **Mutable surface.** `body` + the envelope metadata a consumer may revise\n * (`tags` / `links` / `provenance` / `embeddingRef`). `temporal` is NOT mutable\n * here — `valid_at` / `invalid_at` are set by the store's versioned branch.\n * @public\n */\nexport class TemporalVersionedPolicy implements IWritePolicy {\n /** The temporal mutable surface (mirrors {@link KnowledgeLwwPolicy}). */\n public readonly mutableFields: ReadonlyArray<string> = [\n 'body',\n 'tags',\n 'links',\n 'provenance',\n 'embeddingRef'\n ];\n\n /** Versioned kinds dedup per-entity against the current version (see the class remarks). */\n public readonly dedupScope: DedupScope = 'entity';\n\n /** Deep-clones the mutable view without RFC-7386 null-deletion semantics. */\n private readonly _cloneEditor: JsonEditor;\n /** Applies the RFC-7386 merge patch. */\n private readonly _mergeEditor: JsonEditor;\n\n private constructor(cloneEditor: JsonEditor, mergeEditor: JsonEditor) {\n this._cloneEditor = cloneEditor;\n this._mergeEditor = mergeEditor;\n }\n\n /**\n * Family-convention factory. Constructs the shared `JsonEditor` instances (one\n * for cloning, one for the RFC-7386 merge), rules disabled — the same merge\n * config as the shipped policies.\n */\n public static create(): Result<TemporalVersionedPolicy> {\n return JsonEditor.create({}, []).onSuccess((cloneEditor) =>\n JsonEditor.create(MERGE_PATCH_OPTIONS, []).onSuccess((mergeEditor) =>\n succeed(new TemporalVersionedPolicy(cloneEditor, mergeEditor))\n )\n );\n }\n\n /** {@inheritDoc IWritePolicy.admit} */\n public admit(\n __incoming: IMemoryRecord<unknown>,\n __existing: ReadonlyArray<IMemoryRecord<unknown>>\n ): Result<AdmissionDecision> {\n // Invalidate-don't-delete: always accept. Superseded versions are retained\n // (invalidated), never culled.\n return succeed({ decision: 'accept' });\n }\n\n /** {@inheritDoc IWritePolicy.applyUpdate} */\n public applyUpdate(\n existing: IMemoryRecord<unknown>,\n patch: Record<string, unknown>\n ): Result<IMemoryRecord<unknown>> {\n // Project the mutable fields into a single record-level view, each sourced\n // from its canonical location. `embeddingRef` is omitted when `undefined`.\n const view: Record<string, unknown> = {\n body: existing.body,\n tags: existing.envelope.tags,\n links: existing.envelope.links,\n provenance: existing.envelope.provenance\n };\n if (existing.envelope.embeddingRef !== undefined) {\n view.embeddingRef = existing.envelope.embeddingRef;\n }\n\n // Restrict the incoming patch to the declared mutable fields.\n const scopedPatch: Record<string, unknown> = {};\n for (const field of this.mutableFields) {\n if (field in patch) {\n scopedPatch[field] = patch[field];\n }\n }\n\n // Clone the view (no null-deletion), then apply the RFC-7386 merge patch onto\n // the clone so the current version is never mutated in place.\n return this._cloneEditor\n .mergeObjectInPlace({}, view as JsonObject)\n .onSuccess((clone) => this._mergeEditor.mergeObjectInPlace(clone, scopedPatch as JsonObject))\n .onSuccess((merged) => this._rebuild(existing, merged));\n }\n\n /**\n * Reassemble a record from the merged mutable view. `body` / `tags` / `links` /\n * `provenance` are required and may not be deleted by a patch; `embeddingRef`,\n * when dropped by the merge, is restored as `undefined` (absent) — the same\n * hash-stable semantics as {@link KnowledgeLwwPolicy}.\n */\n private _rebuild(existing: IMemoryRecord<unknown>, merged: JsonObject): Result<IMemoryRecord<unknown>> {\n const required: ReadonlyArray<string> = ['body', 'tags', 'links', 'provenance'];\n const missing: ReadonlyArray<string> = required.filter((field) => !(field in merged));\n if (missing.length > 0) {\n return fail(`temporal versioned: merge patch may not delete required field(s): ${missing.join(', ')}`);\n }\n\n // The merged values are JSON projections of the already-validated typed\n // record; restore the domain types (structural restorations, not fresh\n // untrusted input — mirrors KnowledgeLwwPolicy._rebuild).\n const envelope: IMemoryEnvelope = {\n ...existing.envelope,\n tags: merged.tags as unknown as ReadonlyArray<Tag>,\n links: merged.links as unknown as ReadonlyArray<IEdge>,\n provenance: merged.provenance as unknown as IProvenance,\n embeddingRef: 'embeddingRef' in merged ? (merged.embeddingRef as string | null) : undefined\n };\n return succeed({ envelope, body: merged.body });\n }\n}\n"]}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Antagonist torture test — convert/validate round-trip symmetry (target class
3
+ * 7): every OPTIONAL field the envelope/edge/provenance shapes carry must
4
+ * survive a full on-disk round-trip (serialize → YAML text → parse), not just a
5
+ * single `Converter.convert` pass in memory. This exercises the exact path a
6
+ * corrupted or field-dropping serializer/parser pair would break, mirroring the
7
+ * `aiClientToolConfig`/`annotations` field-drop class named in the brief.
8
+ */
9
+ import '@fgv/ts-utils-jest';
10
+ //# sourceMappingURL=antagonistRoundTrip.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"antagonistRoundTrip.test.d.ts","sourceRoot":"","sources":["../../../../src/test/unit/converters/antagonistRoundTrip.test.ts"],"names":[],"mappings":"AAKA;;;;;;;GAOG;AAEH,OAAO,oBAAoB,CAAC"}
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2026 Erik Fortune
4
+ * SPDX-License-Identifier: MIT
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ /**
8
+ * Antagonist torture test — convert/validate round-trip symmetry (target class
9
+ * 7): every OPTIONAL field the envelope/edge/provenance shapes carry must
10
+ * survive a full on-disk round-trip (serialize → YAML text → parse), not just a
11
+ * single `Converter.convert` pass in memory. This exercises the exact path a
12
+ * corrupted or field-dropping serializer/parser pair would break, mirroring the
13
+ * `aiClientToolConfig`/`annotations` field-drop class named in the brief.
14
+ */
15
+ require("@fgv/ts-utils-jest");
16
+ const ts_utils_1 = require("@fgv/ts-utils");
17
+ const index_1 = require("../../../index");
18
+ const kind = 'note';
19
+ function registry() {
20
+ const reg = index_1.BodyConverterRegistry.create().orThrow();
21
+ reg.register(kind, ts_utils_1.Converters.string);
22
+ return reg;
23
+ }
24
+ describe('antagonist — full on-disk round-trip preserves every optional field', () => {
25
+ // Wrong impl this catches: a serializer/parser pair where one side silently
26
+ // drops an optional field (the exact class of bug the brief calls out for
27
+ // `aiClientToolConfig`/`annotations`-shaped converters) — e.g. omitting
28
+ // `temporal.invalid_at: null`, an edge's `valid_at`/`invalid_at`/`provenance`,
29
+ // a `null` `embeddingRef`, or a provenance extension key, because the author
30
+ // forgot to thread it through both the YAML emit AND the envelope Converter.
31
+ test('every optional envelope/edge/provenance field set simultaneously survives a full YAML round-trip', () => {
32
+ const envelope = {
33
+ id: 'doc-1',
34
+ entityId: 'doc-1',
35
+ kind,
36
+ tags: ['t1', 't2'],
37
+ links: [
38
+ {
39
+ type: 'rel',
40
+ target: 'doc-2',
41
+ confidence: 0.42,
42
+ provenance: { source: 'agent', by: 'curator', extra: { nested: true } },
43
+ valid_at: 111,
44
+ invalid_at: null
45
+ }
46
+ ],
47
+ created: 1000,
48
+ updated: 2000,
49
+ seq: 7,
50
+ contentHash: 'abc123',
51
+ provenance: {
52
+ source: 'host-ingest',
53
+ by: 'erik',
54
+ model: 'gpt-5',
55
+ confidence: 0.87,
56
+ derivedFrom: 'turn-3',
57
+ // Opaque extension keys (per IProvenance's `[key: string]: unknown` arm).
58
+ sentiment: { score: 0.5 },
59
+ epistemic: 'belief'
60
+ },
61
+ temporal: { valid_at: 500, invalid_at: null },
62
+ embeddingRef: null
63
+ };
64
+ const raw = (0, index_1.serializeMemoryFile)(envelope, 'the body text').orThrow();
65
+ expect((0, index_1.parseMemoryFile)(raw, registry())).toSucceedAndSatisfy((record) => {
66
+ // Deep-equal the ENTIRE envelope, not field-by-field — a partial assertion
67
+ // list is exactly how a single dropped field slips through review.
68
+ expect(record.envelope).toEqual(envelope);
69
+ expect(record.body).toBe('the body text');
70
+ });
71
+ });
72
+ test('an absent temporal/embeddingRef/edge-optionals round-trips to fully absent (no null-vs-undefined drift)', () => {
73
+ const envelope = {
74
+ id: 'doc-2',
75
+ entityId: 'doc-2',
76
+ kind,
77
+ tags: [],
78
+ links: [{ type: 'rel', target: 'doc-3' }],
79
+ created: 0,
80
+ updated: 0,
81
+ seq: 0,
82
+ contentHash: '',
83
+ provenance: { source: 'agent' }
84
+ };
85
+ const raw = (0, index_1.serializeMemoryFile)(envelope, 'body').orThrow();
86
+ expect((0, index_1.parseMemoryFile)(raw, registry())).toSucceedAndSatisfy((record) => {
87
+ expect(record.envelope.temporal).toBeUndefined();
88
+ expect(record.envelope.embeddingRef).toBeUndefined();
89
+ expect(record.envelope.links[0].confidence).toBeUndefined();
90
+ expect(record.envelope.links[0].provenance).toBeUndefined();
91
+ expect(record.envelope.links[0].valid_at).toBeUndefined();
92
+ expect(record.envelope.links[0].invalid_at).toBeUndefined();
93
+ expect(record.envelope).toEqual(envelope);
94
+ });
95
+ });
96
+ });
97
+ //# sourceMappingURL=antagonistRoundTrip.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"antagonistRoundTrip.test.js","sourceRoot":"","sources":["../../../../src/test/unit/converters/antagonistRoundTrip.test.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAEH;;;;;;;GAOG;AAEH,8BAA4B;AAC5B,4CAA2C;AAC3C,0CAMwB;AAExB,MAAM,IAAI,GAAG,MAAiC,CAAC;AAE/C,SAAS,QAAQ;IACf,MAAM,GAAG,GAAG,6BAAqB,CAAC,MAAM,EAAE,CAAC,OAAO,EAAE,CAAC;IACrD,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,qBAAU,CAAC,MAAM,CAAC,CAAC;IACtC,OAAO,GAAG,CAAC;AACb,CAAC;AAED,QAAQ,CAAC,qEAAqE,EAAE,GAAG,EAAE;IACnF,4EAA4E;IAC5E,0EAA0E;IAC1E,wEAAwE;IACxE,+EAA+E;IAC/E,6EAA6E;IAC7E,6EAA6E;IAC7E,IAAI,CAAC,kGAAkG,EAAE,GAAG,EAAE;QAC5G,MAAM,QAAQ,GAAoB;YAChC,EAAE,EAAE,OAAgC;YACpC,QAAQ,EAAE,OAAsC;YAChD,IAAI;YACJ,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,CAAuC;YACxD,KAAK,EAAE;gBACL;oBACE,IAAI,EAAE,KAAc;oBACpB,MAAM,EAAE,OAAgB;oBACxB,UAAU,EAAE,IAAI;oBAChB,UAAU,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE;oBACvE,QAAQ,EAAE,GAAG;oBAEb,UAAU,EAAE,IAAI;iBACjB;aACF;YACD,OAAO,EAAE,IAAI;YACb,OAAO,EAAE,IAAI;YACb,GAAG,EAAE,CAAC;YACN,WAAW,EAAE,QAAQ;YAC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B,EAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,OAAO,EAAE,CAAC;QAC5D,MAAM,CAAC,IAAA,uBAAe,EAAC,GAAG,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,MAAM,EAAE,EAAE;YACtE,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,aAAa,EAAE,CAAC;YACjD,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,aAAa,EAAE,CAAC;YACrD,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,aAAa,EAAE,CAAC;YAC5D,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,aAAa,EAAE,CAAC;YAC5D,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,aAAa,EAAE,CAAC;YAC1D,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,aAAa,EAAE,CAAC;YAC5D,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QAC5C,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\n/**\n * Antagonist torture test — convert/validate round-trip symmetry (target class\n * 7): every OPTIONAL field the envelope/edge/provenance shapes carry must\n * survive a full on-disk round-trip (serialize → YAML text → parse), not just a\n * single `Converter.convert` pass in memory. This exercises the exact path a\n * corrupted or field-dropping serializer/parser pair would break, mirroring the\n * `aiClientToolConfig`/`annotations` field-drop class named in the brief.\n */\n\nimport '@fgv/ts-utils-jest';\nimport { Converters } from '@fgv/ts-utils';\nimport {\n BodyConverterRegistry,\n IBodyConverterRegistry,\n IMemoryEnvelope,\n parseMemoryFile,\n serializeMemoryFile\n} from '../../../index';\n\nconst kind = 'note' as IMemoryEnvelope['kind'];\n\nfunction registry(): IBodyConverterRegistry {\n const reg = BodyConverterRegistry.create().orThrow();\n reg.register(kind, Converters.string);\n return reg;\n}\n\ndescribe('antagonist — full on-disk round-trip preserves every optional field', () => {\n // Wrong impl this catches: a serializer/parser pair where one side silently\n // drops an optional field (the exact class of bug the brief calls out for\n // `aiClientToolConfig`/`annotations`-shaped converters) — e.g. omitting\n // `temporal.invalid_at: null`, an edge's `valid_at`/`invalid_at`/`provenance`,\n // a `null` `embeddingRef`, or a provenance extension key, because the author\n // forgot to thread it through both the YAML emit AND the envelope Converter.\n test('every optional envelope/edge/provenance field set simultaneously survives a full YAML round-trip', () => {\n const envelope: IMemoryEnvelope = {\n id: 'doc-1' as IMemoryEnvelope['id'],\n entityId: 'doc-1' as IMemoryEnvelope['entityId'],\n kind,\n tags: ['t1', 't2'] as unknown as IMemoryEnvelope['tags'],\n links: [\n {\n type: 'rel' as never,\n target: 'doc-2' as never,\n confidence: 0.42,\n provenance: { source: 'agent', by: 'curator', extra: { nested: true } },\n valid_at: 111,\n\n invalid_at: null\n }\n ],\n created: 1000,\n updated: 2000,\n seq: 7,\n contentHash: 'abc123',\n provenance: {\n source: 'host-ingest',\n by: 'erik',\n model: 'gpt-5',\n confidence: 0.87,\n derivedFrom: 'turn-3' as never,\n // Opaque extension keys (per IProvenance's `[key: string]: unknown` arm).\n sentiment: { score: 0.5 },\n epistemic: 'belief'\n },\n\n temporal: { valid_at: 500, invalid_at: null },\n\n embeddingRef: null\n };\n\n const raw = serializeMemoryFile(envelope, 'the body text').orThrow();\n expect(parseMemoryFile(raw, registry())).toSucceedAndSatisfy((record) => {\n // Deep-equal the ENTIRE envelope, not field-by-field — a partial assertion\n // list is exactly how a single dropped field slips through review.\n expect(record.envelope).toEqual(envelope);\n expect(record.body).toBe('the body text');\n });\n });\n\n test('an absent temporal/embeddingRef/edge-optionals round-trips to fully absent (no null-vs-undefined drift)', () => {\n const envelope: IMemoryEnvelope = {\n id: 'doc-2' as IMemoryEnvelope['id'],\n entityId: 'doc-2' as IMemoryEnvelope['entityId'],\n kind,\n tags: [],\n links: [{ type: 'rel' as never, target: 'doc-3' as never }],\n created: 0,\n updated: 0,\n seq: 0,\n contentHash: '',\n provenance: { source: 'agent' }\n };\n const raw = serializeMemoryFile(envelope, 'body').orThrow();\n expect(parseMemoryFile(raw, registry())).toSucceedAndSatisfy((record) => {\n expect(record.envelope.temporal).toBeUndefined();\n expect(record.envelope.embeddingRef).toBeUndefined();\n expect(record.envelope.links[0].confidence).toBeUndefined();\n expect(record.envelope.links[0].provenance).toBeUndefined();\n expect(record.envelope.links[0].valid_at).toBeUndefined();\n expect(record.envelope.links[0].invalid_at).toBeUndefined();\n expect(record.envelope).toEqual(envelope);\n });\n });\n});\n"]}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Antagonist torture tests — cycle guard adversarial graphs (target class 6) and
3
+ * enum-branch parity (target class 7), exercised at the ORCHESTRATOR/integration
4
+ * level over a real {@link FileTreeMemoryStore}, complementing the pure-function
5
+ * unit tests in `cycleGuard.test.ts` and the per-verdict tests in
6
+ * `orchestrator.test.ts`.
7
+ */
8
+ import '@fgv/ts-utils-jest';
9
+ //# sourceMappingURL=antagonistCycleAndParity.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"antagonistCycleAndParity.test.d.ts","sourceRoot":"","sources":["../../../../src/test/unit/ingest/antagonistCycleAndParity.test.ts"],"names":[],"mappings":"AAKA;;;;;;GAMG;AAEH,OAAO,oBAAoB,CAAC"}
@@ -0,0 +1,275 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2026 Erik Fortune
4
+ * SPDX-License-Identifier: MIT
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ /**
8
+ * Antagonist torture tests — cycle guard adversarial graphs (target class 6) and
9
+ * enum-branch parity (target class 7), exercised at the ORCHESTRATOR/integration
10
+ * level over a real {@link FileTreeMemoryStore}, complementing the pure-function
11
+ * unit tests in `cycleGuard.test.ts` and the per-verdict tests in
12
+ * `orchestrator.test.ts`.
13
+ */
14
+ require("@fgv/ts-utils-jest");
15
+ const ts_utils_1 = require("@fgv/ts-utils");
16
+ const ts_json_base_1 = require("@fgv/ts-json-base");
17
+ const index_1 = require("../../../index");
18
+ const noteKind = 'note';
19
+ function mutableRoot() {
20
+ const tree = ts_json_base_1.FileTree.inMemory([], { mutable: true }).orThrow();
21
+ const root = tree.getDirectory('/').orThrow();
22
+ if (!ts_json_base_1.FileTree.isMutableDirectoryItem(root)) {
23
+ throw new Error('expected a mutable root directory');
24
+ }
25
+ return root;
26
+ }
27
+ function registry() {
28
+ const reg = index_1.BodyConverterRegistry.create().orThrow();
29
+ reg.register(noteKind, ts_utils_1.Converters.string);
30
+ return reg;
31
+ }
32
+ const codecs = new Map([
33
+ [noteKind, new index_1.KnowledgeIdentityCodec()]
34
+ ]);
35
+ function buildStore() {
36
+ return index_1.FileTreeMemoryStore.create({ root: mutableRoot(), registry: registry(), codecs }).orThrow();
37
+ }
38
+ async function putFull(store, entityId, body, links = []) {
39
+ const rec = {
40
+ envelope: {
41
+ id: entityId,
42
+ entityId: entityId,
43
+ kind: noteKind,
44
+ tags: [],
45
+ links,
46
+ created: 0,
47
+ updated: 0,
48
+ seq: 0,
49
+ contentHash: '',
50
+ provenance: { source: 'agent' }
51
+ },
52
+ body
53
+ };
54
+ (await store.put(rec)).orThrow();
55
+ }
56
+ function classifier(fn) {
57
+ return { classify: (item) => Promise.resolve(fn(item)) };
58
+ }
59
+ function extractor(fn) {
60
+ return { extract: (item, c) => Promise.resolve(fn(item, c)) };
61
+ }
62
+ function relater(fn) {
63
+ return { relate: (ctx) => Promise.resolve(fn(ctx)) };
64
+ }
65
+ function resolver(fn) {
66
+ return { resolve: (candidate, similar) => Promise.resolve(fn(candidate, similar)) };
67
+ }
68
+ const classifyNote = classifier(() => (0, ts_utils_1.succeed)({ kind: noteKind }));
69
+ function candidate(entityId, body, links = []) {
70
+ return {
71
+ envelope: {
72
+ entityId: entityId,
73
+ kind: noteKind,
74
+ tags: [],
75
+ links,
76
+ provenance: { source: 'agent' }
77
+ },
78
+ body
79
+ };
80
+ }
81
+ function candEdge(source, type, target) {
82
+ return { source: source, edge: { type: type, target: target } };
83
+ }
84
+ function buildOrchestrator(params) {
85
+ return index_1.MemoryIngestOrchestrator.create({
86
+ store: params.store,
87
+ registry: registry(),
88
+ codecs,
89
+ classifier: classifyNote,
90
+ extractor: params.extractor,
91
+ relationExtractor: params.relationExtractor,
92
+ entityResolver: params.entityResolver
93
+ }).orThrow();
94
+ }
95
+ describe('antagonist — cycle guard through EXISTING store edges (integration)', () => {
96
+ // Wrong impl this catches: an orchestrator that only feeds the cycle guard the
97
+ // proposed-edge batch (as its own pure-function unit tests do) and forgets to
98
+ // fold in the store snapshot's existing edges, so a cycle that closes THROUGH
99
+ // an already-persisted edge is silently admitted.
100
+ test('a proposed edge that closes a cycle through a pre-existing on-disk edge is rejected', async () => {
101
+ const store = buildStore();
102
+ // Existing on-disk edge: doc-a -> doc-b (persisted before this ingest runs).
103
+ await putFull(store, 'doc-a', 'anchor-a', [{ type: 'rel', target: 'doc-b' }]);
104
+ await putFull(store, 'doc-b', 'anchor-b');
105
+ // This ingest re-writes doc-b (a 'new'-verdict same-id update, since no
106
+ // resolver is wired) and proposes doc-b -> doc-a, which — unioned with the
107
+ // EXISTING doc-a -> doc-b edge — closes a 2-cycle that exists ONLY because of
108
+ // the on-disk edge, not anything proposed in this batch.
109
+ const orch = buildOrchestrator({
110
+ store,
111
+ extractor: extractor(() => (0, ts_utils_1.succeed)([candidate('doc-b', 'anchor-b-v2')])),
112
+ relationExtractor: relater(() => (0, ts_utils_1.succeed)([candEdge('doc-b', 'rel', 'doc-a')]))
113
+ });
114
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(/would create a cycle/);
115
+ // Confirm the guard fired BEFORE any write — doc-b's content must be unchanged.
116
+ expect(await store.get(noteKind, 'doc-b')).toSucceedAndSatisfy((rec) => expect(rec === null || rec === void 0 ? void 0 : rec.body).toBe('anchor-b'));
117
+ });
118
+ test('a long existing chain plus one proposed edge closing the loop is rejected', async () => {
119
+ const store = buildStore();
120
+ // Existing chain: a -> b -> c -> d (four pre-existing on-disk edges spanning
121
+ // three hops), persisted before this ingest.
122
+ await putFull(store, 'chain-a', 'a', [{ type: 'rel', target: 'chain-b' }]);
123
+ await putFull(store, 'chain-b', 'b', [{ type: 'rel', target: 'chain-c' }]);
124
+ await putFull(store, 'chain-c', 'c', [{ type: 'rel', target: 'chain-d' }]);
125
+ await putFull(store, 'chain-d', 'd');
126
+ // Proposed: chain-d -> chain-a, closing the whole loop through the existing chain.
127
+ const orch = buildOrchestrator({
128
+ store,
129
+ extractor: extractor(() => (0, ts_utils_1.succeed)([candidate('chain-d', 'd-v2')])),
130
+ relationExtractor: relater(() => (0, ts_utils_1.succeed)([candEdge('chain-d', 'rel', 'chain-a')]))
131
+ });
132
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(/would create a cycle/);
133
+ });
134
+ test('cycleGuard "off" admits a cycle that closes through an existing edge', async () => {
135
+ const store = buildStore();
136
+ await putFull(store, 'doc-a', 'anchor-a', [{ type: 'rel', target: 'doc-b' }]);
137
+ await putFull(store, 'doc-b', 'anchor-b');
138
+ const orch = index_1.MemoryIngestOrchestrator.create({
139
+ store,
140
+ registry: registry(),
141
+ codecs,
142
+ classifier: classifyNote,
143
+ extractor: extractor(() => (0, ts_utils_1.succeed)([candidate('doc-b', 'anchor-b-v2')])),
144
+ relationExtractor: relater(() => (0, ts_utils_1.succeed)([candEdge('doc-b', 'rel', 'doc-a')])),
145
+ cycleGuard: 'off'
146
+ }).orThrow();
147
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toSucceedAndSatisfy((r) => {
148
+ var _a;
149
+ expect((_a = r.records[0].record) === null || _a === void 0 ? void 0 : _a.envelope.links).toEqual([{ type: 'rel', target: 'doc-a' }]);
150
+ });
151
+ });
152
+ });
153
+ describe('antagonist — resolver target need not be a surfaced `similar` candidate (structural-only gate)', () => {
154
+ // Documents (and locks in) the actual contract: fgv validates a target-bearing
155
+ // verdict STRUCTURALLY (exists in the store + matching kind), uniformly across
156
+ // all three target-bearing verdicts, regardless of whether the resolver's
157
+ // choice was among the `similar` candidates it was shown. Wrong impl this
158
+ // guards against: fgv silently restricting itself to `similar` membership
159
+ // (which would incorrectly reject a host resolver with external knowledge), OR
160
+ // fgv skipping the structural check for one of the three verdicts.
161
+ test.each(['duplicate-of', 'supersede', 'merge-into'])("verdict '%s' targeting a valid existing record OUTSIDE the surfaced similar set is accepted", async (verdict) => {
162
+ const store = buildStore();
163
+ await putFull(store, 'doc-a', 'apple pie'); // will be surfaced as `similar`
164
+ await putFull(store, 'doc-q', 'unrelated target'); // exists, but never surfaced
165
+ const vectorIndex = index_1.InMemoryCosineIndex.create().orThrow();
166
+ const embed = () => Promise.resolve((0, ts_utils_1.succeed)(Float32Array.from([1, 0, 0])));
167
+ // Only doc-a is embedded/indexed; doc-q is never surfaced by similarity —
168
+ // it can only be reached by the resolver's own out-of-band choice.
169
+ (await vectorIndex.add('doc-a', Float32Array.from([1, 0, 0]))).orThrow();
170
+ const orch = index_1.MemoryIngestOrchestrator.create({
171
+ store,
172
+ registry: registry(),
173
+ codecs,
174
+ classifier: classifyNote,
175
+ extractor: extractor(() => (0, ts_utils_1.succeed)([candidate('doc-b', 'apple tart')])),
176
+ relationExtractor: relater(() => (0, ts_utils_1.succeed)([])),
177
+ vectorIndex,
178
+ embed,
179
+ entityResolver: resolver(() => (0, ts_utils_1.succeed)({ verdict, target: 'doc-q' }))
180
+ }).orThrow();
181
+ const result = await orch.ingestItem({ id: 'i', content: 'x' });
182
+ if (verdict === 'duplicate-of') {
183
+ expect(result).toSucceedAndSatisfy((r) => {
184
+ expect(r.records[0].disposition).toBe('deduped');
185
+ expect(r.records[0].id).toBe('doc-q');
186
+ });
187
+ }
188
+ else if (verdict === 'supersede') {
189
+ expect(result).toSucceedAndSatisfy((r) => {
190
+ expect(r.records[0].disposition).toBe('written');
191
+ expect(r.records[0].resolution).toEqual({ verdict: 'supersede', target: 'doc-q' });
192
+ });
193
+ }
194
+ else {
195
+ expect(result).toSucceedAndSatisfy((r) => {
196
+ expect(r.records[0].disposition).toBe('merged');
197
+ expect(r.records[0].id).toBe('doc-q');
198
+ });
199
+ }
200
+ });
201
+ });
202
+ describe('antagonist — enum-branch parity: uniform structural rejection across target-bearing verdicts', () => {
203
+ // A single table-driven test locking in that EVERY target-bearing verdict arm
204
+ // shares the SAME two structural checks (existence, then kind match) in the
205
+ // SAME order — the exact class of hole ("only merge-into checked") that a
206
+ // prior review caught. Wrong impl this guards against: a future edit that adds
207
+ // a fourth verdict or refactors validation per-branch and re-introduces an
208
+ // asymmetric gap.
209
+ const verdicts = ['duplicate-of', 'supersede', 'merge-into'];
210
+ test.each(verdicts)("verdict '%s' rejects a nonexistent target with the SAME message shape", async (verdict) => {
211
+ const store = buildStore();
212
+ await putFull(store, 'doc-a', 'apple pie');
213
+ const vectorIndex = index_1.InMemoryCosineIndex.create().orThrow();
214
+ const embed = () => Promise.resolve((0, ts_utils_1.succeed)(Float32Array.from([1, 0, 0])));
215
+ const orch = index_1.MemoryIngestOrchestrator.create({
216
+ store,
217
+ registry: registry(),
218
+ codecs,
219
+ classifier: classifyNote,
220
+ extractor: extractor(() => (0, ts_utils_1.succeed)([candidate('doc-b', 'apple tart')])),
221
+ relationExtractor: relater(() => (0, ts_utils_1.succeed)([])),
222
+ vectorIndex,
223
+ embed,
224
+ entityResolver: resolver(() => (0, ts_utils_1.succeed)({ verdict, target: 'ghost' }))
225
+ }).orThrow();
226
+ (await vectorIndex.add('doc-a', Float32Array.from([1, 0, 0]))).orThrow();
227
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(`ingest 'i': ${verdict} target 'ghost' does not exist in the store`);
228
+ });
229
+ test.each(verdicts)("verdict '%s' rejects a foreign-kind target with the SAME message shape", async (verdict) => {
230
+ const otherKind = 'other';
231
+ const reg = registry();
232
+ reg.register(otherKind, ts_utils_1.Converters.string);
233
+ const otherCodecs = new Map([
234
+ ...codecs,
235
+ [otherKind, new index_1.KnowledgeIdentityCodec()]
236
+ ]);
237
+ const store = index_1.FileTreeMemoryStore.create({
238
+ root: mutableRoot(),
239
+ registry: reg,
240
+ codecs: otherCodecs
241
+ }).orThrow();
242
+ const foreignRec = {
243
+ envelope: {
244
+ id: 'foreign-1',
245
+ entityId: 'foreign-1',
246
+ kind: otherKind,
247
+ tags: [],
248
+ links: [],
249
+ created: 0,
250
+ updated: 0,
251
+ seq: 0,
252
+ contentHash: '',
253
+ provenance: { source: 'agent' }
254
+ },
255
+ body: 'apple pie'
256
+ };
257
+ (await store.put(foreignRec)).orThrow();
258
+ const vectorIndex = index_1.InMemoryCosineIndex.create().orThrow();
259
+ const embed = () => Promise.resolve((0, ts_utils_1.succeed)(Float32Array.from([1, 0, 0])));
260
+ const orch = index_1.MemoryIngestOrchestrator.create({
261
+ store,
262
+ registry: reg,
263
+ codecs: otherCodecs,
264
+ classifier: classifyNote,
265
+ extractor: extractor(() => (0, ts_utils_1.succeed)([candidate('doc-b', 'apple tart')])),
266
+ relationExtractor: relater(() => (0, ts_utils_1.succeed)([])),
267
+ vectorIndex,
268
+ embed,
269
+ entityResolver: resolver(() => (0, ts_utils_1.succeed)({ verdict, target: 'foreign-1' }))
270
+ }).orThrow();
271
+ (await vectorIndex.add('foreign-1', Float32Array.from([1, 0, 0]))).orThrow();
272
+ expect(await orch.ingestItem({ id: 'i', content: 'x' })).toFailWith(`ingest 'i': ${verdict} target 'foreign-1' is kind 'other' but the candidate is kind 'note'`);
273
+ });
274
+ });
275
+ //# sourceMappingURL=antagonistCycleAndParity.test.js.map