@vellumai/assistant 0.11.9 → 0.11.10-dev.202609091114.7b6342c

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 (433) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/Dockerfile +6 -12
  3. package/docs/architecture/memory.md +17 -9
  4. package/docs/guardian-request-flow.md +7 -4
  5. package/docs/runbook-trusted-contacts.md +13 -2
  6. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/package.json +3 -1
  7. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/__tests__/plan-credit.test.ts +51 -0
  8. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/__tests__/secret-detection.test.ts +2 -0
  9. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/desktop-presence.ts +11 -0
  10. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/index.ts +1 -0
  11. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/plan-credit.ts +66 -0
  12. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/secret-detection.ts +7 -0
  13. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/package.json +3 -1
  14. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/__tests__/plan-credit.test.ts +51 -0
  15. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/__tests__/secret-detection.test.ts +2 -0
  16. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/desktop-presence.ts +11 -0
  17. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/index.ts +1 -0
  18. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/plan-credit.ts +66 -0
  19. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/secret-detection.ts +7 -0
  20. package/node_modules/@vellumai/gateway-client/src/gateway-ipc-contracts.ts +72 -0
  21. package/node_modules/@vellumai/service-contracts/package.json +3 -1
  22. package/node_modules/@vellumai/service-contracts/src/__tests__/plan-credit.test.ts +51 -0
  23. package/node_modules/@vellumai/service-contracts/src/__tests__/secret-detection.test.ts +2 -0
  24. package/node_modules/@vellumai/service-contracts/src/desktop-presence.ts +11 -0
  25. package/node_modules/@vellumai/service-contracts/src/index.ts +1 -0
  26. package/node_modules/@vellumai/service-contracts/src/plan-credit.ts +66 -0
  27. package/node_modules/@vellumai/service-contracts/src/secret-detection.ts +7 -0
  28. package/openapi.yaml +729 -63
  29. package/package.json +1 -1
  30. package/src/__tests__/agent-loop-mutable-latest-user-message.test.ts +19 -21
  31. package/src/__tests__/assistant-event-hub-machine-name.test.ts +40 -0
  32. package/src/__tests__/assistant-event-hub.test.ts +45 -0
  33. package/src/__tests__/cli-memory-v2-reembed-skills.test.ts +0 -1
  34. package/src/__tests__/compactor-assistant-tail-preview.test.ts +111 -0
  35. package/src/__tests__/compactor-tail-resolution.test.ts +116 -0
  36. package/src/__tests__/computer-use-native-history.test.ts +30 -0
  37. package/src/__tests__/computer-use-window-schema.test.ts +24 -0
  38. package/src/__tests__/config-get-vision-flag.test.ts +36 -0
  39. package/src/__tests__/config-loader-validation-reset-notice.test.ts +47 -15
  40. package/src/__tests__/context-search-conversations-source.test.ts +27 -5
  41. package/src/__tests__/conversation-agent-loop-overflow.test.ts +189 -195
  42. package/src/__tests__/conversation-agent-loop.test.ts +690 -50
  43. package/src/__tests__/conversation-fork-crud.test.ts +132 -45
  44. package/src/__tests__/conversation-fork-retrospective.test.ts +9 -7
  45. package/src/__tests__/conversation-lifecycle.test.ts +684 -10
  46. package/src/__tests__/conversation-pairing.test.ts +10 -9
  47. package/src/__tests__/conversation-runtime-assembly.test.ts +288 -1
  48. package/src/__tests__/conversation-surfaces-history-restored-completion.test.ts +21 -4
  49. package/src/__tests__/conversation-surfaces-point-at-budget.test.ts +150 -0
  50. package/src/__tests__/conversation-surfaces-point-at-capability.test.ts +161 -0
  51. package/src/__tests__/copy-composer-tc-templates.test.ts +2 -2
  52. package/src/__tests__/credential-security-invariants.test.ts +1 -0
  53. package/src/__tests__/delivered-post-record.test.ts +107 -0
  54. package/src/__tests__/guardian-action-service-scope.test.ts +53 -0
  55. package/src/__tests__/guardian-question-mode.test.ts +88 -138
  56. package/src/__tests__/headless-browser-mode.test.ts +63 -13
  57. package/src/__tests__/heartbeat-disk-pressure.test.ts +2 -0
  58. package/src/__tests__/heartbeat-service.test.ts +118 -27
  59. package/src/__tests__/host-cu-proxy.test.ts +159 -1
  60. package/src/__tests__/host-proxy-interface.test.ts +15 -0
  61. package/src/__tests__/host-proxy-preactivation.test.ts +61 -0
  62. package/src/__tests__/injector-chain.test.ts +3 -3
  63. package/src/__tests__/injector-registry-order-guard.test.ts +1 -1
  64. package/src/__tests__/injector-v3-suppression.test.ts +587 -45
  65. package/src/__tests__/llm-schema.test.ts +70 -2
  66. package/src/__tests__/logger.test.ts +33 -32
  67. package/src/__tests__/mcp-config-secret-boundary.test.ts +2 -0
  68. package/src/__tests__/memory-config-file-parity.test.ts +18 -0
  69. package/src/__tests__/memory-retrieval-hook.test.ts +53 -3
  70. package/src/__tests__/messages-read-boundary-guard.test.ts +0 -1
  71. package/src/__tests__/messaging-send-tool.test.ts +251 -128
  72. package/src/__tests__/messaging-shared.test.ts +19 -0
  73. package/src/__tests__/notification-decision-fallback.test.ts +98 -76
  74. package/src/__tests__/notification-decision-strategy.test.ts +10 -38
  75. package/src/__tests__/notification-events-source-context-probe.test.ts +211 -0
  76. package/src/__tests__/openai-responses-prompt-cache.test.ts +7 -2
  77. package/src/__tests__/openai-responses-provider.test.ts +42 -0
  78. package/src/__tests__/outlook-messaging-provider.test.ts +9 -0
  79. package/src/__tests__/platform-callback-registration.test.ts +162 -3
  80. package/src/__tests__/plugin-api-webhook-url.test.ts +66 -4
  81. package/src/__tests__/plugin-import-boundary-guard.test.ts +1 -0
  82. package/src/__tests__/pricing.test.ts +29 -0
  83. package/src/__tests__/prompt-cache-cross-turn-stability.test.ts +63 -3
  84. package/src/__tests__/scheduler-result-notification.test.ts +209 -0
  85. package/src/__tests__/strip-memory-injections.test.ts +75 -27
  86. package/src/__tests__/tool-approval-seed-content-blocks.test.ts +4 -13
  87. package/src/acp/auto-install.test.ts +35 -1
  88. package/src/acp/resolve-agent.test.ts +3 -3
  89. package/src/agent/loop.ts +116 -45
  90. package/src/api/constants/personality-sliders.test.ts +21 -0
  91. package/src/api/constants/personality-sliders.ts +64 -0
  92. package/src/api/events/contact-record-request.ts +16 -4
  93. package/src/api/events/contact-request.ts +10 -1
  94. package/src/api/index.ts +12 -0
  95. package/src/api/responses/memory-v3-selection-log.ts +64 -13
  96. package/src/api/surfaces.ts +6 -5
  97. package/src/background-wake/next-wake.test.ts +13 -0
  98. package/src/background-wake/next-wake.ts +4 -2
  99. package/src/calls/__tests__/voice-session-bridge.test.ts +166 -0
  100. package/src/calls/__tests__/voice-turn-sight-hold.test.ts +301 -0
  101. package/src/calls/voice-session-bridge.ts +162 -1
  102. package/src/calls/voice-triage-escalate.ts +1 -1
  103. package/src/channels/types.ts +14 -0
  104. package/src/cli/__tests__/catalog-search-help.test.ts +1 -0
  105. package/src/cli/__tests__/contacts-address-prompt-cli.test.ts +701 -0
  106. package/src/cli/__tests__/contacts-record-prompt-cli.test.ts +276 -15
  107. package/src/cli/__tests__/roadmap-cli.test.ts +313 -0
  108. package/src/cli/__tests__/run-assistant-command.ts +59 -20
  109. package/src/cli/commands/__tests__/conversations-slack.test.ts +12 -0
  110. package/src/cli/commands/__tests__/plugins-search.test.ts +81 -0
  111. package/src/cli/commands/config.help.ts +3 -1
  112. package/src/cli/commands/contacts.help.ts +179 -12
  113. package/src/cli/commands/contacts.ts +442 -47
  114. package/src/cli/commands/memory/worker.ts +1 -1
  115. package/src/cli/commands/platform/__tests__/credits-format.test.ts +152 -0
  116. package/src/cli/commands/platform/__tests__/credits.test.ts +20 -0
  117. package/src/cli/commands/platform/credits-format.ts +108 -0
  118. package/src/cli/commands/platform/index.help.ts +33 -11
  119. package/src/cli/commands/platform/index.ts +7 -18
  120. package/src/cli/commands/plugins.help.ts +4 -1
  121. package/src/cli/commands/plugins.ts +2 -1
  122. package/src/cli/commands/roadmap.help.ts +171 -0
  123. package/src/cli/commands/roadmap.ts +358 -0
  124. package/src/cli/index.help.ts +2 -0
  125. package/src/cli/lib/__tests__/cli-output.test.ts +5 -0
  126. package/src/cli/lib/cli-output.ts +6 -6
  127. package/src/cli/program.ts +2 -0
  128. package/src/config/__tests__/webhook-routing.test.ts +42 -0
  129. package/src/config/acp-defaults.test.ts +3 -3
  130. package/src/config/acp-defaults.ts +5 -5
  131. package/src/config/bundled-skills/acp/SKILL.md +8 -11
  132. package/src/config/bundled-skills/computer-use/SKILL.md +21 -0
  133. package/src/config/bundled-skills/computer-use/TOOLS.json +6 -0
  134. package/src/config/bundled-skills/contacts/SKILL.md +61 -11
  135. package/src/config/bundled-skills/messaging/SKILL.md +2 -0
  136. package/src/config/bundled-skills/messaging/TOOLS.json +4 -4
  137. package/src/config/bundled-skills/messaging/tools/messaging-send.ts +160 -36
  138. package/src/config/bundled-skills/messaging/tools/shared.ts +6 -0
  139. package/src/config/bundled-skills/schedule/SKILL.md +10 -2
  140. package/src/config/bundled-skills/screen-annotation/SKILL.md +80 -0
  141. package/src/config/bundled-skills/screen-annotation/TOOLS.json +73 -0
  142. package/src/config/bundled-skills/screen-annotation/tools/screen-annotation.test.ts +74 -0
  143. package/src/config/bundled-skills/screen-annotation/tools/screen-clear-marks.ts +33 -0
  144. package/src/config/bundled-skills/screen-annotation/tools/screen-point-at.ts +25 -0
  145. package/src/config/env-registry.ts +2 -0
  146. package/src/config/feature-flag-registry.json +39 -7
  147. package/src/config/input-modalities.test.ts +71 -0
  148. package/src/config/input-modalities.ts +95 -0
  149. package/src/config/loader.ts +2 -0
  150. package/src/config/schemas/__tests__/memory-v3.test.ts +58 -15
  151. package/src/config/schemas/heartbeat.ts +3 -3
  152. package/src/config/schemas/llm.ts +47 -10
  153. package/src/config/schemas/memory-storage.test.ts +39 -0
  154. package/src/config/schemas/memory-storage.ts +21 -0
  155. package/src/config/schemas/memory-v3.ts +73 -46
  156. package/src/config/schemas/services.ts +18 -0
  157. package/src/config/webhook-routing.ts +12 -2
  158. package/src/context/compactor.ts +12 -13
  159. package/src/context/strip-injections.ts +29 -25
  160. package/src/context/token-estimator.ts +2 -2
  161. package/src/daemon/__tests__/embedding-reconcile.test.ts +77 -0
  162. package/src/daemon/__tests__/lifecycle-embedding-reconcile.test.ts +3 -0
  163. package/src/daemon/__tests__/turn-actor.test.ts +68 -0
  164. package/src/daemon/conversation-agent-loop-handlers.ts +152 -22
  165. package/src/daemon/conversation-agent-loop.ts +19 -3
  166. package/src/daemon/conversation-messaging.ts +3 -2
  167. package/src/daemon/conversation-runtime-assembly.ts +191 -69
  168. package/src/daemon/conversation-surfaces.ts +32 -62
  169. package/src/daemon/conversation.ts +153 -46
  170. package/src/daemon/embedding-reconcile.ts +64 -1
  171. package/src/daemon/handlers/config-embeddings.ts +31 -0
  172. package/src/daemon/host-cu-proxy.ts +66 -50
  173. package/src/daemon/host-cu-target.ts +139 -0
  174. package/src/daemon/host-proxy-preactivation.ts +29 -1
  175. package/src/daemon/mcp-reload-service.ts +6 -0
  176. package/src/daemon/providers-setup.ts +5 -26
  177. package/src/daemon/trust-context.ts +1 -1
  178. package/src/daemon/turn-actor.ts +46 -0
  179. package/src/heartbeat/heartbeat-service.ts +72 -13
  180. package/src/inbound/platform-callback-registration.ts +77 -11
  181. package/src/inbound/pod-webhook-claim.ts +35 -0
  182. package/src/inbound/velay-webhooks-gate.ts +20 -0
  183. package/src/ipc/gateway-client.ts +91 -0
  184. package/src/live-voice/__tests__/live-voice-photo.test.ts +174 -0
  185. package/src/live-voice/__tests__/live-voice-session-guardian.test.ts +127 -0
  186. package/src/live-voice/__tests__/live-voice-session-telemetry.test.ts +42 -2
  187. package/src/live-voice/__tests__/live-voice-sight-frame.test.ts +81 -0
  188. package/src/live-voice/__tests__/protocol.test.ts +67 -0
  189. package/src/live-voice/live-voice-connection.ts +14 -1
  190. package/src/live-voice/live-voice-photo.ts +109 -4
  191. package/src/live-voice/live-voice-session-manager.ts +10 -1
  192. package/src/live-voice/live-voice-session.ts +196 -31
  193. package/src/live-voice/protocol.ts +134 -1
  194. package/src/mcp/__tests__/reload-signal-emission.test.ts +54 -0
  195. package/src/mcp/__tests__/reload-signal.test.ts +57 -0
  196. package/src/mcp/__tests__/startup.test.ts +150 -0
  197. package/src/mcp/reload-signal.ts +50 -0
  198. package/src/mcp/startup.ts +101 -0
  199. package/src/messaging/providers/outlook/adapter.ts +2 -13
  200. package/src/messaging/providers/outlook/client.ts +13 -1
  201. package/src/messaging/providers/outlook/types.ts +3 -0
  202. package/src/messaging/providers/telegram-bot/adapter.ts +9 -2
  203. package/src/messaging/providers/telegram-bot/client.ts +8 -2
  204. package/src/messaging/providers/whatsapp/adapter.ts +9 -2
  205. package/src/messaging/providers/whatsapp/client.ts +8 -2
  206. package/src/notifications/AGENTS.md +5 -0
  207. package/src/notifications/README.md +21 -7
  208. package/src/notifications/__tests__/assistant-reply-producer.test.ts +3 -10
  209. package/src/notifications/__tests__/background-failure-signal.test.ts +96 -0
  210. package/src/notifications/__tests__/broadcaster.test.ts +171 -7
  211. package/src/notifications/__tests__/decision-engine.test.ts +79 -6
  212. package/src/notifications/__tests__/edit-notification.test.ts +59 -0
  213. package/src/notifications/__tests__/resolve-visible-in-source.test.ts +96 -0
  214. package/src/notifications/__tests__/schedule-result-producer.test.ts +397 -0
  215. package/src/notifications/access-request-copy.ts +5 -5
  216. package/src/notifications/approval-card-data.ts +29 -13
  217. package/src/notifications/assistant-reply-producer.ts +0 -4
  218. package/src/notifications/background-failure-signal.ts +13 -1
  219. package/src/notifications/broadcaster.ts +65 -2
  220. package/src/notifications/conversation-pairing.ts +263 -155
  221. package/src/notifications/copy-composer.ts +38 -22
  222. package/src/notifications/decision-engine.ts +89 -61
  223. package/src/notifications/delivered-post-record.ts +81 -0
  224. package/src/notifications/deliveries-store.ts +8 -1
  225. package/src/notifications/edit-notification.ts +16 -0
  226. package/src/notifications/events-store.ts +68 -2
  227. package/src/notifications/guardian-question-mode.ts +24 -232
  228. package/src/notifications/home-feed-side-effect.ts +1 -0
  229. package/src/notifications/notification-utils.ts +13 -5
  230. package/src/notifications/resolve-visible-in-source.ts +56 -0
  231. package/src/notifications/schedule-result-producer.ts +275 -0
  232. package/src/notifications/signal.ts +5 -0
  233. package/src/oauth/__tests__/seed-providers-managed.test.ts +82 -0
  234. package/src/oauth/seed-providers.ts +201 -3
  235. package/src/onboarding/onboarding-events-store.ts +14 -8
  236. package/src/persistence/conversation-crud.ts +68 -19
  237. package/src/persistence/embeddings/embedding-backend.test.ts +162 -0
  238. package/src/persistence/embeddings/embedding-backend.ts +148 -11
  239. package/src/persistence/embeddings/embedding-gemini.test.ts +328 -9
  240. package/src/persistence/embeddings/embedding-gemini.ts +211 -27
  241. package/src/persistence/embeddings/embedding-openai.test.ts +113 -0
  242. package/src/persistence/embeddings/embedding-openai.ts +55 -4
  243. package/src/persistence/embeddings/embedding-types.test.ts +24 -0
  244. package/src/persistence/embeddings/embedding-types.ts +25 -1
  245. package/src/persistence/job-utils.ts +6 -2
  246. package/src/persistence/message-metadata.ts +20 -0
  247. package/src/persistence/migrations/283-memory-v3-selections-message-id-and-sections.ts +2 -1
  248. package/src/persistence/migrations/376-notification-deliveries-canonical-message-id.ts +37 -0
  249. package/src/persistence/schema/memory-injection.ts +31 -9
  250. package/src/persistence/schema/notifications.ts +8 -0
  251. package/src/persistence/steps.ts +2 -0
  252. package/src/plugin-api/index.ts +2 -1
  253. package/src/plugin-api/vision-support.test.ts +81 -0
  254. package/src/plugin-api/vision-support.ts +57 -10
  255. package/src/plugin-api/webhook-url.ts +18 -4
  256. package/src/plugins/AGENTS.md +1 -1
  257. package/src/plugins/defaults/channel/injectors.ts +3 -1
  258. package/src/plugins/defaults/injector-order.ts +2 -2
  259. package/src/plugins/defaults/memory/AGENTS.md +263 -30
  260. package/src/plugins/defaults/memory/__tests__/conversation-memory-orphan-sweep.test.ts +4 -0
  261. package/src/plugins/defaults/memory/__tests__/conversation-memory-purge.test.ts +6 -0
  262. package/src/plugins/defaults/memory/__tests__/db-memory-attach.test.ts +9 -3
  263. package/src/plugins/defaults/memory/__tests__/memory-log-stores-degraded.test.ts +3 -7
  264. package/src/plugins/defaults/memory/__tests__/relocated-memory-test-rows.ts +18 -0
  265. package/src/plugins/defaults/memory/context-search/sources/conversations.ts +16 -2
  266. package/src/plugins/defaults/memory/conversation-memory-purge.ts +2 -0
  267. package/src/plugins/defaults/memory/fork-conversation-memory.ts +13 -13
  268. package/src/plugins/defaults/memory/graph/__tests__/conversation-graph-memory-v2-routing.test.ts +19 -12
  269. package/src/plugins/defaults/memory/graph/conversation-graph-memory.ts +17 -15
  270. package/src/plugins/defaults/memory/graph-topology/build-memory-graph.ts +1 -1
  271. package/src/plugins/defaults/memory/hooks/__tests__/post-compact.test.ts +121 -0
  272. package/src/plugins/defaults/memory/hooks/init.ts +10 -0
  273. package/src/plugins/defaults/memory/hooks/injection-metadata.ts +100 -0
  274. package/src/plugins/defaults/memory/hooks/post-compact.ts +19 -7
  275. package/src/plugins/defaults/memory/hooks/user-prompt-submit.ts +11 -83
  276. package/src/plugins/defaults/memory/injectors.ts +4 -4
  277. package/src/plugins/defaults/memory/job-handlers.ts +4 -1
  278. package/src/plugins/defaults/memory/jobs/__tests__/embed-concept-page.test.ts +1 -0
  279. package/src/plugins/defaults/memory/jobs/embed-concept-page.ts +11 -3
  280. package/src/plugins/defaults/memory/memory-db.ts +4 -0
  281. package/src/plugins/defaults/memory/memory-marker.ts +28 -17
  282. package/src/plugins/defaults/memory/src/__tests__/memory-v2-simulate-route.test.ts +0 -1
  283. package/src/plugins/defaults/memory/src/__tests__/memory-worker-routes.test.ts +20 -0
  284. package/src/plugins/defaults/memory/src/memory-item-routes.test.ts +0 -1
  285. package/src/plugins/defaults/memory/src/memory-worker-routes.ts +3 -1
  286. package/src/plugins/defaults/memory/substrate/__tests__/cli-command-store.test.ts +1 -1
  287. package/src/plugins/defaults/memory/substrate/__tests__/consolidation-job.test.ts +66 -0
  288. package/src/plugins/defaults/memory/substrate/__tests__/injected-block-slugs.test.ts +345 -0
  289. package/src/plugins/defaults/memory/substrate/__tests__/page-index.test.ts +0 -1
  290. package/src/plugins/defaults/memory/substrate/__tests__/prompts-consolidation.test.ts +170 -1
  291. package/src/plugins/defaults/memory/substrate/__tests__/reembed-job.test.ts +1 -0
  292. package/src/plugins/defaults/memory/substrate/capability-slugs.ts +53 -0
  293. package/src/plugins/defaults/memory/substrate/cli-command-store.ts +4 -18
  294. package/src/plugins/defaults/memory/substrate/consolidation-job.ts +40 -1
  295. package/src/plugins/defaults/memory/substrate/ingest.ts +11 -9
  296. package/src/plugins/defaults/memory/substrate/injected-block-slugs.ts +426 -42
  297. package/src/plugins/defaults/memory/substrate/page-index.ts +5 -4
  298. package/src/plugins/defaults/memory/substrate/prompts/consolidation.ts +127 -14
  299. package/src/plugins/defaults/memory/substrate/skill-store.ts +1 -18
  300. package/src/plugins/defaults/memory/v2/__tests__/backfill-jobs.test.ts +1 -0
  301. package/src/plugins/defaults/memory/v2/__tests__/injection.test.ts +2 -8
  302. package/src/plugins/defaults/memory/v2/__tests__/router.test.ts +0 -1
  303. package/src/plugins/defaults/memory/v2/injection.ts +4 -4
  304. package/src/plugins/defaults/memory/v3/__tests__/capabilities.test.ts +16 -0
  305. package/src/plugins/defaults/memory/v3/__tests__/carry-integration.test.ts +1004 -319
  306. package/src/plugins/defaults/memory/v3/__tests__/dense.test.ts +227 -4
  307. package/src/plugins/defaults/memory/v3/__tests__/injection.test.ts +836 -263
  308. package/src/plugins/defaults/memory/v3/__tests__/live-integration.test.ts +65 -38
  309. package/src/plugins/defaults/memory/v3/__tests__/maintain-job.test.ts +354 -3
  310. package/src/plugins/defaults/memory/v3/__tests__/orchestrate.test.ts +688 -104
  311. package/src/plugins/defaults/memory/v3/__tests__/overlong-sections.test.ts +109 -0
  312. package/src/plugins/defaults/memory/v3/__tests__/page-content.test.ts +144 -0
  313. package/src/plugins/defaults/memory/v3/__tests__/plugin-schema.test.ts +534 -0
  314. package/src/plugins/defaults/memory/v3/__tests__/pool-log-store.test.ts +449 -0
  315. package/src/plugins/defaults/memory/v3/__tests__/pool-select.test.ts +265 -27
  316. package/src/plugins/defaults/memory/v3/__tests__/render-injection.test.ts +34 -117
  317. package/src/plugins/defaults/memory/v3/__tests__/section-dense-store.test.ts +491 -4
  318. package/src/plugins/defaults/memory/v3/__tests__/section-needle.test.ts +124 -1
  319. package/src/plugins/defaults/memory/v3/__tests__/sections.test.ts +264 -4
  320. package/src/plugins/defaults/memory/v3/__tests__/selection-log-store.test.ts +560 -22
  321. package/src/plugins/defaults/memory/v3/__tests__/shadow-integration.test.ts +40 -33
  322. package/src/plugins/defaults/memory/v3/__tests__/shadow-plugin.test.ts +718 -63
  323. package/src/plugins/defaults/memory/v3/__tests__/types.test.ts +83 -2
  324. package/src/plugins/defaults/memory/v3/candidate-match.ts +1 -1
  325. package/src/plugins/defaults/memory/v3/capabilities.ts +90 -14
  326. package/src/plugins/defaults/memory/v3/card.test.ts +15 -16
  327. package/src/plugins/defaults/memory/v3/card.ts +16 -15
  328. package/src/plugins/defaults/memory/v3/dense.ts +10 -0
  329. package/src/plugins/defaults/memory/v3/ever-injected-store.test.ts +643 -140
  330. package/src/plugins/defaults/memory/v3/ever-injected-store.ts +462 -212
  331. package/src/plugins/defaults/memory/v3/hot-set.test.ts +2 -2
  332. package/src/plugins/defaults/memory/v3/injector.ts +366 -278
  333. package/src/plugins/defaults/memory/v3/learned-edges.test.ts +2 -2
  334. package/src/plugins/defaults/memory/v3/maintain-job.ts +299 -73
  335. package/src/plugins/defaults/memory/v3/orchestrate.ts +327 -214
  336. package/src/plugins/defaults/memory/v3/overlong-sections.ts +83 -0
  337. package/src/plugins/defaults/memory/v3/page-content.ts +72 -92
  338. package/src/plugins/defaults/memory/v3/plugin-schema.ts +346 -0
  339. package/src/plugins/defaults/memory/v3/pool-log-store.ts +291 -0
  340. package/src/plugins/defaults/memory/v3/pool-select.test.ts +2 -2
  341. package/src/plugins/defaults/memory/v3/pool-select.ts +160 -60
  342. package/src/plugins/defaults/memory/v3/prune.test.ts +1042 -329
  343. package/src/plugins/defaults/memory/v3/prune.ts +433 -270
  344. package/src/plugins/defaults/memory/v3/rare-term-lane.test.ts +269 -0
  345. package/src/plugins/defaults/memory/v3/rare-term-lane.ts +141 -0
  346. package/src/plugins/defaults/memory/v3/render-injection.ts +43 -82
  347. package/src/plugins/defaults/memory/v3/section-dense-store.ts +316 -28
  348. package/src/plugins/defaults/memory/v3/section-needle.ts +145 -11
  349. package/src/plugins/defaults/memory/v3/sections.ts +103 -16
  350. package/src/plugins/defaults/memory/v3/selection-log-store.ts +243 -78
  351. package/src/plugins/defaults/memory/v3/shadow-plugin.ts +189 -68
  352. package/src/plugins/defaults/memory/v3/tuning-profile.ts +6 -0
  353. package/src/plugins/defaults/memory/v3/types.ts +169 -23
  354. package/src/plugins/defaults/memory/v3-eval/__tests__/eval-packets.test.ts +21 -4
  355. package/src/plugins/defaults/memory/v3-eval/eval-packets.ts +77 -26
  356. package/src/plugins/types.ts +14 -0
  357. package/src/providers/__tests__/connection-model-compat.test.ts +1 -0
  358. package/src/providers/__tests__/provider-secret-catalog.test.ts +4 -0
  359. package/src/providers/__tests__/xml-tool-call-salvage.test.ts +172 -0
  360. package/src/providers/inline-audio-support.test.ts +34 -0
  361. package/src/providers/inline-audio-support.ts +27 -0
  362. package/src/providers/model-catalog.ts +102 -0
  363. package/src/providers/openai/__tests__/chat-completions-extra-body.test.ts +51 -0
  364. package/src/providers/openai/__tests__/chat-completions-provider-xml-salvage.test.ts +291 -0
  365. package/src/providers/openai/chat-completions-provider.ts +114 -14
  366. package/src/providers/openai/codex-models.ts +1 -0
  367. package/src/providers/openai/responses-provider.ts +65 -15
  368. package/src/providers/opencode/client.test.ts +24 -0
  369. package/src/providers/opencode/client.ts +6 -1
  370. package/src/providers/provider-secret-catalog.ts +11 -1
  371. package/src/providers/retry.ts +6 -0
  372. package/src/providers/vellum/client.ts +14 -1
  373. package/src/providers/vellum/personality-directions.test.ts +163 -0
  374. package/src/providers/vellum/personality-directions.ts +120 -0
  375. package/src/providers/xml-tool-call-salvage.ts +212 -0
  376. package/src/runtime/AGENTS.md +7 -2
  377. package/src/runtime/__tests__/background-job-runner.test.ts +115 -0
  378. package/src/runtime/__tests__/guardian-form-registry.test.ts +0 -32
  379. package/src/runtime/__tests__/host-observe.test.ts +44 -0
  380. package/src/runtime/assistant-event-hub.ts +14 -9
  381. package/src/runtime/auth/__tests__/guard-tests.test.ts +1 -4
  382. package/src/runtime/auth/__tests__/route-policy.test.ts +65 -0
  383. package/src/runtime/auth/same-actor.ts +4 -3
  384. package/src/runtime/background-job-runner.ts +10 -0
  385. package/src/runtime/channel-reply-delivery.ts +1 -162
  386. package/src/runtime/guardian-action-service.ts +20 -1
  387. package/src/runtime/host-observe.ts +56 -6
  388. package/src/runtime/http-server.ts +35 -0
  389. package/src/runtime/outbound-post-reconciliation.ts +183 -0
  390. package/src/runtime/routes/__tests__/contact-address-prompt-route.test.ts +231 -0
  391. package/src/runtime/routes/__tests__/contact-record-prompt-route.test.ts +59 -3
  392. package/src/runtime/routes/__tests__/guardian-form-routes.test.ts +85 -0
  393. package/src/runtime/routes/__tests__/heartbeat-routes.test.ts +24 -0
  394. package/src/runtime/routes/__tests__/platform-credits-routes.test.ts +239 -0
  395. package/src/runtime/routes/__tests__/roadmap-routes.test.ts +469 -0
  396. package/src/runtime/routes/__tests__/watch-routes.test.ts +70 -1
  397. package/src/runtime/routes/__tests__/webhook-routes.test.ts +83 -0
  398. package/src/runtime/routes/contact-prompt-routes.ts +177 -28
  399. package/src/runtime/routes/conversation-query-routes.ts +53 -11
  400. package/src/runtime/routes/events-routes.ts +13 -3
  401. package/src/runtime/routes/guardian-action-routes.ts +7 -0
  402. package/src/runtime/routes/guardian-form-routes.ts +6 -4
  403. package/src/runtime/routes/heartbeat-routes.ts +41 -53
  404. package/src/runtime/routes/index.ts +2 -2
  405. package/src/runtime/routes/integrations/a2a.ts +12 -3
  406. package/src/runtime/routes/integrations/vercel.ts +13 -3
  407. package/src/runtime/routes/platform-routes.ts +175 -23
  408. package/src/runtime/routes/roadmap-routes.ts +744 -0
  409. package/src/runtime/routes/watch-routes.ts +50 -0
  410. package/src/runtime/routes/webhook-routes.ts +24 -2
  411. package/src/runtime/web-presence.ts +13 -9
  412. package/src/schedule/__tests__/schedule-timezone.test.ts +21 -3
  413. package/src/schedule/__tests__/worker-mcp-tools.test.ts +88 -0
  414. package/src/schedule/schedule-timezone.ts +25 -0
  415. package/src/schedule/scheduler.ts +19 -0
  416. package/src/schedule/worker.ts +119 -2
  417. package/src/telemetry/__tests__/live-voice-funnel.test.ts +32 -0
  418. package/src/telemetry/live-voice-funnel.ts +33 -0
  419. package/src/tools/acp/list-agents.test.ts +1 -1
  420. package/src/tools/browser/__tests__/browser-status.test.ts +3 -0
  421. package/src/tools/browser/browser-execution.ts +117 -53
  422. package/src/tools/browser/browser-status-constants.ts +6 -6
  423. package/src/tools/capability-offer.test.ts +87 -0
  424. package/src/tools/capability-offer.ts +93 -0
  425. package/src/tools/computer-use/definitions.ts +6 -0
  426. package/src/tools/computer-use/skill-proxy-bridge.ts +10 -0
  427. package/src/tools/terminal/safe-env.ts +2 -0
  428. package/src/watch/__tests__/watch-retro.test.ts +11 -10
  429. package/src/watch/__tests__/watch-session-manager.test.ts +75 -1
  430. package/src/watch/watch-retro.ts +10 -9
  431. package/src/watch/watch-session-manager.ts +17 -0
  432. package/src/runtime/routes/__tests__/sight-frame-routes.test.ts +0 -487
  433. package/src/runtime/routes/sight-frame-routes.ts +0 -136
@@ -1,22 +1,34 @@
1
1
  /**
2
2
  * Tests for `prune.ts` — the memory-v3 resident-footprint prune valve:
3
- * - `filterPrunedCardSections`: card-boundary parsing, byte-identical
4
- * remainders, all-pruned → `""`, no-op → same reference, capability
5
- * chunks (`# Skill:` / `# CLI command:` headers) terminating a card and
6
- * surviving its prune;
7
- * - `planPrune`: no-op below the cap, oldest-first selection-recency
8
- * ranking down to the target, core/hot exemption, `injected_at` fallback,
9
- * zero-byte (capability / fork-seed) rows skipped, idempotence below the
10
- * cap;
11
- * - `runPruneValve` + the live strip: v3-owned blocks stripped in place,
12
- * v2-lookalike blocks untouched, all-pruned blocks removed, and the
13
- * rehydration filter (the same `filterPrunedCardSections` over persisted
14
- * metadata) converging to the same bytes;
3
+ * - `parseInjectedSections` / `filterResidentSections` over the tombstones
4
+ * alone (an empty newest-copy map): section-boundary
5
+ * parsing at the `# memory/concepts/<slug>.md[ § <key>]` headers,
6
+ * byte-identical remainders, all-pruned → `""`, no-op → same reference,
7
+ * non-section chunks (`# Skills`, `# Skill:` / `# CLI command:` headers)
8
+ * terminating a section and surviving its prune, arbitrary `# ` lines
9
+ * inside a section body staying inside it, a body line that would
10
+ * read as a header arriving escaped from the renderer, and a legacy
11
+ * (pre-stamp) block filtered by card under each card's lead ref, never
12
+ * indexed;
13
+ * - `filterResidentPointerEntries`: a pruned section's line, or one whose
14
+ * section was re-injected further down, leaves the `<memory_pointer>`
15
+ * block; an emptied pointer collapses to `""`;
16
+ * - `planPrune`: no-op below the cap, oldest-first selection-recency ranking
17
+ * down to the target at section grain (each row's own `last_selected_at`,
18
+ * so two sections of one page selected on one turn both age from it), no
19
+ * lane exemptions, `injected_at` fallback for an unstamped row, zero-byte
20
+ * (capability) rows skipped, a truncated fork's inherited sections as
21
+ * candidates carrying their spans' bytes, idempotence below the cap;
22
+ * - `runPruneValve` + the live strip: the blocks memory-v3 placed (owned by
23
+ * object identity) stripped in place by header span, an unowned twin
24
+ * untouched even when byte-identical, all-pruned blocks removed,
25
+ * and the rehydration filter (the same `filterResidentSections` over
26
+ * persisted metadata) converging to the same bytes;
15
27
  * - re-injection round-trip: `recordInjected` clears `pruned_at`, after
16
- * which the filter keeps the slug again;
17
- * - accounting-drift regression: a slug with recorded bytes but no
18
- * locatable persisted card section is tombstoned in ONE pass and the
19
- * valve does not loop-fire afterwards;
28
+ * which the filter keeps the section again;
29
+ * - accounting-drift regression: a section with recorded bytes but no
30
+ * locatable persisted text is tombstoned in ONE pass and the valve does
31
+ * not loop-fire afterwards;
20
32
  * - `schedulePruneValve` deferred execution via `flushPruneValveForTests`.
21
33
  *
22
34
  * `mock.module` is process-global and leaks into sibling files in a directory
@@ -28,13 +40,24 @@
28
40
  import { Database } from "bun:sqlite";
29
41
  import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
30
42
 
31
- import type { Message } from "@vellumai/plugin-api";
43
+ import type { ContentBlock, Message } from "@vellumai/plugin-api";
32
44
  import { drizzle } from "drizzle-orm/bun-sqlite";
33
45
 
34
- import { ensureMemoryV3SelectionsSchema } from "../../../../persistence/migrations/338-move-memory-v3-selections-to-memory-db.js";
35
- import { ensureMemoryV3EverInjectedSchema } from "../../../../persistence/migrations/345-move-memory-v3-ever-injected-to-memory-db.js";
36
46
  import * as schema from "../../../../persistence/schema/index.js";
37
- import { wrapMemoryBlock } from "../memory-marker.js";
47
+ import { wrapMemoryBlock, wrapMemoryPointerBlock } from "../memory-marker.js";
48
+ import {
49
+ escapeInjectedBody,
50
+ injectedSectionHeader,
51
+ parseInjectedSections,
52
+ renderedBytes,
53
+ } from "../substrate/injected-block-slugs.js";
54
+ import type { SectionRefSet } from "./ever-injected-store.js";
55
+ import { ensureMemoryV3InjectedSectionsSchema } from "./plugin-schema.js";
56
+ import {
57
+ type InjectedBlock,
58
+ type InjectedBlockFormat,
59
+ sectionRefId,
60
+ } from "./types.js";
38
61
 
39
62
  const realDb = {
40
63
  ...(await import("../../../../persistence/db-connection.js")),
@@ -48,15 +71,15 @@ let pruneConfig: {
48
71
  } | null = null;
49
72
 
50
73
  let testSqlite: Database;
51
- // `planPrune`'s recency ranking reads `memory_v3_selections` over the
52
- // dedicated memory connection, resolved via `getMemorySqlite` — stubbed to a
53
- // second in-memory DB carrying the relocated table's schema.
74
+ // The section store, which carries `planPrune`'s candidates and recency,
75
+ // lives on the dedicated memory connection, resolved via `getMemorySqlite`,
76
+ // stubbed to a second in-memory DB carrying the store's schema.
54
77
  let memorySqlite: Database;
55
78
  let testDb = makeDb();
56
79
  function makeDb() {
57
80
  testSqlite = new Database(":memory:");
58
81
  const db = drizzle(testSqlite, { schema });
59
- // Minimal `messages` shape — `collectPersistedV3Cards` reads only
82
+ // Minimal `messages` shape, `collectPersistedV3Sections` reads only
60
83
  // `conversation_id` and `metadata`.
61
84
  testSqlite.run(/*sql*/ `
62
85
  CREATE TABLE IF NOT EXISTS messages (
@@ -69,8 +92,7 @@ function makeDb() {
69
92
  )
70
93
  `);
71
94
  memorySqlite = new Database(":memory:");
72
- ensureMemoryV3SelectionsSchema(memorySqlite);
73
- ensureMemoryV3EverInjectedSchema(memorySqlite);
95
+ ensureMemoryV3InjectedSectionsSchema(memorySqlite);
74
96
  return db;
75
97
  }
76
98
 
@@ -98,53 +120,120 @@ mock.module("../config.js", () => ({
98
120
  }));
99
121
 
100
122
  const {
101
- collectPersistedV3Cards,
102
- filterPrunedCardSections,
123
+ filterResidentPointerEntries,
124
+ filterResidentSections,
103
125
  flushPruneValveForTests,
104
- parseCardSections,
126
+ newestCopyIndexes,
105
127
  planPrune,
106
128
  runPruneValve,
107
129
  schedulePruneValve,
108
- stripPrunedCardsFromMessages,
130
+ stripPrunedSectionsFromMessages,
109
131
  } = await import("./prune.js");
110
- const { getActiveSlugs, getInjected, getPrunedSlugs, recordInjected } =
111
- await import("./ever-injected-store.js");
112
- const { V3_CARDS_INJECTION_HEADER, renderCardsBlockInner } =
132
+
133
+ /** The filter over the tombstones alone: no newest-copy index, so only a
134
+ * pruned section (or a legacy card whose lead is pruned) leaves. */
135
+ function filterPrunedSections(
136
+ inner: string,
137
+ format: InjectedBlockFormat,
138
+ pruned: SectionRefSet,
139
+ ): string {
140
+ return filterResidentSections(inner, format, 0, pruned, new Map());
141
+ }
142
+ const {
143
+ getActiveSections,
144
+ getInjected,
145
+ getPrunedSections,
146
+ markPruned,
147
+ recordInjected,
148
+ residentBytes,
149
+ seedEverInjectedFromBlocks,
150
+ touchSelected,
151
+ } = await import("./ever-injected-store.js");
152
+ const { markV3LiveBlock, v3LiveBlockFormat } = await import("./types.js");
153
+ const { V3_INJECTION_HEADER, renderInjectionBlockInner, renderPointerInner } =
113
154
  await import("./render-injection.js");
155
+ const { renderV3SectionInjection } = await import("./page-content.js");
114
156
 
115
157
  // ─── fixtures ────────────────────────────────────────────────────────────────
116
158
 
117
- /** A card exactly as `renderCard` shapes it: path header, head, TOC line. */
118
- function card(slug: string): string {
119
- return `# memory/concepts/${slug}.md\nlead for ${slug}\n\n[sections: §One · §Two]`;
159
+ /** A lead entry exactly as `renderV3SectionInjection` shapes it: page header,
160
+ * the page's own `# Title` line, lead text. */
161
+ function lead(slug: string): string {
162
+ return `${injectedSectionHeader(slug, "")}\n# ${slug}\nlead for ${slug}`;
163
+ }
164
+
165
+ /** A heading-section entry: `§ key` header plus body. */
166
+ function section(slug: string, key: string): string {
167
+ return `${injectedSectionHeader(slug, key)}\nbody of ${slug} ${key}`;
168
+ }
169
+
170
+ /** A card exactly as the pre-stamp builds' card renderer shaped one: page
171
+ * header, the page's own `# Title` line, head, one-line section TOC. */
172
+ function legacyCard(slug: string): string {
173
+ return `${injectedSectionHeader(slug, "")}\n# ${slug}\nhead of ${slug}\n\n[sections: §One · §Two]`;
120
174
  }
121
175
 
122
176
  /** A capability chunk exactly as `renderCapabilityContent` shapes it: its own
123
177
  * non-concept top-level header plus the capability content. */
124
178
  const CAPABILITY_CHUNK = "# Skill: meet-join\nJoin a video meeting on request.";
125
179
 
126
- function insertSelection(
180
+ function refSet(
181
+ ...refs: Array<[slug: string, key: string]>
182
+ ): Map<string, Set<string>> {
183
+ const set = new Map<string, Set<string>>();
184
+ for (const [slug, key] of refs) {
185
+ let keys = set.get(slug);
186
+ if (!keys) {
187
+ keys = new Set();
188
+ set.set(slug, keys);
189
+ }
190
+ keys.add(key);
191
+ }
192
+ return set;
193
+ }
194
+
195
+ /** A persisted block with its row's provenance: current (this build's
196
+ * render, stamped) or legacy (a pre-stamp row, read by card). */
197
+ const current = (inner: string): InjectedBlock => ({
198
+ inner,
199
+ format: "current",
200
+ });
201
+ const legacy = (inner: string): InjectedBlock => ({ inner, format: "legacy" });
202
+
203
+ /** A `<memory>` text block as memory-v3 places it in live history: owned by
204
+ * the strip through object identity, which records its format. */
205
+ function v3Block(
206
+ text: string,
207
+ format: InjectedBlockFormat = "current",
208
+ ): ContentBlock {
209
+ return markV3LiveBlock({ type: "text" as const, text }, format);
210
+ }
211
+
212
+ /** Clear a row's selection stamp, as a row written before the column existed
213
+ * carries none. */
214
+ function clearSelectionStamp(
127
215
  conversationId: string,
128
- turn: number,
129
216
  slug: string,
130
- createdAt: number,
217
+ key: string,
131
218
  ): void {
132
219
  memorySqlite
133
220
  .query(
134
221
  /*sql*/ `
135
- INSERT OR REPLACE INTO memory_v3_selections
136
- (conversation_id, turn, slug, source, pinned, created_at)
137
- VALUES (?, ?, ?, 'needle', 0, ?)
222
+ UPDATE memory_v3_injected_sections SET last_selected_at = NULL
223
+ WHERE conversation_id = ? AND slug = ? AND section_key = ?
138
224
  `,
139
225
  )
140
- .run(conversationId, turn, slug, createdAt);
226
+ .run(conversationId, slug, key);
141
227
  }
142
228
 
143
229
  function insertUserRowWithV3Block(
144
230
  conversationId: string,
145
231
  id: string,
146
232
  blockInner: string,
233
+ format: InjectedBlockFormat = "current",
147
234
  ): void {
235
+ // The persisting build stamps the block's format beside it; a legacy row
236
+ // (persisted before the stamp existed) carries the block alone.
148
237
  testSqlite
149
238
  .query(
150
239
  /*sql*/ `
@@ -155,7 +244,10 @@ function insertUserRowWithV3Block(
155
244
  .run(
156
245
  id,
157
246
  conversationId,
158
- JSON.stringify({ memoryV3InjectedBlock: blockInner }),
247
+ JSON.stringify({
248
+ memoryV3InjectedBlock: blockInner,
249
+ ...(format === "current" ? { memoryV3InjectedBlockFormat: 2 } : {}),
250
+ }),
159
251
  );
160
252
  }
161
253
 
@@ -170,121 +262,444 @@ afterAll(async () => {
170
262
  pruneMockActive = false;
171
263
  });
172
264
 
173
- // ─── filterPrunedCardSections ────────────────────────────────────────────────
265
+ // ─── parseInjectedSections / filterPrunedSections ────────────────────────────
174
266
 
175
- describe("parseCardSections / filterPrunedCardSections", () => {
176
- const inner = renderCardsBlockInner([
177
- card("page-a"),
178
- card("page-b"),
179
- card("page-c"),
267
+ describe("parseInjectedSections / filterPrunedSections", () => {
268
+ const inner = renderInjectionBlockInner([
269
+ lead("page-a"),
270
+ section("page-a", "Notes"),
271
+ section("page-b", "Design#1"),
180
272
  ]);
181
273
 
182
- test("parses preamble and per-card sections at the path headers", () => {
183
- const parsed = parseCardSections(inner);
184
- expect(parsed.preamble).toBe(V3_CARDS_INJECTION_HEADER);
185
- expect(parsed.sections.map((s) => s.slug)).toEqual([
186
- "page-a",
187
- "page-b",
188
- "page-c",
274
+ test("parses preamble and per-section pieces at the path headers, keyed by (slug, key)", () => {
275
+ const parsed = parseInjectedSections(inner);
276
+ expect(parsed.preamble).toBe(V3_INJECTION_HEADER);
277
+ expect(parsed.sections.map((s) => [s.slug, s.key])).toEqual([
278
+ ["page-a", ""],
279
+ ["page-a", "Notes"],
280
+ ["page-b", "Design#1"],
189
281
  ]);
190
- expect(parsed.sections[1]!.text).toBe(card("page-b"));
282
+ expect(parsed.sections[1]!.text).toBe(section("page-a", "Notes"));
191
283
  });
192
284
 
193
- test("skill catalog hint is a non-card piece and leaves the read-affordance preamble intact", () => {
194
- const mixed = renderCardsBlockInner([
285
+ test("skill catalog hint is a non-section piece and leaves the read-affordance preamble intact", () => {
286
+ const mixed = renderInjectionBlockInner([
195
287
  "# Skill: telegram-setup\nSet up Telegram.",
196
- card("page-a"),
288
+ lead("page-a"),
197
289
  ]);
198
- const parsed = parseCardSections(mixed);
199
- expect(parsed.preamble).toBe(V3_CARDS_INJECTION_HEADER);
290
+ const parsed = parseInjectedSections(mixed);
291
+ expect(parsed.preamble).toBe(V3_INJECTION_HEADER);
200
292
  expect(parsed.sections.map((s) => s.slug)).toEqual(["page-a"]);
201
- expect(parsed.pieces.some((piece) => piece.kind === "other")).toBe(true);
293
+ expect(parsed.pieces.map((piece) => piece.kind)).toEqual([
294
+ "other",
295
+ "capability",
296
+ "section",
297
+ ]);
202
298
  expect(mixed).toContain("assistant plugins search <name>");
203
299
  });
204
300
 
205
- test("no pruned slug present → returns the SAME reference (no-op)", () => {
206
- expect(filterPrunedCardSections(inner, new Set(["page-z"]))).toBe(inner);
207
- expect(filterPrunedCardSections(inner, new Set())).toBe(inner);
301
+ test("no pruned section present → returns the SAME reference (no-op)", () => {
302
+ expect(filterPrunedSections(inner, "current", refSet(["page-z", ""]))).toBe(
303
+ inner,
304
+ );
305
+ // A pruned key of a present page that is NOT in the block is a no-op too.
306
+ expect(
307
+ filterPrunedSections(inner, "current", refSet(["page-a", "Design"])),
308
+ ).toBe(inner);
309
+ expect(filterPrunedSections(inner, "current", new Map())).toBe(inner);
208
310
  });
209
311
 
210
- test("strips pruned cards, leaving the remainder byte-identical to a fresh render", () => {
211
- const filtered = filterPrunedCardSections(inner, new Set(["page-b"]));
212
- expect(filtered).toBe(
213
- renderCardsBlockInner([card("page-a"), card("page-c")]),
312
+ test("strips exactly the pruned section by header span, leaving siblings and the remainder byte-identical", () => {
313
+ expect(
314
+ filterPrunedSections(inner, "current", refSet(["page-a", "Notes"])),
315
+ ).toBe(
316
+ renderInjectionBlockInner([
317
+ lead("page-a"),
318
+ section("page-b", "Design#1"),
319
+ ]),
214
320
  );
215
- // A `# Title` line inside a card head is NOT a card boundary.
216
- const headerInHead = `${V3_CARDS_INJECTION_HEADER}\n\n# memory/concepts/page-a.md\n# A Title Line\nlead\n\n# memory/concepts/page-b.md\nlead b`;
217
- expect(filterPrunedCardSections(headerInHead, new Set(["page-b"]))).toBe(
218
- `${V3_CARDS_INJECTION_HEADER}\n\n# memory/concepts/page-a.md\n# A Title Line\nlead`,
321
+ expect(filterPrunedSections(inner, "current", refSet(["page-a", ""]))).toBe(
322
+ renderInjectionBlockInner([
323
+ section("page-a", "Notes"),
324
+ section("page-b", "Design#1"),
325
+ ]),
219
326
  );
220
327
  });
221
328
 
222
- test("all cards pruned → empty string (caller drops the block)", () => {
329
+ test("a `# ` line inside a section body is never a boundary", () => {
330
+ // A lead's own `# Title` line follows the path header with a single
331
+ // newline; a heading inside a section body (a code comment, an H1 in
332
+ // page prose) can even sit on a blank-line seam. Neither splits the
333
+ // section: only concept headers and capability chunks do.
334
+ const bodyWithHeadings = `${injectedSectionHeader("page-a", "Setup")}\nrun this:\n\n# not a boundary\n\n# also inside`;
335
+ const block = renderInjectionBlockInner([bodyWithHeadings, lead("page-b")]);
336
+ const parsed = parseInjectedSections(block);
337
+ expect(parsed.sections.map((s) => [s.slug, s.key])).toEqual([
338
+ ["page-a", "Setup"],
339
+ ["page-b", ""],
340
+ ]);
341
+ expect(parsed.sections[0]!.text).toBe(bodyWithHeadings);
223
342
  expect(
224
- filterPrunedCardSections(inner, new Set(["page-a", "page-b", "page-c"])),
343
+ filterPrunedSections(block, "current", refSet(["page-a", "Setup"])),
344
+ ).toBe(renderInjectionBlockInner([lead("page-b")]));
345
+ });
346
+
347
+ test("all sections pruned → empty string (caller drops the block)", () => {
348
+ expect(
349
+ filterPrunedSections(
350
+ inner,
351
+ "current",
352
+ refSet(["page-a", ""], ["page-a", "Notes"], ["page-b", "Design#1"]),
353
+ ),
225
354
  ).toBe("");
226
355
  });
227
356
 
228
- test("text with no card headers passes through unchanged", () => {
357
+ test("text with no section headers passes through unchanged", () => {
229
358
  const plain = "remember: user prefers tea";
230
- expect(filterPrunedCardSections(plain, new Set(["page-a"]))).toBe(plain);
359
+ expect(filterPrunedSections(plain, "current", refSet(["page-a", ""]))).toBe(
360
+ plain,
361
+ );
231
362
  });
232
363
 
233
- test("a capability chunk terminates the preceding card's section", () => {
234
- const mixed = renderCardsBlockInner([
235
- card("page-a"),
364
+ test("a capability chunk terminates the preceding section", () => {
365
+ const mixed = renderInjectionBlockInner([
366
+ lead("page-a"),
236
367
  CAPABILITY_CHUNK,
237
- card("page-b"),
368
+ section("page-b", "Notes"),
238
369
  ]);
239
- const parsed = parseCardSections(mixed);
370
+ const parsed = parseInjectedSections(mixed);
240
371
  expect(parsed.sections.map((s) => s.slug)).toEqual(["page-a", "page-b"]);
241
372
  // page-a's section stops AT the capability header — it must not absorb it.
242
- expect(parsed.sections[0]!.text).toBe(card("page-a"));
373
+ expect(parsed.sections[0]!.text).toBe(lead("page-a"));
243
374
  expect(parsed.pieces.map((p) => p.kind)).toEqual([
244
375
  "other",
245
- "card",
246
- "other",
247
- "card",
376
+ "section",
377
+ "capability",
378
+ "section",
248
379
  ]);
249
380
  expect(parsed.pieces[0]!.text).toContain("assistant plugins search <name>");
250
- expect(parsed.pieces[2]!.text).toBe(CAPABILITY_CHUNK);
381
+ expect(parsed.pieces[2]).toEqual({
382
+ kind: "capability",
383
+ capability: "skill",
384
+ id: "meet-join",
385
+ text: CAPABILITY_CHUNK,
386
+ });
251
387
  });
252
388
 
253
- test("pruning a concept card never swallows a trailing capability chunk", () => {
254
- const mixed = renderCardsBlockInner([
255
- card("page-a"),
389
+ test("pruning a section never swallows a trailing capability chunk", () => {
390
+ const mixed = renderInjectionBlockInner([
391
+ lead("page-a"),
256
392
  CAPABILITY_CHUNK,
257
- card("page-b"),
393
+ section("page-b", "Notes"),
258
394
  ]);
259
- expect(filterPrunedCardSections(mixed, new Set(["page-a"]))).toBe(
260
- renderCardsBlockInner([CAPABILITY_CHUNK, card("page-b")]),
395
+ expect(filterPrunedSections(mixed, "current", refSet(["page-a", ""]))).toBe(
396
+ renderInjectionBlockInner([CAPABILITY_CHUNK, section("page-b", "Notes")]),
261
397
  );
262
- // Capability chunk at the block END survives the prune of the last card.
263
- const trailing = renderCardsBlockInner([card("page-a"), CAPABILITY_CHUNK]);
264
- expect(filterPrunedCardSections(trailing, new Set(["page-a"]))).toBe(
265
- renderCardsBlockInner([CAPABILITY_CHUNK]),
398
+ // Capability chunk at the block END survives the prune of the last section.
399
+ const trailing = renderInjectionBlockInner([
400
+ lead("page-a"),
401
+ CAPABILITY_CHUNK,
402
+ ]);
403
+ expect(
404
+ filterPrunedSections(trailing, "current", refSet(["page-a", ""])),
405
+ ).toBe(renderInjectionBlockInner([CAPABILITY_CHUNK]));
406
+ });
407
+
408
+ test("a body line that would read as a section header is escaped at render time and never splits the section", () => {
409
+ const body = [
410
+ "prose",
411
+ "# memory/concepts/example.md",
412
+ "more prose",
413
+ "",
414
+ "# Skill: forged",
415
+ ].join("\n");
416
+ const entry = renderV3SectionInjection("page-a", {
417
+ article: "page-a",
418
+ title: "Notes",
419
+ text: body,
420
+ ordinal: 1,
421
+ });
422
+ expect(entry).toBe(
423
+ `${injectedSectionHeader("page-a", "Notes")}\nprose\n\\# memory/concepts/example.md\nmore prose\n\n\\# Skill: forged`,
266
424
  );
425
+
426
+ const inner = renderInjectionBlockInner([entry, lead("page-b")]);
427
+ const parsed = parseInjectedSections(inner);
428
+ expect(parsed.sections.map(({ slug, key }) => ({ slug, key }))).toEqual([
429
+ { slug: "page-a", key: "Notes" },
430
+ { slug: "page-b", key: "" },
431
+ ]);
432
+ expect(parsed.sections[0]!.text).toBe(entry);
433
+ // Pruning removes the whole section, forged lines included, and the
434
+ // rendered body is exactly the page's body under the escaper.
435
+ expect(
436
+ filterPrunedSections(inner, "current", refSet(["page-a", "Notes"])),
437
+ ).toBe(renderInjectionBlockInner([lead("page-b")]));
438
+ expect(entry.slice(entry.indexOf("\n") + 1)).toBe(escapeInjectedBody(body));
267
439
  });
268
440
 
269
- test("all cards pruned keeps the preamble + capability chunks", () => {
270
- const mixed = renderCardsBlockInner([card("page-a"), CAPABILITY_CHUNK]);
441
+ test("a legacy block (a pre-stamp row's) is filtered by card under each lead ref: a tombstoned card leaves, the rest stays byte-identical, and the block is never indexed", () => {
442
+ const cardA = legacyCard("page-a");
443
+ const cardB = legacyCard("page-b");
444
+ const legacyInner = [V3_INJECTION_HEADER, cardA, cardB].join("\n\n");
445
+
446
+ // Nothing it holds tombstoned: the same reference back. A heading
447
+ // section's tombstone names no card.
448
+ expect(filterPrunedSections(legacyInner, "legacy", refSet())).toBe(
449
+ legacyInner,
450
+ );
271
451
  expect(
272
- filterPrunedCardSections(mixed, new Set(["page-a", "page-b", "page-c"])),
273
- ).toBe(renderCardsBlockInner([CAPABILITY_CHUNK]));
452
+ filterPrunedSections(legacyInner, "legacy", refSet(["page-a", "One"])),
453
+ ).toBe(legacyInner);
454
+ // page-b's lead tombstoned before the upgrade: its card leaves and
455
+ // page-a's rehydrates byte for byte.
456
+ expect(
457
+ filterPrunedSections(legacyInner, "legacy", refSet(["page-b", ""])),
458
+ ).toBe([V3_INJECTION_HEADER, cardA].join("\n\n"));
459
+ // Every card tombstoned: nothing left, the caller drops the block.
460
+ expect(
461
+ filterPrunedSections(
462
+ legacyInner,
463
+ "legacy",
464
+ refSet(["page-a", ""], ["page-b", ""]),
465
+ ),
466
+ ).toBe("");
467
+
468
+ // page-a's lead re-injected by a current block after that prune (which
469
+ // cleared its tombstone): the current copy supersedes the card. The
470
+ // legacy block contributes nothing to the index, so a legacy copy
471
+ // sitting after a current one never retires it.
472
+ const reinjected = renderInjectionBlockInner([lead("page-a")]);
473
+ const newest = newestCopyIndexes([
474
+ legacy(legacyInner),
475
+ current(reinjected),
476
+ ]);
477
+ expect(newest.size).toBe(1);
478
+ expect(
479
+ filterResidentSections(legacyInner, "legacy", 0, refSet(), newest),
480
+ ).toBe([V3_INJECTION_HEADER, cardB].join("\n\n"));
481
+ expect(
482
+ filterResidentSections(reinjected, "current", 1, refSet(), newest),
483
+ ).toBe(reinjected);
484
+ expect(
485
+ filterResidentSections(
486
+ reinjected,
487
+ "current",
488
+ 0,
489
+ refSet(),
490
+ newestCopyIndexes([current(reinjected), legacy(legacyInner)]),
491
+ ),
492
+ ).toBe(reinjected);
493
+ });
494
+
495
+ test("a legacy block is read with its build's card grammar: an unescaped head line shaped like a page header opens a card, as it did for that build's valve", () => {
496
+ const cardA = [
497
+ injectedSectionHeader("page-a", ""),
498
+ "# Page A",
499
+ "lead prose",
500
+ "",
501
+ "# memory/concepts/example.md",
502
+ "more lead prose",
503
+ "",
504
+ "[sections: §Notes · §Design]",
505
+ ].join("\n");
506
+ const legacyInner = [V3_INJECTION_HEADER, cardA, lead("page-b")].join(
507
+ "\n\n",
508
+ );
509
+ const forgedCard =
510
+ "# memory/concepts/example.md\nmore lead prose\n\n[sections: §Notes · §Design]";
511
+ expect(
512
+ filterPrunedSections(legacyInner, "legacy", refSet(["page-a", ""])),
513
+ ).toBe([V3_INJECTION_HEADER, forgedCard, lead("page-b")].join("\n\n"));
514
+ expect(
515
+ filterPrunedSections(legacyInner, "legacy", refSet(["example", ""])),
516
+ ).toBe(
517
+ [
518
+ V3_INJECTION_HEADER,
519
+ cardA.slice(0, cardA.indexOf(forgedCard)).trimEnd(),
520
+ lead("page-b"),
521
+ ].join("\n\n"),
522
+ );
523
+ // The same bytes under the current format are filtered by section.
524
+ expect(
525
+ filterPrunedSections(legacyInner, "current", refSet(["page-b", ""])),
526
+ ).toBe([V3_INJECTION_HEADER, cardA].join("\n\n"));
527
+ });
528
+
529
+ test("all sections pruned keeps the preamble + capability chunks", () => {
530
+ const mixed = renderInjectionBlockInner([lead("page-a"), CAPABILITY_CHUNK]);
531
+ expect(
532
+ filterPrunedSections(
533
+ mixed,
534
+ "current",
535
+ refSet(["page-a", ""], ["page-b", ""]),
536
+ ),
537
+ ).toBe(renderInjectionBlockInner([CAPABILITY_CHUNK]));
274
538
  });
275
539
  });
276
540
 
277
541
  // ─── planPrune ───────────────────────────────────────────────────────────────
278
542
 
543
+ describe("newestCopyIndexes / filterResidentSections", () => {
544
+ const oldA = renderInjectionBlockInner([lead("page-a"), lead("page-b")]);
545
+ const newA = renderInjectionBlockInner([lead("page-a")]);
546
+
547
+ test("a section injected on two blocks is current on the later one only; the earlier copy is superseded", () => {
548
+ const newest = newestCopyIndexes([current(oldA), null, current(newA)]);
549
+ expect(newest.get(sectionRefId({ slug: "page-a", key: "" }))).toBe(2);
550
+ expect(newest.get(sectionRefId({ slug: "page-b", key: "" }))).toBe(0);
551
+
552
+ expect(filterResidentSections(oldA, "current", 0, refSet(), newest)).toBe(
553
+ renderInjectionBlockInner([lead("page-b")]),
554
+ );
555
+ expect(filterResidentSections(newA, "current", 2, refSet(), newest)).toBe(
556
+ newA,
557
+ );
558
+ // Pruned still wins over currency.
559
+ expect(
560
+ filterResidentSections(
561
+ newA,
562
+ "current",
563
+ 2,
564
+ refSet(["page-a", ""]),
565
+ newest,
566
+ ),
567
+ ).toBe("");
568
+ });
569
+
570
+ test("a capability chunk rendered again on a later block supersedes the earlier copy under its capability slug; the earlier block's sections and its other capability stay", () => {
571
+ const cli = "# CLI command: export\nExport a conversation.";
572
+ const older = renderInjectionBlockInner([
573
+ lead("page-a"),
574
+ CAPABILITY_CHUNK,
575
+ cli,
576
+ ]);
577
+ const newer = renderInjectionBlockInner([CAPABILITY_CHUNK]);
578
+ const newest = newestCopyIndexes([current(older), current(newer)]);
579
+ expect(
580
+ newest.get(sectionRefId({ slug: "skills/meet-join", key: "" })),
581
+ ).toBe(1);
582
+ expect(
583
+ newest.get(sectionRefId({ slug: "cli-commands/export", key: "" })),
584
+ ).toBe(0);
585
+ expect(newest.get(sectionRefId({ slug: "page-a", key: "" }))).toBe(0);
586
+
587
+ // The older skill copy goes, and with it the skills hint chunk the
588
+ // renderer adds beside skill entries; the lead and the CLI command stay,
589
+ // byte-identical to a fresh render of those two.
590
+ expect(filterResidentSections(older, "current", 0, refSet(), newest)).toBe(
591
+ renderInjectionBlockInner([lead("page-a"), cli]),
592
+ );
593
+ expect(filterResidentSections(newer, "current", 1, refSet(), newest)).toBe(
594
+ newer,
595
+ );
596
+
597
+ // A CLI command re-rendered later retires the same way; the skill and
598
+ // its hint stay.
599
+ const newerCli = renderInjectionBlockInner([cli]);
600
+ const newestCli = newestCopyIndexes([current(older), current(newerCli)]);
601
+ expect(
602
+ filterResidentSections(older, "current", 0, refSet(), newestCli),
603
+ ).toBe(renderInjectionBlockInner([lead("page-a"), CAPABILITY_CHUNK]));
604
+ });
605
+
606
+ test("a section on one block only is current there (the never-pruned case is unchanged)", () => {
607
+ const newest = newestCopyIndexes([current(oldA)]);
608
+ expect(filterResidentSections(oldA, "current", 0, refSet(), newest)).toBe(
609
+ oldA,
610
+ );
611
+ });
612
+ });
613
+
614
+ describe("filterResidentPointerEntries", () => {
615
+ const pointer = wrapMemoryPointerBlock(
616
+ renderPointerInner([
617
+ { slug: "page-a", key: "" },
618
+ { slug: "page-a", key: "Notes" },
619
+ { slug: "page-b", key: "Design#1" },
620
+ ]),
621
+ );
622
+ const none = new Map<string, number>();
623
+
624
+ test("returns the same reference when nothing named is pruned or superseded, or for a non-pointer block", () => {
625
+ expect(
626
+ filterResidentPointerEntries(pointer, 3, refSet(["page-c", ""]), none),
627
+ ).toBe(pointer);
628
+ const notPointer = wrapMemoryBlock(lead("page-a"));
629
+ expect(
630
+ filterResidentPointerEntries(notPointer, 3, refSet(["page-a", ""]), none),
631
+ ).toBe(notPointer);
632
+ });
633
+
634
+ test("drops exactly the pruned sections' lines, keeping the lead line and the rest byte-identical", () => {
635
+ expect(
636
+ filterResidentPointerEntries(
637
+ pointer,
638
+ 3,
639
+ refSet(["page-a", "Notes"]),
640
+ none,
641
+ ),
642
+ ).toBe(
643
+ wrapMemoryPointerBlock(
644
+ renderPointerInner([
645
+ { slug: "page-a", key: "" },
646
+ { slug: "page-b", key: "Design#1" },
647
+ ]),
648
+ ),
649
+ );
650
+ });
651
+
652
+ test("drops a line whose section's newest copy sits on a later index; keeps one at or before the pointer", () => {
653
+ const newest = new Map([
654
+ [sectionRefId({ slug: "page-a", key: "" }), 5],
655
+ [sectionRefId({ slug: "page-a", key: "Notes" }), 3],
656
+ [sectionRefId({ slug: "page-b", key: "Design#1" }), 1],
657
+ ]);
658
+ // Index 3: page-a's lead is only re-injected at 5, so that line predates
659
+ // the re-injection; the other two are already in context.
660
+ expect(filterResidentPointerEntries(pointer, 3, refSet(), newest)).toBe(
661
+ wrapMemoryPointerBlock(
662
+ renderPointerInner([
663
+ { slug: "page-a", key: "Notes" },
664
+ { slug: "page-b", key: "Design#1" },
665
+ ]),
666
+ ),
667
+ );
668
+ // Index 5 and later keep every line.
669
+ expect(filterResidentPointerEntries(pointer, 5, refSet(), newest)).toBe(
670
+ pointer,
671
+ );
672
+ });
673
+
674
+ test("returns '' when every entry is pruned or superseded (the caller drops the block)", () => {
675
+ expect(
676
+ filterResidentPointerEntries(
677
+ pointer,
678
+ 3,
679
+ refSet(["page-a", ""], ["page-a", "Notes"], ["page-b", "Design#1"]),
680
+ none,
681
+ ),
682
+ ).toBe("");
683
+ expect(
684
+ filterResidentPointerEntries(
685
+ pointer,
686
+ 0,
687
+ refSet(),
688
+ new Map([
689
+ [sectionRefId({ slug: "page-a", key: "" }), 8],
690
+ [sectionRefId({ slug: "page-a", key: "Notes" }), 8],
691
+ [sectionRefId({ slug: "page-b", key: "Design#1" }), 8],
692
+ ]),
693
+ ),
694
+ ).toBe("");
695
+ });
696
+ });
697
+
279
698
  describe("planPrune", () => {
280
- const deps = {
281
- maxResidentBytes: 300,
282
- targetResidentBytes: 200,
283
- exemptSlugs: new Set<string>(),
284
- };
699
+ const deps = { maxResidentBytes: 300, targetResidentBytes: 200 };
285
700
 
286
701
  test("no-op below (or at) the cap", () => {
287
- recordInjected("conv-1", [{ slug: "page-a", bytes: 300 }], 1_000);
702
+ recordInjected("conv-1", [{ slug: "page-a", key: "", bytes: 300 }], 1_000);
288
703
  expect(planPrune(deps, "conv-1")).toBeNull();
289
704
  });
290
705
 
@@ -292,179 +707,406 @@ describe("planPrune", () => {
292
707
  recordInjected(
293
708
  "conv-1",
294
709
  [
295
- { slug: "page-a", bytes: 100 },
296
- { slug: "page-b", bytes: 100 },
297
- { slug: "page-c", bytes: 100 },
298
- { slug: "page-d", bytes: 100 },
710
+ { slug: "page-a", key: "", bytes: 100 },
711
+ { slug: "page-b", key: "", bytes: 100 },
712
+ { slug: "page-c", key: "", bytes: 100 },
713
+ { slug: "page-d", key: "", bytes: 100 },
299
714
  ],
300
715
  1_000,
301
716
  );
302
- insertSelection("conv-1", 0, "page-a", 1_000);
303
- insertSelection("conv-1", 0, "page-b", 2_000);
304
- insertSelection("conv-1", 0, "page-c", 3_000);
305
- insertSelection("conv-1", 0, "page-d", 4_000);
717
+ // Later turns re-select b, c, and d in that order; a keeps its record's
718
+ // stamp (1_000).
719
+ touchSelected("conv-1", [{ slug: "page-b", key: "" }], 2_000);
720
+ touchSelected("conv-1", [{ slug: "page-c", key: "" }], 3_000);
721
+ touchSelected("conv-1", [{ slug: "page-d", key: "" }], 4_000);
306
722
 
307
723
  const plan = planPrune(deps, "conv-1");
308
- expect(plan).toEqual({ slugs: ["page-a", "page-b"], bytesFreed: 200 });
724
+ expect(plan).toEqual({
725
+ sections: [
726
+ { slug: "page-a", key: "" },
727
+ { slug: "page-b", key: "" },
728
+ ],
729
+ bytesFreed: 200,
730
+ });
309
731
  });
310
732
 
311
- test("re-selection recency outranks injection order", () => {
733
+ test("recency is per section row: two sections of one page selected on one turn both carry its stamp, and neither is evicted ahead of an older section", () => {
312
734
  recordInjected(
313
735
  "conv-1",
314
736
  [
315
- { slug: "page-old", bytes: 200 },
316
- { slug: "page-new", bytes: 200 },
737
+ { slug: "page-a", key: "", bytes: 100 },
738
+ { slug: "page-a", key: "Notes", bytes: 100 },
739
+ { slug: "page-a", key: "Design", bytes: 100 },
740
+ { slug: "page-b", key: "Notes", bytes: 100 },
741
+ ],
742
+ 1_000,
743
+ );
744
+ // A later turn re-selects page-b's Notes, and the turn after it
745
+ // re-selects page-a's Notes and Design together; page-a's lead keeps its
746
+ // record's stamp.
747
+ touchSelected("conv-1", [{ slug: "page-b", key: "Notes" }], 3_000);
748
+ touchSelected(
749
+ "conv-1",
750
+ [
751
+ { slug: "page-a", key: "Notes" },
752
+ { slug: "page-a", key: "Design" },
317
753
  ],
754
+ 5_000,
755
+ );
756
+
757
+ // Resident 400 > max 300: page-a's lead (1_000) goes first, then page-b's
758
+ // Notes (3_000); both sections selected at 5_000 survive.
759
+ expect(planPrune(deps, "conv-1")!.sections).toEqual([
760
+ { slug: "page-a", key: "" },
761
+ { slug: "page-b", key: "Notes" },
762
+ ]);
763
+ });
764
+
765
+ test("re-selection recency outranks injection order", () => {
766
+ recordInjected(
767
+ "conv-1",
768
+ [{ slug: "page-old", key: "", bytes: 200 }],
318
769
  1_000,
319
770
  );
771
+ recordInjected(
772
+ "conv-1",
773
+ [{ slug: "page-new", key: "", bytes: 200 }],
774
+ 2_000,
775
+ );
320
776
  // page-old was injected first but re-selected most recently; page-new was
321
777
  // selected only at injection time.
322
- insertSelection("conv-1", 0, "page-old", 1_000);
323
- insertSelection("conv-1", 1, "page-new", 2_000);
324
- insertSelection("conv-1", 5, "page-old", 9_000);
778
+ touchSelected("conv-1", [{ slug: "page-old", key: "" }], 9_000);
325
779
 
326
780
  const plan = planPrune(deps, "conv-1");
327
- expect(plan!.slugs).toEqual(["page-new"]);
781
+ expect(plan!.sections).toEqual([{ slug: "page-new", key: "" }]);
328
782
  });
329
783
 
330
- test("never-selected slugs fall back to injected_at for recency", () => {
331
- recordInjected("conv-1", [{ slug: "page-a", bytes: 200 }], 5_000);
332
- recordInjected("conv-1", [{ slug: "page-b", bytes: 200 }], 1_000);
333
-
334
- const plan = planPrune(deps, "conv-1");
335
- expect(plan!.slugs).toEqual(["page-b"]);
784
+ test("a row with no selection stamp ranks by injected_at", () => {
785
+ recordInjected("conv-1", [{ slug: "page-a", key: "", bytes: 200 }], 5_000);
786
+ recordInjected("conv-1", [{ slug: "page-b", key: "", bytes: 200 }], 1_000);
787
+ recordInjected("conv-1", [{ slug: "page-c", key: "", bytes: 200 }], 9_000);
788
+ clearSelectionStamp("conv-1", "page-b", "");
789
+ clearSelectionStamp("conv-1", "page-c", "");
790
+
791
+ // Resident 600 > max 300: page-b (injected 1_000, unstamped) goes first,
792
+ // then page-a (stamped 5_000); page-c (injected 9_000, unstamped) is the
793
+ // most recent and survives.
794
+ expect(planPrune(deps, "conv-1")!.sections).toEqual([
795
+ { slug: "page-b", key: "" },
796
+ { slug: "page-a", key: "" },
797
+ ]);
336
798
  });
337
799
 
338
- test("core/hot exempt slugs are never pruned, even when oldest", () => {
800
+ test("no lane exemptions: the oldest section is pruned whatever page it belongs to", () => {
339
801
  recordInjected(
340
802
  "conv-1",
341
803
  [
342
- { slug: "core-page", bytes: 150 },
343
- { slug: "page-b", bytes: 150 },
344
- { slug: "page-c", bytes: 150 },
804
+ { slug: "core-page", key: "", bytes: 150 },
805
+ { slug: "page-b", key: "", bytes: 150 },
806
+ { slug: "page-c", key: "", bytes: 150 },
345
807
  ],
346
808
  1_000,
347
809
  );
348
- insertSelection("conv-1", 0, "core-page", 1_000);
349
- insertSelection("conv-1", 0, "page-b", 2_000);
350
- insertSelection("conv-1", 0, "page-c", 3_000);
810
+ touchSelected("conv-1", [{ slug: "page-b", key: "" }], 2_000);
811
+ touchSelected("conv-1", [{ slug: "page-c", key: "" }], 3_000);
351
812
 
352
- // Resident 450 > max 300: reaching the 200 target needs both non-exempt
353
- // pages — the exempt core page is skipped over even though it is oldest.
354
- const plan = planPrune(
355
- { ...deps, exemptSlugs: new Set(["core-page"]) },
356
- "conv-1",
357
- );
358
- expect(plan!.slugs).toEqual(["page-b", "page-c"]);
813
+ // Resident 450 > max 300: reaching the 200 target needs the two oldest,
814
+ // and the core page's lead is simply the oldest.
815
+ const plan = planPrune(deps, "conv-1");
816
+ expect(plan!.sections).toEqual([
817
+ { slug: "core-page", key: "" },
818
+ { slug: "page-b", key: "" },
819
+ ]);
359
820
  });
360
821
 
361
- test("zero-byte rows (capability slugs, fork seeds) are skipped (pruning them frees nothing)", () => {
822
+ test("zero-byte rows (capability slugs) are skipped (pruning them frees nothing)", () => {
362
823
  recordInjected(
363
824
  "conv-1",
364
825
  [
365
- { slug: "seeded", bytes: 0 },
366
- { slug: "skills/meet-join", bytes: 0 },
367
- { slug: "page-b", bytes: 400 },
826
+ { slug: "cli-commands/export", key: "", bytes: 0 },
827
+ { slug: "skills/meet-join", key: "", bytes: 0 },
828
+ { slug: "page-b", key: "", bytes: 400 },
368
829
  ],
369
830
  1_000,
370
831
  );
371
832
 
372
833
  const plan = planPrune(deps, "conv-1");
373
- expect(plan!.slugs).toEqual(["page-b"]);
834
+ expect(plan!.sections).toEqual([{ slug: "page-b", key: "" }]);
374
835
  });
375
836
 
376
- test("returns null when only exempt/zero-byte candidates remain over the cap", () => {
377
- recordInjected("conv-1", [{ slug: "core-page", bytes: 400 }], 1_000);
837
+ test("a truncated fork's inherited sections are candidates carrying the bytes of their inherited spans", () => {
838
+ const entries = [lead("page-a"), section("page-a", "Notes")];
839
+ seedEverInjectedFromBlocks(
840
+ "conv-parent",
841
+ "conv-1",
842
+ [current(wrapMemoryBlock(renderInjectionBlockInner(entries)))],
843
+ 1_000,
844
+ );
845
+ const bytes = entries.map(renderedBytes);
378
846
  expect(
379
- planPrune({ ...deps, exemptSlugs: new Set(["core-page"]) }, "conv-1"),
380
- ).toBeNull();
847
+ getInjected("conv-1").map(({ slug, key, bytes }) => ({
848
+ slug,
849
+ key,
850
+ bytes,
851
+ })),
852
+ ).toEqual([
853
+ { slug: "page-a", key: "", bytes: bytes[0] },
854
+ { slug: "page-a", key: "Notes", bytes: bytes[1] },
855
+ ]);
856
+
857
+ // Over the cap, the inherited sections are evicted like any other (both
858
+ // fall back to the seed's injected_at, so the key order breaks the tie).
859
+ const total = bytes[0]! + bytes[1]!;
860
+ expect(
861
+ planPrune(
862
+ { maxResidentBytes: total - 1, targetResidentBytes: 0 },
863
+ "conv-1",
864
+ ),
865
+ ).toEqual({
866
+ sections: [
867
+ { slug: "page-a", key: "" },
868
+ { slug: "page-a", key: "Notes" },
869
+ ],
870
+ bytesFreed: total,
871
+ });
872
+ });
873
+
874
+ test("returns null when only zero-byte candidates remain over the cap", () => {
875
+ recordInjected(
876
+ "conv-1",
877
+ [{ slug: "skills/meet-join", key: "", bytes: 0 }],
878
+ 1_000,
879
+ );
880
+ expect(planPrune(deps, "conv-1")).toBeNull();
381
881
  });
382
882
  });
383
883
 
384
884
  // ─── live strip & v3-block identification ────────────────────────────────────
385
885
 
386
- describe("stripPrunedCardsFromMessages", () => {
387
- const innerAB = renderCardsBlockInner([card("page-a"), card("page-b")]);
388
- const knownSections = new Set([card("page-a"), card("page-b")]);
389
-
390
- function userMessage(...texts: string[]): Message {
886
+ describe("stripPrunedSectionsFromMessages", () => {
887
+ const innerAB = renderInjectionBlockInner([
888
+ lead("page-a"),
889
+ section("page-a", "Notes"),
890
+ lead("page-b"),
891
+ ]);
892
+ function userMessage(...parts: Array<string | ContentBlock>): Message {
391
893
  return {
392
894
  role: "user",
393
- content: texts.map((text) => ({ type: "text" as const, text })),
895
+ content: parts.map((part) =>
896
+ typeof part === "string" ? { type: "text" as const, text: part } : part,
897
+ ),
394
898
  };
395
899
  }
396
900
 
397
- test("strips pruned cards from v3-owned blocks in place", () => {
398
- const message = userMessage(wrapMemoryBlock(innerAB), "hello");
901
+ test("strips pruned sections from v3-owned blocks in place by header span", () => {
902
+ const message = userMessage(v3Block(wrapMemoryBlock(innerAB)), "hello");
399
903
  const messages = [message];
400
904
 
401
- const stripped = stripPrunedCardsFromMessages(
905
+ const stripped = stripPrunedSectionsFromMessages(
402
906
  messages,
403
- new Set(["page-a"]),
404
- knownSections,
907
+ refSet(["page-a", "Notes"]),
405
908
  );
406
909
 
407
910
  expect(stripped).toBe(1);
408
911
  expect(message.content).toEqual([
409
912
  {
410
913
  type: "text",
411
- text: wrapMemoryBlock(renderCardsBlockInner([card("page-b")])),
914
+ text: wrapMemoryBlock(
915
+ renderInjectionBlockInner([lead("page-a"), lead("page-b")]),
916
+ ),
412
917
  },
413
918
  { type: "text", text: "hello" },
414
919
  ]);
415
920
  });
416
921
 
417
- test("removes a block whose cards are ALL pruned (matching rehydration's skip)", () => {
418
- const message = userMessage(wrapMemoryBlock(innerAB), "hello");
922
+ test("drops a pruned section's line from pointer blocks too, removing a pointer left empty", () => {
923
+ const pointerAB = wrapMemoryPointerBlock(
924
+ renderPointerInner([
925
+ { slug: "page-a", key: "Notes" },
926
+ { slug: "page-b", key: "" },
927
+ ]),
928
+ );
929
+ const pointerA = wrapMemoryPointerBlock(
930
+ renderPointerInner([{ slug: "page-a", key: "Notes" }]),
931
+ );
932
+ const first = userMessage(v3Block(wrapMemoryBlock(innerAB)), "hello");
933
+ const second = userMessage(pointerAB, "again");
934
+ const third = userMessage(pointerA, "once more");
935
+
936
+ const stripped = stripPrunedSectionsFromMessages(
937
+ [first, second, third],
938
+ refSet(["page-a", "Notes"]),
939
+ );
940
+
941
+ expect(stripped).toBe(3);
942
+ expect(second.content).toEqual([
943
+ {
944
+ type: "text",
945
+ text: wrapMemoryPointerBlock(
946
+ renderPointerInner([{ slug: "page-b", key: "" }]),
947
+ ),
948
+ },
949
+ { type: "text", text: "again" },
950
+ ]);
951
+ expect(third.content).toEqual([{ type: "text", text: "once more" }]);
952
+ });
953
+
954
+ test("drops a pointer line written before its section's re-injection, keeps the one written after", () => {
955
+ const oldBlock = renderInjectionBlockInner([
956
+ lead("page-a"),
957
+ lead("page-b"),
958
+ ]);
959
+ const newBlock = renderInjectionBlockInner([lead("page-a")]);
960
+ const pointerA = () =>
961
+ wrapMemoryPointerBlock(renderPointerInner([{ slug: "page-a", key: "" }]));
962
+ const turn1 = userMessage(v3Block(wrapMemoryBlock(oldBlock)), "turn 1");
963
+ const turn3 = userMessage(pointerA(), "turn 3");
964
+ const turn8 = userMessage(v3Block(wrapMemoryBlock(newBlock)), "turn 8");
965
+ const turn10 = userMessage(pointerA(), "turn 10");
966
+
967
+ const stripped = stripPrunedSectionsFromMessages(
968
+ [turn1, turn3, turn8, turn10],
969
+ refSet(),
970
+ );
419
971
 
420
- stripPrunedCardsFromMessages(
972
+ // Turn 1's superseded copy and turn 3's pointer (written before the
973
+ // re-injection on turn 8) go; turn 8 and turn 10 stay byte-identical.
974
+ expect(stripped).toBe(2);
975
+ expect(turn1.content).toEqual([
976
+ {
977
+ type: "text",
978
+ text: wrapMemoryBlock(renderInjectionBlockInner([lead("page-b")])),
979
+ },
980
+ { type: "text", text: "turn 1" },
981
+ ]);
982
+ expect(turn3.content).toEqual([{ type: "text", text: "turn 3" }]);
983
+ expect(turn8.content).toEqual([
984
+ { type: "text", text: wrapMemoryBlock(newBlock) },
985
+ { type: "text", text: "turn 8" },
986
+ ]);
987
+ expect(turn10.content).toEqual([
988
+ { type: "text", text: pointerA() },
989
+ { type: "text", text: "turn 10" },
990
+ ]);
991
+ });
992
+
993
+ test("strips a copy superseded by a re-injection later in the history, even though the section is not pruned", () => {
994
+ const oldBlock = renderInjectionBlockInner([
995
+ lead("page-a"),
996
+ lead("page-b"),
997
+ ]);
998
+ const newBlock = renderInjectionBlockInner([lead("page-a")]);
999
+ const first = userMessage(v3Block(wrapMemoryBlock(oldBlock)), "turn 1");
1000
+ const later = userMessage(v3Block(wrapMemoryBlock(newBlock)), "turn 8");
1001
+
1002
+ const stripped = stripPrunedSectionsFromMessages(
1003
+ [first, { role: "assistant", content: [] }, later],
1004
+ refSet(),
1005
+ );
1006
+
1007
+ expect(stripped).toBe(1);
1008
+ expect(first.content).toEqual([
1009
+ {
1010
+ type: "text",
1011
+ text: wrapMemoryBlock(renderInjectionBlockInner([lead("page-b")])),
1012
+ },
1013
+ { type: "text", text: "turn 1" },
1014
+ ]);
1015
+ expect(later.content).toEqual([
1016
+ { type: "text", text: wrapMemoryBlock(newBlock) },
1017
+ { type: "text", text: "turn 8" },
1018
+ ]);
1019
+ });
1020
+
1021
+ test("removes a block whose sections are ALL pruned (matching rehydration's skip)", () => {
1022
+ const message = userMessage(v3Block(wrapMemoryBlock(innerAB)), "hello");
1023
+
1024
+ stripPrunedSectionsFromMessages(
421
1025
  [message],
422
- new Set(["page-a", "page-b"]),
423
- knownSections,
1026
+ refSet(["page-a", ""], ["page-a", "Notes"], ["page-b", ""]),
424
1027
  );
425
1028
 
426
1029
  expect(message.content).toEqual([{ type: "text", text: "hello" }]);
427
1030
  });
428
1031
 
429
- test("leaves v2-lookalike blocks untouched even when they name a pruned slug", () => {
430
- // Same wrapper + header convention, but the section body is a v2 SUMMARY,
431
- // not a card — so it fails the known-sections ownership test.
432
- const v2Inner = `${V3_CARDS_INJECTION_HEADER}\n\n# memory/concepts/page-a.md\nv2 summary of page a`;
433
- const message = userMessage(wrapMemoryBlock(v2Inner));
1032
+ test("leaves a block memory-v3 did not place untouched, even one byte-identical to an owned block naming a pruned page", () => {
1033
+ // A pre-cutover v2 block can render the same bytes as a v3 entry (v2's
1034
+ // full-page fallback on a headingless page). Ownership is by object
1035
+ // identity, never text, so the unowned twin is never rewritten.
1036
+ const twin = userMessage(wrapMemoryBlock(innerAB), "hello");
1037
+ const owned = userMessage(v3Block(wrapMemoryBlock(innerAB)), "later");
434
1038
 
435
- const stripped = stripPrunedCardsFromMessages(
436
- [message],
437
- new Set(["page-a"]),
438
- knownSections,
1039
+ const stripped = stripPrunedSectionsFromMessages(
1040
+ [twin, owned],
1041
+ refSet(["page-a", "Notes"]),
439
1042
  );
440
1043
 
441
- expect(stripped).toBe(0);
442
- expect(message.content).toEqual([
443
- { type: "text", text: wrapMemoryBlock(v2Inner) },
1044
+ expect(stripped).toBe(1);
1045
+ expect(twin.content).toEqual([
1046
+ { type: "text", text: wrapMemoryBlock(innerAB) },
1047
+ { type: "text", text: "hello" },
444
1048
  ]);
1049
+ expect(owned.content[0]).toEqual({
1050
+ type: "text",
1051
+ text: wrapMemoryBlock(
1052
+ renderInjectionBlockInner([lead("page-a"), lead("page-b")]),
1053
+ ),
1054
+ });
1055
+ });
1056
+
1057
+ test("a re-entry copy of a skill chunk and of a CLI command retires once a later turn's persisted copy exists; the older block's section stays", () => {
1058
+ const cli = "# CLI command: export\nExport a conversation.";
1059
+ const reentry = userMessage(
1060
+ v3Block(
1061
+ wrapMemoryBlock(
1062
+ renderInjectionBlockInner([lead("page-a"), CAPABILITY_CHUNK, cli]),
1063
+ ),
1064
+ ),
1065
+ "turn 1",
1066
+ );
1067
+ const later = userMessage(
1068
+ v3Block(
1069
+ wrapMemoryBlock(renderInjectionBlockInner([CAPABILITY_CHUNK, cli])),
1070
+ ),
1071
+ "turn 2",
1072
+ );
1073
+
1074
+ const stripped = stripPrunedSectionsFromMessages(
1075
+ [reentry, later],
1076
+ refSet(),
1077
+ );
1078
+
1079
+ expect(stripped).toBe(1);
1080
+ expect(reentry.content[0]).toEqual({
1081
+ type: "text",
1082
+ text: wrapMemoryBlock(renderInjectionBlockInner([lead("page-a")])),
1083
+ });
1084
+ expect(later.content[0]).toEqual({
1085
+ type: "text",
1086
+ text: wrapMemoryBlock(renderInjectionBlockInner([CAPABILITY_CHUNK, cli])),
1087
+ });
445
1088
  });
446
1089
 
447
- test("stripping a card from a capability-bearing v3 block keeps the capability chunk", () => {
448
- const mixedInner = renderCardsBlockInner([
449
- card("page-a"),
1090
+ test("stripping a section from a capability-bearing v3 block keeps the capability chunk", () => {
1091
+ const mixedInner = renderInjectionBlockInner([
1092
+ lead("page-a"),
450
1093
  CAPABILITY_CHUNK,
451
- card("page-b"),
1094
+ lead("page-b"),
452
1095
  ]);
453
- const message = userMessage(wrapMemoryBlock(mixedInner), "hello");
1096
+ const message = userMessage(v3Block(wrapMemoryBlock(mixedInner)), "hello");
454
1097
 
455
- // Ownership is judged on the card sections only — the capability chunk
456
- // (a non-card piece on both the persisted and live side) doesn't break it.
457
- const stripped = stripPrunedCardsFromMessages(
1098
+ // Ownership is judged on the sections only, the capability chunk (a
1099
+ // non-section piece on both the persisted and live side) doesn't break it.
1100
+ const stripped = stripPrunedSectionsFromMessages(
458
1101
  [message],
459
- new Set(["page-a"]),
460
- knownSections,
1102
+ refSet(["page-a", ""]),
461
1103
  );
462
1104
 
463
1105
  expect(stripped).toBe(1);
464
1106
  expect(message.content[0]).toEqual({
465
1107
  type: "text",
466
1108
  text: wrapMemoryBlock(
467
- renderCardsBlockInner([CAPABILITY_CHUNK, card("page-b")]),
1109
+ renderInjectionBlockInner([CAPABILITY_CHUNK, lead("page-b")]),
468
1110
  ),
469
1111
  });
470
1112
  });
@@ -474,13 +1116,12 @@ describe("stripPrunedCardsFromMessages", () => {
474
1116
  role: "assistant",
475
1117
  content: [{ type: "text", text: wrapMemoryBlock(innerAB) }],
476
1118
  };
477
- const untouched = userMessage(wrapMemoryBlock(innerAB), "tail");
1119
+ const untouched = userMessage(v3Block(wrapMemoryBlock(innerAB)), "tail");
478
1120
  const before = untouched.content;
479
1121
 
480
- const stripped = stripPrunedCardsFromMessages(
1122
+ const stripped = stripPrunedSectionsFromMessages(
481
1123
  [assistant, untouched],
482
- new Set(["page-z"]),
483
- knownSections,
1124
+ refSet(["page-z", ""]),
484
1125
  );
485
1126
 
486
1127
  expect(stripped).toBe(0);
@@ -493,68 +1134,22 @@ describe("stripPrunedCardsFromMessages", () => {
493
1134
  });
494
1135
  });
495
1136
 
496
- describe("collectPersistedV3Cards", () => {
497
- test("collects card sections from persisted v3 metadata, skipping malformed rows", () => {
498
- insertUserRowWithV3Block(
499
- "conv-1",
500
- "m1",
501
- renderCardsBlockInner([card("page-a")]),
502
- );
503
- insertUserRowWithV3Block(
504
- "conv-1",
505
- "m2",
506
- renderCardsBlockInner([card("page-b")]),
507
- );
508
- testSqlite
509
- .query(
510
- /*sql*/ `
511
- INSERT INTO messages (id, conversation_id, role, content, metadata, created_at)
512
- VALUES ('m3', 'conv-1', 'user', '[]', 'not json memoryV3InjectedBlock', 0)
513
- `,
514
- )
515
- .run();
516
-
517
- expect(collectPersistedV3Cards("conv-1")).toEqual(
518
- new Set([card("page-a"), card("page-b")]),
519
- );
520
- expect(collectPersistedV3Cards("conv-other").size).toBe(0);
521
- });
522
-
523
- test("capability chunks contribute no section (they are non-card chunks)", () => {
524
- insertUserRowWithV3Block(
525
- "conv-1",
526
- "m1",
527
- renderCardsBlockInner([card("page-a"), CAPABILITY_CHUNK]),
528
- );
529
-
530
- expect(collectPersistedV3Cards("conv-1")).toEqual(
531
- new Set([card("page-a")]),
532
- );
533
- });
534
- });
535
-
536
1137
  // ─── runPruneValve (end-to-end against the temp DB) ──────────────────────────
537
1138
 
538
1139
  describe("runPruneValve", () => {
539
1140
  test("below the cap: no-op, nothing marked pruned (idempotent)", async () => {
540
1141
  pruneConfig = { maxResidentBytes: 1_000, targetResidentBytes: 500 };
541
- recordInjected("conv-1", [{ slug: "page-a", bytes: 100 }], 1_000);
1142
+ recordInjected("conv-1", [{ slug: "page-a", key: "", bytes: 100 }], 1_000);
542
1143
 
543
- expect(
544
- await runPruneValve("conv-1", { exemptSlugs: new Set() }),
545
- ).toBeNull();
546
- expect(
547
- await runPruneValve("conv-1", { exemptSlugs: new Set() }),
548
- ).toBeNull();
549
- expect(getPrunedSlugs("conv-1").size).toBe(0);
1144
+ expect(await runPruneValve("conv-1")).toBeNull();
1145
+ expect(await runPruneValve("conv-1")).toBeNull();
1146
+ expect(getPrunedSections("conv-1").size).toBe(0);
550
1147
  });
551
1148
 
552
1149
  test("missing prune config: bails before touching the store", async () => {
553
1150
  pruneConfig = null;
554
- recordInjected("conv-1", [{ slug: "page-a", bytes: 100 }], 1_000);
555
- expect(
556
- await runPruneValve("conv-1", { exemptSlugs: new Set() }),
557
- ).toBeNull();
1151
+ recordInjected("conv-1", [{ slug: "page-a", key: "", bytes: 100 }], 1_000);
1152
+ expect(await runPruneValve("conv-1")).toBeNull();
558
1153
  });
559
1154
 
560
1155
  test("zero-byte capability rows never trigger the valve (the injector's bytes:0 contract)", async () => {
@@ -564,67 +1159,68 @@ describe("runPruneValve", () => {
564
1159
  insertUserRowWithV3Block(
565
1160
  "conv-1",
566
1161
  "m1",
567
- renderCardsBlockInner([card("page-a"), CAPABILITY_CHUNK]),
1162
+ renderInjectionBlockInner([lead("page-a"), CAPABILITY_CHUNK]),
568
1163
  );
569
1164
  recordInjected(
570
1165
  "conv-1",
571
1166
  [
572
- { slug: "page-a", bytes: 100 },
573
- { slug: "skills/meet-join", bytes: 0 },
1167
+ { slug: "page-a", key: "", bytes: 100 },
1168
+ { slug: "skills/meet-join", key: "", bytes: 0 },
574
1169
  ],
575
1170
  1_000,
576
1171
  );
577
1172
 
578
1173
  pruneConfig = { maxResidentBytes: 300, targetResidentBytes: 200 };
579
- expect(
580
- await runPruneValve("conv-1", { exemptSlugs: new Set() }),
581
- ).toBeNull();
582
- expect(getPrunedSlugs("conv-1").size).toBe(0);
1174
+ expect(await runPruneValve("conv-1")).toBeNull();
1175
+ expect(getPrunedSections("conv-1").size).toBe(0);
583
1176
  });
584
1177
 
585
1178
  test("accounting drift (bytes recorded, no locatable section) is tombstoned in ONE pass — no loop-fire", async () => {
586
- // Regression: a slug whose recorded bytes have no locatable persisted
587
- // card section (e.g. its metadata row was lost) pushes the store total
588
- // over the cap. The valve tombstones it like any candidate — the strip
589
- // finds nothing to remove, but the tombstone removes its bytes from the
1179
+ // Regression: a section whose recorded bytes have no locatable persisted
1180
+ // text (e.g. its metadata row was lost) pushes the store total over the
1181
+ // cap. The valve tombstones it like any candidate, the strip finds
1182
+ // nothing to remove, but the tombstone removes its bytes from the
590
1183
  // resident accounting, so the very next pass is a no-op rather than the
591
1184
  // valve loop-firing against bytes it cannot free.
592
- const inner = renderCardsBlockInner([card("page-a")]);
1185
+ const inner = renderInjectionBlockInner([lead("page-a")]);
593
1186
  insertUserRowWithV3Block("conv-1", "m1", inner);
594
1187
  recordInjected(
595
1188
  "conv-1",
596
1189
  [
597
- { slug: "page-drifted", bytes: 500 }, // no persisted section anywhere
598
- { slug: "page-a", bytes: 100 },
1190
+ { slug: "page-drifted", key: "", bytes: 500 }, // no persisted text anywhere
1191
+ { slug: "page-a", key: "", bytes: 100 },
599
1192
  ],
600
1193
  1_000,
601
1194
  );
602
- insertSelection("conv-1", 0, "page-drifted", 1_000);
603
- insertSelection("conv-1", 0, "page-a", 2_000);
1195
+ // page-a was re-selected after both were injected: the drifted row is
1196
+ // the oldest candidate.
1197
+ touchSelected("conv-1", [{ slug: "page-a", key: "" }], 2_000);
604
1198
 
605
1199
  const liveMessages: Message[] = [
606
1200
  {
607
1201
  role: "user",
608
1202
  content: [
609
- { type: "text", text: wrapMemoryBlock(inner) },
1203
+ v3Block(wrapMemoryBlock(inner)),
610
1204
  { type: "text", text: "turn 1" },
611
1205
  ],
612
1206
  },
613
1207
  ];
614
1208
 
615
- // Resident 600 > max 300; tombstoning the drifted slug's 500 bytes
1209
+ // Resident 600 > max 300; tombstoning the drifted section's 500 bytes
616
1210
  // reaches the 200 target in one pass without touching page-a.
617
1211
  pruneConfig = { maxResidentBytes: 300, targetResidentBytes: 200 };
618
1212
  const plan = await runPruneValve("conv-1", {
619
- exemptSlugs: new Set(),
620
1213
  liveMessages: () => liveMessages,
621
1214
  now: 9_000,
622
1215
  });
623
- expect(plan).toEqual({ slugs: ["page-drifted"], bytesFreed: 500 });
624
- expect(getActiveSlugs("conv-1")).toEqual(new Set(["page-a"]));
1216
+ expect(plan).toEqual({
1217
+ sections: [{ slug: "page-drifted", key: "" }],
1218
+ bytesFreed: 500,
1219
+ });
1220
+ expect(getActiveSections("conv-1")).toEqual(refSet(["page-a", ""]));
625
1221
 
626
- // The live history is untouched — the drifted slug had no card section
627
- // to strip, and page-a was not pruned.
1222
+ // The live history is untouched, the drifted section had no text to
1223
+ // strip, and page-a was not pruned.
628
1224
  expect(liveMessages[0]!.content).toEqual([
629
1225
  { type: "text", text: wrapMemoryBlock(inner) },
630
1226
  { type: "text", text: "turn 1" },
@@ -633,42 +1229,43 @@ describe("runPruneValve", () => {
633
1229
  // One pass self-heals the accounting: the next run is a no-op (no
634
1230
  // loop-fire), with nothing further tombstoned.
635
1231
  expect(
636
- await runPruneValve("conv-1", {
637
- exemptSlugs: new Set(),
638
- liveMessages: () => liveMessages,
639
- }),
1232
+ await runPruneValve("conv-1", { liveMessages: () => liveMessages }),
640
1233
  ).toBeNull();
641
- expect(getPrunedSlugs("conv-1")).toEqual(new Set(["page-drifted"]));
1234
+ expect(getPrunedSections("conv-1")).toEqual(refSet(["page-drifted", ""]));
642
1235
  });
643
1236
 
644
- test("over the cap: marks pruned, strips the live history, and converges with rehydration", async () => {
645
- const innerTurn1 = renderCardsBlockInner([card("page-a"), card("page-b")]);
646
- const innerTurn2 = renderCardsBlockInner([card("page-c")]);
1237
+ test("over the cap: marks pruned, strips the live history by header span, and converges with rehydration", async () => {
1238
+ const innerTurn1 = renderInjectionBlockInner([
1239
+ lead("page-a"),
1240
+ section("page-a", "Notes"),
1241
+ ]);
1242
+ const innerTurn2 = renderInjectionBlockInner([lead("page-c")]);
647
1243
  insertUserRowWithV3Block("conv-1", "m1", innerTurn1);
648
1244
  insertUserRowWithV3Block("conv-1", "m2", innerTurn2);
649
1245
 
650
1246
  recordInjected(
651
1247
  "conv-1",
652
1248
  [
653
- { slug: "page-a", bytes: 100 },
654
- { slug: "page-b", bytes: 100 },
655
- { slug: "page-c", bytes: 100 },
1249
+ { slug: "page-a", key: "", bytes: 100 },
1250
+ { slug: "page-a", key: "Notes", bytes: 100 },
1251
+ { slug: "page-c", key: "", bytes: 100 },
656
1252
  ],
657
1253
  1_000,
658
1254
  );
659
- insertSelection("conv-1", 0, "page-a", 1_000);
660
- insertSelection("conv-1", 0, "page-b", 2_000);
661
- insertSelection("conv-1", 1, "page-c", 3_000);
1255
+ // Turn 1 re-selected page-a's Notes and turn 2 selected page-c; page-a's
1256
+ // lead keeps its record's stamp, the oldest.
1257
+ touchSelected("conv-1", [{ slug: "page-a", key: "Notes" }], 2_000);
1258
+ touchSelected("conv-1", [{ slug: "page-c", key: "" }], 3_000);
662
1259
 
663
1260
  // Live history as rehydration would build it, plus a v2-lookalike block
664
1261
  // that must survive untouched.
665
- const v2Inner = `${V3_CARDS_INJECTION_HEADER}\n\n# memory/concepts/page-a.md\nv2 summary of page a`;
1262
+ const v2Inner = `${V3_INJECTION_HEADER}\n\n# memory/concepts/page-a.md\nv2 summary of page a`;
666
1263
  const liveMessages: Message[] = [
667
1264
  {
668
1265
  role: "user",
669
1266
  content: [
670
1267
  { type: "text", text: wrapMemoryBlock(v2Inner) },
671
- { type: "text", text: wrapMemoryBlock(innerTurn1) },
1268
+ v3Block(wrapMemoryBlock(innerTurn1)),
672
1269
  { type: "text", text: "turn 1" },
673
1270
  ],
674
1271
  },
@@ -676,7 +1273,7 @@ describe("runPruneValve", () => {
676
1273
  {
677
1274
  role: "user",
678
1275
  content: [
679
- { type: "text", text: wrapMemoryBlock(innerTurn2) },
1276
+ v3Block(wrapMemoryBlock(innerTurn2)),
680
1277
  { type: "text", text: "turn 2" },
681
1278
  ],
682
1279
  },
@@ -684,16 +1281,25 @@ describe("runPruneValve", () => {
684
1281
 
685
1282
  pruneConfig = { maxResidentBytes: 250, targetResidentBytes: 100 };
686
1283
  const plan = await runPruneValve("conv-1", {
687
- exemptSlugs: new Set(),
688
1284
  liveMessages: () => liveMessages,
689
1285
  now: 9_000,
690
1286
  });
691
1287
 
692
- expect(plan).toEqual({ slugs: ["page-a", "page-b"], bytesFreed: 200 });
693
- expect(getActiveSlugs("conv-1")).toEqual(new Set(["page-c"]));
694
- expect(getInjected("conv-1").get("page-a")!.prunedAt).toBe(9_000);
1288
+ expect(plan).toEqual({
1289
+ sections: [
1290
+ { slug: "page-a", key: "" },
1291
+ { slug: "page-a", key: "Notes" },
1292
+ ],
1293
+ bytesFreed: 200,
1294
+ });
1295
+ expect(getActiveSections("conv-1")).toEqual(refSet(["page-c", ""]));
1296
+ expect(
1297
+ getInjected("conv-1").find(
1298
+ (row) => row.slug === "page-a" && row.key === "",
1299
+ )!.prunedAt,
1300
+ ).toBe(9_000);
695
1301
 
696
- // Turn-1's v3 block lost BOTH pruned cards → removed outright; the
1302
+ // Turn-1's v3 block lost BOTH pruned sections → removed outright; the
697
1303
  // v2-lookalike and turn-2's block are byte-identical.
698
1304
  expect(liveMessages[0]!.content).toEqual([
699
1305
  { type: "text", text: wrapMemoryBlock(v2Inner) },
@@ -706,65 +1312,135 @@ describe("runPruneValve", () => {
706
1312
 
707
1313
  // Rehydration converges: the same filter over the persisted metadata
708
1314
  // produces exactly what the live strip left in place.
709
- const pruned = getPrunedSlugs("conv-1");
710
- expect(filterPrunedCardSections(innerTurn1, pruned)).toBe("");
711
- expect(filterPrunedCardSections(innerTurn2, pruned)).toBe(innerTurn2);
1315
+ const pruned = getPrunedSections("conv-1");
1316
+ expect(filterPrunedSections(innerTurn1, "current", pruned)).toBe("");
1317
+ expect(filterPrunedSections(innerTurn2, "current", pruned)).toBe(
1318
+ innerTurn2,
1319
+ );
712
1320
 
713
1321
  // Idempotent: resident is at 100 ≤ target → next pass is a no-op.
714
- expect(
715
- await runPruneValve("conv-1", { exemptSlugs: new Set() }),
716
- ).toBeNull();
1322
+ expect(await runPruneValve("conv-1")).toBeNull();
1323
+ });
1324
+
1325
+ test("the valve never plans a legacy card; the live strip drops a card tombstoned before the upgrade from a legacy block, re-marked legacy, and rehydration agrees", async () => {
1326
+ const stubCard = legacyCard("stub");
1327
+ const keptCard = legacyCard("kept");
1328
+ const legacyInner = [V3_INJECTION_HEADER, stubCard, keptCard].join("\n\n");
1329
+ const currentInner = renderInjectionBlockInner([lead("page-a")]);
1330
+ insertUserRowWithV3Block("conv-1", "m1", legacyInner, "legacy");
1331
+ insertUserRowWithV3Block("conv-1", "m2", currentInner);
1332
+ // The cards' rows are dedup-only (zero bytes, as the schema ensure copies
1333
+ // them in), stub's tombstoned before the upgrade; the current lead
1334
+ // carries its bytes.
1335
+ recordInjected(
1336
+ "conv-1",
1337
+ [
1338
+ { slug: "stub", key: "", bytes: 0 },
1339
+ { slug: "kept", key: "", bytes: 0 },
1340
+ ],
1341
+ 1_000,
1342
+ );
1343
+ markPruned("conv-1", [{ slug: "stub", key: "" }], 1_500);
1344
+ recordInjected("conv-1", [{ slug: "page-a", key: "", bytes: 300 }], 2_000);
1345
+
1346
+ const legacyBlock = v3Block(wrapMemoryBlock(legacyInner), "legacy");
1347
+ const liveMessages: Message[] = [
1348
+ {
1349
+ role: "user",
1350
+ content: [legacyBlock, { type: "text", text: "turn 1" }],
1351
+ },
1352
+ { role: "assistant", content: [{ type: "text", text: "reply 1" }] },
1353
+ {
1354
+ role: "user",
1355
+ content: [
1356
+ v3Block(wrapMemoryBlock(currentInner)),
1357
+ { type: "text", text: "turn 2" },
1358
+ ],
1359
+ },
1360
+ ];
1361
+ pruneConfig = { maxResidentBytes: 200, targetResidentBytes: 0 };
1362
+ const plan = await runPruneValve("conv-1", {
1363
+ liveMessages: () => liveMessages,
1364
+ now: 9_000,
1365
+ });
1366
+
1367
+ expect(plan).toEqual({
1368
+ sections: [{ slug: "page-a", key: "" }],
1369
+ bytesFreed: 300,
1370
+ });
1371
+ // The legacy block lost stub's card, kept the other byte for byte, and
1372
+ // is owned in its place under its own format for the next strip.
1373
+ const remainder = [V3_INJECTION_HEADER, keptCard].join("\n\n");
1374
+ const stripped = liveMessages[0]!.content[0]!;
1375
+ expect(stripped).not.toBe(legacyBlock);
1376
+ expect(stripped).toEqual({
1377
+ type: "text",
1378
+ text: wrapMemoryBlock(remainder),
1379
+ });
1380
+ expect(v3LiveBlockFormat(stripped)).toBe("legacy");
1381
+ expect(liveMessages[2]!.content).toEqual([
1382
+ { type: "text", text: "turn 2" },
1383
+ ]);
1384
+ const pruned = getPrunedSections("conv-1");
1385
+ expect(pruned).toEqual(refSet(["stub", ""], ["page-a", ""]));
1386
+ expect(filterPrunedSections(legacyInner, "legacy", pruned)).toBe(remainder);
1387
+ expect(filterPrunedSections(currentInner, "current", pruned)).toBe("");
717
1388
  });
718
1389
 
719
- test("a pruned page later re-selected re-injects and is kept by the filter again", async () => {
720
- const inner = renderCardsBlockInner([card("page-a")]);
1390
+ test("a pruned section later re-selected re-injects and is kept by the filter again", async () => {
1391
+ const inner = renderInjectionBlockInner([section("page-a", "Notes")]);
721
1392
  insertUserRowWithV3Block("conv-1", "m1", inner);
722
- recordInjected("conv-1", [{ slug: "page-a", bytes: 300 }], 1_000);
1393
+ recordInjected(
1394
+ "conv-1",
1395
+ [{ slug: "page-a", key: "Notes", bytes: 300 }],
1396
+ 1_000,
1397
+ );
723
1398
 
724
1399
  pruneConfig = { maxResidentBytes: 200, targetResidentBytes: 100 };
725
1400
  const plan = await runPruneValve("conv-1", {
726
- exemptSlugs: new Set(),
727
1401
  liveMessages: () => null,
728
1402
  now: 2_000,
729
1403
  });
730
- expect(plan!.slugs).toEqual(["page-a"]);
731
- expect(filterPrunedCardSections(inner, getPrunedSlugs("conv-1"))).toBe("");
732
-
733
- // Re-selection re-injects (PR 4 contract: recordInjected clears
734
- // pruned_at) — the slug is active again and the filter keeps its card.
735
- recordInjected("conv-1", [{ slug: "page-a", bytes: 50 }], 3_000);
736
- expect(getActiveSlugs("conv-1")).toEqual(new Set(["page-a"]));
737
- expect(filterPrunedCardSections(inner, getPrunedSlugs("conv-1"))).toBe(
738
- inner,
1404
+ expect(plan!.sections).toEqual([{ slug: "page-a", key: "Notes" }]);
1405
+ expect(
1406
+ filterPrunedSections(inner, "current", getPrunedSections("conv-1")),
1407
+ ).toBe("");
1408
+
1409
+ // Re-selection re-injects (recordInjected clears pruned_at), the section
1410
+ // is active again and the filter keeps it.
1411
+ recordInjected(
1412
+ "conv-1",
1413
+ [{ slug: "page-a", key: "Notes", bytes: 50 }],
1414
+ 3_000,
739
1415
  );
1416
+ expect(getActiveSections("conv-1")).toEqual(refSet(["page-a", "Notes"]));
1417
+ expect(
1418
+ filterPrunedSections(inner, "current", getPrunedSections("conv-1")),
1419
+ ).toBe(inner);
740
1420
  });
741
1421
  });
742
1422
 
743
1423
  describe("schedulePruneValve", () => {
744
1424
  test("defers the valve run; flush awaits completion", async () => {
745
- const inner = renderCardsBlockInner([card("page-a"), card("page-b")]);
1425
+ const inner = renderInjectionBlockInner([lead("page-a"), lead("page-b")]);
746
1426
  insertUserRowWithV3Block("conv-1", "m1", inner);
747
1427
  recordInjected(
748
1428
  "conv-1",
749
1429
  [
750
- { slug: "page-a", bytes: 200 },
751
- { slug: "page-b", bytes: 200 },
1430
+ { slug: "page-a", key: "", bytes: 200 },
1431
+ { slug: "page-b", key: "", bytes: 200 },
752
1432
  ],
753
1433
  1_000,
754
1434
  );
755
- insertSelection("conv-1", 0, "page-a", 1_000);
756
- insertSelection("conv-1", 0, "page-b", 2_000);
1435
+ touchSelected("conv-1", [{ slug: "page-b", key: "" }], 2_000);
757
1436
 
758
1437
  pruneConfig = { maxResidentBytes: 300, targetResidentBytes: 200 };
759
- schedulePruneValve("conv-1", {
760
- exemptSlugs: new Set(),
761
- liveMessages: () => null,
762
- });
1438
+ schedulePruneValve("conv-1", { liveMessages: () => null });
763
1439
  // Synchronously after scheduling, nothing has been pruned yet.
764
- expect(getPrunedSlugs("conv-1").size).toBe(0);
1440
+ expect(getPrunedSections("conv-1").size).toBe(0);
765
1441
 
766
1442
  await flushPruneValveForTests();
767
- expect(getPrunedSlugs("conv-1")).toEqual(new Set(["page-a"]));
1443
+ expect(getPrunedSections("conv-1")).toEqual(refSet(["page-a", ""]));
768
1444
  });
769
1445
 
770
1446
  test("valve failures are swallowed (never affect the turn)", async () => {
@@ -772,11 +1448,10 @@ describe("schedulePruneValve", () => {
772
1448
  insertUserRowWithV3Block(
773
1449
  "conv-1",
774
1450
  "m1",
775
- renderCardsBlockInner([card("page-a")]),
1451
+ renderInjectionBlockInner([lead("page-a")]),
776
1452
  );
777
- recordInjected("conv-1", [{ slug: "page-a", bytes: 100 }], 1_000);
1453
+ recordInjected("conv-1", [{ slug: "page-a", key: "", bytes: 100 }], 1_000);
778
1454
  schedulePruneValve("conv-1", {
779
- exemptSlugs: new Set(),
780
1455
  liveMessages: () => {
781
1456
  throw new Error("boom");
782
1457
  },
@@ -784,6 +1459,44 @@ describe("schedulePruneValve", () => {
784
1459
  await flushPruneValveForTests();
785
1460
  // The markPruned preceding the failing strip still landed; the error
786
1461
  // itself did not propagate.
787
- expect(getPrunedSlugs("conv-1")).toEqual(new Set(["page-a"]));
1462
+ expect(getPrunedSections("conv-1")).toEqual(refSet(["page-a", ""]));
1463
+ });
1464
+ });
1465
+
1466
+ describe("legacy card rows", () => {
1467
+ test("the schema ensure copies memory_v3_ever_injected rows in at zero bytes: dedup-only, never counted, never planned", () => {
1468
+ memorySqlite.run(/*sql*/ `
1469
+ CREATE TABLE memory_v3_ever_injected (
1470
+ conversation_id TEXT NOT NULL,
1471
+ slug TEXT NOT NULL,
1472
+ injected_at INTEGER NOT NULL,
1473
+ bytes INTEGER NOT NULL DEFAULT 0,
1474
+ pruned_at INTEGER,
1475
+ PRIMARY KEY (conversation_id, slug)
1476
+ )
1477
+ `);
1478
+ memorySqlite.run(/*sql*/ `
1479
+ INSERT INTO memory_v3_ever_injected
1480
+ (conversation_id, slug, injected_at, bytes, pruned_at)
1481
+ VALUES ('conv-1', 'page-a', 1000, 640, NULL)
1482
+ `);
1483
+ // The one-shot copy records itself in the checkpoint ledger; this suite
1484
+ // runs on a bare memory database, so hand the ensure a map-backed one.
1485
+ const values = new Map<string, string>();
1486
+ ensureMemoryV3InjectedSectionsSchema(memorySqlite, {
1487
+ get: (key) => values.get(key) ?? null,
1488
+ set: (key, value) => {
1489
+ values.set(key, value);
1490
+ },
1491
+ });
1492
+ recordInjected("conv-1", [{ slug: "page-b", key: "", bytes: 100 }], 2_000);
1493
+
1494
+ expect(getActiveSections("conv-1")).toEqual(
1495
+ refSet(["page-a", ""], ["page-b", ""]),
1496
+ );
1497
+ expect(residentBytes("conv-1")).toBe(100);
1498
+ expect(
1499
+ planPrune({ maxResidentBytes: 50, targetResidentBytes: 0 }, "conv-1"),
1500
+ ).toEqual({ sections: [{ slug: "page-b", key: "" }], bytesFreed: 100 });
788
1501
  });
789
1502
  });