@caupulican/pi-adaptative 0.85.4 → 0.85.8

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 (282) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/bun/cli.d.ts +1 -1
  3. package/dist/bun/cli.d.ts.map +1 -1
  4. package/dist/bun/cli.js +1 -0
  5. package/dist/bun/cli.js.map +1 -1
  6. package/dist/core/agent-session-runtime.d.ts +1 -1
  7. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  8. package/dist/core/agent-session-runtime.js +1 -1
  9. package/dist/core/agent-session-runtime.js.map +1 -1
  10. package/dist/core/agent-session.d.ts +6 -3
  11. package/dist/core/agent-session.d.ts.map +1 -1
  12. package/dist/core/agent-session.js +7 -2
  13. package/dist/core/agent-session.js.map +1 -1
  14. package/dist/core/auth-storage.d.ts +2 -2
  15. package/dist/core/auth-storage.d.ts.map +1 -1
  16. package/dist/core/auth-storage.js +2 -2
  17. package/dist/core/auth-storage.js.map +1 -1
  18. package/dist/core/bash-executor.js +2 -2
  19. package/dist/core/bash-executor.js.map +1 -1
  20. package/dist/core/billing-failover-controller.d.ts +2 -2
  21. package/dist/core/billing-failover-controller.d.ts.map +1 -1
  22. package/dist/core/billing-failover-controller.js +1 -1
  23. package/dist/core/billing-failover-controller.js.map +1 -1
  24. package/dist/core/compaction-controller.d.ts +8 -2
  25. package/dist/core/compaction-controller.d.ts.map +1 -1
  26. package/dist/core/compaction-controller.js +73 -3
  27. package/dist/core/compaction-controller.js.map +1 -1
  28. package/dist/core/compaction-support.d.ts +2 -2
  29. package/dist/core/compaction-support.d.ts.map +1 -1
  30. package/dist/core/compaction-support.js +9 -1
  31. package/dist/core/compaction-support.js.map +1 -1
  32. package/dist/core/context/artifact-retrieval.d.ts +1 -1
  33. package/dist/core/context/artifact-retrieval.d.ts.map +1 -1
  34. package/dist/core/context/artifact-retrieval.js +1 -1
  35. package/dist/core/context/artifact-retrieval.js.map +1 -1
  36. package/dist/core/context/context-artifacts.d.ts +6 -6
  37. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  38. package/dist/core/context/context-artifacts.js +151 -63
  39. package/dist/core/context/context-artifacts.js.map +1 -1
  40. package/dist/core/context/context-composition.js +1 -1
  41. package/dist/core/context/context-composition.js.map +1 -1
  42. package/dist/core/context/context-store-retention.d.ts.map +1 -1
  43. package/dist/core/context/context-store-retention.js +5 -2
  44. package/dist/core/context/context-store-retention.js.map +1 -1
  45. package/dist/core/context/file-store-memory-provider.js +1 -1
  46. package/dist/core/context/file-store-memory-provider.js.map +1 -1
  47. package/dist/core/context/tool-output-packer.d.ts +1 -1
  48. package/dist/core/context/tool-output-packer.d.ts.map +1 -1
  49. package/dist/core/context/tool-output-packer.js +1 -1
  50. package/dist/core/context/tool-output-packer.js.map +1 -1
  51. package/dist/core/context-gc.d.ts.map +1 -1
  52. package/dist/core/context-gc.js +7 -5
  53. package/dist/core/context-gc.js.map +1 -1
  54. package/dist/core/context-pipeline.d.ts +2 -2
  55. package/dist/core/context-pipeline.d.ts.map +1 -1
  56. package/dist/core/context-pipeline.js +8 -4
  57. package/dist/core/context-pipeline.js.map +1 -1
  58. package/dist/core/cost/cost-summary.d.ts +1 -1
  59. package/dist/core/cost/cost-summary.d.ts.map +1 -1
  60. package/dist/core/cost/cost-summary.js +1 -1
  61. package/dist/core/cost/cost-summary.js.map +1 -1
  62. package/dist/core/cost/daily-usage.d.ts +1 -1
  63. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  64. package/dist/core/cost/daily-usage.js +2 -2
  65. package/dist/core/cost/daily-usage.js.map +1 -1
  66. package/dist/core/cost/session-usage.d.ts +1 -1
  67. package/dist/core/cost/session-usage.d.ts.map +1 -1
  68. package/dist/core/cost/session-usage.js +1 -1
  69. package/dist/core/cost/session-usage.js.map +1 -1
  70. package/dist/core/delegation/worker-actions.js +1 -1
  71. package/dist/core/delegation/worker-actions.js.map +1 -1
  72. package/dist/core/delegation/worker-attempt-executor.d.ts +1 -1
  73. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
  74. package/dist/core/delegation/worker-attempt-executor.js +3 -2
  75. package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
  76. package/dist/core/delegation/worker-conversation-store.d.ts +2 -1
  77. package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
  78. package/dist/core/delegation/worker-conversation-store.js +3 -2
  79. package/dist/core/delegation/worker-conversation-store.js.map +1 -1
  80. package/dist/core/extensions/builtin.d.ts +2 -2
  81. package/dist/core/extensions/builtin.d.ts.map +1 -1
  82. package/dist/core/extensions/builtin.js +2 -2
  83. package/dist/core/extensions/builtin.js.map +1 -1
  84. package/dist/core/extensions/bundled-virtual-modules.d.ts +2 -0
  85. package/dist/core/extensions/bundled-virtual-modules.d.ts.map +1 -0
  86. package/dist/core/extensions/bundled-virtual-modules.js +129 -0
  87. package/dist/core/extensions/bundled-virtual-modules.js.map +1 -0
  88. package/dist/core/extensions/factory-runtime.d.ts +22 -0
  89. package/dist/core/extensions/factory-runtime.d.ts.map +1 -0
  90. package/dist/core/extensions/factory-runtime.js +334 -0
  91. package/dist/core/extensions/factory-runtime.js.map +1 -0
  92. package/dist/core/extensions/index.d.ts +1 -1
  93. package/dist/core/extensions/index.d.ts.map +1 -1
  94. package/dist/core/extensions/index.js +1 -1
  95. package/dist/core/extensions/index.js.map +1 -1
  96. package/dist/core/extensions/lifecycle.d.ts +13 -0
  97. package/dist/core/extensions/lifecycle.d.ts.map +1 -0
  98. package/dist/core/extensions/lifecycle.js +52 -0
  99. package/dist/core/extensions/lifecycle.js.map +1 -0
  100. package/dist/core/extensions/loader.d.ts +3 -24
  101. package/dist/core/extensions/loader.d.ts.map +1 -1
  102. package/dist/core/extensions/loader.js +21 -531
  103. package/dist/core/extensions/loader.js.map +1 -1
  104. package/dist/core/extensions/virtual-modules.d.ts +51 -0
  105. package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
  106. package/dist/core/extensions/virtual-modules.js +59 -0
  107. package/dist/core/extensions/virtual-modules.js.map +1 -0
  108. package/dist/core/foreground-recovery-controller.d.ts +2 -1
  109. package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
  110. package/dist/core/foreground-recovery-controller.js +3 -3
  111. package/dist/core/foreground-recovery-controller.js.map +1 -1
  112. package/dist/core/goal-loop-controller.js +1 -1
  113. package/dist/core/goal-loop-controller.js.map +1 -1
  114. package/dist/core/goals/compact-goal-context.d.ts +1 -1
  115. package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
  116. package/dist/core/goals/compact-goal-context.js +1 -1
  117. package/dist/core/goals/compact-goal-context.js.map +1 -1
  118. package/dist/core/goals/goal-auto-continue-controller.js +1 -1
  119. package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
  120. package/dist/core/goals/goal-session-controller.d.ts +1 -1
  121. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  122. package/dist/core/goals/goal-session-controller.js +1 -1
  123. package/dist/core/goals/goal-session-controller.js.map +1 -1
  124. package/dist/core/http-dispatcher.d.ts +1 -1
  125. package/dist/core/http-dispatcher.d.ts.map +1 -1
  126. package/dist/core/http-dispatcher.js +1 -1
  127. package/dist/core/http-dispatcher.js.map +1 -1
  128. package/dist/core/index.d.ts +3 -2
  129. package/dist/core/index.d.ts.map +1 -1
  130. package/dist/core/index.js +2 -1
  131. package/dist/core/index.js.map +1 -1
  132. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  133. package/dist/core/memory/providers/file-store.js +1 -1
  134. package/dist/core/memory/providers/file-store.js.map +1 -1
  135. package/dist/core/memory/providers/user-memory-archive.js +1 -1
  136. package/dist/core/memory/providers/user-memory-archive.js.map +1 -1
  137. package/dist/core/model-registry.d.ts +2 -1
  138. package/dist/core/model-registry.d.ts.map +1 -1
  139. package/dist/core/model-registry.js +4 -1
  140. package/dist/core/model-registry.js.map +1 -1
  141. package/dist/core/model-resolver.d.ts +1 -1
  142. package/dist/core/model-resolver.d.ts.map +1 -1
  143. package/dist/core/model-resolver.js +1 -1
  144. package/dist/core/model-resolver.js.map +1 -1
  145. package/dist/core/model-router-controller.js +1 -1
  146. package/dist/core/model-router-controller.js.map +1 -1
  147. package/dist/core/model-selection-controller.js +1 -1
  148. package/dist/core/model-selection-controller.js.map +1 -1
  149. package/dist/core/model-tool-protocol.d.ts +1 -1
  150. package/dist/core/model-tool-protocol.d.ts.map +1 -1
  151. package/dist/core/model-tool-protocol.js +1 -1
  152. package/dist/core/model-tool-protocol.js.map +1 -1
  153. package/dist/core/models/llamacpp-runtime.d.ts +7 -0
  154. package/dist/core/models/llamacpp-runtime.d.ts.map +1 -1
  155. package/dist/core/models/llamacpp-runtime.js +8 -3
  156. package/dist/core/models/llamacpp-runtime.js.map +1 -1
  157. package/dist/core/models/local-runtime.js +1 -1
  158. package/dist/core/models/local-runtime.js.map +1 -1
  159. package/dist/core/orchestration/model-binding.d.ts +1 -1
  160. package/dist/core/orchestration/model-binding.d.ts.map +1 -1
  161. package/dist/core/orchestration/model-binding.js +1 -1
  162. package/dist/core/orchestration/model-binding.js.map +1 -1
  163. package/dist/core/orchestration/task-profile-writer.js +1 -1
  164. package/dist/core/orchestration/task-profile-writer.js.map +1 -1
  165. package/dist/core/process-matrix/runtime.d.ts +15 -1
  166. package/dist/core/process-matrix/runtime.d.ts.map +1 -1
  167. package/dist/core/process-matrix/runtime.js +55 -34
  168. package/dist/core/process-matrix/runtime.js.map +1 -1
  169. package/dist/core/reflection-controller.d.ts +4 -3
  170. package/dist/core/reflection-controller.d.ts.map +1 -1
  171. package/dist/core/reflection-controller.js +2 -2
  172. package/dist/core/reflection-controller.js.map +1 -1
  173. package/dist/core/research/model-fitness-controller.js +1 -1
  174. package/dist/core/research/model-fitness-controller.js.map +1 -1
  175. package/dist/core/research/research-lane-controller.d.ts +2 -2
  176. package/dist/core/research/research-lane-controller.d.ts.map +1 -1
  177. package/dist/core/research/research-lane-controller.js +1 -1
  178. package/dist/core/research/research-lane-controller.js.map +1 -1
  179. package/dist/core/resource-loader.d.ts +10 -19
  180. package/dist/core/resource-loader.d.ts.map +1 -1
  181. package/dist/core/resource-loader.js +8 -70
  182. package/dist/core/resource-loader.js.map +1 -1
  183. package/dist/core/runtime-builder.d.ts.map +1 -1
  184. package/dist/core/runtime-builder.js +13 -3
  185. package/dist/core/runtime-builder.js.map +1 -1
  186. package/dist/core/scout-controller.d.ts +1 -1
  187. package/dist/core/scout-controller.d.ts.map +1 -1
  188. package/dist/core/scout-controller.js +1 -1
  189. package/dist/core/scout-controller.js.map +1 -1
  190. package/dist/core/sdk.d.ts +2 -2
  191. package/dist/core/sdk.d.ts.map +1 -1
  192. package/dist/core/sdk.js +3 -3
  193. package/dist/core/sdk.js.map +1 -1
  194. package/dist/core/security/context-threat-scanner.d.ts +14 -0
  195. package/dist/core/security/context-threat-scanner.d.ts.map +1 -0
  196. package/dist/core/security/context-threat-scanner.js +71 -0
  197. package/dist/core/security/context-threat-scanner.js.map +1 -0
  198. package/dist/core/session-supervision-runtime.d.ts +4 -1
  199. package/dist/core/session-supervision-runtime.d.ts.map +1 -1
  200. package/dist/core/session-supervision-runtime.js +49 -11
  201. package/dist/core/session-supervision-runtime.js.map +1 -1
  202. package/dist/core/settings-manager.js +1 -1
  203. package/dist/core/settings-manager.js.map +1 -1
  204. package/dist/core/tool-recovery-logger.js +1 -1
  205. package/dist/core/tool-recovery-logger.js.map +1 -1
  206. package/dist/core/tools/artifact-retrieve.js +1 -1
  207. package/dist/core/tools/artifact-retrieve.js.map +1 -1
  208. package/dist/core/tools/bash.d.ts +2 -2
  209. package/dist/core/tools/bash.d.ts.map +1 -1
  210. package/dist/core/tools/bash.js +16 -4
  211. package/dist/core/tools/bash.js.map +1 -1
  212. package/dist/core/tools/extensionify-runtime.d.ts +44 -0
  213. package/dist/core/tools/extensionify-runtime.d.ts.map +1 -0
  214. package/dist/core/tools/extensionify-runtime.js +115 -0
  215. package/dist/core/tools/extensionify-runtime.js.map +1 -0
  216. package/dist/core/tools/extensionify.d.ts +9 -30
  217. package/dist/core/tools/extensionify.d.ts.map +1 -1
  218. package/dist/core/tools/extensionify.js +10 -140
  219. package/dist/core/tools/extensionify.js.map +1 -1
  220. package/dist/core/tools/find.d.ts +1 -1
  221. package/dist/core/tools/find.d.ts.map +1 -1
  222. package/dist/core/tools/find.js +1 -1
  223. package/dist/core/tools/find.js.map +1 -1
  224. package/dist/core/tools/index.d.ts +2 -4
  225. package/dist/core/tools/index.d.ts.map +1 -1
  226. package/dist/core/tools/index.js +7 -43
  227. package/dist/core/tools/index.js.map +1 -1
  228. package/dist/core/tools/ls.d.ts +1 -1
  229. package/dist/core/tools/ls.d.ts.map +1 -1
  230. package/dist/core/tools/ls.js +1 -1
  231. package/dist/core/tools/ls.js.map +1 -1
  232. package/dist/core/tools/output-accumulator.d.ts +1 -1
  233. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  234. package/dist/core/tools/output-accumulator.js +1 -1
  235. package/dist/core/tools/output-accumulator.js.map +1 -1
  236. package/dist/core/tools/render-utils.js +1 -1
  237. package/dist/core/tools/render-utils.js.map +1 -1
  238. package/dist/core/tools/search-command-guard.d.ts +8 -0
  239. package/dist/core/tools/search-command-guard.d.ts.map +1 -1
  240. package/dist/core/tools/search-command-guard.js +54 -0
  241. package/dist/core/tools/search-command-guard.js.map +1 -1
  242. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  243. package/dist/core/tools/shell-contract-router.js +9 -4
  244. package/dist/core/tools/shell-contract-router.js.map +1 -1
  245. package/dist/core/tools/shell-session.d.ts.map +1 -1
  246. package/dist/core/tools/shell-session.js +6 -4
  247. package/dist/core/tools/shell-session.js.map +1 -1
  248. package/dist/core/tools/tool-definition-factory.d.ts +32 -0
  249. package/dist/core/tools/tool-definition-factory.d.ts.map +1 -0
  250. package/dist/core/tools/tool-definition-factory.js +55 -0
  251. package/dist/core/tools/tool-definition-factory.js.map +1 -0
  252. package/dist/core/util/atomic-file.d.ts.map +1 -1
  253. package/dist/core/util/atomic-file.js +79 -32
  254. package/dist/core/util/atomic-file.js.map +1 -1
  255. package/dist/index.d.ts +2 -1
  256. package/dist/index.d.ts.map +1 -1
  257. package/dist/index.js +2 -1
  258. package/dist/index.js.map +1 -1
  259. package/dist/main.d.ts +2 -0
  260. package/dist/main.d.ts.map +1 -1
  261. package/dist/main.js +24 -18
  262. package/dist/main.js.map +1 -1
  263. package/dist/modes/interactive/auto-learn-controller.js +1 -1
  264. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  265. package/dist/modes/interactive/components/tool-execution.js +1 -1
  266. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  267. package/dist/modes/interactive/interactive-event-controller.js +1 -1
  268. package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
  269. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  270. package/dist/modes/interactive/interactive-mode.js +1 -1
  271. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  272. package/dist/utils/child-process.js +1 -1
  273. package/dist/utils/child-process.js.map +1 -1
  274. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  275. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  276. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  277. package/examples/extensions/sandbox/package-lock.json +2 -2
  278. package/examples/extensions/sandbox/package.json +1 -1
  279. package/examples/extensions/with-deps/package-lock.json +2 -2
  280. package/examples/extensions/with-deps/package.json +1 -1
  281. package/npm-shrinkwrap.json +12 -12
  282. package/package.json +7 -5
@@ -1 +1 @@
1
- {"version":3,"file":"context-store-retention.js","sourceRoot":"","sources":["../../../src/core/context/context-store-retention.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAC3G,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACN,cAAc,EACd,aAAa,EACb,gB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AC;QAC3C,OAAO;YACN,IAAI,QAAQ;gBAAE,OAAO;YACrB,QAAQ,GAAG,IAAI,CAAC;YAChB,KAAK,CAAC,OAAO,EAAE,CAAC;QACjB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { existsSync, lstatSync, mkdirSync, readdirSync, renameSync, rmdirSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n\tacquireWorkRun,\n\tgetWorkRunDir,\n\tgetWorkTenantDir,\n\thasActiveWorkRunLease,\n\tpruneWorkTenant,\n\ttype WorkRetentionOptions,\n} from \"../../utils/work-directory.ts\";\n\nconst DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_SESSION_DIRS = 64;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;\nconst MAX_LEGACY_SESSION_DIRS = 10_000;\nconst MAX_LEGACY_FILES_PER_SESSION = 100_000;\nconst CONTEXT_WORK_TENANT = \"sessions\";\nconst WORK_RUN_MANIFEST_FILE = \".pi-work-run.json\";\n\nexport type ContextStoreKind = \"gc\" | \"artifacts\";\n\nexport interface ContextStoreRetentionOptions {\n\tmaxAgeMs?: number;\n\tmaxSessionDirs?: number;\n\tmaxTotalBytes?: number;\n\tnow?: number;\n}\n\nexport interface ContextStoreRetentionLease {\n\treadonly gcDir: string;\n\treadonly artifactsDir: string;\n\trelease(): void;\n}\n\ninterface LegacyContextStore {\n\troot: string;\n\tkind: ContextStoreKind;\n\tmanagedRun: boolean;\n}\n\nfunction toWorkRetention(options: ContextStoreRetentionOptions): WorkRetentionOptions {\n\treturn {\n\t\tmaxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,\n\t\tmaxRuns: options.maxSessionDirs ?? DEFAULT_MAX_SESSION_DIRS,\n\t\tmaxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,\n\t\tnow: options.now,\n\t};\n}\n\nfunction legacyContextStores(agentDir: string): LegacyContextStore[] {\n\treturn [\n\t\t{ root: join(agentDir, \"context-gc\"), kind: \"gc\", managedRun: false },\n\t\t{ root: join(agentDir, \"context-artifacts\"), kind: \"artifacts\", managedRun: false },\n\t\t{ root: getWorkTenantDir(agentDir, \"context\", \"gc\"), kind: \"gc\", managedRun: true },\n\t\t{ root: getWorkTenantDir(agentDir, \"context\", \"artifacts\"), kind: \"artifacts\", managedRun: true },\n\t];\n}\n\nfunction isRecognizedPayload(kind: ContextStoreKind, name: string): boolean {\n\tif (kind === \"gc\") return /^[0-9a-f]{1,64}\\.txt$/.test(name);\n\treturn /^[0-9a-f]{1,64}(?:\\.payload|\\.meta\\.json)$/.test(name);\n}\n\nfunction isRealDirectory(path: string): boolean {\n\ttry {\n\t\tconst stats = lstatSync(path);\n\t\treturn stats.isDirectory() && !stats.isSymbolicLink();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction recognizedPayloads(sourceDir: string, kind: ContextStoreKind): string[] | undefined {\n\ttry {\n\t\tconst entries = readdirSync(sourceDir, { withFileTypes: true });\n\t\tif (entries.length > MAX_LEGACY_FILES_PER_SESSION) return undefined;\n\t\treturn entries\n\t\t\t.filter((entry) => entry.isFile() && !entry.isSymbolicLink() && isRecognizedPayload(kind, entry.name))\n\t\t\t.map((entry) => entry.name);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction removeLegacyRunIfEmpty(sourceDir: string, managedRun: boolean): void {\n\ttry {\n\t\trmdirSync(join(sourceDir, \".leases\"));\n\t} catch {}\n\tif (managedRun) {\n\t\ttry {\n\t\t\tconst entries = readdirSync(sourceDir);\n\t\t\tif (entries.length === 1 && entries[0] === WORK_RUN_MANIFEST_FILE) {\n\t\t\t\tunlinkSync(join(sourceDir, WORK_RUN_MANIFEST_FILE));\n\t\t\t}\n\t\t} catch {}\n\t}\n\ttry {\n\t\trmdirSync(sourceDir);\n\t} catch {}\n}\n\nfunction migrateLegacySessionStore(agentDir: string, sessionId: string, store: LegacyContextStore): void {\n\tconst sourceDir = join(store.root, sessionId);\n\tif (!isRealDirectory(sourceDir)) return;\n\tif (store.managedRun && hasActiveWorkRunLease(sourceDir)) return;\n\tconst payloads = recognizedPayloads(sourceDir, store.kind);\n\tif (!payloads) return;\n\n\tif (payloads.length > 0) {\n\t\tlet lease: ReturnType<typeof acquireWorkRun> | undefined;\n\t\ttry {\n\t\t\tlease = acquireWorkRun({\n\t\t\t\tagentDir,\n\t\t\t\tcategory: \"context\",\n\t\t\t\ttenant: CONTEXT_WORK_TENANT,\n\t\t\t\trunId: sessionId,\n\t\t\t\tretention: false,\n\t\t\t});\n\t\t\tconst targetDir = join(lease.path, store.kind);\n\t\t\tmkdirSync(targetDir, { recursive: true });\n\t\t\tfor (const name of payloads) {\n\t\t\t\tconst sourcePath = join(sourceDir, name);\n\t\t\t\tconst targetPath = join(targetDir, name);\n\t\t\t\tif (existsSync(targetPath)) continue;\n\t\t\t\ttry {\n\t\t\t\t\trenameSync(sourcePath, targetPath);\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t} catch {\n\t\t\treturn;\n\t\t} finally {\n\t\t\tlease?.release();\n\t\t}\n\t}\n\n\tremoveLegacyRunIfEmpty(sourceDir, store.managedRun);\n}\n\n/**\n * Move recognized context payloads from both historical layouts into the single leased session\n * namespace. Unknown files, symlinks, active runs, and conflicting destinations are left untouched.\n */\nexport function migrateLegacyContextStores(agentDir: string, onlySessionId?: string): void {\n\tfor (const store of legacyContextStores(agentDir)) {\n\t\tlet sessionIds: string[];\n\t\tif (onlySessionId) {\n\t\t\tsessionIds = [onlySessionId];\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tsessionIds = readdirSync(store.root, { withFileTypes: true })\n\t\t\t\t\t.slice(0, MAX_LEGACY_SESSION_DIRS)\n\t\t\t\t\t.filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())\n\t\t\t\t\t.map((entry) => entry.name);\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tfor (const sessionId of sessionIds) {\n\t\t\tmigrateLegacySessionStore(agentDir, sessionId, store);\n\t\t}\n\t\ttry {\n\t\t\trmdirSync(store.root);\n\t\t} catch {}\n\t}\n\ttry {\n\t\trmdirSync(join(agentDir, \"work\", \"context\"));\n\t} catch {}\n}\n\nexport function pruneContextStores(agentDir: string, options: ContextStoreRetentionOptions = {}): string[] {\n\treturn pruneWorkTenant(agentDir, \"context\", CONTEXT_WORK_TENANT, toWorkRetention(options));\n}\n\nexport function getContextStoreDir(agentDir: string, kind: ContextStoreKind, sessionId: string): string {\n\treturn join(getWorkRunDir(agentDir, \"context\", CONTEXT_WORK_TENANT, sessionId), kind);\n}\n\nexport function acquireContextStoreRetention(\n\tagentDir: string,\n\tsessionId: string,\n\toptions: ContextStoreRetentionOptions = {},\n): ContextStoreRetentionLease {\n\tmigrateLegacyContextStores(agentDir, sessionId);\n\tconst lease = acquireWorkRun({\n\t\tagentDir,\n\t\tcategory: \"context\",\n\t\ttenant: CONTEXT_WORK_TENANT,\n\t\trunId: sessionId,\n\t\tretention: toWorkRetention(options),\n\t});\n\tlet released = false;\n\treturn {\n\t\tgcDir: join(lease.path, \"gc\"),\n\t\tartifactsDir: join(lease.path, \"artifacts\"),\n\t\trelease(): void {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tlease.release();\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"context-store-retention.js","sourceRoot":"","sources":["../../../src/core/context/context-store-retention.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAC3G,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACN,cAAc,EACd,aAAa,EACb,gBAAgB,EAChB,qBAAqB,EACrB,eAAe,GAEf,MAAM,+BAA+B,CAAC;AAEvC,MAAM,kBAAkB,GAAG,EAAE,GAAG,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KAAK,CAAC,IAAI,EAAE,WAAW,CAAC;QAC3C,OAAO;YACN,IAAI,QAAQ;gBAAE,OAAO;YACrB,QAAQ,GAAG,IAAI,CAAC;YAChB,KAAK,CAAC,OAAO,EAAE,CAAC;QACjB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { existsSync, lstatSync, mkdirSync, readdirSync, renameSync, rmdirSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n\tacquireWorkRun,\n\tgetWorkRunDir,\n\tgetWorkTenantDir,\n\thasActiveWorkRunLease,\n\tpruneWorkTenant,\n\ttype WorkRetentionOptions,\n} from \"../../utils/work-directory.ts\";\n\nconst DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_SESSION_DIRS = 64;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;\nconst MAX_LEGACY_SESSION_DIRS = 10_000;\nconst MAX_LEGACY_FILES_PER_SESSION = 100_000;\nconst CONTEXT_WORK_TENANT = \"sessions\";\nconst WORK_RUN_MANIFEST_FILE = \".pi-work-run.json\";\n\nexport type ContextStoreKind = \"gc\" | \"artifacts\";\n\nexport interface ContextStoreRetentionOptions {\n\tmaxAgeMs?: number;\n\tmaxSessionDirs?: number;\n\tmaxTotalBytes?: number;\n\tnow?: number;\n}\n\nexport interface ContextStoreRetentionLease {\n\treadonly gcDir: string;\n\treadonly artifactsDir: string;\n\trelease(): void;\n}\n\ninterface LegacyContextStore {\n\troot: string;\n\tkind: ContextStoreKind;\n\tmanagedRun: boolean;\n}\n\nfunction toWorkRetention(options: ContextStoreRetentionOptions): WorkRetentionOptions {\n\treturn {\n\t\tmaxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,\n\t\tmaxRuns: options.maxSessionDirs ?? DEFAULT_MAX_SESSION_DIRS,\n\t\tmaxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,\n\t\tnow: options.now,\n\t};\n}\n\nfunction legacyContextStores(agentDir: string): LegacyContextStore[] {\n\treturn [\n\t\t{ root: join(agentDir, \"context-gc\"), kind: \"gc\", managedRun: false },\n\t\t{ root: join(agentDir, \"context-artifacts\"), kind: \"artifacts\", managedRun: false },\n\t\t{ root: getWorkTenantDir(agentDir, \"context\", \"gc\"), kind: \"gc\", managedRun: true },\n\t\t{ root: getWorkTenantDir(agentDir, \"context\", \"artifacts\"), kind: \"artifacts\", managedRun: true },\n\t];\n}\n\nfunction isRecognizedPayload(kind: ContextStoreKind, name: string): boolean {\n\tif (kind === \"gc\") return /^[0-9a-f]{1,64}\\.txt$/.test(name);\n\treturn /^[0-9a-f]{1,64}(?:\\.payload|\\.meta\\.json|\\.refs)$/.test(name);\n}\n\nfunction isRealDirectory(path: string): boolean {\n\ttry {\n\t\tconst stats = lstatSync(path);\n\t\treturn stats.isDirectory() && !stats.isSymbolicLink();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction recognizedPayloads(sourceDir: string, kind: ContextStoreKind): string[] | undefined {\n\ttry {\n\t\tconst entries = readdirSync(sourceDir, { withFileTypes: true });\n\t\tif (entries.length > MAX_LEGACY_FILES_PER_SESSION) return undefined;\n\t\treturn entries\n\t\t\t.filter(\n\t\t\t\t(entry) =>\n\t\t\t\t\t(entry.isFile() ||\n\t\t\t\t\t\t(kind === \"artifacts\" && entry.isDirectory() && /^[0-9a-f]{1,64}\\.refs$/.test(entry.name))) &&\n\t\t\t\t\t!entry.isSymbolicLink() &&\n\t\t\t\t\tisRecognizedPayload(kind, entry.name),\n\t\t\t)\n\t\t\t.map((entry) => entry.name);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction removeLegacyRunIfEmpty(sourceDir: string, managedRun: boolean): void {\n\ttry {\n\t\trmdirSync(join(sourceDir, \".leases\"));\n\t} catch {}\n\tif (managedRun) {\n\t\ttry {\n\t\t\tconst entries = readdirSync(sourceDir);\n\t\t\tif (entries.length === 1 && entries[0] === WORK_RUN_MANIFEST_FILE) {\n\t\t\t\tunlinkSync(join(sourceDir, WORK_RUN_MANIFEST_FILE));\n\t\t\t}\n\t\t} catch {}\n\t}\n\ttry {\n\t\trmdirSync(sourceDir);\n\t} catch {}\n}\n\nfunction migrateLegacySessionStore(agentDir: string, sessionId: string, store: LegacyContextStore): void {\n\tconst sourceDir = join(store.root, sessionId);\n\tif (!isRealDirectory(sourceDir)) return;\n\tif (store.managedRun && hasActiveWorkRunLease(sourceDir)) return;\n\tconst payloads = recognizedPayloads(sourceDir, store.kind);\n\tif (!payloads) return;\n\n\tif (payloads.length > 0) {\n\t\tlet lease: ReturnType<typeof acquireWorkRun> | undefined;\n\t\ttry {\n\t\t\tlease = acquireWorkRun({\n\t\t\t\tagentDir,\n\t\t\t\tcategory: \"context\",\n\t\t\t\ttenant: CONTEXT_WORK_TENANT,\n\t\t\t\trunId: sessionId,\n\t\t\t\tretention: false,\n\t\t\t});\n\t\t\tconst targetDir = join(lease.path, store.kind);\n\t\t\tmkdirSync(targetDir, { recursive: true });\n\t\t\tfor (const name of payloads) {\n\t\t\t\tconst sourcePath = join(sourceDir, name);\n\t\t\t\tconst targetPath = join(targetDir, name);\n\t\t\t\tif (existsSync(targetPath)) continue;\n\t\t\t\ttry {\n\t\t\t\t\trenameSync(sourcePath, targetPath);\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t} catch {\n\t\t\treturn;\n\t\t} finally {\n\t\t\tlease?.release();\n\t\t}\n\t}\n\n\tremoveLegacyRunIfEmpty(sourceDir, store.managedRun);\n}\n\n/**\n * Move recognized context payloads from both historical layouts into the single leased session\n * namespace. Unknown files, symlinks, active runs, and conflicting destinations are left untouched.\n */\nexport function migrateLegacyContextStores(agentDir: string, onlySessionId?: string): void {\n\tfor (const store of legacyContextStores(agentDir)) {\n\t\tlet sessionIds: string[];\n\t\tif (onlySessionId) {\n\t\t\tsessionIds = [onlySessionId];\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tsessionIds = readdirSync(store.root, { withFileTypes: true })\n\t\t\t\t\t.slice(0, MAX_LEGACY_SESSION_DIRS)\n\t\t\t\t\t.filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())\n\t\t\t\t\t.map((entry) => entry.name);\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tfor (const sessionId of sessionIds) {\n\t\t\tmigrateLegacySessionStore(agentDir, sessionId, store);\n\t\t}\n\t\ttry {\n\t\t\trmdirSync(store.root);\n\t\t} catch {}\n\t}\n\ttry {\n\t\trmdirSync(join(agentDir, \"work\", \"context\"));\n\t} catch {}\n}\n\nexport function pruneContextStores(agentDir: string, options: ContextStoreRetentionOptions = {}): string[] {\n\treturn pruneWorkTenant(agentDir, \"context\", CONTEXT_WORK_TENANT, toWorkRetention(options));\n}\n\nexport function getContextStoreDir(agentDir: string, kind: ContextStoreKind, sessionId: string): string {\n\treturn join(getWorkRunDir(agentDir, \"context\", CONTEXT_WORK_TENANT, sessionId), kind);\n}\n\nexport function acquireContextStoreRetention(\n\tagentDir: string,\n\tsessionId: string,\n\toptions: ContextStoreRetentionOptions = {},\n): ContextStoreRetentionLease {\n\tmigrateLegacyContextStores(agentDir, sessionId);\n\tconst lease = acquireWorkRun({\n\t\tagentDir,\n\t\tcategory: \"context\",\n\t\ttenant: CONTEXT_WORK_TENANT,\n\t\trunId: sessionId,\n\t\tretention: toWorkRetention(options),\n\t});\n\tlet released = false;\n\treturn {\n\t\tgcDir: join(lease.path, \"gc\"),\n\t\tartifactsDir: join(lease.path, \"artifacts\"),\n\t\trelease(): void {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tlease.release();\n\t\t},\n\t};\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { basename } from "node:path";
3
- import { scanContextFileThreats, stripInvisibleUnicode } from "../resource-loader.js";
3
+ import { scanContextFileThreats, stripInvisibleUnicode } from "../security/context-threat-scanner.js";
4
4
  import { fetchLocalMemoryItem, searchLocalMemoryItems, tokenOverlapScore } from "./local-memory-search.js";
5
5
  export const PI_FILE_STORE_MEMORY_PROVIDER_ID = "pi-file-store";
6
6
  const FILE_STORE_MEMORY_CAPABILITIES = {
@@ -1 +1 @@
1
- {"version":3,"file":"file-store-memory-provider.js","sourceRoot":"","sources":["../../../src/core/context/file-store-memory-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAEtF,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAW3G,MAAM,CAAC,MAAM,gCAAgC,GAAG,eAAe,CAAC;AAehE,MAAM,8BAA8B,GAA+B;IAClE,MAAM,EAAE,IAAI;IACZ,KAAK,EAAE,IAAI;IACX,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,KAAK;IACb,SAAS,EAAE,KAAK;IAChB,QAAQ,EAAE,IAAI;IACd,KAAK,EAAE,KAAK;IACZ,SAAS,EAAE,IAAI;IACf,MAAM,EAAE,CAAC,MAAM,EAAE,QAAQ,CAAC;IAC1B,SAAS,EAAE,IAAI;CACf,CAAC;AAEF,SAAS,SAAS,CAAC,WAAgC,EAAE,IAAgB;IACpE,IAAI,WAAW,CAAC,IAAI,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC,IAAI,KAAK,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7E,MAAM,KAAK,GAAG,iBAAiB,CAAC,WAAW,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IACzE,gGAAgG;IAChG,oGAAoG;IACpG,OAAO,IAAI,CAAC,IAAI,KAAK,iBAAiB,CAAC,C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AAO,sBAAsB,CAAC,KAAK,EAAE,EAAE,OAAO,EAAE;gBAC/C,KAAK,EAAE,SAAS;gBAChB,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,+BAA+B,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;aACpE,CAAC,CAAC;QACJ,CAAC;QACD,KAAK,CAAC,KAAK,CAAC,GAAc;YACzB,OAAO,oBAAoB,CAAC,KAAK,EAAE,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QACvD,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { basename } from \"node:path\";\nimport { scanContextFileThreats, stripInvisibleUnicode } from \"../resource-loader.ts\";\nimport type { MemoryScope } from \"./context-item.ts\";\nimport { fetchLocalMemoryItem, searchLocalMemoryItems, tokenOverlapScore } from \"./local-memory-search.ts\";\nimport type {\n\tMemoryItem,\n\tMemoryItemKind,\n\tMemoryProvider,\n\tMemoryProviderCapabilities,\n\tMemoryRef,\n\tMemorySearchRequest,\n\tMemorySearchResult,\n} from \"./memory-provider-contract.ts\";\n\nexport const PI_FILE_STORE_MEMORY_PROVIDER_ID = \"pi-file-store\";\n\nexport interface FileStoreMemoryProviderOptions {\n\tmemoryFilePath: string;\n\tuserFilePath: string;\n\tproviderId?: string;\n}\n\ninterface FileStoreLineSource {\n\tpath: string;\n\tfileName: \"MEMORY.md\" | \"USER.md\";\n\tscope: MemoryScope;\n\tkind: MemoryItemKind;\n}\n\nconst FILE_STORE_MEMORY_CAPABILITIES: MemoryProviderCapabilities = {\n\tsearch: true,\n\tfetch: true,\n\twrite: false,\n\tdelete: false,\n\tshortTerm: false,\n\tlongTerm: true,\n\tgraph: false,\n\tcitations: true,\n\tscopes: [\"user\", \"global\"],\n\tlocalOnly: true,\n};\n\nfunction scoreItem(queryTokens: ReadonlySet<string>, item: MemoryItem): number {\n\tif (queryTokens.size === 0) return item.kind === \"user_preference\" ? 0.2 : 0;\n\tconst score = tokenOverlapScore(queryTokens, [item.title, item.summary]);\n\t// USER.md lines are standing preferences. When file-store retrieval is used as a compact-window\n\t// fallback for the static prompt, keep them eligible even if the latest query has no token overlap.\n\treturn item.kind === \"user_preference\" ? Math.max(0.2, Math.min(1, score + 0.05)) : score;\n}\n\nfunction refFor(providerId: string, source: FileStoreLineSource, lineNumber: number, kind: MemoryItemKind): MemoryRef {\n\treturn {\n\t\tproviderId,\n\t\titemId: `${source.fileName}:line-${lineNumber}`,\n\t\tscope: source.scope,\n\t\tkind,\n\t\turi: `file-store:${source.fileName}#line-${lineNumber}`,\n\t};\n}\n\nfunction readLines(source: FileStoreLineSource, providerId: string): MemoryItem[] {\n\tif (!existsSync(source.path)) return [];\n\tconst cleaned = stripInvisibleUnicode(readFileSync(source.path, \"utf8\")).cleaned;\n\treturn cleaned\n\t\t.split(\"\\n\")\n\t\t.map((rawLine, index) => ({ text: rawLine.trim(), lineNumber: index + 1 }))\n\t\t.filter((line) => line.text.length > 0 && !line.text.startsWith(\"#\"))\n\t\t.filter((line) => scanContextFileThreats(line.text).length === 0)\n\t\t.map((line) => {\n\t\t\tconst ref = refFor(providerId, source, line.lineNumber, source.kind);\n\t\t\treturn {\n\t\t\t\tid: ref.itemId,\n\t\t\t\tproviderId,\n\t\t\t\tsource: \"pi_native\" as const,\n\t\t\t\tkind: source.kind,\n\t\t\t\tscope: source.scope,\n\t\t\t\tdurability: \"durable\" as const,\n\t\t\t\ttitle: `${basename(source.path)} line ${line.lineNumber}`,\n\t\t\t\tsummary: line.text,\n\t\t\t\trefs: [ref],\n\t\t\t\tevidenceRefs: [{ type: \"memory\" as const, ref }],\n\t\t\t};\n\t\t});\n}\n\nexport function createFileStoreMemoryProvider(options: FileStoreMemoryProviderOptions): MemoryProvider {\n\tconst providerId = options.providerId ?? PI_FILE_STORE_MEMORY_PROVIDER_ID;\n\tconst sources: FileStoreLineSource[] = [\n\t\t{ path: options.userFilePath, fileName: \"USER.md\", scope: \"user\", kind: \"user_preference\" },\n\t\t{ path: options.memoryFilePath, fileName: \"MEMORY.md\", scope: \"global\", kind: \"fact\" },\n\t];\n\n\tfunction items(): MemoryItem[] {\n\t\treturn sources.flatMap((source) => readLines(source, providerId));\n\t}\n\n\treturn {\n\t\tid: providerId,\n\t\tlabel: \"Pi File-Store Memory\",\n\t\tsource: \"pi_native\",\n\t\tcapabilities: FILE_STORE_MEMORY_CAPABILITIES,\n\t\tasync search(request: MemorySearchRequest): Promise<MemorySearchResult[]> {\n\t\t\treturn searchLocalMemoryItems(items(), request, {\n\t\t\t\tscore: scoreItem,\n\t\t\t\treason: (score) => `file-store line match score ${score.toFixed(3)}`,\n\t\t\t});\n\t\t},\n\t\tasync fetch(ref: MemoryRef): Promise<MemoryItem | undefined> {\n\t\t\treturn fetchLocalMemoryItem(items(), providerId, ref);\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"file-store-memory-provider.js","sourceRoot":"","sources":["../../../src/core/context/file-store-memory-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAEtG,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAW3G,MAAM,CAAC,MAAM,gCAAgC,GAAG,eAAe,CAAC;AAehE,MAAM,8BAA8B,GAA+B;IAClE,MAAM,EAAE,IAAI;IACZ,KAAK,EAAE,IAAI;IACX,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,KAAK;IACb,SAAS,EAAE,KAAK;IAChB,QAAQ,EAAE,IAAI;IACd,KAAK,EAAE,KAAK;IACZ,SAAS,EAAE,IAAI;IACf,MAAM,EAAE,CAAC,MAAM,EAAE,QAAQ,CAAC;IAC1B,SAAS,EAAE,IAAI;CACf,CAAC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AAQ,EAAE,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE;KACtF,CAAC;IAEF,SAAS,KAAK;QACb,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC;IACnE,CAAC;IAED,OAAO;QACN,EAAE,EAAE,UAAU;QACd,KAAK,EAAE,sBAAsB;QAC7B,MAAM,EAAE,WAAW;QACnB,YAAY,EAAE,8BAA8B;QAC5C,KAAK,CAAC,MAAM,CAAC,OAA4B;YACxC,OAAO,sBAAsB,CAAC,KAAK,EAAE,EAAE,OAAO,EAAE;gBAC/C,KAAK,EAAE,SAAS;gBAChB,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,+BAA+B,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;aACpE,CAAC,CAAC;QACJ,CAAC;QACD,KAAK,CAAC,KAAK,CAAC,GAAc;YACzB,OAAO,oBAAoB,CAAC,KAAK,EAAE,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QACvD,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { basename } from \"node:path\";\nimport { scanContextFileThreats, stripInvisibleUnicode } from \"../security/context-threat-scanner.ts\";\nimport type { MemoryScope } from \"./context-item.ts\";\nimport { fetchLocalMemoryItem, searchLocalMemoryItems, tokenOverlapScore } from \"./local-memory-search.ts\";\nimport type {\n\tMemoryItem,\n\tMemoryItemKind,\n\tMemoryProvider,\n\tMemoryProviderCapabilities,\n\tMemoryRef,\n\tMemorySearchRequest,\n\tMemorySearchResult,\n} from \"./memory-provider-contract.ts\";\n\nexport const PI_FILE_STORE_MEMORY_PROVIDER_ID = \"pi-file-store\";\n\nexport interface FileStoreMemoryProviderOptions {\n\tmemoryFilePath: string;\n\tuserFilePath: string;\n\tproviderId?: string;\n}\n\ninterface FileStoreLineSource {\n\tpath: string;\n\tfileName: \"MEMORY.md\" | \"USER.md\";\n\tscope: MemoryScope;\n\tkind: MemoryItemKind;\n}\n\nconst FILE_STORE_MEMORY_CAPABILITIES: MemoryProviderCapabilities = {\n\tsearch: true,\n\tfetch: true,\n\twrite: false,\n\tdelete: false,\n\tshortTerm: false,\n\tlongTerm: true,\n\tgraph: false,\n\tcitations: true,\n\tscopes: [\"user\", \"global\"],\n\tlocalOnly: true,\n};\n\nfunction scoreItem(queryTokens: ReadonlySet<string>, item: MemoryItem): number {\n\tif (queryTokens.size === 0) return item.kind === \"user_preference\" ? 0.2 : 0;\n\tconst score = tokenOverlapScore(queryTokens, [item.title, item.summary]);\n\t// USER.md lines are standing preferences. When file-store retrieval is used as a compact-window\n\t// fallback for the static prompt, keep them eligible even if the latest query has no token overlap.\n\treturn item.kind === \"user_preference\" ? Math.max(0.2, Math.min(1, score + 0.05)) : score;\n}\n\nfunction refFor(providerId: string, source: FileStoreLineSource, lineNumber: number, kind: MemoryItemKind): MemoryRef {\n\treturn {\n\t\tproviderId,\n\t\titemId: `${source.fileName}:line-${lineNumber}`,\n\t\tscope: source.scope,\n\t\tkind,\n\t\turi: `file-store:${source.fileName}#line-${lineNumber}`,\n\t};\n}\n\nfunction readLines(source: FileStoreLineSource, providerId: string): MemoryItem[] {\n\tif (!existsSync(source.path)) return [];\n\tconst cleaned = stripInvisibleUnicode(readFileSync(source.path, \"utf8\")).cleaned;\n\treturn cleaned\n\t\t.split(\"\\n\")\n\t\t.map((rawLine, index) => ({ text: rawLine.trim(), lineNumber: index + 1 }))\n\t\t.filter((line) => line.text.length > 0 && !line.text.startsWith(\"#\"))\n\t\t.filter((line) => scanContextFileThreats(line.text).length === 0)\n\t\t.map((line) => {\n\t\t\tconst ref = refFor(providerId, source, line.lineNumber, source.kind);\n\t\t\treturn {\n\t\t\t\tid: ref.itemId,\n\t\t\t\tproviderId,\n\t\t\t\tsource: \"pi_native\" as const,\n\t\t\t\tkind: source.kind,\n\t\t\t\tscope: source.scope,\n\t\t\t\tdurability: \"durable\" as const,\n\t\t\t\ttitle: `${basename(source.path)} line ${line.lineNumber}`,\n\t\t\t\tsummary: line.text,\n\t\t\t\trefs: [ref],\n\t\t\t\tevidenceRefs: [{ type: \"memory\" as const, ref }],\n\t\t\t};\n\t\t});\n}\n\nexport function createFileStoreMemoryProvider(options: FileStoreMemoryProviderOptions): MemoryProvider {\n\tconst providerId = options.providerId ?? PI_FILE_STORE_MEMORY_PROVIDER_ID;\n\tconst sources: FileStoreLineSource[] = [\n\t\t{ path: options.userFilePath, fileName: \"USER.md\", scope: \"user\", kind: \"user_preference\" },\n\t\t{ path: options.memoryFilePath, fileName: \"MEMORY.md\", scope: \"global\", kind: \"fact\" },\n\t];\n\n\tfunction items(): MemoryItem[] {\n\t\treturn sources.flatMap((source) => readLines(source, providerId));\n\t}\n\n\treturn {\n\t\tid: providerId,\n\t\tlabel: \"Pi File-Store Memory\",\n\t\tsource: \"pi_native\",\n\t\tcapabilities: FILE_STORE_MEMORY_CAPABILITIES,\n\t\tasync search(request: MemorySearchRequest): Promise<MemorySearchResult[]> {\n\t\t\treturn searchLocalMemoryItems(items(), request, {\n\t\t\t\tscore: scoreItem,\n\t\t\t\treason: (score) => `file-store line match score ${score.toFixed(3)}`,\n\t\t\t});\n\t\t},\n\t\tasync fetch(ref: MemoryRef): Promise<MemoryItem | undefined> {\n\t\t\treturn fetchLocalMemoryItem(items(), providerId, ref);\n\t\t},\n\t};\n}\n"]}
@@ -9,7 +9,7 @@
9
9
  * (grep/find) that never passes an `ArtifactStore` gets byte-for-byte its prior behavior --
10
10
  * packing is opt-in per call site, not a global switch.
11
11
  */
12
- import { type TruncationOptions, type TruncationResult } from "@caupulican/pi-agent-core/node";
12
+ import { type TruncationOptions, type TruncationResult } from "@caupulican/pi-agent-core/truncate";
13
13
  import type { ArtifactStore } from "./context-artifacts.ts";
14
14
  export interface PackToolOutputRequest {
15
15
  toolName: string;
@@ -1 +1 @@
1
- {"version":3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AC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;CACd,GAAG,MAAM,CAET;AAID;;;;;GAKG;AACH,wBAAgB,0BAA0B,CACzC,OAAO,EAAE,iBAAiB,GAAG,SAAS,EACtC,GAAG,EAAE,MAAM,EACX,qBAAqB,EAAE,MAAM,GAC3B,MAAM,GAAG,SAAS,CAKpB"}
1
+ {"version":3,"file":"tool-output-packer.d.ts","sourceRoot":"","sources":["../../../src/core/context/tool-output-packer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,KAAK,iBAAiB,EAAE,KAAK,gBAAgB,EAAgB,MAAM,oCAAoC,CAAC;AACjH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAE5D,MAAM,WAAW,qBAAqB;IACrC,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,yFAAyF;IACzF,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,UAAU,CAAC,EAAE,iBAAiB,CAAC;CAC/B;AAED,MAAM,WAAW,gBAAgB;IAChC;;;;;OAKG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,gBAAgB,CAAC;IAC7B,oFAAoF;IACpF,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,OAAO,CAAC;CAChB;AAED,4FAA4F;AAC5F,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAC7B,OAAO,EAAE,qBAAqB,EAC9B,aAAa,EAAE,aAAa,GAAG,SAAS,EACxC,QAAQ,EAAE,MAAM,GACd,gBAAgB,CAuBlB;AAED,MAAM,WAAW,iBAAiB;IACjC,kGAAkG;IAClG,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CACtC;AAED,wBAAgB,+BAA+B,IAAI,iBAAiB,CASnE;AAED,6FAA6F;AAC7F,wBAAgB,sBAAsB,CAAC,KAAK,EAAE;IAC7C,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;CACd,GAAG,MAAM,CAET;AAID;;;;;GAKG;AACH,wBAAgB,0BAA0B,CACzC,OAAO,EAAE,iBAAiB,GAAG,SAAS,EACtC,GAAG,EAAE,MAAM,EACX,qBAAqB,EAAE,MAAM,GAC3B,MAAM,GAAG,SAAS,CAKpB"}
@@ -9,7 +9,7 @@
9
9
  * (grep/find) that never passes an `ArtifactStore` gets byte-for-byte its prior behavior --
10
10
  * packing is opt-in per call site, not a global switch.
11
11
  */
12
- import { truncateHead } from "@caupulican/pi-agent-core/node";
12
+ import { truncateHead } from "@caupulican/pi-agent-core/truncate";
13
13
  /** Footer notice text for a packed artifact, for callers to fold into their own notices. */
14
14
  export function formatArtifactNotice(artifactId) {
15
15
  return `Full output: artifact tool-output:${artifactId}`;
@@ -1 +1 @@
1
- {"version":3,"file":"tool-output-packer.js","sourceRoot":"","sources":["../../../src/core/context/tool-output-packer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAiD,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAiC7G,4FAA4F;AAC5F,MAAM,UAAU,oBAAoB,CAAC,UAAkB;IACtD,OAAO,qCAAqC,UAAU,EAAE,CAAC;AAC1D,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,cAAc,CAC7B,OAA8B,EAC9B,aA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xC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;YACtB,OAAO,IAAI,CAAC;QACb,CAAC;KACD,CAAC;AACH,CAAC;AAED,6FAA6F;AAC7F,MAAM,UAAU,sBAAsB,CAAC,KAKtC;IACA,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,OAAO,IAAI,EAAE,EAAE,KAAK,CAAC,IAAI,IAAI,EAAE,EAAE,KAAK,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC5F,CAAC;AAED,MAAM,8BAA8B,GAAG,CAAC,CAAC;AAEzC;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACzC,OAAsC,EACtC,GAAW,EACX,qBAA6B;IAE7B,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,MAAM,KAAK,GAAG,OAAO,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAC5C,IAAI,KAAK,GAAG,8BAA8B;QAAE,OAAO,SAAS,CAAC;IAC7D,OAAO,kBAAkB,qBAAqB,yCAAyC,KAAK,uDAAuD,CAAC;AACrJ,CAAC","sourcesContent":["/**\n * Tool output digesting and packing (Phase 3): \"measure -> digest/preview/artifact ->\n * prompt item\", per tool-output-artifacts.md's boundary rule. Large raw tool output is\n * captured to an artifact BEFORE truncation, so the artifact holds the exact raw payload;\n * the model only ever sees the bounded preview plus an artifact reference.\n *\n * This module is pure with respect to wiring: it takes an `ArtifactStore` by dependency\n * injection and does not know about sessions, transcripts, or prompt construction. A tool\n * (grep/find) that never passes an `ArtifactStore` gets byte-for-byte its prior behavior --\n * packing is opt-in per call site, not a global switch.\n */\n\nimport { type TruncationOptions, type TruncationResult, truncateHead } from \"@caupulican/pi-agent-core/node\";\nimport type { ArtifactStore } from \"./context-artifacts.ts\";\n\nexport interface PackToolOutputRequest {\n\ttoolName: string;\n\tcommand?: string;\n\tpath?: string;\n\trawContent: string;\n\tsessionEntryId?: string;\n\t/**\n\t * Turn number for artifact capture identity. Real session-turn wiring lands in a later\n\t * slice; callers that don't track turns yet may pass 0.\n\t */\n\tcreatedAtTurn?: number;\n\t/** Whether re-running the same tool call would reproduce this content. Default: true. */\n\treproducible?: boolean;\n\ttruncation?: TruncationOptions;\n}\n\nexport interface PackedToolOutput {\n\t/**\n\t * Bounded preview content -- exactly what `truncateHead` alone would have produced.\n\t * No footer/notice text is appended here; callers already have their own per-tool\n\t * footer conventions (grep's vs. find's bracket ordering differ) and own formatting\n\t * the artifact notice into their own notice list via `formatArtifactNotice`.\n\t */\n\tcontent: string;\n\ttruncation: TruncationResult;\n\t/** Present only if packing succeeded and the artifact is protected from cleanup. */\n\tartifactId?: string;\n\tpacked: boolean;\n}\n\n/** Footer notice text for a packed artifact, for callers to fold into their own notices. */\nexport function formatArtifactNotice(artifactId: string): string {\n\treturn `Full output: artifact tool-output:${artifactId}`;\n}\n\n/**\n * Measure `request.rawContent`; if it fits within the caps, return it unchanged (small\n * output stays exactly as readable as before this module existed). If it's oversized and\n * an `ArtifactStore` is provided, capture the exact raw payload as an artifact first, then\n * return the same bounded preview `truncateHead` would have produced anyway.\n *\n * Fails closed: if the artifact write succeeds but registering `holderId` as a reference\n * fails (`addReference` returns false), the artifact is not claimed in the result at all --\n * the caller falls back to the bounded/truncated content exactly as if no store had been\n * provided, since an unprotected artifact could be cleaned up at any time.\n */\nexport function packToolOutput(\n\trequest: PackToolOutputRequest,\n\tartifactStore: ArtifactStore | undefined,\n\tholderId: string,\n): PackedToolOutput {\n\tconst truncation = truncateHead(request.rawContent, request.truncation);\n\n\tif (!truncation.truncated || !artifactStore) {\n\t\treturn { content: truncation.content, truncation, packed: false };\n\t}\n\n\tconst { ref } = artifactStore.write({\n\t\tkind: \"tool_output\",\n\t\tcontent: request.rawContent,\n\t\ttoolName: request.toolName,\n\t\tcommand: request.command,\n\t\tpath: request.path,\n\t\tsessionEntryId: request.sessionEntryId,\n\t\tcreatedAtTurn: request.createdAtTurn ?? 0,\n\t\treproducible: request.reproducible ?? true,\n\t});\n\n\tif (!artifactStore.addReference(ref.id, holderId)) {\n\t\treturn { content: truncation.content, truncation, packed: false };\n\t}\n\n\treturn { content: truncation.content, truncation, artifactId: ref.id, packed: true };\n}\n\nexport interface BroadQueryTracker {\n\t/** Record one more broad occurrence of `key`; returns the cumulative count including this one. */\n\trecordBroadQuery(key: string): number;\n}\n\nexport function createInMemoryBroadQueryTracker(): BroadQueryTracker {\n\tconst counts = new Map<string, number>();\n\treturn {\n\t\trecordBroadQuery(key: string): number {\n\t\t\tconst next = (counts.get(key) ?? 0) + 1;\n\t\t\tcounts.set(key, next);\n\t\t\treturn next;\n\t\t},\n\t};\n}\n\n/** Normalize a search-tool call into a stable repetition key: same query, same broadness. */\nexport function normalizeBroadQueryKey(input: {\n\ttoolName: string;\n\tpattern?: string;\n\tpath?: string;\n\tglob?: string;\n}): string {\n\treturn [input.toolName, input.pattern ?? \"\", input.path ?? \"\", input.glob ?? \"\"].join(\"␟\");\n}\n\nconst REPEATED_BROAD_QUERY_THRESHOLD = 2;\n\n/**\n * When a broad-query condition (match/result limit hit, or byte truncation) repeats for\n * the same normalized query, produce a compact \"do not repeat\" style note. This is only\n * the Phase 3 signal; the durable invalidation ledger (supersession/expiry rules) is\n * Phase 6 per implementation-phases.md.\n */\nexport function broadQueryInvalidationNote(\n\ttracker: BroadQueryTracker | undefined,\n\tkey: string,\n\thumanQueryDescription: string,\n): string | undefined {\n\tif (!tracker) return undefined;\n\tconst count = tracker.recordBroadQuery(key);\n\tif (count < REPEATED_BROAD_QUERY_THRESHOLD) return undefined;\n\treturn `Do not repeat: ${humanQueryDescription} has produced broad/truncated results ${count} times in this session. Narrow the path/glob/pattern.`;\n}\n"]}
1
+ {"version":3,"file":"tool-output-packer.js","sourceRoot":"","sources":["../../../src/core/context/tool-output-packer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAiD,YAAY,EAAE,MAA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;IAC9C,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAC;IACzC,OAAO;QACN,gBAAgB,CAAC,GAAW;YAC3B,MAAM,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;YACxC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;YACtB,OAAO,IAAI,CAAC;QACb,CAAC;KACD,CAAC;AACH,CAAC;AAED,6FAA6F;AAC7F,MAAM,UAAU,sBAAsB,CAAC,KAKtC;IACA,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,OAAO,IAAI,EAAE,EAAE,KAAK,CAAC,IAAI,IAAI,EAAE,EAAE,KAAK,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC5F,CAAC;AAED,MAAM,8BAA8B,GAAG,CAAC,CAAC;AAEzC;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACzC,OAAsC,EACtC,GAAW,EACX,qBAA6B;IAE7B,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,MAAM,KAAK,GAAG,OAAO,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAC5C,IAAI,KAAK,GAAG,8BAA8B;QAAE,OAAO,SAAS,CAAC;IAC7D,OAAO,kBAAkB,qBAAqB,yCAAyC,KAAK,uDAAuD,CAAC;AACrJ,CAAC","sourcesContent":["/**\n * Tool output digesting and packing (Phase 3): \"measure -> digest/preview/artifact ->\n * prompt item\", per tool-output-artifacts.md's boundary rule. Large raw tool output is\n * captured to an artifact BEFORE truncation, so the artifact holds the exact raw payload;\n * the model only ever sees the bounded preview plus an artifact reference.\n *\n * This module is pure with respect to wiring: it takes an `ArtifactStore` by dependency\n * injection and does not know about sessions, transcripts, or prompt construction. A tool\n * (grep/find) that never passes an `ArtifactStore` gets byte-for-byte its prior behavior --\n * packing is opt-in per call site, not a global switch.\n */\n\nimport { type TruncationOptions, type TruncationResult, truncateHead } from \"@caupulican/pi-agent-core/truncate\";\nimport type { ArtifactStore } from \"./context-artifacts.ts\";\n\nexport interface PackToolOutputRequest {\n\ttoolName: string;\n\tcommand?: string;\n\tpath?: string;\n\trawContent: string;\n\tsessionEntryId?: string;\n\t/**\n\t * Turn number for artifact capture identity. Real session-turn wiring lands in a later\n\t * slice; callers that don't track turns yet may pass 0.\n\t */\n\tcreatedAtTurn?: number;\n\t/** Whether re-running the same tool call would reproduce this content. Default: true. */\n\treproducible?: boolean;\n\ttruncation?: TruncationOptions;\n}\n\nexport interface PackedToolOutput {\n\t/**\n\t * Bounded preview content -- exactly what `truncateHead` alone would have produced.\n\t * No footer/notice text is appended here; callers already have their own per-tool\n\t * footer conventions (grep's vs. find's bracket ordering differ) and own formatting\n\t * the artifact notice into their own notice list via `formatArtifactNotice`.\n\t */\n\tcontent: string;\n\ttruncation: TruncationResult;\n\t/** Present only if packing succeeded and the artifact is protected from cleanup. */\n\tartifactId?: string;\n\tpacked: boolean;\n}\n\n/** Footer notice text for a packed artifact, for callers to fold into their own notices. */\nexport function formatArtifactNotice(artifactId: string): string {\n\treturn `Full output: artifact tool-output:${artifactId}`;\n}\n\n/**\n * Measure `request.rawContent`; if it fits within the caps, return it unchanged (small\n * output stays exactly as readable as before this module existed). If it's oversized and\n * an `ArtifactStore` is provided, capture the exact raw payload as an artifact first, then\n * return the same bounded preview `truncateHead` would have produced anyway.\n *\n * Fails closed: if the artifact write succeeds but registering `holderId` as a reference\n * fails (`addReference` returns false), the artifact is not claimed in the result at all --\n * the caller falls back to the bounded/truncated content exactly as if no store had been\n * provided, since an unprotected artifact could be cleaned up at any time.\n */\nexport function packToolOutput(\n\trequest: PackToolOutputRequest,\n\tartifactStore: ArtifactStore | undefined,\n\tholderId: string,\n): PackedToolOutput {\n\tconst truncation = truncateHead(request.rawContent, request.truncation);\n\n\tif (!truncation.truncated || !artifactStore) {\n\t\treturn { content: truncation.content, truncation, packed: false };\n\t}\n\n\tconst { ref } = artifactStore.write({\n\t\tkind: \"tool_output\",\n\t\tcontent: request.rawContent,\n\t\ttoolName: request.toolName,\n\t\tcommand: request.command,\n\t\tpath: request.path,\n\t\tsessionEntryId: request.sessionEntryId,\n\t\tcreatedAtTurn: request.createdAtTurn ?? 0,\n\t\treproducible: request.reproducible ?? true,\n\t});\n\n\tif (!artifactStore.addReference(ref.id, holderId)) {\n\t\treturn { content: truncation.content, truncation, packed: false };\n\t}\n\n\treturn { content: truncation.content, truncation, artifactId: ref.id, packed: true };\n}\n\nexport interface BroadQueryTracker {\n\t/** Record one more broad occurrence of `key`; returns the cumulative count including this one. */\n\trecordBroadQuery(key: string): number;\n}\n\nexport function createInMemoryBroadQueryTracker(): BroadQueryTracker {\n\tconst counts = new Map<string, number>();\n\treturn {\n\t\trecordBroadQuery(key: string): number {\n\t\t\tconst next = (counts.get(key) ?? 0) + 1;\n\t\t\tcounts.set(key, next);\n\t\t\treturn next;\n\t\t},\n\t};\n}\n\n/** Normalize a search-tool call into a stable repetition key: same query, same broadness. */\nexport function normalizeBroadQueryKey(input: {\n\ttoolName: string;\n\tpattern?: string;\n\tpath?: string;\n\tglob?: string;\n}): string {\n\treturn [input.toolName, input.pattern ?? \"\", input.path ?? \"\", input.glob ?? \"\"].join(\"␟\");\n}\n\nconst REPEATED_BROAD_QUERY_THRESHOLD = 2;\n\n/**\n * When a broad-query condition (match/result limit hit, or byte truncation) repeats for\n * the same normalized query, produce a compact \"do not repeat\" style note. This is only\n * the Phase 3 signal; the durable invalidation ledger (supersession/expiry rules) is\n * Phase 6 per implementation-phases.md.\n */\nexport function broadQueryInvalidationNote(\n\ttracker: BroadQueryTracker | undefined,\n\tkey: string,\n\thumanQueryDescription: string,\n): string | undefined {\n\tif (!tracker) return undefined;\n\tconst count = tracker.recordBroadQuery(key);\n\tif (count < REPEATED_BROAD_QUERY_THRESHOLD) return undefined;\n\treturn `Do not repeat: ${humanQueryDescription} has produced broad/truncated results ${count} times in this session. Narrow the path/glob/pattern.`;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"context-gc.d.ts","sourceRoot":"","sources":["../../src/core/context-gc.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAM9D,MAAM,WAAW,wBAAwB;IACxC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,0EAA0E;IAC1E,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,yFAAyF;IACzF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,uEAAuE;IACvE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,MAAM,WAAW,iBAAiB;IACjC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,oEAAoE;IACpE,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,gFAAgF;IAChF,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,oDAAoD;IACpD,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,sFAAsF;IACtF,cAAc,CAAC,EAAE,wBAAwB,CAAC;CAC1C;AAED,MAAM,WAAW,2BAA4B,SAAQ,IAAI,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,gBAAgB,CAAC;IACvG,cAAc,EAAE,QAAQ,CAAC,wBAAwB,CAAC,CAAC;CACnD;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,sBAAsB;IACtC,aAAa,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;IAC1D,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,KAAK,IAAI,CAAC;CACzE;AAED,MAAM,WAAW,gBAAiB,SAAQ,2BAA2B;IACpE,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,kFAAkF;IAClF,iBAAiB,CA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AE,MAAM,MAAM,CAAC;IACjC,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,EAAE,sBAAsB,CAAC;CAClC,GACC,eAAe,CAgIjB"}
@@ -1,9 +1,10 @@
1
1
  import { createHash } from "node:crypto";
2
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { existsSync } from "node:fs";
3
3
  import { isAbsolute, resolve } from "node:path";
4
- import { estimateTokens } from "@caupulican/pi-agent-core/node";
4
+ import { estimateTokens } from "@caupulican/pi-agent-core/compaction/compaction";
5
5
  import { normalizePath } from "../utils/paths.js";
6
6
  import { boundedTextPreview } from "./text-preview.js";
7
+ import { withFileLockSync, writeFileAtomicSync } from "./util/atomic-file.js";
7
8
  const DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS = {
8
9
  enabled: true,
9
10
  preserveRecentPages: 1,
@@ -241,9 +242,10 @@ function maybeStoreOriginal(options, key, original) {
241
242
  const path = storagePathFor(storageDir, key);
242
243
  if (!path || !storageDir)
243
244
  return undefined;
244
- mkdirSync(storageDir, { recursive: true });
245
- if (!existsSync(path))
246
- writeFileSync(path, original, "utf8");
245
+ withFileLockSync(path, () => {
246
+ if (!existsSync(path))
247
+ writeFileAtomicSync(path, original);
248
+ });
247
249
  return path;
248
250
  }
249
251
  catch {
@@ -1 +1 @@
1
- {"version":3,"file":"context-gc.js","sourceRoot":"","sources":["../../src/core/context-gc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAEhE,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC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,CAAC,IAAI,CAAC;aACZ,MAAM,CAAC,YAAY,CAAC;aACpB,MAAM,CAAC,KAAK,CAAC;aACb,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACf,MAAM,WAAW,GAAG,kBAAkB,CAAC,OAAO,EAAE,GAAG,EAAE,YAAY,CAAC,CAAC;QACnE,MAAM,MAAM,GAA0B;YACrC,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,UAAU,EAAE,OAAO,CAAC,UAAU;YAC9B,YAAY,EAAE,KAAK;YACnB,MAAM;YACN,aAAa,EAAE,YAAY,CAAC,MAAM;YAClC,cAAc;YACd,YAAY,EAAE,CAAC;YACf,WAAW;YACX,IAAI;YACJ,OAAO,EAAE,OAAO,IAAI,EAAE,IAAI,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS;YAC/E,GAAG;SACH,CAAC;QACF,mBAAmB,CAClB,OAAO,EACP,UAAU,EACV,YAAY,EACZ,KAAK,EACL,OAAO,EACP,YAAY,EACZ,GAAG,EACH,MAAM,EACN,oBAAoB,CACpB,CAAC;QACF,OAAO,GAAG,IAAI,CAAC;IAChB,CAAC;IAED,UAAU,CAAC,WAAW,GAAG,UAAU,CAAC,OAAO,CAAC,MAAM,CAAC;IACnD,UAAU,CAAC,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,CAAC,cAAc,GAAG,UAAU,CAAC,YAAY,CAAC,CAAC;IAC1F,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;AAC5E,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { isAbsolute, resolve } from \"node:path\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport { estimateTokens } from \"@caupulican/pi-agent-core/node\";\nimport type { ToolResultMessage } from \"@caupulican/pi-ai\";\nimport { normalizePath } from \"../utils/paths.ts\";\nimport { boundedTextPreview } from \"./text-preview.ts\";\n\nexport interface SemanticMemoryGcSettings {\n\tenabled?: boolean;\n\t/** Number of newest Automata/Mind injected pages to preserve verbatim. */\n\tpreserveRecentPages?: number;\n\t/** Minimum provider-visible text chars before a stale semantic memory page is packed. */\n\tminChars?: number;\n\t/** Markers that identify deterministic Automata/Mind context pages. */\n\tmarkers?: string[];\n}\n\nexport interface ContextGcSettings {\n\tenabled?: boolean;\n\t/** Number of most recent AgentMessage rows to preserve verbatim. */\n\tpreserveRecentMessages?: number;\n\t/** Minimum provider-visible text chars before a stale tool result is packed. */\n\tminToolResultChars?: number;\n\t/** Tool names eligible for stale result packing. */\n\ttools?: string[];\n\t/** Provider-context control for deterministic Automata/Mind semantic memory pages. */\n\tsemanticMemory?: SemanticMemoryGcSettings;\n}\n\nexport interface NormalizedContextGcSettings extends Omit<Required<ContextGcSettings>, \"semanticMemory\"> {\n\tsemanticMemory: Required<SemanticMemoryGcSettings>;\n}\n\n/**\n * Brain-curation hooks (both optional; absent hooks are byte-for-byte today's behavior).\n * `resolveDigest` is a pure lookup keyed by the record's content hash — it must return the digest\n * already fenced in the untrusted-content boundary (e.g. BrainCurator.getDigest), with the fence's\n * nonce fixed once at store time, since GC re-renders the stub from raw messages on every request\n * and renders the returned string VERBATIM. `onPacked` lets the caller enqueue digest work with the\n * exact original text at the moment it is packed.\n */\nexport interface ContextGcCurationHooks {\n\tresolveDigest?: (digestKey: string) => string | undefined;\n\tonPacked?: (record: ContextGcPackedRecord, originalText: string) => void;\n}\n\nexport interface ContextGcOptions extends NormalizedContextGcSettings {\n\tcwd: string;\n\tstorageDir?: string;\n\t/** Acquire the leased store only when an eligible payload is actually written. */\n\tacquireStorageDir?: () => string;\n\twritePayloads?: boolean;\n\tcuration?: ContextGcCurationHooks;\n}\n\nexport interface ContextGcPackedRecord {\n\ttoolName: string;\n\ttoolCallId: string;\n\tmessageIndex: number;\n\treason: \"superseded-read\" | \"stale-tool-result\" | \"stale-semantic-memory\";\n\toriginalChars: number;\n\toriginalTokens: number;\n\tpackedTokens: number;\n\tstoragePath?: string;\n\tpath?: string;\n\tcommand?: string;\n\tkey?: string;\n\t/** Brain-curator semantic digest of the packed content (model-generated; advisory only). Arrives\n\t * already fenced in the untrusted-content boundary (see ContextGcCurationHooks.resolveDigest) —\n\t * render verbatim, never re-wrap. */\n\tdigest?: string;\n}\n\nexport interface ContextGcReport {\n\tenabled: boolean;\n\tpackedCount: number;\n\toriginalTokens: number;\n\tpackedTokens: number;\n\tsavedTokens: number;\n\trecords: ContextGcPackedRecord[];\n}\n\nexport interface ContextGcResult {\n\tmessages: AgentMessage[];\n\treport: ContextGcReport;\n}\n\nconst DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS: Required<SemanticMemoryGcSettings> = {\n\tenabled: true,\n\tpreserveRecentPages: 1,\n\tminChars: 900,\n\tmarkers: [\n\t\t// Generic memory-subsystem recall page marker (brand-free). Provider-specific markers are\n\t\t// merged in dynamically at runtime via MemoryManager.getContextMarkers().\n\t\t\"<memory_context\",\n\t\t// Pre-existing provider-specific markers (to be generalized to provider-declared markers).\n\t\t\"<automata_context\",\n\t\t\"<automata_response\",\n\t\t\"<automata_query\",\n\t\t\"<automata_fetch\",\n\t\t\"<memory_lifecycle_audit\",\n\t\t\"<memory_lifecycle_purge\",\n\t\t\"<automata_doctor\",\n\t\t\"<automata_optimizer\",\n\t\t\"<automata_mesh\",\n\t\t// Injected task_steps checklist page (tasks/task-state.ts formatTaskStepsContext), re-derived\n\t\t// fresh every turn from live TaskStepsState -- same GC treatment as a memory recall page (Bug\n\t\t// #7 lineage): pack stale turn-copies down to the most recent one instead of accumulating.\n\t\t\"<task_steps_context\",\n\t],\n};\n\nexport const DEFAULT_CONTEXT_GC_SETTINGS: NormalizedContextGcSettings = {\n\tenabled: true,\n\tpreserveRecentMessages: 8,\n\tminToolResultChars: 1200,\n\ttools: [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"python\",\n\t\t\"powershell\",\n\t\t\"rg\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"run_toolkit_script\",\n\t\t\"ls\",\n\t\t\"skill_open\",\n\t\t\"automata_graph_status\",\n\t\t\"automata_graph_search\",\n\t\t\"automata_graph_query\",\n\t\t\"automata_graph_neighbors\",\n\t\t\"automata_graph_path\",\n\t\t\"automata_graph_pointer_pack\",\n\t\t\"learning_query_memory\",\n\t\t\"subagent\",\n\t\t\"delegate\",\n\t\t\"task_steps\",\n\t\t\"task_background\",\n\t\t\"task_goal\",\n\t\t\"run_ledger\",\n\t\t\"context_headroom_retrieve\",\n\t\t\"headroom_retrieve\",\n\t],\n\tsemanticMemory: DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS,\n};\n\ntype ToolCallMeta = {\n\tid: string;\n\tname: string;\n\targs: Record<string, unknown>;\n\tmessageIndex: number;\n};\n\nfunction normalizeSemanticMemoryGcSettings(settings?: SemanticMemoryGcSettings): Required<SemanticMemoryGcSettings> {\n\treturn {\n\t\tenabled: settings?.enabled ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.enabled,\n\t\tpreserveRecentPages: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.preserveRecentPages ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.preserveRecentPages),\n\t\t),\n\t\tminChars: Math.max(0, Math.floor(settings?.minChars ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.minChars)),\n\t\tmarkers:\n\t\t\tsettings?.markers && settings.markers.length > 0\n\t\t\t\t? settings.markers\n\t\t\t\t: DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.markers,\n\t};\n}\n\nfunction normalizeContextGcSettings(settings?: ContextGcSettings): NormalizedContextGcSettings {\n\treturn {\n\t\tenabled: settings?.enabled ?? DEFAULT_CONTEXT_GC_SETTINGS.enabled,\n\t\tpreserveRecentMessages: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.preserveRecentMessages ?? DEFAULT_CONTEXT_GC_SETTINGS.preserveRecentMessages),\n\t\t),\n\t\tminToolResultChars: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.minToolResultChars ?? DEFAULT_CONTEXT_GC_SETTINGS.minToolResultChars),\n\t\t),\n\t\ttools: settings?.tools && settings.tools.length > 0 ? settings.tools : DEFAULT_CONTEXT_GC_SETTINGS.tools,\n\t\tsemanticMemory: normalizeSemanticMemoryGcSettings(settings?.semanticMemory),\n\t};\n}\n\nexport function getContextGcSettings(settings?: ContextGcSettings): NormalizedContextGcSettings {\n\treturn normalizeContextGcSettings(settings);\n}\n\nfunction textContentParts(content: unknown): string[] | undefined {\n\tif (typeof content === \"string\") return [content];\n\tif (!Array.isArray(content)) return undefined;\n\tconst parts: string[] = [];\n\tfor (const part of content) {\n\t\tif (typeof part !== \"object\" || part === null) return undefined;\n\t\tconst typed = part as { type?: string; text?: string; mimeType?: string };\n\t\tif (typed.type === \"text\" && typeof typed.text === \"string\") parts.push(typed.text);\n\t\telse if (typed.type === \"image\") return undefined;\n\t\telse return undefined;\n\t}\n\treturn parts;\n}\n\nfunction joinTextParts(parts: readonly string[]): string {\n\tif (parts.length === 0) return \"\";\n\tif (parts.length === 1) return parts[0];\n\treturn parts.join(\"\\n\");\n}\n\nfunction contentText(content: unknown): string | undefined {\n\tif (typeof content === \"string\") return content;\n\tconst parts = textContentParts(content);\n\treturn parts ? joinTextParts(parts) : undefined;\n}\n\nfunction toolResultParts(message: ToolResultMessage): string[] {\n\tconst parts: string[] = [];\n\tfor (const part of message.content) {\n\t\tif (part.type === \"text\" && part.text) parts.push(part.text);\n\t\telse if (part.type === \"image\") parts.push(`[image ${part.mimeType}]`);\n\t}\n\treturn parts;\n}\n\nfunction toolResultText(message: ToolResultMessage): string {\n\treturn joinTextParts(toolResultParts(message));\n}\n\nfunction smallStringSlice(value: string, start?: number, end?: number): string {\n\tconst sliced = value.slice(start, end);\n\treturn sliced ? ` ${sliced}`.slice(1) : \"\";\n}\n\nfunction joinedPartsContainMarker(parts: string[], marker: string): boolean {\n\tif (marker.length === 0) return true;\n\tconst tailLength = marker.length - 1;\n\tlet tail = \"\";\n\tlet first = true;\n\tfor (const part of parts) {\n\t\tif (part.includes(marker)) return true;\n\t\tif (!first && `${tail}\\n${smallStringSlice(part, 0, tailLength)}`.includes(marker)) return true;\n\t\tif (tailLength === 0) tail = \"\";\n\t\telse if (part.length >= tailLength) tail = smallStringSlice(part, -tailLength);\n\t\telse tail = `${tail}${first ? \"\" : \"\\n\"}${part}`.slice(-tailLength);\n\t\tfirst = false;\n\t}\n\treturn false;\n}\n\nfunction joinedPartsContainAnyMarker(parts: string[], markers: readonly string[]): boolean {\n\treturn markers.some((marker) => joinedPartsContainMarker(parts, marker));\n}\n\n// Gates which custom-message types are eligible for the semantic-memory packer below. Despite the\n// name, this now also covers the injected task_steps checklist page (customType \"task_steps_context\",\n// see agent-session.ts) -- it is a deterministic, re-derivable-from-live-state context page exactly\n// like a memory recall page, so it gets the same GC treatment. A marker match alone\n// is not enough: semanticMessageHasMarker/agentMessageText only inspect a custom message's text at all\n// once it passes this gate, so a customType that doesn't match here never reaches the marker check.\nfunction isSemanticMemoryCustomMessage(message: AgentMessage): boolean {\n\tif (message.role !== \"custom\") return false;\n\tconst customType = String((message as { customType?: unknown }).customType ?? \"\").toLowerCase();\n\treturn (\n\t\tcustomType.includes(\"automata\") ||\n\t\tcustomType.includes(\"memory\") ||\n\t\tcustomType.includes(\"mind\") ||\n\t\tcustomType.includes(\"task_steps\")\n\t);\n}\n\nfunction agentMessageText(message: AgentMessage): string | undefined {\n\tif (message.role === \"toolResult\") return toolResultText(message);\n\tif (isSemanticMemoryCustomMessage(message)) return contentText((message as { content?: unknown }).content);\n\treturn undefined;\n}\n\nfunction semanticMessageHasMarker(message: AgentMessage, settings: Required<SemanticMemoryGcSettings>): boolean {\n\tif (message.role === \"toolResult\") return joinedPartsContainAnyMarker(toolResultParts(message), settings.markers);\n\tif (isSemanticMemoryCustomMessage(message)) {\n\t\tconst parts = textContentParts((message as { content?: unknown }).content);\n\t\treturn parts ? joinedPartsContainAnyMarker(parts, settings.markers) : false;\n\t}\n\treturn false;\n}\n\ninterface ContextGcPlan {\n\tcalls: Map<string, ToolCallMeta>;\n\tlatestReadByPath: Map<string, string>;\n\tsemanticIndexes: number[];\n}\n\nfunction normalizeToolPath(cwd: string, value: unknown): string | undefined {\n\tif (typeof value !== \"string\" || value.trim() === \"\") return undefined;\n\tconst path = value.trim();\n\treturn normalizePath(isAbsolute(path) ? path : resolve(cwd, path));\n}\n\nfunction collectContextGcPlan(\n\tmessages: AgentMessage[],\n\tcwd: string,\n\tsemanticSettings: Required<SemanticMemoryGcSettings>,\n): ContextGcPlan {\n\tconst calls = new Map<string, ToolCallMeta>();\n\tconst readResultCallIds: string[] = [];\n\tconst semanticIndexes: number[] = [];\n\n\tfor (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {\n\t\tconst message = messages[messageIndex];\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const part of message.content) {\n\t\t\t\tif (part.type !== \"toolCall\") continue;\n\t\t\t\tcalls.set(part.id, {\n\t\t\t\t\tid: part.id,\n\t\t\t\t\tname: part.name,\n\t\t\t\t\targs: part.arguments ?? {},\n\t\t\t\t\tmessageIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (message.role === \"toolResult\" && message.toolName === \"read\") {\n\t\t\treadResultCallIds.push(message.toolCallId);\n\t\t}\n\n\t\tif (semanticSettings.enabled && semanticMessageHasMarker(message, semanticSettings)) {\n\t\t\tsemanticIndexes.push(messageIndex);\n\t\t}\n\t}\n\n\tconst latestReadByPath = new Map<string, string>();\n\tfor (const toolCallId of readResultCallIds) {\n\t\tconst call = calls.get(toolCallId);\n\t\tconst path = normalizeToolPath(cwd, call?.args.path);\n\t\tif (path) latestReadByPath.set(path, toolCallId);\n\t}\n\n\treturn { calls, latestReadByPath, semanticIndexes };\n}\n\nfunction storagePathFor(storageDir: string | undefined, key: string): string | undefined {\n\tif (!storageDir || !isAbsolute(storageDir)) return undefined;\n\treturn resolve(storageDir, `${key}.txt`);\n}\n\nfunction maybeStoreOriginal(options: ContextGcOptions, key: string, original: string): string | undefined {\n\tconst plannedPath = storagePathFor(options.storageDir, key);\n\tif (!plannedPath || !options.writePayloads) return plannedPath;\n\ttry {\n\t\tconst storageDir = options.acquireStorageDir?.() ?? options.storageDir;\n\t\tconst path = storagePathFor(storageDir, key);\n\t\tif (!path || !storageDir) return undefined;\n\t\tmkdirSync(storageDir, { recursive: true });\n\t\tif (!existsSync(path)) writeFileSync(path, original, \"utf8\");\n\t\treturn path;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction reasonText(record: ContextGcPackedRecord): string {\n\tif (record.reason === \"superseded-read\") return \"older read snapshot superseded by a later read of the same file\";\n\tif (record.reason === \"stale-semantic-memory\") {\n\t\treturn \"older Automata/Mind semantic context page outside the semantic-memory freshness window\";\n\t}\n\treturn \"stale bulky tool output outside the recent context window\";\n}\n\nfunction buildSummary(record: ContextGcPackedRecord): string {\n\tconst semantic = record.reason === \"stale-semantic-memory\";\n\tconst lines = [\n\t\tsemantic ? \"[Semantic GC packed stale Automata/Mind context page]\" : \"[Context GC packed stale tool result]\",\n\t\tsemantic ? undefined : `tool: ${record.toolName}`,\n\t\trecord.path ? `path: ${record.path}` : undefined,\n\t\trecord.command ? `command: ${boundedTextPreview(record.command)}` : undefined,\n\t\t`reason: ${reasonText(record)}`,\n\t\t`original: ${record.originalChars} chars (~${record.originalTokens} tokens)`,\n\t\t// The digest arrives PRE-FENCED from the curator (brain-curator.ts wraps it once, in the\n\t\t// standard untrusted-content boundary — the same treatment memory recall pages get — at the\n\t\t// moment it is stored, not here). Render it VERBATIM: re-wrapping on every GC render would\n\t\t// regenerate the fence's nonce each time, making the packed stub byte-different on every\n\t\t// provider request and busting prompt caching (BUG E).\n\t\trecord.digest ? `summary (auto-digest, machine paraphrase, not authoritative): ${record.digest}` : undefined,\n\t\trecord.storagePath\n\t\t\t? `exact old provider-visible text stored at: ${record.storagePath}`\n\t\t\t: \"exact old provider-visible text retained in the session log, not inline in provider context\",\n\t\tsemantic\n\t\t\t? \"If this memory context matters, query Automata/Mind again with the same topic/filter or fetch the drawer pointers from the stored page.\"\n\t\t\t: record.path\n\t\t\t\t? \"For current file contents, use the read tool on the path above. For the exact old output, read the stored payload path if present.\"\n\t\t\t\t: \"If this exact old output matters, retrieve/read the stored payload path if present or rerun the tool command.\",\n\t\t\"Do not rely on this summary as the original content.\",\n\t].filter((line): line is string => line !== undefined);\n\treturn lines.join(\"\\n\");\n}\n\nfunction gcDetails(message: { details?: unknown }, record: ContextGcPackedRecord): Record<string, unknown> {\n\treturn {\n\t\t...(typeof message.details === \"object\" && message.details !== null ? message.details : {}),\n\t\tcontextGc: {\n\t\t\tpacked: true,\n\t\t\toriginalChars: record.originalChars,\n\t\t\toriginalTokens: record.originalTokens,\n\t\t\tstoragePath: record.storagePath,\n\t\t\treason: record.reason,\n\t\t},\n\t};\n}\n\nfunction makePackedToolResult(message: ToolResultMessage, record: ContextGcPackedRecord): ToolResultMessage {\n\tconst summary = buildSummary(record);\n\treturn {\n\t\t...message,\n\t\tcontent: [{ type: \"text\", text: summary }],\n\t\tdetails: gcDetails(message, record),\n\t};\n}\n\nfunction makePackedSemanticMemoryMessage(message: AgentMessage, record: ContextGcPackedRecord): AgentMessage {\n\tconst summary = buildSummary(record);\n\treturn {\n\t\t...(message as unknown as Record<string, unknown>),\n\t\tcontent: [{ type: \"text\", text: summary }],\n\t\tdetails: gcDetails(message as { details?: unknown }, record),\n\t} as AgentMessage;\n}\n\nfunction commitPackedMessage<TMessage extends AgentMessage>(\n\toptions: ContextGcOptions,\n\treport: ContextGcReport,\n\tnextMessages: AgentMessage[],\n\tmessageIndex: number,\n\tmessage: TMessage,\n\toriginalText: string,\n\tkey: string,\n\trecord: ContextGcPackedRecord,\n\tmakePacked: (message: TMessage, record: ContextGcPackedRecord) => AgentMessage,\n): void {\n\trecord.digest = options.curation?.resolveDigest?.(key);\n\toptions.curation?.onPacked?.(record, originalText);\n\tconst packed = makePacked(message, record);\n\trecord.packedTokens = estimateTokens(packed);\n\tnextMessages[messageIndex] = packed;\n\treport.records.push(record);\n\treport.originalTokens += record.originalTokens;\n\treport.packedTokens += record.packedTokens;\n}\n\nexport function applyContextGc(\n\tmessages: AgentMessage[],\n\trawSettings: ContextGcSettings & {\n\t\tcwd?: string;\n\t\tstorageDir?: string;\n\t\tacquireStorageDir?: () => string;\n\t\twritePayloads?: boolean;\n\t\tcuration?: ContextGcCurationHooks;\n\t},\n): ContextGcResult {\n\tconst settings = normalizeContextGcSettings(rawSettings);\n\tconst baseReport: ContextGcReport = {\n\t\tenabled: settings.enabled,\n\t\tpackedCount: 0,\n\t\toriginalTokens: 0,\n\t\tpackedTokens: 0,\n\t\tsavedTokens: 0,\n\t\trecords: [],\n\t};\n\tif (!settings.enabled) return { messages, report: baseReport };\n\n\tconst options: ContextGcOptions = {\n\t\t...settings,\n\t\tcwd: rawSettings.cwd ?? process.cwd(),\n\t\tstorageDir: rawSettings.storageDir,\n\t\tacquireStorageDir: rawSettings.acquireStorageDir,\n\t\twritePayloads: rawSettings.writePayloads ?? true,\n\t\tcuration: rawSettings.curation,\n\t};\n\tconst eligibleTools = new Set(options.tools);\n\tconst plan = collectContextGcPlan(messages, options.cwd, options.semanticMemory);\n\tconst recentStart = Math.max(0, messages.length - options.preserveRecentMessages);\n\tconst semanticIndexSet = new Set(plan.semanticIndexes);\n\tconst preservedSemanticIndexes = new Set(\n\t\toptions.semanticMemory.preserveRecentPages > 0\n\t\t\t? plan.semanticIndexes.slice(-options.semanticMemory.preserveRecentPages)\n\t\t\t: [],\n\t);\n\tconst nextMessages = messages.slice();\n\tlet changed = false;\n\n\tfor (let index = 0; index < messages.length; index++) {\n\t\tconst message = messages[index];\n\t\tif (semanticIndexSet.has(index) && !preservedSemanticIndexes.has(index) && index < recentStart) {\n\t\t\tconst originalText = agentMessageText(message);\n\t\t\tif (originalText && originalText.length >= options.semanticMemory.minChars) {\n\t\t\t\tconst originalTokens = estimateTokens(message);\n\t\t\t\tconst key = createHash(\"sha256\")\n\t\t\t\t\t.update(\"semantic-memory\\0\")\n\t\t\t\t\t.update(String(index))\n\t\t\t\t\t.update(\"\\0\")\n\t\t\t\t\t.update(originalText)\n\t\t\t\t\t.digest(\"hex\")\n\t\t\t\t\t.slice(0, 24);\n\t\t\t\tconst storagePath = maybeStoreOriginal(options, key, originalText);\n\t\t\t\tconst record: ContextGcPackedRecord = {\n\t\t\t\t\ttoolName: \"automata-mind\",\n\t\t\t\t\ttoolCallId: `semantic-${index}`,\n\t\t\t\t\tmessageIndex: index,\n\t\t\t\t\treason: \"stale-semantic-memory\",\n\t\t\t\t\toriginalChars: originalText.length,\n\t\t\t\t\toriginalTokens,\n\t\t\t\t\tpackedTokens: 0,\n\t\t\t\t\tstoragePath,\n\t\t\t\t\tkey,\n\t\t\t\t};\n\t\t\t\tcommitPackedMessage(\n\t\t\t\t\toptions,\n\t\t\t\t\tbaseReport,\n\t\t\t\t\tnextMessages,\n\t\t\t\t\tindex,\n\t\t\t\t\tmessage,\n\t\t\t\t\toriginalText,\n\t\t\t\t\tkey,\n\t\t\t\t\trecord,\n\t\t\t\t\tmakePackedSemanticMemoryMessage,\n\t\t\t\t);\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (message.role !== \"toolResult\") continue;\n\t\tif (!eligibleTools.has(message.toolName)) continue;\n\t\tif (index >= recentStart) continue;\n\n\t\tconst originalText = toolResultText(message);\n\t\tif (originalText.length < options.minToolResultChars) continue;\n\n\t\tconst call = plan.calls.get(message.toolCallId);\n\t\tconst path = normalizeToolPath(options.cwd, call?.args.path);\n\t\tlet reason: ContextGcPackedRecord[\"reason\"] = \"stale-tool-result\";\n\t\tif (message.toolName === \"read\" && path) {\n\t\t\tif (plan.latestReadByPath.get(path) === message.toolCallId) continue;\n\t\t\treason = \"superseded-read\";\n\t\t}\n\n\t\tconst originalTokens = estimateTokens(message);\n\t\tconst key = createHash(\"sha256\")\n\t\t\t.update(message.toolName)\n\t\t\t.update(\"\\0\")\n\t\t\t.update(message.toolCallId)\n\t\t\t.update(\"\\0\")\n\t\t\t.update(originalText)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 24);\n\t\tconst storagePath = maybeStoreOriginal(options, key, originalText);\n\t\tconst record: ContextGcPackedRecord = {\n\t\t\ttoolName: message.toolName,\n\t\t\ttoolCallId: message.toolCallId,\n\t\t\tmessageIndex: index,\n\t\t\treason,\n\t\t\toriginalChars: originalText.length,\n\t\t\toriginalTokens,\n\t\t\tpackedTokens: 0,\n\t\t\tstoragePath,\n\t\t\tpath,\n\t\t\tcommand: typeof call?.args.command === \"string\" ? call.args.command : undefined,\n\t\t\tkey,\n\t\t};\n\t\tcommitPackedMessage(\n\t\t\toptions,\n\t\t\tbaseReport,\n\t\t\tnextMessages,\n\t\t\tindex,\n\t\t\tmessage,\n\t\t\toriginalText,\n\t\t\tkey,\n\t\t\trecord,\n\t\t\tmakePackedToolResult,\n\t\t);\n\t\tchanged = true;\n\t}\n\n\tbaseReport.packedCount = baseReport.records.length;\n\tbaseReport.savedTokens = Math.max(0, baseReport.originalTokens - baseReport.packedTokens);\n\treturn { messages: changed ? nextMessages : messages, report: baseReport };\n}\n"]}
1
+ {"version":3,"file":"context-gc.js","sourceRoot":"","sources":["../../src/core/context-gc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,MAAM,iDAAiD,CAAC;AAEjF,OAAO,EAAE,aAAa,EAAE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Hash } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { isAbsolute, resolve } from \"node:path\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport { estimateTokens } from \"@caupulican/pi-agent-core/compaction/compaction\";\nimport type { ToolResultMessage } from \"@caupulican/pi-ai\";\nimport { normalizePath } from \"../utils/paths.ts\";\nimport { boundedTextPreview } from \"./text-preview.ts\";\nimport { withFileLockSync, writeFileAtomicSync } from \"./util/atomic-file.ts\";\n\nexport interface SemanticMemoryGcSettings {\n\tenabled?: boolean;\n\t/** Number of newest Automata/Mind injected pages to preserve verbatim. */\n\tpreserveRecentPages?: number;\n\t/** Minimum provider-visible text chars before a stale semantic memory page is packed. */\n\tminChars?: number;\n\t/** Markers that identify deterministic Automata/Mind context pages. */\n\tmarkers?: string[];\n}\n\nexport interface ContextGcSettings {\n\tenabled?: boolean;\n\t/** Number of most recent AgentMessage rows to preserve verbatim. */\n\tpreserveRecentMessages?: number;\n\t/** Minimum provider-visible text chars before a stale tool result is packed. */\n\tminToolResultChars?: number;\n\t/** Tool names eligible for stale result packing. */\n\ttools?: string[];\n\t/** Provider-context control for deterministic Automata/Mind semantic memory pages. */\n\tsemanticMemory?: SemanticMemoryGcSettings;\n}\n\nexport interface NormalizedContextGcSettings extends Omit<Required<ContextGcSettings>, \"semanticMemory\"> {\n\tsemanticMemory: Required<SemanticMemoryGcSettings>;\n}\n\n/**\n * Brain-curation hooks (both optional; absent hooks are byte-for-byte today's behavior).\n * `resolveDigest` is a pure lookup keyed by the record's content hash — it must return the digest\n * already fenced in the untrusted-content boundary (e.g. BrainCurator.getDigest), with the fence's\n * nonce fixed once at store time, since GC re-renders the stub from raw messages on every request\n * and renders the returned string VERBATIM. `onPacked` lets the caller enqueue digest work with the\n * exact original text at the moment it is packed.\n */\nexport interface ContextGcCurationHooks {\n\tresolveDigest?: (digestKey: string) => string | undefined;\n\tonPacked?: (record: ContextGcPackedRecord, originalText: string) => void;\n}\n\nexport interface ContextGcOptions extends NormalizedContextGcSettings {\n\tcwd: string;\n\tstorageDir?: string;\n\t/** Acquire the leased store only when an eligible payload is actually written. */\n\tacquireStorageDir?: () => string;\n\twritePayloads?: boolean;\n\tcuration?: ContextGcCurationHooks;\n}\n\nexport interface ContextGcPackedRecord {\n\ttoolName: string;\n\ttoolCallId: string;\n\tmessageIndex: number;\n\treason: \"superseded-read\" | \"stale-tool-result\" | \"stale-semantic-memory\";\n\toriginalChars: number;\n\toriginalTokens: number;\n\tpackedTokens: number;\n\tstoragePath?: string;\n\tpath?: string;\n\tcommand?: string;\n\tkey?: string;\n\t/** Brain-curator semantic digest of the packed content (model-generated; advisory only). Arrives\n\t * already fenced in the untrusted-content boundary (see ContextGcCurationHooks.resolveDigest) —\n\t * render verbatim, never re-wrap. */\n\tdigest?: string;\n}\n\nexport interface ContextGcReport {\n\tenabled: boolean;\n\tpackedCount: number;\n\toriginalTokens: number;\n\tpackedTokens: number;\n\tsavedTokens: number;\n\trecords: ContextGcPackedRecord[];\n}\n\nexport interface ContextGcResult {\n\tmessages: AgentMessage[];\n\treport: ContextGcReport;\n}\n\nconst DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS: Required<SemanticMemoryGcSettings> = {\n\tenabled: true,\n\tpreserveRecentPages: 1,\n\tminChars: 900,\n\tmarkers: [\n\t\t// Generic memory-subsystem recall page marker (brand-free). Provider-specific markers are\n\t\t// merged in dynamically at runtime via MemoryManager.getContextMarkers().\n\t\t\"<memory_context\",\n\t\t// Pre-existing provider-specific markers (to be generalized to provider-declared markers).\n\t\t\"<automata_context\",\n\t\t\"<automata_response\",\n\t\t\"<automata_query\",\n\t\t\"<automata_fetch\",\n\t\t\"<memory_lifecycle_audit\",\n\t\t\"<memory_lifecycle_purge\",\n\t\t\"<automata_doctor\",\n\t\t\"<automata_optimizer\",\n\t\t\"<automata_mesh\",\n\t\t// Injected task_steps checklist page (tasks/task-state.ts formatTaskStepsContext), re-derived\n\t\t// fresh every turn from live TaskStepsState -- same GC treatment as a memory recall page (Bug\n\t\t// #7 lineage): pack stale turn-copies down to the most recent one instead of accumulating.\n\t\t\"<task_steps_context\",\n\t],\n};\n\nexport const DEFAULT_CONTEXT_GC_SETTINGS: NormalizedContextGcSettings = {\n\tenabled: true,\n\tpreserveRecentMessages: 8,\n\tminToolResultChars: 1200,\n\ttools: [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"python\",\n\t\t\"powershell\",\n\t\t\"rg\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"run_toolkit_script\",\n\t\t\"ls\",\n\t\t\"skill_open\",\n\t\t\"automata_graph_status\",\n\t\t\"automata_graph_search\",\n\t\t\"automata_graph_query\",\n\t\t\"automata_graph_neighbors\",\n\t\t\"automata_graph_path\",\n\t\t\"automata_graph_pointer_pack\",\n\t\t\"learning_query_memory\",\n\t\t\"subagent\",\n\t\t\"delegate\",\n\t\t\"task_steps\",\n\t\t\"task_background\",\n\t\t\"task_goal\",\n\t\t\"run_ledger\",\n\t\t\"context_headroom_retrieve\",\n\t\t\"headroom_retrieve\",\n\t],\n\tsemanticMemory: DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS,\n};\n\ntype ToolCallMeta = {\n\tid: string;\n\tname: string;\n\targs: Record<string, unknown>;\n\tmessageIndex: number;\n};\n\nfunction normalizeSemanticMemoryGcSettings(settings?: SemanticMemoryGcSettings): Required<SemanticMemoryGcSettings> {\n\treturn {\n\t\tenabled: settings?.enabled ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.enabled,\n\t\tpreserveRecentPages: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.preserveRecentPages ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.preserveRecentPages),\n\t\t),\n\t\tminChars: Math.max(0, Math.floor(settings?.minChars ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.minChars)),\n\t\tmarkers:\n\t\t\tsettings?.markers && settings.markers.length > 0\n\t\t\t\t? settings.markers\n\t\t\t\t: DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.markers,\n\t};\n}\n\nfunction normalizeContextGcSettings(settings?: ContextGcSettings): NormalizedContextGcSettings {\n\treturn {\n\t\tenabled: settings?.enabled ?? DEFAULT_CONTEXT_GC_SETTINGS.enabled,\n\t\tpreserveRecentMessages: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.preserveRecentMessages ?? DEFAULT_CONTEXT_GC_SETTINGS.preserveRecentMessages),\n\t\t),\n\t\tminToolResultChars: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.minToolResultChars ?? DEFAULT_CONTEXT_GC_SETTINGS.minToolResultChars),\n\t\t),\n\t\ttools: settings?.tools && settings.tools.length > 0 ? settings.tools : DEFAULT_CONTEXT_GC_SETTINGS.tools,\n\t\tsemanticMemory: normalizeSemanticMemoryGcSettings(settings?.semanticMemory),\n\t};\n}\n\nexport function getContextGcSettings(settings?: ContextGcSettings): NormalizedContextGcSettings {\n\treturn normalizeContextGcSettings(settings);\n}\n\nfunction textContentParts(content: unknown): string[] | undefined {\n\tif (typeof content === \"string\") return [content];\n\tif (!Array.isArray(content)) return undefined;\n\tconst parts: string[] = [];\n\tfor (const part of content) {\n\t\tif (typeof part !== \"object\" || part === null) return undefined;\n\t\tconst typed = part as { type?: string; text?: string; mimeType?: string };\n\t\tif (typed.type === \"text\" && typeof typed.text === \"string\") parts.push(typed.text);\n\t\telse if (typed.type === \"image\") return undefined;\n\t\telse return undefined;\n\t}\n\treturn parts;\n}\n\nfunction joinTextParts(parts: readonly string[]): string {\n\tif (parts.length === 0) return \"\";\n\tif (parts.length === 1) return parts[0];\n\treturn parts.join(\"\\n\");\n}\n\nfunction contentText(content: unknown): string | undefined {\n\tif (typeof content === \"string\") return content;\n\tconst parts = textContentParts(content);\n\treturn parts ? joinTextParts(parts) : undefined;\n}\n\nfunction toolResultParts(message: ToolResultMessage): string[] {\n\tconst parts: string[] = [];\n\tfor (const part of message.content) {\n\t\tif (part.type === \"text\" && part.text) parts.push(part.text);\n\t\telse if (part.type === \"image\") parts.push(`[image ${part.mimeType}]`);\n\t}\n\treturn parts;\n}\n\nfunction toolResultText(message: ToolResultMessage): string {\n\treturn joinTextParts(toolResultParts(message));\n}\n\nfunction smallStringSlice(value: string, start?: number, end?: number): string {\n\tconst sliced = value.slice(start, end);\n\treturn sliced ? ` ${sliced}`.slice(1) : \"\";\n}\n\nfunction joinedPartsContainMarker(parts: string[], marker: string): boolean {\n\tif (marker.length === 0) return true;\n\tconst tailLength = marker.length - 1;\n\tlet tail = \"\";\n\tlet first = true;\n\tfor (const part of parts) {\n\t\tif (part.includes(marker)) return true;\n\t\tif (!first && `${tail}\\n${smallStringSlice(part, 0, tailLength)}`.includes(marker)) return true;\n\t\tif (tailLength === 0) tail = \"\";\n\t\telse if (part.length >= tailLength) tail = smallStringSlice(part, -tailLength);\n\t\telse tail = `${tail}${first ? \"\" : \"\\n\"}${part}`.slice(-tailLength);\n\t\tfirst = false;\n\t}\n\treturn false;\n}\n\nfunction joinedPartsContainAnyMarker(parts: string[], markers: readonly string[]): boolean {\n\treturn markers.some((marker) => joinedPartsContainMarker(parts, marker));\n}\n\n// Gates which custom-message types are eligible for the semantic-memory packer below. Despite the\n// name, this now also covers the injected task_steps checklist page (customType \"task_steps_context\",\n// see agent-session.ts) -- it is a deterministic, re-derivable-from-live-state context page exactly\n// like a memory recall page, so it gets the same GC treatment. A marker match alone\n// is not enough: semanticMessageHasMarker/agentMessageText only inspect a custom message's text at all\n// once it passes this gate, so a customType that doesn't match here never reaches the marker check.\nfunction isSemanticMemoryCustomMessage(message: AgentMessage): boolean {\n\tif (message.role !== \"custom\") return false;\n\tconst customType = String((message as { customType?: unknown }).customType ?? \"\").toLowerCase();\n\treturn (\n\t\tcustomType.includes(\"automata\") ||\n\t\tcustomType.includes(\"memory\") ||\n\t\tcustomType.includes(\"mind\") ||\n\t\tcustomType.includes(\"task_steps\")\n\t);\n}\n\nfunction agentMessageText(message: AgentMessage): string | undefined {\n\tif (message.role === \"toolResult\") return toolResultText(message);\n\tif (isSemanticMemoryCustomMessage(message)) return contentText((message as { content?: unknown }).content);\n\treturn undefined;\n}\n\nfunction semanticMessageHasMarker(message: AgentMessage, settings: Required<SemanticMemoryGcSettings>): boolean {\n\tif (message.role === \"toolResult\") return joinedPartsContainAnyMarker(toolResultParts(message), settings.markers);\n\tif (isSemanticMemoryCustomMessage(message)) {\n\t\tconst parts = textContentParts((message as { content?: unknown }).content);\n\t\treturn parts ? joinedPartsContainAnyMarker(parts, settings.markers) : false;\n\t}\n\treturn false;\n}\n\ninterface ContextGcPlan {\n\tcalls: Map<string, ToolCallMeta>;\n\tlatestReadByPath: Map<string, string>;\n\tsemanticIndexes: number[];\n}\n\nfunction normalizeToolPath(cwd: string, value: unknown): string | undefined {\n\tif (typeof value !== \"string\" || value.trim() === \"\") return undefined;\n\tconst path = value.trim();\n\treturn normalizePath(isAbsolute(path) ? path : resolve(cwd, path));\n}\n\nfunction collectContextGcPlan(\n\tmessages: AgentMessage[],\n\tcwd: string,\n\tsemanticSettings: Required<SemanticMemoryGcSettings>,\n): ContextGcPlan {\n\tconst calls = new Map<string, ToolCallMeta>();\n\tconst readResultCallIds: string[] = [];\n\tconst semanticIndexes: number[] = [];\n\n\tfor (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {\n\t\tconst message = messages[messageIndex];\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const part of message.content) {\n\t\t\t\tif (part.type !== \"toolCall\") continue;\n\t\t\t\tcalls.set(part.id, {\n\t\t\t\t\tid: part.id,\n\t\t\t\t\tname: part.name,\n\t\t\t\t\targs: part.arguments ?? {},\n\t\t\t\t\tmessageIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (message.role === \"toolResult\" && message.toolName === \"read\") {\n\t\t\treadResultCallIds.push(message.toolCallId);\n\t\t}\n\n\t\tif (semanticSettings.enabled && semanticMessageHasMarker(message, semanticSettings)) {\n\t\t\tsemanticIndexes.push(messageIndex);\n\t\t}\n\t}\n\n\tconst latestReadByPath = new Map<string, string>();\n\tfor (const toolCallId of readResultCallIds) {\n\t\tconst call = calls.get(toolCallId);\n\t\tconst path = normalizeToolPath(cwd, call?.args.path);\n\t\tif (path) latestReadByPath.set(path, toolCallId);\n\t}\n\n\treturn { calls, latestReadByPath, semanticIndexes };\n}\n\nfunction storagePathFor(storageDir: string | undefined, key: string): string | undefined {\n\tif (!storageDir || !isAbsolute(storageDir)) return undefined;\n\treturn resolve(storageDir, `${key}.txt`);\n}\n\nfunction maybeStoreOriginal(options: ContextGcOptions, key: string, original: string): string | undefined {\n\tconst plannedPath = storagePathFor(options.storageDir, key);\n\tif (!plannedPath || !options.writePayloads) return plannedPath;\n\ttry {\n\t\tconst storageDir = options.acquireStorageDir?.() ?? options.storageDir;\n\t\tconst path = storagePathFor(storageDir, key);\n\t\tif (!path || !storageDir) return undefined;\n\t\twithFileLockSync(path, () => {\n\t\t\tif (!existsSync(path)) writeFileAtomicSync(path, original);\n\t\t});\n\t\treturn path;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction reasonText(record: ContextGcPackedRecord): string {\n\tif (record.reason === \"superseded-read\") return \"older read snapshot superseded by a later read of the same file\";\n\tif (record.reason === \"stale-semantic-memory\") {\n\t\treturn \"older Automata/Mind semantic context page outside the semantic-memory freshness window\";\n\t}\n\treturn \"stale bulky tool output outside the recent context window\";\n}\n\nfunction buildSummary(record: ContextGcPackedRecord): string {\n\tconst semantic = record.reason === \"stale-semantic-memory\";\n\tconst lines = [\n\t\tsemantic ? \"[Semantic GC packed stale Automata/Mind context page]\" : \"[Context GC packed stale tool result]\",\n\t\tsemantic ? undefined : `tool: ${record.toolName}`,\n\t\trecord.path ? `path: ${record.path}` : undefined,\n\t\trecord.command ? `command: ${boundedTextPreview(record.command)}` : undefined,\n\t\t`reason: ${reasonText(record)}`,\n\t\t`original: ${record.originalChars} chars (~${record.originalTokens} tokens)`,\n\t\t// The digest arrives PRE-FENCED from the curator (brain-curator.ts wraps it once, in the\n\t\t// standard untrusted-content boundary — the same treatment memory recall pages get — at the\n\t\t// moment it is stored, not here). Render it VERBATIM: re-wrapping on every GC render would\n\t\t// regenerate the fence's nonce each time, making the packed stub byte-different on every\n\t\t// provider request and busting prompt caching (BUG E).\n\t\trecord.digest ? `summary (auto-digest, machine paraphrase, not authoritative): ${record.digest}` : undefined,\n\t\trecord.storagePath\n\t\t\t? `exact old provider-visible text stored at: ${record.storagePath}`\n\t\t\t: \"exact old provider-visible text retained in the session log, not inline in provider context\",\n\t\tsemantic\n\t\t\t? \"If this memory context matters, query Automata/Mind again with the same topic/filter or fetch the drawer pointers from the stored page.\"\n\t\t\t: record.path\n\t\t\t\t? \"For current file contents, use the read tool on the path above. For the exact old output, read the stored payload path if present.\"\n\t\t\t\t: \"If this exact old output matters, retrieve/read the stored payload path if present or rerun the tool command.\",\n\t\t\"Do not rely on this summary as the original content.\",\n\t].filter((line): line is string => line !== undefined);\n\treturn lines.join(\"\\n\");\n}\n\nfunction gcDetails(message: { details?: unknown }, record: ContextGcPackedRecord): Record<string, unknown> {\n\treturn {\n\t\t...(typeof message.details === \"object\" && message.details !== null ? message.details : {}),\n\t\tcontextGc: {\n\t\t\tpacked: true,\n\t\t\toriginalChars: record.originalChars,\n\t\t\toriginalTokens: record.originalTokens,\n\t\t\tstoragePath: record.storagePath,\n\t\t\treason: record.reason,\n\t\t},\n\t};\n}\n\nfunction makePackedToolResult(message: ToolResultMessage, record: ContextGcPackedRecord): ToolResultMessage {\n\tconst summary = buildSummary(record);\n\treturn {\n\t\t...message,\n\t\tcontent: [{ type: \"text\", text: summary }],\n\t\tdetails: gcDetails(message, record),\n\t};\n}\n\nfunction makePackedSemanticMemoryMessage(message: AgentMessage, record: ContextGcPackedRecord): AgentMessage {\n\tconst summary = buildSummary(record);\n\treturn {\n\t\t...(message as unknown as Record<string, unknown>),\n\t\tcontent: [{ type: \"text\", text: summary }],\n\t\tdetails: gcDetails(message as { details?: unknown }, record),\n\t} as AgentMessage;\n}\n\nfunction commitPackedMessage<TMessage extends AgentMessage>(\n\toptions: ContextGcOptions,\n\treport: ContextGcReport,\n\tnextMessages: AgentMessage[],\n\tmessageIndex: number,\n\tmessage: TMessage,\n\toriginalText: string,\n\tkey: string,\n\trecord: ContextGcPackedRecord,\n\tmakePacked: (message: TMessage, record: ContextGcPackedRecord) => AgentMessage,\n): void {\n\trecord.digest = options.curation?.resolveDigest?.(key);\n\toptions.curation?.onPacked?.(record, originalText);\n\tconst packed = makePacked(message, record);\n\trecord.packedTokens = estimateTokens(packed);\n\tnextMessages[messageIndex] = packed;\n\treport.records.push(record);\n\treport.originalTokens += record.originalTokens;\n\treport.packedTokens += record.packedTokens;\n}\n\nexport function applyContextGc(\n\tmessages: AgentMessage[],\n\trawSettings: ContextGcSettings & {\n\t\tcwd?: string;\n\t\tstorageDir?: string;\n\t\tacquireStorageDir?: () => string;\n\t\twritePayloads?: boolean;\n\t\tcuration?: ContextGcCurationHooks;\n\t},\n): ContextGcResult {\n\tconst settings = normalizeContextGcSettings(rawSettings);\n\tconst baseReport: ContextGcReport = {\n\t\tenabled: settings.enabled,\n\t\tpackedCount: 0,\n\t\toriginalTokens: 0,\n\t\tpackedTokens: 0,\n\t\tsavedTokens: 0,\n\t\trecords: [],\n\t};\n\tif (!settings.enabled) return { messages, report: baseReport };\n\n\tconst options: ContextGcOptions = {\n\t\t...settings,\n\t\tcwd: rawSettings.cwd ?? process.cwd(),\n\t\tstorageDir: rawSettings.storageDir,\n\t\tacquireStorageDir: rawSettings.acquireStorageDir,\n\t\twritePayloads: rawSettings.writePayloads ?? true,\n\t\tcuration: rawSettings.curation,\n\t};\n\tconst eligibleTools = new Set(options.tools);\n\tconst plan = collectContextGcPlan(messages, options.cwd, options.semanticMemory);\n\tconst recentStart = Math.max(0, messages.length - options.preserveRecentMessages);\n\tconst semanticIndexSet = new Set(plan.semanticIndexes);\n\tconst preservedSemanticIndexes = new Set(\n\t\toptions.semanticMemory.preserveRecentPages > 0\n\t\t\t? plan.semanticIndexes.slice(-options.semanticMemory.preserveRecentPages)\n\t\t\t: [],\n\t);\n\tconst nextMessages = messages.slice();\n\tlet changed = false;\n\n\tfor (let index = 0; index < messages.length; index++) {\n\t\tconst message = messages[index];\n\t\tif (semanticIndexSet.has(index) && !preservedSemanticIndexes.has(index) && index < recentStart) {\n\t\t\tconst originalText = agentMessageText(message);\n\t\t\tif (originalText && originalText.length >= options.semanticMemory.minChars) {\n\t\t\t\tconst originalTokens = estimateTokens(message);\n\t\t\t\tconst key = createHash(\"sha256\")\n\t\t\t\t\t.update(\"semantic-memory\\0\")\n\t\t\t\t\t.update(String(index))\n\t\t\t\t\t.update(\"\\0\")\n\t\t\t\t\t.update(originalText)\n\t\t\t\t\t.digest(\"hex\")\n\t\t\t\t\t.slice(0, 24);\n\t\t\t\tconst storagePath = maybeStoreOriginal(options, key, originalText);\n\t\t\t\tconst record: ContextGcPackedRecord = {\n\t\t\t\t\ttoolName: \"automata-mind\",\n\t\t\t\t\ttoolCallId: `semantic-${index}`,\n\t\t\t\t\tmessageIndex: index,\n\t\t\t\t\treason: \"stale-semantic-memory\",\n\t\t\t\t\toriginalChars: originalText.length,\n\t\t\t\t\toriginalTokens,\n\t\t\t\t\tpackedTokens: 0,\n\t\t\t\t\tstoragePath,\n\t\t\t\t\tkey,\n\t\t\t\t};\n\t\t\t\tcommitPackedMessage(\n\t\t\t\t\toptions,\n\t\t\t\t\tbaseReport,\n\t\t\t\t\tnextMessages,\n\t\t\t\t\tindex,\n\t\t\t\t\tmessage,\n\t\t\t\t\toriginalText,\n\t\t\t\t\tkey,\n\t\t\t\t\trecord,\n\t\t\t\t\tmakePackedSemanticMemoryMessage,\n\t\t\t\t);\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (message.role !== \"toolResult\") continue;\n\t\tif (!eligibleTools.has(message.toolName)) continue;\n\t\tif (index >= recentStart) continue;\n\n\t\tconst originalText = toolResultText(message);\n\t\tif (originalText.length < options.minToolResultChars) continue;\n\n\t\tconst call = plan.calls.get(message.toolCallId);\n\t\tconst path = normalizeToolPath(options.cwd, call?.args.path);\n\t\tlet reason: ContextGcPackedRecord[\"reason\"] = \"stale-tool-result\";\n\t\tif (message.toolName === \"read\" && path) {\n\t\t\tif (plan.latestReadByPath.get(path) === message.toolCallId) continue;\n\t\t\treason = \"superseded-read\";\n\t\t}\n\n\t\tconst originalTokens = estimateTokens(message);\n\t\tconst key = createHash(\"sha256\")\n\t\t\t.update(message.toolName)\n\t\t\t.update(\"\\0\")\n\t\t\t.update(message.toolCallId)\n\t\t\t.update(\"\\0\")\n\t\t\t.update(originalText)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 24);\n\t\tconst storagePath = maybeStoreOriginal(options, key, originalText);\n\t\tconst record: ContextGcPackedRecord = {\n\t\t\ttoolName: message.toolName,\n\t\t\ttoolCallId: message.toolCallId,\n\t\t\tmessageIndex: index,\n\t\t\treason,\n\t\t\toriginalChars: originalText.length,\n\t\t\toriginalTokens,\n\t\t\tpackedTokens: 0,\n\t\t\tstoragePath,\n\t\t\tpath,\n\t\t\tcommand: typeof call?.args.command === \"string\" ? call.args.command : undefined,\n\t\t\tkey,\n\t\t};\n\t\tcommitPackedMessage(\n\t\t\toptions,\n\t\t\tbaseReport,\n\t\t\tnextMessages,\n\t\t\tindex,\n\t\t\tmessage,\n\t\t\toriginalText,\n\t\t\tkey,\n\t\t\trecord,\n\t\t\tmakePackedToolResult,\n\t\t);\n\t\tchanged = true;\n\t}\n\n\tbaseReport.packedCount = baseReport.records.length;\n\tbaseReport.savedTokens = Math.max(0, baseReport.originalTokens - baseReport.packedTokens);\n\treturn { messages: changed ? nextMessages : messages, report: baseReport };\n}\n"]}
@@ -22,8 +22,8 @@
22
22
  * {@link ContextPipelineDeps.getMemoryManager} (never imports it), and MemoryController never imports
23
23
  * the pipeline — keeping the transform the one place the two subsystems meet.
24
24
  */
25
- import { type AgentMessage } from "@caupulican/pi-agent-core";
26
- import { type SessionManager } from "@caupulican/pi-agent-core/node";
25
+ import { type SessionManager } from "@caupulican/pi-agent-core/session";
26
+ import type { AgentMessage } from "@caupulican/pi-agent-core/types";
27
27
  import type { Api, AssistantMessage, Model, Usage } from "@caupulican/pi-ai";
28
28
  import type { IsolatedCompletionOptions, IsolatedCompletionResult } from "./agent-session-contracts.ts";
29
29
  import { type CurationTelemetrySnapshot } from "./context/brain-curator.ts";
@@ -1 +1 @@
1
- {"version":3,"file":"context-pipeline.d.ts","sourceRoot":"","sources":["../../src/core/context-pipeline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,KAAK,YAAY,EAA8B,MAAM,2BAA2B,CAAC;AAC1F,OAAO,EAON,KAAK,cAAc,EAEnB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAE,GAAG,EAAE,gBAAgB,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC7E,OAAO,KAAK,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxG,OAAO,EAAgB,KAAK,yBAAyB,EAA6B,MAAM,4BAA4B,CAAC;AACrH,OAAO,EAAE,KAAK,aAAa,EAA2B,MAAM,gCAAgC,CAAC;AAC7F,OAAO,EAGN,KAAK,kBAAkB,EAEvB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAuB,KAAK,uBAAuB,EAAE,MAAM,yCAAyC,CAAC;AAC5G,OAAO,EAEN,KAAK,+BAA+B,EACpC,KAAK,wBAAwB,EAE7B,MAAM,oCAAoC,CAAC;AAQ5C,OAAO,EAAkB,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEvE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMzD,OAAO,KAAK,EAAE,eAAe,EAAE,M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,YAAY,EAAE,EAAE,YAAY,EAAE,wBAAwB,GAAG,IAAI,CAqB/F;IAED;;;;OAIG;IACH;;;;;OAKG;IACH,OAAO,CAAC,kCAAkC;IAQ1C,yBAAyB,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CA4BlD;IAED,uBAAuB,IAAI,IAAI,CAqB9B;IAED;;;;;OAKG;IACH,wBAAwB,IAAI,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,SAAS,CAgDhG;YAEa,mBAAmB;IAmDjC,gGAAgG;IAChG,wBAAwB,IAAI;QAC3B,OAAO,EAAE,OAAO,CAAC;QACjB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,SAAS,EAAE,yBAAyB,CAAC;QACrC,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,uBAAuB,CAAC,EAAE,MAAM,CAAC;KACjC,CASA;IAED,yFAAyF;IACzF,0BAA0B,IAAI,uBAAuB,CAEpD;IAED,cAAc,CACb,QAAQ,EAAE,YAAY,EAAE,EACxB,aAAa,EAAE,OAAO,GACpB;QAAE,QAAQ,EAAE,YAAY,EAAE,CAAC;QAAC,MAAM,EAAE,eAAe,CAAA;KAAE,CA8DvD;IAED;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,kCAAkC;IAkB1C,kBAAkB,CAAC,QAAQ,CAAC,EAAE,YAAY,EAAE,GAAG,eAAe,CAY7D;IAED,oBAAoB,CAAC,QAAQ,EAAE,YAAY,EAAE,EAAE,YAAY,EAAE,gBAAgB,GAAG,IAAI,CAkCnF;IAED,4BAA4B,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,MAAM,CAuB7D;CACD"}
@@ -22,8 +22,10 @@
22
22
  * {@link ContextPipelineDeps.getMemoryManager} (never imports it), and MemoryController never imports
23
23
  * the pipeline — keeping the transform the one place the two subsystems meet.
24
24
  */
25
- import { addUsage, createEmptyUsage } from "@caupulican/pi-agent-core";
26
- import { calculateContextTokens, estimateTokens, getApplicableAssistantUsageInfo, getLatestCompactionEntry, TokenBudget, } from "@caupulican/pi-agent-core/node";
25
+ import { calculateContextTokens, estimateTokens, getApplicableAssistantUsageInfo, } from "@caupulican/pi-agent-core/compaction/compaction";
26
+ import { TokenBudget } from "@caupulican/pi-agent-core/compaction/token-budget";
27
+ import { getLatestCompactionEntry, } from "@caupulican/pi-agent-core/session";
28
+ import { addUsage, createEmptyUsage } from "@caupulican/pi-agent-core/usage";
27
29
  import { BrainCurator, preDigestConversationText } from "./context/brain-curator.js";
28
30
  import { createFileArtifactStore } from "./context/context-artifacts.js";
29
31
  import { runContextAudit, } from "./context/context-audit.js";
@@ -646,7 +648,8 @@ export class ContextPipeline {
646
648
  }
647
649
  : undefined,
648
650
  });
649
- this._latestContextGcReport = result.report;
651
+ if (writePayloads)
652
+ this._latestContextGcReport = result.report;
650
653
  // Only release/reclaim on the real per-turn pass (writePayloads=true), never on
651
654
  // the read-only status-report path (getContextGcReport with writePayloads=false),
652
655
  // so merely inspecting the report can't have side effects.
@@ -664,7 +667,8 @@ export class ContextPipeline {
664
667
  savedTokens: 0,
665
668
  records: [],
666
669
  };
667
- this._latestContextGcReport = report;
670
+ if (writePayloads)
671
+ this._latestContextGcReport = report;
668
672
  return { messages, report };
669
673
  }
670
674
  }