@caupulican/pi-adaptative 0.81.31 → 0.81.35

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 (237) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +69 -0
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +53 -0
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -0
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +1282 -0
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -0
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +1453 -0
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/builder-validator.json +14 -0
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/claude-trio.json +32 -0
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/full-provider-review.json +15 -0
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/provider-prompt-smoke.json +14 -0
  12. package/dist/bundled-resources/prompts/extensionify.md +5 -4
  13. package/dist/bundled-resources/prompts/skillify.md +5 -5
  14. package/dist/bundled-resources/skills/pi-harness-learning/SKILL.md +6 -3
  15. package/dist/config.d.ts +5 -1
  16. package/dist/config.d.ts.map +1 -1
  17. package/dist/config.js +10 -2
  18. package/dist/config.js.map +1 -1
  19. package/dist/core/agent-session.d.ts +7 -0
  20. package/dist/core/agent-session.d.ts.map +1 -1
  21. package/dist/core/agent-session.js +25 -2
  22. package/dist/core/agent-session.js.map +1 -1
  23. package/dist/core/background-lane-controller.d.ts +12 -3
  24. package/dist/core/background-lane-controller.d.ts.map +1 -1
  25. package/dist/core/background-lane-controller.js +67 -26
  26. package/dist/core/background-lane-controller.js.map +1 -1
  27. package/dist/core/bash-executor.d.ts.map +1 -1
  28. package/dist/core/bash-executor.js +7 -3
  29. package/dist/core/bash-executor.js.map +1 -1
  30. package/dist/core/context/context-store-retention.d.ts +4 -1
  31. package/dist/core/context/context-store-retention.d.ts.map +1 -1
  32. package/dist/core/context/context-store-retention.js +42 -151
  33. package/dist/core/context/context-store-retention.js.map +1 -1
  34. package/dist/core/context-pipeline.d.ts.map +1 -1
  35. package/dist/core/context-pipeline.js +6 -6
  36. package/dist/core/context-pipeline.js.map +1 -1
  37. package/dist/core/exec.d.ts.map +1 -1
  38. package/dist/core/exec.js +25 -39
  39. package/dist/core/exec.js.map +1 -1
  40. package/dist/core/extensions/loader.d.ts +9 -2
  41. package/dist/core/extensions/loader.d.ts.map +1 -1
  42. package/dist/core/extensions/loader.js +105 -21
  43. package/dist/core/extensions/loader.js.map +1 -1
  44. package/dist/core/footer-data-provider.d.ts.map +1 -1
  45. package/dist/core/footer-data-provider.js +2 -0
  46. package/dist/core/footer-data-provider.js.map +1 -1
  47. package/dist/core/goals/goal-state.d.ts +10 -0
  48. package/dist/core/goals/goal-state.d.ts.map +1 -1
  49. package/dist/core/goals/goal-state.js +37 -0
  50. package/dist/core/goals/goal-state.js.map +1 -1
  51. package/dist/core/goals/goal-tool-core.d.ts +11 -0
  52. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  53. package/dist/core/goals/goal-tool-core.js +51 -1
  54. package/dist/core/goals/goal-tool-core.js.map +1 -1
  55. package/dist/core/improvement-loop.d.ts.map +1 -1
  56. package/dist/core/improvement-loop.js +26 -5
  57. package/dist/core/improvement-loop.js.map +1 -1
  58. package/dist/core/models/fitness-store.d.ts.map +1 -1
  59. package/dist/core/models/fitness-store.js +1 -1
  60. package/dist/core/models/fitness-store.js.map +1 -1
  61. package/dist/core/models/local-runtime.d.ts +6 -4
  62. package/dist/core/models/local-runtime.d.ts.map +1 -1
  63. package/dist/core/models/local-runtime.js +108 -36
  64. package/dist/core/models/local-runtime.js.map +1 -1
  65. package/dist/core/output-guard.d.ts.map +1 -1
  66. package/dist/core/output-guard.js +23 -8
  67. package/dist/core/output-guard.js.map +1 -1
  68. package/dist/core/package-manager.d.ts.map +1 -1
  69. package/dist/core/package-manager.js +44 -59
  70. package/dist/core/package-manager.js.map +1 -1
  71. package/dist/core/profile-resource-selection.d.ts +16 -0
  72. package/dist/core/profile-resource-selection.d.ts.map +1 -1
  73. package/dist/core/profile-resource-selection.js +41 -0
  74. package/dist/core/profile-resource-selection.js.map +1 -1
  75. package/dist/core/reflection-controller.d.ts.map +1 -1
  76. package/dist/core/reflection-controller.js +18 -1
  77. package/dist/core/reflection-controller.js.map +1 -1
  78. package/dist/core/reload-blockers.d.ts +1 -0
  79. package/dist/core/reload-blockers.d.ts.map +1 -1
  80. package/dist/core/reload-blockers.js +6 -2
  81. package/dist/core/reload-blockers.js.map +1 -1
  82. package/dist/core/resource-loader.d.ts +2 -0
  83. package/dist/core/resource-loader.d.ts.map +1 -1
  84. package/dist/core/resource-loader.js +50 -28
  85. package/dist/core/resource-loader.js.map +1 -1
  86. package/dist/core/settings-manager.d.ts.map +1 -1
  87. package/dist/core/settings-manager.js +1 -1
  88. package/dist/core/settings-manager.js.map +1 -1
  89. package/dist/core/slash-commands.d.ts.map +1 -1
  90. package/dist/core/slash-commands.js +1 -1
  91. package/dist/core/slash-commands.js.map +1 -1
  92. package/dist/core/toolkit/script-runner.d.ts.map +1 -1
  93. package/dist/core/toolkit/script-runner.js +58 -24
  94. package/dist/core/toolkit/script-runner.js.map +1 -1
  95. package/dist/core/tools/bash.d.ts.map +1 -1
  96. package/dist/core/tools/bash.js +13 -26
  97. package/dist/core/tools/bash.js.map +1 -1
  98. package/dist/core/tools/extensionify.d.ts +2 -1
  99. package/dist/core/tools/extensionify.d.ts.map +1 -1
  100. package/dist/core/tools/extensionify.js +11 -8
  101. package/dist/core/tools/extensionify.js.map +1 -1
  102. package/dist/core/tools/find.d.ts.map +1 -1
  103. package/dist/core/tools/find.js +54 -48
  104. package/dist/core/tools/find.js.map +1 -1
  105. package/dist/core/tools/git-filter.d.ts.map +1 -1
  106. package/dist/core/tools/git-filter.js +20 -32
  107. package/dist/core/tools/git-filter.js.map +1 -1
  108. package/dist/core/tools/goal.d.ts +1 -1
  109. package/dist/core/tools/goal.d.ts.map +1 -1
  110. package/dist/core/tools/goal.js +10 -3
  111. package/dist/core/tools/goal.js.map +1 -1
  112. package/dist/core/tools/grep.d.ts.map +1 -1
  113. package/dist/core/tools/grep.js +89 -80
  114. package/dist/core/tools/grep.js.map +1 -1
  115. package/dist/core/tools/output-accumulator.d.ts +2 -0
  116. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  117. package/dist/core/tools/output-accumulator.js +7 -4
  118. package/dist/core/tools/output-accumulator.js.map +1 -1
  119. package/dist/core/tools/read.d.ts.map +1 -1
  120. package/dist/core/tools/read.js +4 -3
  121. package/dist/core/tools/read.js.map +1 -1
  122. package/dist/index.d.ts +2 -1
  123. package/dist/index.d.ts.map +1 -1
  124. package/dist/index.js +2 -1
  125. package/dist/index.js.map +1 -1
  126. package/dist/main.d.ts +2 -0
  127. package/dist/main.d.ts.map +1 -1
  128. package/dist/main.js +23 -4
  129. package/dist/main.js.map +1 -1
  130. package/dist/migrations.d.ts.map +1 -1
  131. package/dist/migrations.js +18 -4
  132. package/dist/migrations.js.map +1 -1
  133. package/dist/modes/interactive/auth-dialogs-controller.d.ts +10 -0
  134. package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
  135. package/dist/modes/interactive/auth-dialogs-controller.js +94 -27
  136. package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
  137. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  138. package/dist/modes/interactive/auto-learn-controller.js +2 -1
  139. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  140. package/dist/modes/interactive/components/bordered-loader.d.ts +1 -0
  141. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
  142. package/dist/modes/interactive/components/bordered-loader.js +8 -0
  143. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  144. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  145. package/dist/modes/interactive/components/extension-editor.js +6 -15
  146. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  147. package/dist/modes/interactive/components/login-dialog.d.ts +3 -1
  148. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  149. package/dist/modes/interactive/components/login-dialog.js +20 -8
  150. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  151. package/dist/modes/interactive/components/profile-resource-editor.d.ts +4 -1
  152. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  153. package/dist/modes/interactive/components/profile-resource-editor.js +22 -39
  154. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  155. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  156. package/dist/modes/interactive/components/session-selector.js +1 -1
  157. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  158. package/dist/modes/interactive/config-backup.d.ts +1 -0
  159. package/dist/modes/interactive/config-backup.d.ts.map +1 -1
  160. package/dist/modes/interactive/config-backup.js +14 -3
  161. package/dist/modes/interactive/config-backup.js.map +1 -1
  162. package/dist/modes/interactive/editor-overlay-host.d.ts +12 -0
  163. package/dist/modes/interactive/editor-overlay-host.d.ts.map +1 -1
  164. package/dist/modes/interactive/editor-overlay-host.js +55 -0
  165. package/dist/modes/interactive/editor-overlay-host.js.map +1 -1
  166. package/dist/modes/interactive/extension-ui-host.d.ts +2 -1
  167. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
  168. package/dist/modes/interactive/extension-ui-host.js +161 -96
  169. package/dist/modes/interactive/extension-ui-host.js.map +1 -1
  170. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  171. package/dist/modes/interactive/external-editor.js +23 -28
  172. package/dist/modes/interactive/external-editor.js.map +1 -1
  173. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  174. package/dist/modes/interactive/interactive-mode.js +14 -8
  175. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  176. package/dist/modes/interactive/profile-menu-controller.d.ts +5 -1
  177. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
  178. package/dist/modes/interactive/profile-menu-controller.js +118 -24
  179. package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
  180. package/dist/modes/interactive/resource-shell-commands.d.ts +1 -0
  181. package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -1
  182. package/dist/modes/interactive/resource-shell-commands.js +5 -1
  183. package/dist/modes/interactive/resource-shell-commands.js.map +1 -1
  184. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  185. package/dist/modes/interactive/session-flow-commands.js +100 -7
  186. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  187. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
  188. package/dist/modes/interactive/session-io-commands.js +80 -50
  189. package/dist/modes/interactive/session-io-commands.js.map +1 -1
  190. package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
  191. package/dist/modes/interactive/startup-checks.js +14 -17
  192. package/dist/modes/interactive/startup-checks.js.map +1 -1
  193. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  194. package/dist/modes/rpc/rpc-client.js +20 -19
  195. package/dist/modes/rpc/rpc-client.js.map +1 -1
  196. package/dist/package-manager-cli.d.ts.map +1 -1
  197. package/dist/package-manager-cli.js +10 -19
  198. package/dist/package-manager-cli.js.map +1 -1
  199. package/dist/utils/child-process.d.ts +13 -7
  200. package/dist/utils/child-process.d.ts.map +1 -1
  201. package/dist/utils/child-process.js +56 -3
  202. package/dist/utils/child-process.js.map +1 -1
  203. package/dist/utils/clipboard-image.d.ts.map +1 -1
  204. package/dist/utils/clipboard-image.js +3 -2
  205. package/dist/utils/clipboard-image.js.map +1 -1
  206. package/dist/utils/clipboard.d.ts.map +1 -1
  207. package/dist/utils/clipboard.js +17 -10
  208. package/dist/utils/clipboard.js.map +1 -1
  209. package/dist/utils/external-editor-command.d.ts +8 -0
  210. package/dist/utils/external-editor-command.d.ts.map +1 -0
  211. package/dist/utils/external-editor-command.js +60 -0
  212. package/dist/utils/external-editor-command.js.map +1 -0
  213. package/dist/utils/paths.d.ts.map +1 -1
  214. package/dist/utils/paths.js +10 -2
  215. package/dist/utils/paths.js.map +1 -1
  216. package/dist/utils/tools-manager.d.ts.map +1 -1
  217. package/dist/utils/tools-manager.js +23 -10
  218. package/dist/utils/tools-manager.js.map +1 -1
  219. package/dist/utils/work-directory.d.ts +36 -0
  220. package/dist/utils/work-directory.d.ts.map +1 -0
  221. package/dist/utils/work-directory.js +462 -0
  222. package/dist/utils/work-directory.js.map +1 -0
  223. package/docs/index.md +2 -0
  224. package/docs/resources.md +2 -2
  225. package/docs/rpc.md +1 -1
  226. package/docs/tmux-agent-manager.md +48 -0
  227. package/docs/windows.md +100 -7
  228. package/docs/work-directory.md +41 -0
  229. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  230. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  231. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  232. package/examples/extensions/sandbox/package-lock.json +2 -2
  233. package/examples/extensions/sandbox/package.json +1 -1
  234. package/examples/extensions/with-deps/package-lock.json +2 -2
  235. package/examples/extensions/with-deps/package.json +1 -1
  236. package/npm-shrinkwrap.json +42 -42
  237. package/package.json +4 -4
@@ -5,8 +5,11 @@ export interface ContextStoreRetentionOptions {
5
5
  now?: number;
6
6
  }
7
7
  export interface ContextStoreRetentionLease {
8
+ readonly gcDir: string;
9
+ readonly artifactsDir: string;
8
10
  release(): void;
9
11
  }
10
- export declare function pruneContextStoreRoot(rootDir: string, options?: ContextStoreRetentionOptions): string[];
12
+ export declare function pruneContextStores(agentDir: string, tenant: "gc" | "artifacts", options?: ContextStoreRetentionOptions): string[];
13
+ export declare function getContextStoreDir(agentDir: string, tenant: "gc" | "artifacts", sessionId: string): string;
11
14
  export declare function acquireContextStoreRetention(agentDir: string, sessionId: string, options?: ContextStoreRetentionOptions): ContextStoreRetentionLease;
12
15
  //# sourceMappingURL=context-store-retention.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-store-retention.d.ts","sourceRoot":"","sources":["../../../src/core/context/context-store-retention.ts"],"names":[],"mappings":"AAsBA,MAAM,WAAW,4BAA4B;IAC5C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,0BAA0B;IAC1C,OAAO,IAAI,IAAI,CAAC;CAChB;AAuFD,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,4BAAiC,GAAG,MAAM,EAAE,CAyB3G;AAED,wBAAgB,4BAA4B,CAC3C,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,4BAAiC,GACxC,0BAA0B,CAkC5B","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmdirSync,\n\trmSync,\n\tstatSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nconst LEASES_DIRECTORY = \".leases\";\nconst ACTIVE_MARKER_PREFIX = \"active-\";\nconst ACTIVE_MARKER_SUFFIX = \".json\";\nconst DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_SESSION_DIRS = 64;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;\n\nexport interface ContextStoreRetentionOptions {\n\tmaxAgeMs?: number;\n\tmaxSessionDirs?: number;\n\tmaxTotalBytes?: number;\n\tnow?: number;\n}\n\nexport interface ContextStoreRetentionLease {\n\trelease(): void;\n}\n\ninterface SessionDirectory {\n\tpath: string;\n\tmtimeMs: number;\n\tbytes: number;\n\tactive: boolean;\n}\n\nfunction positiveLimit(value: number | undefined, fallback: number): number {\n\treturn value !== undefined && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;\n}\n\nfunction directoryBytes(path: string): number {\n\tlet total = 0;\n\tfor (const entry of readdirSync(path, { withFileTypes: true })) {\n\t\tconst child = join(path, entry.name);\n\t\ttry {\n\t\t\tif (entry.isDirectory()) total += directoryBytes(child);\n\t\t\telse total += lstatSync(child).size;\n\t\t} catch {\n\t\t\t// Concurrent cleanup or an unreadable entry is ignored by best-effort retention.\n\t\t}\n\t}\n\treturn total;\n}\n\nfunction markerProcessIsAlive(path: string): boolean {\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as { pid?: unknown };\n\t\tif (typeof parsed.pid !== \"number\" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0) return false;\n\t\ttry {\n\t\t\tprocess.kill(parsed.pid, 0);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\";\n\t\t}\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction cleanupStaleLeases(rootDir: string): void {\n\tconst leasesRoot = join(rootDir, LEASES_DIRECTORY);\n\tif (!existsSync(leasesRoot)) return;\n\tfor (const entry of readdirSync(leasesRoot, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory()) continue;\n\t\tconst leaseDir = join(leasesRoot, entry.name);\n\t\ttry {\n\t\t\tfor (const marker of readdirSync(leaseDir)) {\n\t\t\t\tconst markerPath = join(leaseDir, marker);\n\t\t\t\tif (!markerProcessIsAlive(markerPath)) unlinkSync(markerPath);\n\t\t\t}\n\t\t\trmdirSync(leaseDir);\n\t\t} catch {\n\t\t\t// A live marker or concurrent lease keeps the directory in place.\n\t\t}\n\t}\n}\n\nfunction inspectSessionDirectories(rootDir: string): SessionDirectory[] {\n\tif (!existsSync(rootDir)) return [];\n\tcleanupStaleLeases(rootDir);\n\tconst directories: SessionDirectory[] = [];\n\tfor (const entry of readdirSync(rootDir, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory() || entry.name === LEASES_DIRECTORY) continue;\n\t\tconst path = join(rootDir, entry.name);\n\t\ttry {\n\t\t\tconst leaseDir = join(rootDir, LEASES_DIRECTORY, entry.name);\n\t\t\tconst markerPaths = existsSync(leaseDir)\n\t\t\t\t? readdirSync(leaseDir)\n\t\t\t\t\t\t.filter((name) => name.startsWith(ACTIVE_MARKER_PREFIX) && name.endsWith(ACTIVE_MARKER_SUFFIX))\n\t\t\t\t\t\t.map((name) => join(leaseDir, name))\n\t\t\t\t: [];\n\t\t\tdirectories.push({\n\t\t\t\tpath,\n\t\t\t\tmtimeMs: Math.max(statSync(path).mtimeMs, ...markerPaths.map((markerPath) => statSync(markerPath).mtimeMs)),\n\t\t\t\tbytes: directoryBytes(path),\n\t\t\t\tactive: markerPaths.some(markerProcessIsAlive),\n\t\t\t});\n\t\t} catch {\n\t\t\t// Ignore a directory that disappeared or became unreadable during the scan.\n\t\t}\n\t}\n\treturn directories;\n}\n\nexport function pruneContextStoreRoot(rootDir: string, options: ContextStoreRetentionOptions = {}): string[] {\n\tconst now = options.now ?? Date.now();\n\tconst maxAgeMs = positiveLimit(options.maxAgeMs, DEFAULT_MAX_AGE_MS);\n\tconst maxSessionDirs = positiveLimit(options.maxSessionDirs, DEFAULT_MAX_SESSION_DIRS);\n\tconst maxTotalBytes = positiveLimit(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES);\n\tconst directories = inspectSessionDirectories(rootDir);\n\tconst removed: string[] = [];\n\tlet retainedCount = directories.length;\n\tlet retainedBytes = directories.reduce((sum, directory) => sum + directory.bytes, 0);\n\tfor (const directory of directories.sort((left, right) => left.mtimeMs - right.mtimeMs)) {\n\t\tif (directory.active) continue;\n\t\tconst expired = now - directory.mtimeMs > maxAgeMs;\n\t\tconst overCount = retainedCount > maxSessionDirs;\n\t\tconst overBytes = retainedBytes > maxTotalBytes;\n\t\tif (!expired && !overCount && !overBytes) continue;\n\t\ttry {\n\t\t\trmSync(directory.path, { recursive: true, force: true });\n\t\t\tremoved.push(directory.path);\n\t\t\tretainedCount--;\n\t\t\tretainedBytes -= directory.bytes;\n\t\t} catch {\n\t\t\t// Retention is best-effort and must never block a live session.\n\t\t}\n\t}\n\treturn removed;\n}\n\nexport function acquireContextStoreRetention(\n\tagentDir: string,\n\tsessionId: string,\n\toptions: ContextStoreRetentionOptions = {},\n): ContextStoreRetentionLease {\n\tif (!/^[A-Za-z0-9_-]+$/.test(sessionId)) return { release: () => {} };\n\tconst roots = [join(agentDir, \"context-gc\"), join(agentDir, \"context-artifacts\")];\n\tconst markerPaths: string[] = [];\n\tfor (const root of roots) {\n\t\tconst sessionDir = join(root, sessionId);\n\t\ttry {\n\t\t\tmkdirSync(sessionDir, { recursive: true });\n\t\t\tconst leaseDir = join(root, LEASES_DIRECTORY, sessionId);\n\t\t\tmkdirSync(leaseDir, { recursive: true });\n\t\t\tconst markerPath = join(\n\t\t\t\tleaseDir,\n\t\t\t\t`${ACTIVE_MARKER_PREFIX}${process.pid}-${randomUUID()}${ACTIVE_MARKER_SUFFIX}`,\n\t\t\t);\n\t\t\twriteFileSync(markerPath, JSON.stringify({ pid: process.pid, touchedAt: Date.now() }), \"utf-8\");\n\t\t\tmarkerPaths.push(markerPath);\n\t\t\tpruneContextStoreRoot(root, options);\n\t\t} catch {\n\t\t\t// Retention is best-effort; the caller can still use its normal store path.\n\t\t}\n\t}\n\tlet released = false;\n\treturn {\n\t\trelease(): void {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tfor (const markerPath of markerPaths) {\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(markerPath);\n\t\t\t\t\trmdirSync(dirname(markerPath));\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"context-store-retention.d.ts","sourceRoot":"","sources":["../../../src/core/context/context-store-retention.ts"],"names":[],"mappings":"AAYA,MAAM,WAAW,4BAA4B;IAC5C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,0BAA0B;IAC1C,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,OAAO,IAAI,IAAI,CAAC;CAChB;AAWD,wBAAgB,kBAAkB,CACjC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,IAAI,GAAG,WAAW,EAC1B,OAAO,GAAE,4BAAiC,GACxC,MAAM,EAAE,CAEV;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,GAAG,WAAW,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAE1G;AAED,wBAAgB,4BAA4B,CAC3C,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,4BAAiC,GACxC,0BAA0B,CA4B5B","sourcesContent":["import {\n\tacquireWorkRun,\n\tgetWorkRunDir,\n\tpruneWorkTenant,\n\ttype WorkRetentionOptions,\n\ttype WorkRunLease,\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;\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\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\nexport function pruneContextStores(\n\tagentDir: string,\n\ttenant: \"gc\" | \"artifacts\",\n\toptions: ContextStoreRetentionOptions = {},\n): string[] {\n\treturn pruneWorkTenant(agentDir, \"context\", tenant, toWorkRetention(options));\n}\n\nexport function getContextStoreDir(agentDir: string, tenant: \"gc\" | \"artifacts\", sessionId: string): string {\n\treturn getWorkRunDir(agentDir, \"context\", tenant, sessionId);\n}\n\nexport function acquireContextStoreRetention(\n\tagentDir: string,\n\tsessionId: string,\n\toptions: ContextStoreRetentionOptions = {},\n): ContextStoreRetentionLease {\n\tconst retention = toWorkRetention(options);\n\tconst leases: WorkRunLease[] = [];\n\ttry {\n\t\tconst gc = acquireWorkRun({ agentDir, category: \"context\", tenant: \"gc\", runId: sessionId, retention });\n\t\tleases.push(gc);\n\t\tconst artifacts = acquireWorkRun({\n\t\t\tagentDir,\n\t\t\tcategory: \"context\",\n\t\t\ttenant: \"artifacts\",\n\t\t\trunId: sessionId,\n\t\t\tretention,\n\t\t});\n\t\tleases.push(artifacts);\n\t\tlet released = false;\n\t\treturn {\n\t\t\tgcDir: gc.path,\n\t\t\tartifactsDir: artifacts.path,\n\t\t\trelease(): void {\n\t\t\t\tif (released) return;\n\t\t\t\treleased = true;\n\t\t\t\tfor (const lease of leases) lease.release();\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tfor (const lease of leases) lease.release();\n\t\tthrow error;\n\t}\n}\n"]}
@@ -1,161 +1,52 @@
1
- import { randomUUID } from "node:crypto";
2
- import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
3
- import { dirname, join } from "node:path";
4
- const LEASES_DIRECTORY = ".leases";
5
- const ACTIVE_MARKER_PREFIX = "active-";
6
- const ACTIVE_MARKER_SUFFIX = ".json";
1
+ import { acquireWorkRun, getWorkRunDir, pruneWorkTenant, } from "../../utils/work-directory.js";
7
2
  const DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
8
3
  const DEFAULT_MAX_SESSION_DIRS = 64;
9
4
  const DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;
10
- function positiveLimit(value, fallback) {
11
- return value !== undefined && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
12
- }
13
- function directoryBytes(path) {
14
- let total = 0;
15
- for (const entry of readdirSync(path, { withFileTypes: true })) {
16
- const child = join(path, entry.name);
17
- try {
18
- if (entry.isDirectory())
19
- total += directoryBytes(child);
20
- else
21
- total += lstatSync(child).size;
22
- }
23
- catch {
24
- // Concurrent cleanup or an unreadable entry is ignored by best-effort retention.
25
- }
26
- }
27
- return total;
28
- }
29
- function markerProcessIsAlive(path) {
30
- try {
31
- const parsed = JSON.parse(readFileSync(path, "utf-8"));
32
- if (typeof parsed.pid !== "number" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0)
33
- return false;
34
- try {
35
- process.kill(parsed.pid, 0);
36
- return true;
37
- }
38
- catch (error) {
39
- return error.code === "EPERM";
40
- }
41
- }
42
- catch {
43
- return false;
44
- }
45
- }
46
- function cleanupStaleLeases(rootDir) {
47
- const leasesRoot = join(rootDir, LEASES_DIRECTORY);
48
- if (!existsSync(leasesRoot))
49
- return;
50
- for (const entry of readdirSync(leasesRoot, { withFileTypes: true })) {
51
- if (!entry.isDirectory())
52
- continue;
53
- const leaseDir = join(leasesRoot, entry.name);
54
- try {
55
- for (const marker of readdirSync(leaseDir)) {
56
- const markerPath = join(leaseDir, marker);
57
- if (!markerProcessIsAlive(markerPath))
58
- unlinkSync(markerPath);
59
- }
60
- rmdirSync(leaseDir);
61
- }
62
- catch {
63
- // A live marker or concurrent lease keeps the directory in place.
64
- }
65
- }
5
+ function toWorkRetention(options) {
6
+ return {
7
+ maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
8
+ maxRuns: options.maxSessionDirs ?? DEFAULT_MAX_SESSION_DIRS,
9
+ maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
10
+ now: options.now,
11
+ };
66
12
  }
67
- function inspectSessionDirectories(rootDir) {
68
- if (!existsSync(rootDir))
69
- return [];
70
- cleanupStaleLeases(rootDir);
71
- const directories = [];
72
- for (const entry of readdirSync(rootDir, { withFileTypes: true })) {
73
- if (!entry.isDirectory() || entry.name === LEASES_DIRECTORY)
74
- continue;
75
- const path = join(rootDir, entry.name);
76
- try {
77
- const leaseDir = join(rootDir, LEASES_DIRECTORY, entry.name);
78
- const markerPaths = existsSync(leaseDir)
79
- ? readdirSync(leaseDir)
80
- .filter((name) => name.startsWith(ACTIVE_MARKER_PREFIX) && name.endsWith(ACTIVE_MARKER_SUFFIX))
81
- .map((name) => join(leaseDir, name))
82
- : [];
83
- directories.push({
84
- path,
85
- mtimeMs: Math.max(statSync(path).mtimeMs, ...markerPaths.map((markerPath) => statSync(markerPath).mtimeMs)),
86
- bytes: directoryBytes(path),
87
- active: markerPaths.some(markerProcessIsAlive),
88
- });
89
- }
90
- catch {
91
- // Ignore a directory that disappeared or became unreadable during the scan.
92
- }
93
- }
94
- return directories;
13
+ export function pruneContextStores(agentDir, tenant, options = {}) {
14
+ return pruneWorkTenant(agentDir, "context", tenant, toWorkRetention(options));
95
15
  }
96
- export function pruneContextStoreRoot(rootDir, options = {}) {
97
- const now = options.now ?? Date.now();
98
- const maxAgeMs = positiveLimit(options.maxAgeMs, DEFAULT_MAX_AGE_MS);
99
- const maxSessionDirs = positiveLimit(options.maxSessionDirs, DEFAULT_MAX_SESSION_DIRS);
100
- const maxTotalBytes = positiveLimit(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES);
101
- const directories = inspectSessionDirectories(rootDir);
102
- const removed = [];
103
- let retainedCount = directories.length;
104
- let retainedBytes = directories.reduce((sum, directory) => sum + directory.bytes, 0);
105
- for (const directory of directories.sort((left, right) => left.mtimeMs - right.mtimeMs)) {
106
- if (directory.active)
107
- continue;
108
- const expired = now - directory.mtimeMs > maxAgeMs;
109
- const overCount = retainedCount > maxSessionDirs;
110
- const overBytes = retainedBytes > maxTotalBytes;
111
- if (!expired && !overCount && !overBytes)
112
- continue;
113
- try {
114
- rmSync(directory.path, { recursive: true, force: true });
115
- removed.push(directory.path);
116
- retainedCount--;
117
- retainedBytes -= directory.bytes;
118
- }
119
- catch {
120
- // Retention is best-effort and must never block a live session.
121
- }
122
- }
123
- return removed;
16
+ export function getContextStoreDir(agentDir, tenant, sessionId) {
17
+ return getWorkRunDir(agentDir, "context", tenant, sessionId);
124
18
  }
125
19
  export function acquireContextStoreRetention(agentDir, sessionId, options = {}) {
126
- if (!/^[A-Za-z0-9_-]+$/.test(sessionId))
127
- return { release: () => { } };
128
- const roots = [join(agentDir, "context-gc"), join(agentDir, "context-artifacts")];
129
- const markerPaths = [];
130
- for (const root of roots) {
131
- const sessionDir = join(root, sessionId);
132
- try {
133
- mkdirSync(sessionDir, { recursive: true });
134
- const leaseDir = join(root, LEASES_DIRECTORY, sessionId);
135
- mkdirSync(leaseDir, { recursive: true });
136
- const markerPath = join(leaseDir, `${ACTIVE_MARKER_PREFIX}${process.pid}-${randomUUID()}${ACTIVE_MARKER_SUFFIX}`);
137
- writeFileSync(markerPath, JSON.stringify({ pid: process.pid, touchedAt: Date.now() }), "utf-8");
138
- markerPaths.push(markerPath);
139
- pruneContextStoreRoot(root, options);
140
- }
141
- catch {
142
- // Retention is best-effort; the caller can still use its normal store path.
143
- }
20
+ const retention = toWorkRetention(options);
21
+ const leases = [];
22
+ try {
23
+ const gc = acquireWorkRun({ agentDir, category: "context", tenant: "gc", runId: sessionId, retention });
24
+ leases.push(gc);
25
+ const artifacts = acquireWorkRun({
26
+ agentDir,
27
+ category: "context",
28
+ tenant: "artifacts",
29
+ runId: sessionId,
30
+ retention,
31
+ });
32
+ leases.push(artifacts);
33
+ let released = false;
34
+ return {
35
+ gcDir: gc.path,
36
+ artifactsDir: artifacts.path,
37
+ release() {
38
+ if (released)
39
+ return;
40
+ released = true;
41
+ for (const lease of leases)
42
+ lease.release();
43
+ },
44
+ };
45
+ }
46
+ catch (error) {
47
+ for (const lease of leases)
48
+ lease.release();
49
+ throw error;
144
50
  }
145
- let released = false;
146
- return {
147
- release() {
148
- if (released)
149
- return;
150
- released = true;
151
- for (const markerPath of markerPaths) {
152
- try {
153
- unlinkSync(markerPath);
154
- rmdirSync(dirname(markerPath));
155
- }
156
- catch { }
157
- }
158
- },
159
- };
160
51
  }
161
52
  //# sourceMappingURL=context-store-retention.js.map
@@ -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,MAAM,aAAa,CAAC;AACzC,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,YAAY,EACZ,SAAS,EACT,MAAM,EACN,QAAQ,EACR,UAAU,EACV,aAAa,GACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE1C,MAAM,gBAAgB,GAAG,SAAS,CAAC;AACnC,MAAM,oBAAoB,GAAG,SAAS,CAAC;AACvC,MAAM,oBAAoB,GAAG,OAAO,CAAC;AACrC,MAAM,kBAAkB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACpD,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,uBAAuB,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC;AAoBlD,SAAS,aAAa,CAAC,KAAyB,EAAE,QAAgB,EAAU;IAC3E,OAAO,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KA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AAC;YAChB,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE,CAAC;gBACtC,IAAI,CAAC;oBACJ,UAAU,CAAC,UAAU,CAAC,CAAC;oBACvB,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;gBAChC,CAAC;gBAAC,MAAM,CAAC,CAAA,CAAC;YACX,CAAC;QAAA,CACD;KACD,CAAC;AAAA,CACF","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmdirSync,\n\trmSync,\n\tstatSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nconst LEASES_DIRECTORY = \".leases\";\nconst ACTIVE_MARKER_PREFIX = \"active-\";\nconst ACTIVE_MARKER_SUFFIX = \".json\";\nconst DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_SESSION_DIRS = 64;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;\n\nexport interface ContextStoreRetentionOptions {\n\tmaxAgeMs?: number;\n\tmaxSessionDirs?: number;\n\tmaxTotalBytes?: number;\n\tnow?: number;\n}\n\nexport interface ContextStoreRetentionLease {\n\trelease(): void;\n}\n\ninterface SessionDirectory {\n\tpath: string;\n\tmtimeMs: number;\n\tbytes: number;\n\tactive: boolean;\n}\n\nfunction positiveLimit(value: number | undefined, fallback: number): number {\n\treturn value !== undefined && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;\n}\n\nfunction directoryBytes(path: string): number {\n\tlet total = 0;\n\tfor (const entry of readdirSync(path, { withFileTypes: true })) {\n\t\tconst child = join(path, entry.name);\n\t\ttry {\n\t\t\tif (entry.isDirectory()) total += directoryBytes(child);\n\t\t\telse total += lstatSync(child).size;\n\t\t} catch {\n\t\t\t// Concurrent cleanup or an unreadable entry is ignored by best-effort retention.\n\t\t}\n\t}\n\treturn total;\n}\n\nfunction markerProcessIsAlive(path: string): boolean {\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as { pid?: unknown };\n\t\tif (typeof parsed.pid !== \"number\" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0) return false;\n\t\ttry {\n\t\t\tprocess.kill(parsed.pid, 0);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\";\n\t\t}\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction cleanupStaleLeases(rootDir: string): void {\n\tconst leasesRoot = join(rootDir, LEASES_DIRECTORY);\n\tif (!existsSync(leasesRoot)) return;\n\tfor (const entry of readdirSync(leasesRoot, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory()) continue;\n\t\tconst leaseDir = join(leasesRoot, entry.name);\n\t\ttry {\n\t\t\tfor (const marker of readdirSync(leaseDir)) {\n\t\t\t\tconst markerPath = join(leaseDir, marker);\n\t\t\t\tif (!markerProcessIsAlive(markerPath)) unlinkSync(markerPath);\n\t\t\t}\n\t\t\trmdirSync(leaseDir);\n\t\t} catch {\n\t\t\t// A live marker or concurrent lease keeps the directory in place.\n\t\t}\n\t}\n}\n\nfunction inspectSessionDirectories(rootDir: string): SessionDirectory[] {\n\tif (!existsSync(rootDir)) return [];\n\tcleanupStaleLeases(rootDir);\n\tconst directories: SessionDirectory[] = [];\n\tfor (const entry of readdirSync(rootDir, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory() || entry.name === LEASES_DIRECTORY) continue;\n\t\tconst path = join(rootDir, entry.name);\n\t\ttry {\n\t\t\tconst leaseDir = join(rootDir, LEASES_DIRECTORY, entry.name);\n\t\t\tconst markerPaths = existsSync(leaseDir)\n\t\t\t\t? readdirSync(leaseDir)\n\t\t\t\t\t\t.filter((name) => name.startsWith(ACTIVE_MARKER_PREFIX) && name.endsWith(ACTIVE_MARKER_SUFFIX))\n\t\t\t\t\t\t.map((name) => join(leaseDir, name))\n\t\t\t\t: [];\n\t\t\tdirectories.push({\n\t\t\t\tpath,\n\t\t\t\tmtimeMs: Math.max(statSync(path).mtimeMs, ...markerPaths.map((markerPath) => statSync(markerPath).mtimeMs)),\n\t\t\t\tbytes: directoryBytes(path),\n\t\t\t\tactive: markerPaths.some(markerProcessIsAlive),\n\t\t\t});\n\t\t} catch {\n\t\t\t// Ignore a directory that disappeared or became unreadable during the scan.\n\t\t}\n\t}\n\treturn directories;\n}\n\nexport function pruneContextStoreRoot(rootDir: string, options: ContextStoreRetentionOptions = {}): string[] {\n\tconst now = options.now ?? Date.now();\n\tconst maxAgeMs = positiveLimit(options.maxAgeMs, DEFAULT_MAX_AGE_MS);\n\tconst maxSessionDirs = positiveLimit(options.maxSessionDirs, DEFAULT_MAX_SESSION_DIRS);\n\tconst maxTotalBytes = positiveLimit(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES);\n\tconst directories = inspectSessionDirectories(rootDir);\n\tconst removed: string[] = [];\n\tlet retainedCount = directories.length;\n\tlet retainedBytes = directories.reduce((sum, directory) => sum + directory.bytes, 0);\n\tfor (const directory of directories.sort((left, right) => left.mtimeMs - right.mtimeMs)) {\n\t\tif (directory.active) continue;\n\t\tconst expired = now - directory.mtimeMs > maxAgeMs;\n\t\tconst overCount = retainedCount > maxSessionDirs;\n\t\tconst overBytes = retainedBytes > maxTotalBytes;\n\t\tif (!expired && !overCount && !overBytes) continue;\n\t\ttry {\n\t\t\trmSync(directory.path, { recursive: true, force: true });\n\t\t\tremoved.push(directory.path);\n\t\t\tretainedCount--;\n\t\t\tretainedBytes -= directory.bytes;\n\t\t} catch {\n\t\t\t// Retention is best-effort and must never block a live session.\n\t\t}\n\t}\n\treturn removed;\n}\n\nexport function acquireContextStoreRetention(\n\tagentDir: string,\n\tsessionId: string,\n\toptions: ContextStoreRetentionOptions = {},\n): ContextStoreRetentionLease {\n\tif (!/^[A-Za-z0-9_-]+$/.test(sessionId)) return { release: () => {} };\n\tconst roots = [join(agentDir, \"context-gc\"), join(agentDir, \"context-artifacts\")];\n\tconst markerPaths: string[] = [];\n\tfor (const root of roots) {\n\t\tconst sessionDir = join(root, sessionId);\n\t\ttry {\n\t\t\tmkdirSync(sessionDir, { recursive: true });\n\t\t\tconst leaseDir = join(root, LEASES_DIRECTORY, sessionId);\n\t\t\tmkdirSync(leaseDir, { recursive: true });\n\t\t\tconst markerPath = join(\n\t\t\t\tleaseDir,\n\t\t\t\t`${ACTIVE_MARKER_PREFIX}${process.pid}-${randomUUID()}${ACTIVE_MARKER_SUFFIX}`,\n\t\t\t);\n\t\t\twriteFileSync(markerPath, JSON.stringify({ pid: process.pid, touchedAt: Date.now() }), \"utf-8\");\n\t\t\tmarkerPaths.push(markerPath);\n\t\t\tpruneContextStoreRoot(root, options);\n\t\t} catch {\n\t\t\t// Retention is best-effort; the caller can still use its normal store path.\n\t\t}\n\t}\n\tlet released = false;\n\treturn {\n\t\trelease(): void {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tfor (const markerPath of markerPaths) {\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(markerPath);\n\t\t\t\t\trmdirSync(dirname(markerPath));\n\t\t\t\t} catch {}\n\t\t\t}\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,EACN,cAAc,EACd,aAAa,EACb,eAAe,GAGf,MAAM,+BAA+B,CAAC;AAEvC,MAAM,kBAAkB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACpD,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,uBAAuB,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC;AAelD,SAAS,eAAe,CAAC,OAAqC,EAAwB;IACrF,OAAO;QACN,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,kBAAkB;QAChD,OAAO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AAO,GAAS;gBACf,IAAI,QAAQ;oBAAE,OAAO;gBACrB,QAAQ,GAAG,IAAI,CAAC;gBAChB,KAAK,MAAM,KAAK,IAAI,MAAM;oBAAE,KAAK,CAAC,OAAO,EAAE,CAAC;YAAA,CAC5C;SACD,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,KAAK,MAAM,KAAK,IAAI,MAAM;YAAE,KAAK,CAAC,OAAO,EAAE,CAAC;QAC5C,MAAM,KAAK,CAAC;IACb,CAAC;AAAA,CACD","sourcesContent":["import {\n\tacquireWorkRun,\n\tgetWorkRunDir,\n\tpruneWorkTenant,\n\ttype WorkRetentionOptions,\n\ttype WorkRunLease,\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;\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\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\nexport function pruneContextStores(\n\tagentDir: string,\n\ttenant: \"gc\" | \"artifacts\",\n\toptions: ContextStoreRetentionOptions = {},\n): string[] {\n\treturn pruneWorkTenant(agentDir, \"context\", tenant, toWorkRetention(options));\n}\n\nexport function getContextStoreDir(agentDir: string, tenant: \"gc\" | \"artifacts\", sessionId: string): string {\n\treturn getWorkRunDir(agentDir, \"context\", tenant, sessionId);\n}\n\nexport function acquireContextStoreRetention(\n\tagentDir: string,\n\tsessionId: string,\n\toptions: ContextStoreRetentionOptions = {},\n): ContextStoreRetentionLease {\n\tconst retention = toWorkRetention(options);\n\tconst leases: WorkRunLease[] = [];\n\ttry {\n\t\tconst gc = acquireWorkRun({ agentDir, category: \"context\", tenant: \"gc\", runId: sessionId, retention });\n\t\tleases.push(gc);\n\t\tconst artifacts = acquireWorkRun({\n\t\t\tagentDir,\n\t\t\tcategory: \"context\",\n\t\t\ttenant: \"artifacts\",\n\t\t\trunId: sessionId,\n\t\t\tretention,\n\t\t});\n\t\tleases.push(artifacts);\n\t\tlet released = false;\n\t\treturn {\n\t\t\tgcDir: gc.path,\n\t\t\tartifactsDir: artifacts.path,\n\t\t\trelease(): void {\n\t\t\t\tif (released) return;\n\t\t\t\treleased = true;\n\t\t\t\tfor (const lease of leases) lease.release();\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tfor (const lease of leases) lease.release();\n\t\tthrow error;\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"context-pipeline.d.ts","sourceRoot":"","sources":["../../src/core/context-pipeline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAKN,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,oBAAoB,CAAC;AAC9F,OAAO,EAAgB,KAAK,yBAAyB,EAA6B,MAAM,4BAA4B,CAAC;AACrH,OAAO,EAAE,KAAK,aAAa,EAA2B,MAAM,gCAAgC,CAAC;AAC7F,OAAO,EAAE,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,GACpB;QAAE,QAAQ,EAAE,YAAY,EAAE,CAAC;QAAC,MAAM,EAAE,eAAe,CAAA;KAAE,CA6DvD;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","sourcesContent":["/**\n * Context pipeline: the session's per-turn context-shaping subsystem — the observe-only context\n * audit, the shadow prompt-policy plan and its correlation with legacy context-gc, the enforcement\n * pilot, the relevance-curation queue + the fitness-gated curation model resolver / brain-curation\n * drain + compaction pre-digest, the legacy context-gc pass and its packed-artifact reference\n * release, the tool-output artifact store, and the current-context token estimate.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the latest\n * audit/policy/correlation/enforcement/gc reports, the {@link BrainCurator} sidecar and its last\n * skip reasons, and the lazily-built tool-artifact store. Everything else it needs — the turn\n * index, the session/settings managers, the model registry, agent/workspace dirs, the active tool\n * names, the disposed flag, the isolated-completion primitive, spawned-usage accounting, and the\n * live {@link MemoryManager} — is reached through narrow deps accessors rather than the whole\n * AgentSession.\n *\n * Context-transform boundary (deliberate): the per-turn stages ({@link estimateCurrentContextTokens},\n * {@link runContextAudit}, {@link runPromptPolicyPlanning}, {@link applyContextGc},\n * {@link correlatePromptPolicyWithContextGc}, {@link runPromptEnforcement},\n * {@link enqueueRelevanceCuration}, {@link maybeDrainBrainCuration}) are invoked from the session's\n * context transform as one-line delegations, so the transform stays the single owner of the pass\n * ordering. This controller reaches {@link MemoryController} functionality only through\n * {@link ContextPipelineDeps.getMemoryManager} (never imports it), and MemoryController never imports\n * the pipeline — keeping the transform the one place the two subsystems meet.\n */\n\nimport { join } from \"node:path\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport {\n\ttype CompactionEntry,\n\testimateContextTokens,\n\tgetLatestCompactionEntry,\n\ttype SessionEntry,\n\ttype SessionManager,\n\tTokenBudget,\n} from \"@caupulican/pi-agent-core/node\";\nimport type { Api, AssistantMessage, Model, Usage } from \"@caupulican/pi-ai\";\nimport type { IsolatedCompletionOptions, IsolatedCompletionResult } from \"./agent-session.ts\";\nimport { BrainCurator, type CurationTelemetrySnapshot, preDigestConversationText } from \"./context/brain-curator.ts\";\nimport { type ArtifactStore, createFileArtifactStore } from \"./context/context-artifacts.ts\";\nimport { type ContextAuditReport, runContextAudit } from \"./context/context-audit.ts\";\nimport { enforcePromptPolicy, type PromptEnforcementReport } from \"./context/context-prompt-enforcement.ts\";\nimport {\n\tcorrelateWithContextGc,\n\ttype PromptPolicyGcCorrelationReport,\n\ttype PromptPolicyShadowReport,\n\tplanPromptPolicy,\n} from \"./context/context-prompt-policy.ts\";\nimport { acquireContextStoreRetention, type ContextStoreRetentionLease } from \"./context/context-store-retention.ts\";\nimport { applyContextGc, type ContextGcReport } from \"./context-gc.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { evaluateSurfaceFitness } from \"./model-router/fitness-gate.ts\";\nimport { FitnessStore } from \"./models/fitness-store.ts\";\nimport { HF_TRANSFORMERS_PROVIDER, OLLAMA_PROVIDER } from \"./models/local-registration.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nfunction joinTextPrefix(content: readonly unknown[], maxChars = Number.POSITIVE_INFINITY): string {\n\tlet found = false;\n\tlet text = \"\";\n\tfor (const part of content) {\n\t\tif (typeof part !== \"object\" || part === null || (part as { type?: unknown }).type !== \"text\") continue;\n\t\tconst blockText = (part as { text?: unknown }).text;\n\t\tif (typeof blockText !== \"string\") continue;\n\t\tif (!found) {\n\t\t\tfound = true;\n\t\t\tif (blockText.length >= maxChars) return blockText.slice(0, maxChars);\n\t\t\ttext = blockText;\n\t\t\tcontinue;\n\t\t}\n\t\tconst available = maxChars - text.length;\n\t\tif (available <= 0) return text;\n\t\tif (available === 1) return `${text}\\n`;\n\t\tconst remaining = available - 1;\n\t\ttext += `\\n${blockText.slice(0, remaining)}`;\n\t\tif (blockText.length >= remaining) return text;\n\t}\n\treturn text;\n}\n\n/** Latest user prompt text in the provider-visible array. */\nexport function latestUserPromptText(messages: AgentMessage[], maxChars = Number.POSITIVE_INFINITY): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (!message || message.role !== \"user\") continue;\n\t\tif (typeof message.content === \"string\") {\n\t\t\treturn message.content.length > maxChars ? message.content.slice(0, maxChars) : message.content;\n\t\t}\n\t\tconst text = joinTextPrefix(message.content, maxChars);\n\t\tif (text.length > 0) return text;\n\t}\n\treturn \"\";\n}\n\n/** Read a packed artifact-producing tool result's `details.artifactId`, if present, without `any`. */\nfunction extractArtifactId(message: AgentMessage | undefined): string | undefined {\n\tif (!message || message.role !== \"toolResult\") return undefined;\n\tconst details = (message as { details?: unknown }).details;\n\tif (typeof details !== \"object\" || details === null) return undefined;\n\tconst artifactId = (details as { artifactId?: unknown }).artifactId;\n\treturn typeof artifactId === \"string\" ? artifactId : undefined;\n}\n\nexport interface ContextPipelineDeps {\n\t/** Current turn index, stamped into audit/policy/enforcement reports. */\n\tgetTurnIndex(): number;\n\t/** Session log: audit lookup, gc/artifact storage dirs, curation entries, token-estimate compaction anchor. */\n\tgetSessionManager(): SessionManager;\n\t/** Context-gc / prompt-enforcement / curation settings (all opt-in gates). */\n\tgetSettingsManager(): SettingsManager;\n\t/** Resolves a configured curation model pattern against configured auth. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Foreground model currently executing the transformed request. */\n\tgetModel(): Model<Api> | undefined;\n\t/** Root dir the host-keyed {@link FitnessStore} and per-session gc/artifact storage live under. */\n\tgetAgentDir(): string;\n\t/** Workspace root, passed to the context-gc pass. */\n\tgetCwd(): string;\n\t/** Currently-active tool names — enforcement checks whether artifact_retrieve is a live affordance. */\n\tgetActiveToolNames(): string[];\n\t/** A disposed session must never persist a curation/pre-digest entry. */\n\tisDisposed(): boolean;\n\t/** The live memory manager — the active providers' page markers feed the semantic-gc scan. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Roll a curation drain's spawned usage into session accounting (idempotent per reportId). */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\t/** One-shot LLM call fully isolated from the main session — the curation/pre-digest execution primitive. */\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n}\n\nexport class ContextPipeline {\n\tprivate _latestContextGcReport: ContextGcReport | undefined = undefined;\n\t/** Brain-curation sidecar (design: brain-context-curation-design.md). Inert unless the\n\t * contextPolicy.curation setting is enabled AND the model passes the digest fitness gate. */\n\tprivate readonly _brainCurator = new BrainCurator();\n\tprivate _lastCurationSkipReason: string | undefined = undefined;\n\tprivate _lastPreDigestSkipReason: string | undefined = undefined;\n\tprivate _toolArtifactStore: ArtifactStore | undefined = undefined;\n\tprivate _contextStoreRetentionLease: ContextStoreRetentionLease | undefined;\n\tprivate _latestContextAuditReport: ContextAuditReport | undefined = undefined;\n\tprivate _latestPromptPolicyReport: PromptPolicyShadowReport | undefined = undefined;\n\tprivate _latestPromptPolicyGcCorrelation: PromptPolicyGcCorrelationReport | undefined = undefined;\n\tprivate _latestPromptEnforcementReport: PromptEnforcementReport | undefined = undefined;\n\tprivate readonly _tokenBudget = new TokenBudget();\n\tprivate _hasTokenBudgetAnchor = false;\n\tprivate _tokenBudgetAnchorCompactionId: string | undefined = undefined;\n\tprivate _lastTokenBudgetAnchorKey: string | undefined = undefined;\n\t/** Incremental current-branch lookup used by the per-turn audit. It retains only tool calls\n\t * still present in the provider-visible context, so compaction also bounds this cache. */\n\tprivate _sessionEntryLookupCache: { leafId: string | null; byToolCallId: Map<string, string> } | undefined =\n\t\tundefined;\n\n\tprivate readonly deps: ContextPipelineDeps;\n\n\tconstructor(deps: ContextPipelineDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tprivate _ensureContextStoreRetention(): void {\n\t\tthis._contextStoreRetentionLease ??= acquireContextStoreRetention(\n\t\t\tthis.deps.getAgentDir(),\n\t\t\tthis.deps.getSessionManager().getSessionId(),\n\t\t);\n\t}\n\n\tprivate _contextGcStorageDir(): string {\n\t\tthis._ensureContextStoreRetention();\n\t\treturn join(this.deps.getAgentDir(), \"context-gc\", this.deps.getSessionManager().getSessionId());\n\t}\n\n\tprivate _toolArtifactsDir(): string {\n\t\tthis._ensureContextStoreRetention();\n\t\treturn join(this.deps.getAgentDir(), \"context-artifacts\", this.deps.getSessionManager().getSessionId());\n\t}\n\n\t/**\n\t * Session-scoped, filesystem-backed artifact store for first-capture-then-bound tool\n\t * output (grep/find/run_toolkit_script -- see tool-output-artifacts.md). Lazily created and\n\t * cached so every tool construction in this session shares one store instance.\n\t *\n\t * `packToolOutput()` registers a reference (the packing tool call's id) at pack time\n\t * and fails closed, so packed artifacts are never prematurely collected.\n\t * `_releaseGcPackedArtifactReferences()` (called from `applyContextGc()`) releases\n\t * that reference once context-gc packs the result out of live context, and\n\t * opportunistically reclaims now-unreferenced artifacts via `cleanup()`.\n\t * Cross-session retention is enforced when either payload store is first used. Active\n\t * sessions hold PID-marked leases; inactive stores are pruned by age, count, and bytes.\n\t */\n\tgetToolArtifactStore(): ArtifactStore {\n\t\tthis._toolArtifactStore ??= createFileArtifactStore({ baseDir: this._toolArtifactsDir() });\n\t\treturn this._toolArtifactStore;\n\t}\n\n\t/**\n\t * Best-effort final sweep of any already-released (zero-reference) tool-output artifact at\n\t * session dispose. Reads the field (not the getter) so a session that never packed anything\n\t * doesn't force-create a store/dir just to sweep it.\n\t */\n\tcleanupToolArtifactStoreOnDispose(): void {\n\t\tthis._toolArtifactStore?.cleanup();\n\t\tthis._contextStoreRetentionLease?.release();\n\t\tthis._contextStoreRetentionLease = undefined;\n\t}\n\n\t/**\n\t * Map tool-result call ids to persisted session-entry ids. Linear branch growth is handled\n\t * incrementally by walking only entries appended since the cached leaf; a branch switch falls\n\t * back to one full rebuild so lookups never leak entries from the abandoned branch.\n\t */\n\tprivate _getLatestCompactionEntry(): CompactionEntry | null {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst indexedSessionManager = sessionManager as unknown as {\n\t\t\tgetLeafId?: () => string | null;\n\t\t\tgetEntry?: (id: string) => SessionEntry | undefined;\n\t\t};\n\t\tconst getLeafId = indexedSessionManager.getLeafId?.bind(sessionManager);\n\t\tconst getEntry = indexedSessionManager.getEntry?.bind(sessionManager);\n\t\tconst leafId = getLeafId?.();\n\t\tif (getLeafId && getEntry && leafId !== undefined) {\n\t\t\tlet currentId = leafId;\n\t\t\twhile (currentId !== null) {\n\t\t\t\tconst entry = getEntry(currentId);\n\t\t\t\tif (!entry) break;\n\t\t\t\tif (entry.type === \"compaction\") return entry;\n\t\t\t\tcurrentId = entry.parentId;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\treturn getLatestCompactionEntry(sessionManager.getBranch());\n\t}\n\n\tprivate _buildSessionEntryIdLookup(\n\t\twantedToolCallIds: ReadonlySet<string>,\n\t): (toolCallId: string) => string | undefined {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst indexedSessionManager = sessionManager as unknown as {\n\t\t\tgetLeafId?: () => string | null;\n\t\t\tgetEntry?: (id: string) => SessionEntry | undefined;\n\t\t};\n\t\tconst getLeafId = indexedSessionManager.getLeafId?.bind(sessionManager);\n\t\tconst getEntry = indexedSessionManager.getEntry?.bind(sessionManager);\n\t\tconst leafId = getLeafId?.();\n\t\tconst cached = this._sessionEntryLookupCache;\n\t\tif (cached) {\n\t\t\tfor (const toolCallId of cached.byToolCallId.keys()) {\n\t\t\t\tif (!wantedToolCallIds.has(toolCallId)) cached.byToolCallId.delete(toolCallId);\n\t\t\t}\n\t\t}\n\t\tif (getLeafId && getEntry && leafId !== undefined) {\n\t\t\tif (cached?.leafId === leafId) {\n\t\t\t\treturn (toolCallId) => cached.byToolCallId.get(toolCallId);\n\t\t\t}\n\t\t\tif (cached) {\n\t\t\t\tconst appendedEntries: SessionEntry[] = [];\n\t\t\t\tlet cursor = leafId;\n\t\t\t\twhile (cursor !== null && cursor !== cached.leafId) {\n\t\t\t\t\tconst entry = getEntry(cursor);\n\t\t\t\t\tif (!entry) break;\n\t\t\t\t\tappendedEntries.push(entry);\n\t\t\t\t\tcursor = entry.parentId;\n\t\t\t\t}\n\t\t\t\tif (cursor === cached.leafId) {\n\t\t\t\t\tfor (let index = appendedEntries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = appendedEntries[index];\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tentry.type === \"message\" &&\n\t\t\t\t\t\t\tentry.message.role === \"toolResult\" &&\n\t\t\t\t\t\t\twantedToolCallIds.has(entry.message.toolCallId)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tcached.byToolCallId.set(entry.message.toolCallId, entry.id);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcached.leafId = leafId;\n\t\t\t\t\treturn (toolCallId) => cached.byToolCallId.get(toolCallId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst byToolCallId = new Map<string, string>();\n\t\tfor (const entry of sessionManager.getBranch()) {\n\t\t\tif (\n\t\t\t\tentry.type === \"message\" &&\n\t\t\t\tentry.message.role === \"toolResult\" &&\n\t\t\t\twantedToolCallIds.has(entry.message.toolCallId)\n\t\t\t) {\n\t\t\t\tbyToolCallId.set(entry.message.toolCallId, entry.id);\n\t\t\t}\n\t\t}\n\t\tif (leafId !== undefined) this._sessionEntryLookupCache = { leafId, byToolCallId };\n\t\treturn (toolCallId) => byToolCallId.get(toolCallId);\n\t}\n\n\t/**\n\t * Phase 1 observe-only audit pass (see context/context-audit.ts): converts live\n\t * toolResult messages into ContextItems and runs the existing retention/hard-constraint\n\t * evaluators over them, storing the latest deterministic report for tests/debugging.\n\t * Read-only with respect to messages, the transcript, and artifact references -- uses\n\t * `_toolArtifactStore` (the field), not `getToolArtifactStore()` (the getter), so a\n\t * session that never packed anything doesn't force-create a store/dir just to audit.\n\t * Never throws into a live turn: any failure degrades to an empty report.\n\t */\n\trunContextAudit(messages: AgentMessage[]): ContextAuditReport {\n\t\ttry {\n\t\t\tconst wantedToolCallIds = new Set(\n\t\t\t\tmessages.filter((message) => message.role === \"toolResult\").map((message) => message.toolCallId),\n\t\t\t);\n\t\t\tconst report = runContextAudit(messages, {\n\t\t\t\tturnIndex: this.deps.getTurnIndex(),\n\t\t\t\tartifactStore: this._toolArtifactStore,\n\t\t\t\tsessionEntryIdForToolCallId: this._buildSessionEntryIdLookup(wantedToolCallIds),\n\t\t\t});\n\t\t\tthis._latestContextAuditReport = report;\n\t\t\treturn report;\n\t\t} catch {\n\t\t\tconst report: ContextAuditReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestContextAuditReport = report;\n\t\t\treturn report;\n\t\t}\n\t}\n\n\t/**\n\t * Read-only inspection of the context audit. With `messages`, recomputes fresh against\n\t * the given array (still no mutation of messages/transcript/artifact refs); without,\n\t * returns the last report computed during a real transform pass.\n\t */\n\tgetContextAuditReport(messages?: AgentMessage[]): ContextAuditReport {\n\t\tif (messages) return this.runContextAudit(messages);\n\t\treturn this._latestContextAuditReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t}\n\n\t/**\n\t * Observe-first shadow/planning pass (see context/context-prompt-policy.ts): re-shapes\n\t * the audit report into a per-item policy plan whose `appliedAction` is always\n\t * \"keep_raw\" -- this never enforces anything, it only records what the policy engine\n\t * would say. Never throws into a live turn: any failure degrades to an empty report.\n\t */\n\trunPromptPolicyPlanning(auditReport: ContextAuditReport): PromptPolicyShadowReport {\n\t\ttry {\n\t\t\tconst report = planPromptPolicy(auditReport);\n\t\t\tthis._latestPromptPolicyReport = report;\n\t\t\treturn report;\n\t\t} catch {\n\t\t\tconst report: PromptPolicyShadowReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestPromptPolicyReport = report;\n\t\t\treturn report;\n\t\t}\n\t}\n\n\t/**\n\t * Read-only inspection of the shadow policy plan. With `messages`, recomputes fresh\n\t * (audit + plan) against the given array; without, returns the last plan computed\n\t * during a real transform pass. Never mutates messages/transcript/artifact refs.\n\t */\n\tgetPromptPolicyReport(messages?: AgentMessage[]): PromptPolicyShadowReport {\n\t\tif (messages) return this.runPromptPolicyPlanning(this.runContextAudit(messages));\n\t\treturn this._latestPromptPolicyReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t}\n\n\t/**\n\t * Report-only correlation between the shadow plan just computed this turn and what the\n\t * legacy context-gc pass actually packed. Runs after `applyContextGc()` has already\n\t * produced its report; never influences context-gc itself. Never throws into a live\n\t * turn: any failure degrades to an empty correlation.\n\t */\n\tcorrelatePromptPolicyWithContextGc(gcReport: ContextGcReport): void {\n\t\tconst shadowReport = this._latestPromptPolicyReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\ttry {\n\t\t\tthis._latestPromptPolicyGcCorrelation = correlateWithContextGc(shadowReport, gcReport);\n\t\t} catch {\n\t\t\tthis._latestPromptPolicyGcCorrelation = { turnIndex: this.deps.getTurnIndex(), entries: [] };\n\t\t}\n\t}\n\n\t/** Read-only inspection of the latest shadow-plan/legacy-gc correlation, for tests/debugging. */\n\tgetPromptPolicyGcCorrelation(): PromptPolicyGcCorrelationReport {\n\t\treturn this._latestPromptPolicyGcCorrelation ?? { turnIndex: this.deps.getTurnIndex(), entries: [] };\n\t}\n\n\t/**\n\t * First enforcement pilot (see context/context-prompt-enforcement.ts): opt-in,\n\t * default-disabled stub-in-place of stale artifact-backed tool_output results in the\n\t * provider-visible message array only. Runs on `messages` AFTER context-gc has already\n\t * produced its own result, so legacy context-gc's own packing/reporting is completely\n\t * unaffected by this pass -- it only ever acts on messages gc left untouched this turn.\n\t * Never throws into a live turn: any failure degrades to returning `messages` unchanged.\n\t */\n\trunPromptEnforcement(\n\t\tmessages: AgentMessage[],\n\t\tshadowReport: PromptPolicyShadowReport,\n\t): { messages: AgentMessage[]; report: PromptEnforcementReport } {\n\t\ttry {\n\t\t\tconst persistedSettings = this.deps.getSettingsManager().getContextPromptEnforcementSettings();\n\t\t\tconst curationEnabled = this.deps.getSettingsManager().getContextCurationSettings().enabled;\n\t\t\tconst settings = {\n\t\t\t\t...persistedSettings,\n\t\t\t\t// Runtime fact, never assumed: artifact_retrieve is a companion affordance\n\t\t\t\t// (auto-activated alongside grep/find), not a default/global tool, so active\n\t\t\t\t// tools can differ turn to turn -- see context-prompt-enforcement.ts's doc\n\t\t\t\t// comment on why this is checked separately from hasAvailableRetrievalPath.\n\t\t\t\tretrievalToolAvailable: this.deps.getActiveToolNames().includes(\"artifact_retrieve\"),\n\t\t\t\tbrainRelevance: curationEnabled ? (itemId: string) => this._brainCurator.getRelevance(itemId) : undefined,\n\t\t\t};\n\t\t\tconst result = enforcePromptPolicy(messages, shadowReport, settings);\n\t\t\tthis._latestPromptEnforcementReport = result.report;\n\t\t\treturn result;\n\t\t} catch {\n\t\t\tconst report: PromptEnforcementReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestPromptEnforcementReport = report;\n\t\t\treturn { messages, report };\n\t\t}\n\t}\n\n\t/**\n\t * Enqueue relevance-scoring jobs for stale, artifact-backed tool outputs the enforcement\n\t * pilot could act on. Pure queueing — the verdicts only ever take effect through the\n\t * asymmetric advisory lever inside enforcePromptPolicy. Never throws into a turn.\n\t */\n\tenqueueRelevanceCuration(messages: AgentMessage[], shadowReport: PromptPolicyShadowReport): void {\n\t\ttry {\n\t\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\t\tif (!settings.enabled) return;\n\t\t\tconst goal = latestUserPromptText(messages, 400);\n\t\t\tfor (const item of shadowReport.items) {\n\t\t\t\tif (!item.hasAvailableRetrievalPath) continue;\n\t\t\t\tconst message = messages[item.messageIndex];\n\t\t\t\tif (!message || message.role !== \"toolResult\" || message.toolCallId !== item.toolCallId) continue;\n\t\t\t\tif (message.isError) continue;\n\t\t\t\tconst details = message.details as\n\t\t\t\t\t| { contextGc?: { packed?: unknown }; promptPolicy?: { enforced?: unknown } }\n\t\t\t\t\t| undefined;\n\t\t\t\tif (details?.contextGc?.packed === true || details?.promptPolicy?.enforced === true) continue;\n\t\t\t\tconst text = joinTextPrefix(message.content, 4000);\n\t\t\t\tif (text.length === 0) continue;\n\t\t\t\tthis._brainCurator.enqueue({ kind: \"relevance\", key: item.itemId, content: text, goal });\n\t\t\t}\n\t\t} catch {\n\t\t\t// curation is a sidecar; it must never disrupt a turn\n\t\t}\n\t}\n\n\t/**\n\t * Drain gate: settings on, model configured+authed, and the model has PASSED the digest\n\t * fitness probe on THIS host (design: unfit or unprobed models are refused with a visible\n\t * reason, never silently degraded). Fire-and-forget; never throws into a turn.\n\t */\n\t/**\n\t * Resolve the curation model IFF every gate passes: setting enabled, model configured,\n\t * resolvable+authed, and digest-fitness-proven on THIS host (canonical \"provider/id\" ref —\n\t * runModelFitness stores reports under it, while settings.model may be a bare id or pattern).\n\t * Sets _lastCurationSkipReason on refusal; never throws.\n\t */\n\tprivate _effectiveContextWindowFromFitness(model: Model<Api>): number {\n\t\tconst registered = model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n\t\tconst capacity = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t.getForHost()\n\t\t\t.find((entry) => entry.model === `${model.provider}/${model.id}`)?.report.capacity?.servedContextWindow;\n\t\treturn capacity && capacity > 0 ? Math.min(registered, capacity) : registered;\n\t}\n\n\tresolveCurationModelIfFit(): Model<Api> | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\tif (!settings.enabled) {\n\t\t\t// Never surface a stale refusal reason for a feature the user has since disabled.\n\t\t\tthis._lastCurationSkipReason = undefined;\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!settings.model) {\n\t\t\tthis._lastCurationSkipReason = \"curation_model_unset\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst resolved = resolveCliModel({ cliModel: settings.model, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model || !this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) {\n\t\t\tthis._lastCurationSkipReason = \"curation_model_unresolved\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst canonicalRef = `${resolved.model.provider}/${resolved.model.id}`;\n\t\tconst fitness = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t.getForHost()\n\t\t\t.find((entry) => entry.model === canonicalRef);\n\t\tconst verdict = evaluateSurfaceFitness(\"curation\", fitness?.report);\n\t\tif (!verdict.fit) {\n\t\t\tthis._lastCurationSkipReason =\n\t\t\t\tverdict.reason === \"unprobed\" ? \"curation_model_unprobed\" : \"curation_model_digest_unfit\";\n\t\t\treturn undefined;\n\t\t}\n\t\tthis._lastCurationSkipReason = undefined;\n\t\treturn resolved.model;\n\t}\n\n\tmaybeDrainBrainCuration(): void {\n\t\ttry {\n\t\t\tif (!this._brainCurator.hasWork() || this._brainCurator.isDraining) return;\n\t\t\tconst model = this.resolveCurationModelIfFit();\n\t\t\tif (!model) return;\n\t\t\tconst foregroundModel = this.deps.getModel();\n\t\t\tconst foregroundIsManagedLocal =\n\t\t\t\tforegroundModel?.provider === OLLAMA_PROVIDER || foregroundModel?.provider === HF_TRANSFORMERS_PROVIDER;\n\t\t\tconst curatorIsManagedLocal =\n\t\t\t\tmodel.provider === OLLAMA_PROVIDER || model.provider === HF_TRANSFORMERS_PROVIDER;\n\t\t\tif (foregroundIsManagedLocal && curatorIsManagedLocal) {\n\t\t\t\t// Local foreground accuracy/latency wins. A fire-and-forget curator can otherwise reach\n\t\t\t\t// a single-parallel server first and make the user's request wait behind sidecar work.\n\t\t\t\tthis._lastCurationSkipReason = \"curation_deferred_for_local_foreground\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\t\tvoid this._drainBrainCuration(model, settings.maxJobsPerTurn);\n\t\t} catch {\n\t\t\t// curation is a sidecar; it must never disrupt a turn\n\t\t}\n\t}\n\n\t/**\n\t * Compaction pre-digest gate (design surface 3): everything the drain gate requires PLUS a\n\t * RUNTIME reliability proof — the curator must have run >=5 jobs on this session with a parse\n\t * failure rate <=5% before it is trusted to pre-digest compaction input. Returns undefined\n\t * (verbatim compaction, byte-for-byte today's behavior) whenever any gate refuses.\n\t */\n\tbuildCompactionPreDigest(): ((text: string, signal?: AbortSignal) => Promise<string>) | undefined {\n\t\ttry {\n\t\t\tconst model = this.resolveCurationModelIfFit();\n\t\t\tif (!model) return undefined;\n\t\t\tconst telemetry = this._brainCurator.telemetry();\n\t\t\tif (telemetry.jobsRun < 5 || telemetry.parseFailures / telemetry.jobsRun > 0.05) {\n\t\t\t\tthis._lastPreDigestSkipReason = \"curation_predigest_reliability_unproven\";\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tthis._lastPreDigestSkipReason = undefined;\n\t\t\treturn async (text, signal) => {\n\t\t\t\tconst effectiveWindow = this._effectiveContextWindowFromFitness(model);\n\t\t\t\tconst chunkChars = Number.isFinite(effectiveWindow)\n\t\t\t\t\t? Math.max(1_000, Math.floor((effectiveWindow - 1024) * 4))\n\t\t\t\t\t: undefined;\n\t\t\t\tconst result = await preDigestConversationText({\n\t\t\t\t\ttext,\n\t\t\t\t\tsignal,\n\t\t\t\t\tchunkChars,\n\t\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal: chunkSignal }) => {\n\t\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\t\t\tmaxTokens: 512,\n\t\t\t\t\t\t\tsignal: chunkSignal,\n\t\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (!this.deps.isDisposed() && result.totalChunks > 0) {\n\t\t\t\t\tthis.deps.getSessionManager().appendCustomEntry(\"brain-curation-predigest\", {\n\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\ttotalChunks: result.totalChunks,\n\t\t\t\t\t\tdigested: result.digested,\n\t\t\t\t\t\tfailed: result.failed,\n\t\t\t\t\t\tcharsBefore: text.length,\n\t\t\t\t\t\tcharsAfter: result.text.length,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn result.text;\n\t\t\t};\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate async _drainBrainCuration(model: Model<Api>, maxJobs: number): Promise<void> {\n\t\ttry {\n\t\t\t// ACCUMULATE across all drained jobs (the drain runs the completer once PER job) —\n\t\t\t// keeping only the last job's usage would under-report every multi-job drain.\n\t\t\tlet spentUsage: AssistantMessage[\"usage\"] | undefined;\n\t\t\tconst results = await this._brainCurator.drain({\n\t\t\t\tmaxJobs,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\t\tmaxTokens: 256,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Both curation system prompts are static — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tconst usage = completion.usage;\n\t\t\t\t\tif (!spentUsage) {\n\t\t\t\t\t\tspentUsage = structuredClone(usage);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tspentUsage.input += usage.input;\n\t\t\t\t\t\tspentUsage.output += usage.output;\n\t\t\t\t\t\tspentUsage.cacheRead += usage.cacheRead;\n\t\t\t\t\t\tspentUsage.cacheWrite += usage.cacheWrite;\n\t\t\t\t\t\tspentUsage.totalTokens += usage.totalTokens;\n\t\t\t\t\t\tspentUsage.cost.input += usage.cost.input;\n\t\t\t\t\t\tspentUsage.cost.output += usage.cost.output;\n\t\t\t\t\t\tspentUsage.cost.cacheRead += usage.cost.cacheRead;\n\t\t\t\t\t\tspentUsage.cost.cacheWrite += usage.cost.cacheWrite;\n\t\t\t\t\t\tspentUsage.cost.total += usage.cost.total;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\t\t\t// Honest accounting even for free local models: token visibility is the contract.\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, { label: \"context-curator\" });\n\t\t\t}\n\t\t\tif (this.deps.isDisposed() || results.length === 0) return;\n\t\t\tthis.deps.getSessionManager().appendCustomEntry(\"brain-curation\", {\n\t\t\t\tversion: 1,\n\t\t\t\tresults: results.map((result) => ({\n\t\t\t\t\tkey: result.key,\n\t\t\t\t\tkind: result.kind,\n\t\t\t\t\tok: result.ok,\n\t\t\t\t\tms: result.ms,\n\t\t\t\t\t...(result.digest !== undefined ? { digest: result.digest } : {}),\n\t\t\t\t\t...(result.relevant !== undefined ? { relevant: result.relevant, confidence: result.confidence } : {}),\n\t\t\t\t})),\n\t\t\t\ttelemetry: this._brainCurator.telemetry(),\n\t\t\t});\n\t\t} catch {\n\t\t\t// curation is a sidecar; it must never disrupt a turn\n\t\t}\n\t}\n\n\t/** Curation status for diagnostics/dashboard: settings, live telemetry, last refusal reason. */\n\tgetContextCurationStatus(): {\n\t\tenabled: boolean;\n\t\tmodel?: string;\n\t\ttelemetry: CurationTelemetrySnapshot;\n\t\tlastSkipReason?: string;\n\t\tlastPreDigestSkipReason?: string;\n\t} {\n\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\treturn {\n\t\t\tenabled: settings.enabled,\n\t\t\tmodel: settings.model,\n\t\t\ttelemetry: this._brainCurator.telemetry(),\n\t\t\tlastSkipReason: this._lastCurationSkipReason,\n\t\t\tlastPreDigestSkipReason: this._lastPreDigestSkipReason,\n\t\t};\n\t}\n\n\t/** Read-only inspection of the latest prompt-enforcement report, for tests/debugging. */\n\tgetPromptEnforcementReport(): PromptEnforcementReport {\n\t\treturn this._latestPromptEnforcementReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t}\n\n\tapplyContextGc(\n\t\tmessages: AgentMessage[],\n\t\twritePayloads: boolean,\n\t): { messages: AgentMessage[]; report: ContextGcReport } {\n\t\ttry {\n\t\t\tconst settings = this.deps.getSettingsManager().getContextGcSettings();\n\t\t\t// Merge the ACTIVE memory providers' own page markers (e.g. transcript-recall's\n\t\t\t// \"<memory_context\") into the semantic-memory marker list. The settings default is\n\t\t\t// provider-agnostic and non-empty, so without this merge the recall pages the bundled\n\t\t\t// default provider actually emits are never recognized as semantic-memory pages and\n\t\t\t// accumulate raw for the life of the session — the exact growth Bug #7 GC exists to stop.\n\t\t\tconst providerMarkers = this.deps.getMemoryManager().getContextMarkers();\n\t\t\tconst curationSettings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\t\tconst result = applyContextGc(messages, {\n\t\t\t\t...settings,\n\t\t\t\tsemanticMemory: {\n\t\t\t\t\t...settings.semanticMemory,\n\t\t\t\t\tmarkers: [...new Set([...settings.semanticMemory.markers, ...providerMarkers])],\n\t\t\t\t},\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tstorageDir: this._contextGcStorageDir(),\n\t\t\t\twritePayloads,\n\t\t\t\tcuration: curationSettings.enabled\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tresolveDigest: (digestKey) => {\n\t\t\t\t\t\t\t\tconst digest = this._brainCurator.getDigest(digestKey);\n\t\t\t\t\t\t\t\t// Count serves on the REAL per-turn pass only, never the report path.\n\t\t\t\t\t\t\t\tif (digest !== undefined && writePayloads) this._brainCurator.noteDigestServed();\n\t\t\t\t\t\t\t\treturn digest;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t// Only the real per-turn pass enqueues work; the read-only report path\n\t\t\t\t\t\t\t// (writePayloads=false) stays side-effect free.\n\t\t\t\t\t\t\tonPacked: writePayloads\n\t\t\t\t\t\t\t\t? (record, originalText) => {\n\t\t\t\t\t\t\t\t\t\tthis._brainCurator.enqueue({\n\t\t\t\t\t\t\t\t\t\t\tkind: \"stub_digest\",\n\t\t\t\t\t\t\t\t\t\t\tkey: record.key ?? record.toolCallId,\n\t\t\t\t\t\t\t\t\t\t\tcontent: originalText,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t\tthis._latestContextGcReport = result.report;\n\t\t\t// Only release/reclaim on the real per-turn pass (writePayloads=true), never on\n\t\t\t// the read-only status-report path (getContextGcReport with writePayloads=false),\n\t\t\t// so merely inspecting the report can't have side effects.\n\t\t\tif (writePayloads && result.report.packedCount > 0) {\n\t\t\t\tthis._releaseGcPackedArtifactReferences(messages, result.report);\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch {\n\t\t\tconst report: ContextGcReport = {\n\t\t\t\tenabled: false,\n\t\t\t\tpackedCount: 0,\n\t\t\t\toriginalTokens: 0,\n\t\t\t\tpackedTokens: 0,\n\t\t\t\tsavedTokens: 0,\n\t\t\t\trecords: [],\n\t\t\t};\n\t\t\tthis._latestContextGcReport = report;\n\t\t\treturn { messages, report };\n\t\t}\n\t}\n\n\t/**\n\t * Reference-release + cleanup lifecycle: once context-gc has packed an artifact-producing\n\t * tool result (grep/find/run_toolkit_script) out of the live prompt (the message is no longer current/active working\n\t * context -- see contracts-and-retention.md's \"ephemeral\"/\"expired\" retention\n\t * classes), release the pack-time reference `packToolOutput()` registered for it, and\n\t * opportunistically reclaim now-unreferenced artifacts. This is the other half of the\n\t * D2b-1 gate: artifacts were being registered but never released, so they accumulated\n\t * for the life of the session.\n\t *\n\t * `record.toolCallId` (from context-gc's packed record) is exactly the holder id\n\t * `packToolOutput()` used when it called `addReference()` -- both trace back to the\n\t * same tool call's id -- so no separate bookkeeping is needed to find it.\n\t */\n\tprivate _releaseGcPackedArtifactReferences(messages: AgentMessage[], report: ContextGcReport): void {\n\t\tconst store = this._toolArtifactStore;\n\t\tif (!store) return; // no store was ever constructed, so nothing could have been packed to one\n\n\t\tlet releasedAny = false;\n\t\tfor (const record of report.records) {\n\t\t\tif (record.toolName !== \"grep\" && record.toolName !== \"find\" && record.toolName !== \"run_toolkit_script\")\n\t\t\t\tcontinue;\n\t\t\tconst artifactId = extractArtifactId(messages[record.messageIndex]);\n\t\t\tif (!artifactId) continue;\n\t\t\tif (store.removeReference(artifactId, record.toolCallId)) releasedAny = true;\n\t\t}\n\t\t// Cleanup only runs immediately after a release actually happened in this pass, so\n\t\t// a long session doesn't re-scan the artifact directory on every turn once nothing\n\t\t// new became eligible for release.\n\t\tif (releasedAny) store.cleanup();\n\t}\n\n\tgetContextGcReport(messages?: AgentMessage[]): ContextGcReport {\n\t\tif (messages) return this.applyContextGc(messages, false).report;\n\t\treturn (\n\t\t\tthis._latestContextGcReport ?? {\n\t\t\t\tenabled: this.deps.getSettingsManager().getContextGcSettings().enabled,\n\t\t\t\tpackedCount: 0,\n\t\t\t\toriginalTokens: 0,\n\t\t\t\tpackedTokens: 0,\n\t\t\t\tsavedTokens: 0,\n\t\t\t\trecords: [],\n\t\t\t}\n\t\t);\n\t}\n\n\tobserveProviderUsage(messages: AgentMessage[], usageMessage: AssistantMessage): void {\n\t\tif (usageMessage.stopReason === \"error\" || usageMessage.stopReason === \"aborted\") {\n\t\t\treturn;\n\t\t}\n\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null || messages[estimate.lastUsageIndex] !== usageMessage) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst compactionEntry = this._getLatestCompactionEntry();\n\t\tif (!compactionEntry) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst compactionTimestamp = new Date(compactionEntry.timestamp).getTime();\n\t\tif (usageMessage.timestamp <= compactionTimestamp) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst coveredChars = estimateConversationChars(messages, 0, estimate.lastUsageIndex + 1);\n\t\tif (estimate.usageTokens <= 0 || coveredChars <= 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst anchorKey = `${compactionEntry.id}:${usageMessage.timestamp}:${estimate.usageTokens}:${coveredChars}`;\n\t\tif (anchorKey === this._lastTokenBudgetAnchorKey) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._tokenBudget.anchor(estimate.usageTokens, coveredChars);\n\t\tthis._hasTokenBudgetAnchor = true;\n\t\tthis._tokenBudgetAnchorCompactionId = compactionEntry.id;\n\t\tthis._lastTokenBudgetAnchorKey = anchorKey;\n\t}\n\n\testimateCurrentContextTokens(messages: AgentMessage[]): number {\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) {\n\t\t\treturn this._tokenBudget.estimateDelta(estimateConversationChars(messages));\n\t\t}\n\n\t\tconst usageMessage = messages[estimate.lastUsageIndex];\n\t\tconst compactionEntry = this._getLatestCompactionEntry();\n\t\tif (usageMessage?.role !== \"assistant\" || !compactionEntry) {\n\t\t\treturn estimate.tokens;\n\t\t}\n\t\tconst usageTimestamp = (usageMessage as AssistantMessage).timestamp;\n\t\tconst compactionTimestamp = new Date(compactionEntry.timestamp).getTime();\n\t\tif (usageTimestamp <= compactionTimestamp) {\n\t\t\treturn this._tokenBudget.estimateDelta(estimateConversationChars(messages));\n\t\t}\n\n\t\tif (!this._hasTokenBudgetAnchor || this._tokenBudgetAnchorCompactionId !== compactionEntry.id) {\n\t\t\treturn estimate.tokens;\n\t\t}\n\n\t\tconst deltaChars = estimateConversationChars(messages, estimate.lastUsageIndex + 1, messages.length);\n\t\treturn this._tokenBudget.current(deltaChars, estimate.tokens);\n\t}\n}\n\n/**\n * Estimate covered characters from the provider-visible context messages.\n */\nfunction estimateConversationChars(messages: AgentMessage[], start = 0, end = messages.length): number {\n\tlet total = 0;\n\tfor (let index = Math.max(0, start); index < Math.min(messages.length, end); index++) {\n\t\tconst message = messages[index];\n\t\tif (!message) continue;\n\t\tconst rawContent = (message as { content?: unknown }).content;\n\t\tif (typeof rawContent === \"string\") {\n\t\t\ttotal += rawContent.length;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!Array.isArray(rawContent)) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const block of rawContent) {\n\t\t\tif (typeof block === \"string\") {\n\t\t\t\ttotal += block.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!block || typeof block !== \"object\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (typeof (block as { text?: unknown }).text === \"string\") {\n\t\t\t\ttotal += (block as { text?: string }).text?.length ?? 0;\n\t\t\t}\n\t\t\tif (typeof (block as { thinking?: unknown }).thinking === \"string\") {\n\t\t\t\ttotal += (block as { thinking?: string }).thinking?.length ?? 0;\n\t\t\t}\n\t\t}\n\t}\n\treturn total;\n}\n"]}
1
+ {"version":3,"file":"context-pipeline.d.ts","sourceR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CAqB9B;IAED;;;;;OAKG;IACH,wBAAwB,IAAI,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,SAAS,CAmDhG;YAEa,mBAAmB;IA8DjC,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,CA6DvD;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","sourcesContent":["/**\n * Context pipeline: the session's per-turn context-shaping subsystem — the observe-only context\n * audit, the shadow prompt-policy plan and its correlation with legacy context-gc, the enforcement\n * pilot, the relevance-curation queue + the fitness-gated curation model resolver / brain-curation\n * drain + compaction pre-digest, the legacy context-gc pass and its packed-artifact reference\n * release, the tool-output artifact store, and the current-context token estimate.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the latest\n * audit/policy/correlation/enforcement/gc reports, the {@link BrainCurator} sidecar and its last\n * skip reasons, and the lazily-built tool-artifact store. Everything else it needs — the turn\n * index, the session/settings managers, the model registry, agent/workspace dirs, the active tool\n * names, the disposed flag, the isolated-completion primitive, spawned-usage accounting, and the\n * live {@link MemoryManager} — is reached through narrow deps accessors rather than the whole\n * AgentSession.\n *\n * Context-transform boundary (deliberate): the per-turn stages ({@link estimateCurrentContextTokens},\n * {@link runContextAudit}, {@link runPromptPolicyPlanning}, {@link applyContextGc},\n * {@link correlatePromptPolicyWithContextGc}, {@link runPromptEnforcement},\n * {@link enqueueRelevanceCuration}, {@link maybeDrainBrainCuration}) are invoked from the session's\n * context transform as one-line delegations, so the transform stays the single owner of the pass\n * ordering. This controller reaches {@link MemoryController} functionality only through\n * {@link ContextPipelineDeps.getMemoryManager} (never imports it), and MemoryController never imports\n * the pipeline — keeping the transform the one place the two subsystems meet.\n */\n\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport {\n\ttype CompactionEntry,\n\testimateContextTokens,\n\tgetLatestCompactionEntry,\n\ttype SessionEntry,\n\ttype SessionManager,\n\tTokenBudget,\n} from \"@caupulican/pi-agent-core/node\";\nimport type { Api, AssistantMessage, Model, Usage } from \"@caupulican/pi-ai\";\nimport type { IsolatedCompletionOptions, IsolatedCompletionResult } from \"./agent-session.ts\";\nimport { BrainCurator, type CurationTelemetrySnapshot, preDigestConversationText } from \"./context/brain-curator.ts\";\nimport { type ArtifactStore, createFileArtifactStore } from \"./context/context-artifacts.ts\";\nimport { type ContextAuditReport, runContextAudit } from \"./context/context-audit.ts\";\nimport { enforcePromptPolicy, type PromptEnforcementReport } from \"./context/context-prompt-enforcement.ts\";\nimport {\n\tcorrelateWithContextGc,\n\ttype PromptPolicyGcCorrelationReport,\n\ttype PromptPolicyShadowReport,\n\tplanPromptPolicy,\n} from \"./context/context-prompt-policy.ts\";\nimport { acquireContextStoreRetention, type ContextStoreRetentionLease } from \"./context/context-store-retention.ts\";\nimport { applyContextGc, type ContextGcReport } from \"./context-gc.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { evaluateSurfaceFitness } from \"./model-router/fitness-gate.ts\";\nimport { FitnessStore } from \"./models/fitness-store.ts\";\nimport { HF_TRANSFORMERS_PROVIDER, OLLAMA_PROVIDER } from \"./models/local-registration.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nfunction joinTextPrefix(content: readonly unknown[], maxChars = Number.POSITIVE_INFINITY): string {\n\tlet found = false;\n\tlet text = \"\";\n\tfor (const part of content) {\n\t\tif (typeof part !== \"object\" || part === null || (part as { type?: unknown }).type !== \"text\") continue;\n\t\tconst blockText = (part as { text?: unknown }).text;\n\t\tif (typeof blockText !== \"string\") continue;\n\t\tif (!found) {\n\t\t\tfound = true;\n\t\t\tif (blockText.length >= maxChars) return blockText.slice(0, maxChars);\n\t\t\ttext = blockText;\n\t\t\tcontinue;\n\t\t}\n\t\tconst available = maxChars - text.length;\n\t\tif (available <= 0) return text;\n\t\tif (available === 1) return `${text}\\n`;\n\t\tconst remaining = available - 1;\n\t\ttext += `\\n${blockText.slice(0, remaining)}`;\n\t\tif (blockText.length >= remaining) return text;\n\t}\n\treturn text;\n}\n\n/** Latest user prompt text in the provider-visible array. */\nexport function latestUserPromptText(messages: AgentMessage[], maxChars = Number.POSITIVE_INFINITY): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (!message || message.role !== \"user\") continue;\n\t\tif (typeof message.content === \"string\") {\n\t\t\treturn message.content.length > maxChars ? message.content.slice(0, maxChars) : message.content;\n\t\t}\n\t\tconst text = joinTextPrefix(message.content, maxChars);\n\t\tif (text.length > 0) return text;\n\t}\n\treturn \"\";\n}\n\n/** Read a packed artifact-producing tool result's `details.artifactId`, if present, without `any`. */\nfunction extractArtifactId(message: AgentMessage | undefined): string | undefined {\n\tif (!message || message.role !== \"toolResult\") return undefined;\n\tconst details = (message as { details?: unknown }).details;\n\tif (typeof details !== \"object\" || details === null) return undefined;\n\tconst artifactId = (details as { artifactId?: unknown }).artifactId;\n\treturn typeof artifactId === \"string\" ? artifactId : undefined;\n}\n\nexport interface ContextPipelineDeps {\n\t/** Current turn index, stamped into audit/policy/enforcement reports. */\n\tgetTurnIndex(): number;\n\t/** Session log: audit lookup, gc/artifact storage dirs, curation entries, token-estimate compaction anchor. */\n\tgetSessionManager(): SessionManager;\n\t/** Context-gc / prompt-enforcement / curation settings (all opt-in gates). */\n\tgetSettingsManager(): SettingsManager;\n\t/** Resolves a configured curation model pattern against configured auth. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Foreground model currently executing the transformed request. */\n\tgetModel(): Model<Api> | undefined;\n\t/** Root dir the host-keyed {@link FitnessStore} and per-session gc/artifact storage live under. */\n\tgetAgentDir(): string;\n\t/** Workspace root, passed to the context-gc pass. */\n\tgetCwd(): string;\n\t/** Currently-active tool names — enforcement checks whether artifact_retrieve is a live affordance. */\n\tgetActiveToolNames(): string[];\n\t/** A disposed session must never persist a curation/pre-digest entry. */\n\tisDisposed(): boolean;\n\t/** The live memory manager — the active providers' page markers feed the semantic-gc scan. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Roll a curation drain's spawned usage into session accounting (idempotent per reportId). */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\t/** One-shot LLM call fully isolated from the main session — the curation/pre-digest execution primitive. */\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n}\n\nexport class ContextPipeline {\n\tprivate _latestContextGcReport: ContextGcReport | undefined = undefined;\n\t/** Brain-curation sidecar (design: brain-context-curation-design.md). Inert unless the\n\t * contextPolicy.curation setting is enabled AND the model passes the digest fitness gate. */\n\tprivate readonly _brainCurator = new BrainCurator();\n\tprivate _lastCurationSkipReason: string | undefined = undefined;\n\tprivate _lastPreDigestSkipReason: string | undefined = undefined;\n\tprivate _toolArtifactStore: ArtifactStore | undefined = undefined;\n\tprivate _contextStoreRetentionLease: ContextStoreRetentionLease | undefined;\n\tprivate _latestContextAuditReport: ContextAuditReport | undefined = undefined;\n\tprivate _latestPromptPolicyReport: PromptPolicyShadowReport | undefined = undefined;\n\tprivate _latestPromptPolicyGcCorrelation: PromptPolicyGcCorrelationReport | undefined = undefined;\n\tprivate _latestPromptEnforcementReport: PromptEnforcementReport | undefined = undefined;\n\tprivate readonly _tokenBudget = new TokenBudget();\n\tprivate _hasTokenBudgetAnchor = false;\n\tprivate _tokenBudgetAnchorCompactionId: string | undefined = undefined;\n\tprivate _lastTokenBudgetAnchorKey: string | undefined = undefined;\n\t/** Incremental current-branch lookup used by the per-turn audit. It retains only tool calls\n\t * still present in the provider-visible context, so compaction also bounds this cache. */\n\tprivate _sessionEntryLookupCache: { leafId: string | null; byToolCallId: Map<string, string> } | undefined =\n\t\tundefined;\n\n\tprivate readonly deps: ContextPipelineDeps;\n\n\tconstructor(deps: ContextPipelineDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tprivate _ensureContextStoreRetention(): ContextStoreRetentionLease {\n\t\tif (!this._contextStoreRetentionLease) {\n\t\t\tthis._contextStoreRetentionLease = acquireContextStoreRetention(\n\t\t\t\tthis.deps.getAgentDir(),\n\t\t\t\tthis.deps.getSessionManager().getSessionId(),\n\t\t\t);\n\t\t}\n\t\treturn this._contextStoreRetentionLease;\n\t}\n\n\tprivate _contextGcStorageDir(): string {\n\t\treturn this._ensureContextStoreRetention().gcDir;\n\t}\n\n\tprivate _toolArtifactsDir(): string {\n\t\treturn this._ensureContextStoreRetention().artifactsDir;\n\t}\n\n\t/**\n\t * Session-scoped, filesystem-backed artifact store for first-capture-then-bound tool\n\t * output (grep/find/run_toolkit_script -- see tool-output-artifacts.md). Lazily created and\n\t * cached so every tool construction in this session shares one store instance.\n\t *\n\t * `packToolOutput()` registers a reference (the packing tool call's id) at pack time\n\t * and fails closed, so packed artifacts are never prematurely collected.\n\t * `_releaseGcPackedArtifactReferences()` (called from `applyContextGc()`) releases\n\t * that reference once context-gc packs the result out of live context, and\n\t * opportunistically reclaims now-unreferenced artifacts via `cleanup()`.\n\t * Cross-session retention is enforced when either payload store is first used. Active\n\t * sessions hold PID-marked leases; inactive stores are pruned by age, count, and bytes.\n\t */\n\tgetToolArtifactStore(): ArtifactStore {\n\t\tthis._toolArtifactStore ??= createFileArtifactStore({ baseDir: this._toolArtifactsDir() });\n\t\treturn this._toolArtifactStore;\n\t}\n\n\t/**\n\t * Best-effort final sweep of any already-released (zero-reference) tool-output artifact at\n\t * session dispose. Reads the field (not the getter) so a session that never packed anything\n\t * doesn't force-create a store/dir just to sweep it.\n\t */\n\tcleanupToolArtifactStoreOnDispose(): void {\n\t\tthis._toolArtifactStore?.cleanup();\n\t\tthis._contextStoreRetentionLease?.release();\n\t\tthis._contextStoreRetentionLease = undefined;\n\t}\n\n\t/**\n\t * Map tool-result call ids to persisted session-entry ids. Linear branch growth is handled\n\t * incrementally by walking only entries appended since the cached leaf; a branch switch falls\n\t * back to one full rebuild so lookups never leak entries from the abandoned branch.\n\t */\n\tprivate _getLatestCompactionEntry(): CompactionEntry | null {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst indexedSessionManager = sessionManager as unknown as {\n\t\t\tgetLeafId?: () => string | null;\n\t\t\tgetEntry?: (id: string) => SessionEntry | undefined;\n\t\t};\n\t\tconst getLeafId = indexedSessionManager.getLeafId?.bind(sessionManager);\n\t\tconst getEntry = indexedSessionManager.getEntry?.bind(sessionManager);\n\t\tconst leafId = getLeafId?.();\n\t\tif (getLeafId && getEntry && leafId !== undefined) {\n\t\t\tlet currentId = leafId;\n\t\t\twhile (currentId !== null) {\n\t\t\t\tconst entry = getEntry(currentId);\n\t\t\t\tif (!entry) break;\n\t\t\t\tif (entry.type === \"compaction\") return entry;\n\t\t\t\tcurrentId = entry.parentId;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\treturn getLatestCompactionEntry(sessionManager.getBranch());\n\t}\n\n\tprivate _buildSessionEntryIdLookup(\n\t\twantedToolCallIds: ReadonlySet<string>,\n\t): (toolCallId: string) => string | undefined {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst indexedSessionManager = sessionManager as unknown as {\n\t\t\tgetLeafId?: () => string | null;\n\t\t\tgetEntry?: (id: string) => SessionEntry | undefined;\n\t\t};\n\t\tconst getLeafId = indexedSessionManager.getLeafId?.bind(sessionManager);\n\t\tconst getEntry = indexedSessionManager.getEntry?.bind(sessionManager);\n\t\tconst leafId = getLeafId?.();\n\t\tconst cached = this._sessionEntryLookupCache;\n\t\tif (cached) {\n\t\t\tfor (const toolCallId of cached.byToolCallId.keys()) {\n\t\t\t\tif (!wantedToolCallIds.has(toolCallId)) cached.byToolCallId.delete(toolCallId);\n\t\t\t}\n\t\t}\n\t\tif (getLeafId && getEntry && leafId !== undefined) {\n\t\t\tif (cached?.leafId === leafId) {\n\t\t\t\treturn (toolCallId) => cached.byToolCallId.get(toolCallId);\n\t\t\t}\n\t\t\tif (cached) {\n\t\t\t\tconst appendedEntries: SessionEntry[] = [];\n\t\t\t\tlet cursor = leafId;\n\t\t\t\twhile (cursor !== null && cursor !== cached.leafId) {\n\t\t\t\t\tconst entry = getEntry(cursor);\n\t\t\t\t\tif (!entry) break;\n\t\t\t\t\tappendedEntries.push(entry);\n\t\t\t\t\tcursor = entry.parentId;\n\t\t\t\t}\n\t\t\t\tif (cursor === cached.leafId) {\n\t\t\t\t\tfor (let index = appendedEntries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = appendedEntries[index];\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tentry.type === \"message\" &&\n\t\t\t\t\t\t\tentry.message.role === \"toolResult\" &&\n\t\t\t\t\t\t\twantedToolCallIds.has(entry.message.toolCallId)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tcached.byToolCallId.set(entry.message.toolCallId, entry.id);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcached.leafId = leafId;\n\t\t\t\t\treturn (toolCallId) => cached.byToolCallId.get(toolCallId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst byToolCallId = new Map<string, string>();\n\t\tfor (const entry of sessionManager.getBranch()) {\n\t\t\tif (\n\t\t\t\tentry.type === \"message\" &&\n\t\t\t\tentry.message.role === \"toolResult\" &&\n\t\t\t\twantedToolCallIds.has(entry.message.toolCallId)\n\t\t\t) {\n\t\t\t\tbyToolCallId.set(entry.message.toolCallId, entry.id);\n\t\t\t}\n\t\t}\n\t\tif (leafId !== undefined) this._sessionEntryLookupCache = { leafId, byToolCallId };\n\t\treturn (toolCallId) => byToolCallId.get(toolCallId);\n\t}\n\n\t/**\n\t * Phase 1 observe-only audit pass (see context/context-audit.ts): converts live\n\t * toolResult messages into ContextItems and runs the existing retention/hard-constraint\n\t * evaluators over them, storing the latest deterministic report for tests/debugging.\n\t * Read-only with respect to messages, the transcript, and artifact references -- uses\n\t * `_toolArtifactStore` (the field), not `getToolArtifactStore()` (the getter), so a\n\t * session that never packed anything doesn't force-create a store/dir just to audit.\n\t * Never throws into a live turn: any failure degrades to an empty report.\n\t */\n\trunContextAudit(messages: AgentMessage[]): ContextAuditReport {\n\t\ttry {\n\t\t\tconst wantedToolCallIds = new Set(\n\t\t\t\tmessages.filter((message) => message.role === \"toolResult\").map((message) => message.toolCallId),\n\t\t\t);\n\t\t\tconst report = runContextAudit(messages, {\n\t\t\t\tturnIndex: this.deps.getTurnIndex(),\n\t\t\t\tartifactStore: this._toolArtifactStore,\n\t\t\t\tsessionEntryIdForToolCallId: this._buildSessionEntryIdLookup(wantedToolCallIds),\n\t\t\t});\n\t\t\tthis._latestContextAuditReport = report;\n\t\t\treturn report;\n\t\t} catch {\n\t\t\tconst report: ContextAuditReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestContextAuditReport = report;\n\t\t\treturn report;\n\t\t}\n\t}\n\n\t/**\n\t * Read-only inspection of the context audit. With `messages`, recomputes fresh against\n\t * the given array (still no mutation of messages/transcript/artifact refs); without,\n\t * returns the last report computed during a real transform pass.\n\t */\n\tgetContextAuditReport(messages?: AgentMessage[]): ContextAuditReport {\n\t\tif (messages) return this.runContextAudit(messages);\n\t\treturn this._latestContextAuditReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t}\n\n\t/**\n\t * Observe-first shadow/planning pass (see context/context-prompt-policy.ts): re-shapes\n\t * the audit report into a per-item policy plan whose `appliedAction` is always\n\t * \"keep_raw\" -- this never enforces anything, it only records what the policy engine\n\t * would say. Never throws into a live turn: any failure degrades to an empty report.\n\t */\n\trunPromptPolicyPlanning(auditReport: ContextAuditReport): PromptPolicyShadowReport {\n\t\ttry {\n\t\t\tconst report = planPromptPolicy(auditReport);\n\t\t\tthis._latestPromptPolicyReport = report;\n\t\t\treturn report;\n\t\t} catch {\n\t\t\tconst report: PromptPolicyShadowReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestPromptPolicyReport = report;\n\t\t\treturn report;\n\t\t}\n\t}\n\n\t/**\n\t * Read-only inspection of the shadow policy plan. With `messages`, recomputes fresh\n\t * (audit + plan) against the given array; without, returns the last plan computed\n\t * during a real transform pass. Never mutates messages/transcript/artifact refs.\n\t */\n\tgetPromptPolicyReport(messages?: AgentMessage[]): PromptPolicyShadowReport {\n\t\tif (messages) return this.runPromptPolicyPlanning(this.runContextAudit(messages));\n\t\treturn this._latestPromptPolicyReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t}\n\n\t/**\n\t * Report-only correlation between the shadow plan just computed this turn and what the\n\t * legacy context-gc pass actually packed. Runs after `applyContextGc()` has already\n\t * produced its report; never influences context-gc itself. Never throws into a live\n\t * turn: any failure degrades to an empty correlation.\n\t */\n\tcorrelatePromptPolicyWithContextGc(gcReport: ContextGcReport): void {\n\t\tconst shadowReport = this._latestPromptPolicyReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\ttry {\n\t\t\tthis._latestPromptPolicyGcCorrelation = correlateWithContextGc(shadowReport, gcReport);\n\t\t} catch {\n\t\t\tthis._latestPromptPolicyGcCorrelation = { turnIndex: this.deps.getTurnIndex(), entries: [] };\n\t\t}\n\t}\n\n\t/** Read-only inspection of the latest shadow-plan/legacy-gc correlation, for tests/debugging. */\n\tgetPromptPolicyGcCorrelation(): PromptPolicyGcCorrelationReport {\n\t\treturn this._latestPromptPolicyGcCorrelation ?? { turnIndex: this.deps.getTurnIndex(), entries: [] };\n\t}\n\n\t/**\n\t * First enforcement pilot (see context/context-prompt-enforcement.ts): opt-in,\n\t * default-disabled stub-in-place of stale artifact-backed tool_output results in the\n\t * provider-visible message array only. Runs on `messages` AFTER context-gc has already\n\t * produced its own result, so legacy context-gc's own packing/reporting is completely\n\t * unaffected by this pass -- it only ever acts on messages gc left untouched this turn.\n\t * Never throws into a live turn: any failure degrades to returning `messages` unchanged.\n\t */\n\trunPromptEnforcement(\n\t\tmessages: AgentMessage[],\n\t\tshadowReport: PromptPolicyShadowReport,\n\t): { messages: AgentMessage[]; report: PromptEnforcementReport } {\n\t\ttry {\n\t\t\tconst persistedSettings = this.deps.getSettingsManager().getContextPromptEnforcementSettings();\n\t\t\tconst curationEnabled = this.deps.getSettingsManager().getContextCurationSettings().enabled;\n\t\t\tconst settings = {\n\t\t\t\t...persistedSettings,\n\t\t\t\t// Runtime fact, never assumed: artifact_retrieve is a companion affordance\n\t\t\t\t// (auto-activated alongside grep/find), not a default/global tool, so active\n\t\t\t\t// tools can differ turn to turn -- see context-prompt-enforcement.ts's doc\n\t\t\t\t// comment on why this is checked separately from hasAvailableRetrievalPath.\n\t\t\t\tretrievalToolAvailable: this.deps.getActiveToolNames().includes(\"artifact_retrieve\"),\n\t\t\t\tbrainRelevance: curationEnabled ? (itemId: string) => this._brainCurator.getRelevance(itemId) : undefined,\n\t\t\t};\n\t\t\tconst result = enforcePromptPolicy(messages, shadowReport, settings);\n\t\t\tthis._latestPromptEnforcementReport = result.report;\n\t\t\treturn result;\n\t\t} catch {\n\t\t\tconst report: PromptEnforcementReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestPromptEnforcementReport = report;\n\t\t\treturn { messages, report };\n\t\t}\n\t}\n\n\t/**\n\t * Enqueue relevance-scoring jobs for stale, artifact-backed tool outputs the enforcement\n\t * pilot could act on. Pure queueing — the verdicts only ever take effect through the\n\t * asymmetric advisory lever inside enforcePromptPolicy. Never throws into a turn.\n\t */\n\tenqueueRelevanceCuration(messages: AgentMessage[], shadowReport: PromptPolicyShadowReport): void {\n\t\ttry {\n\t\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\t\tif (!settings.enabled) return;\n\t\t\tconst goal = latestUserPromptText(messages, 400);\n\t\t\tfor (const item of shadowReport.items) {\n\t\t\t\tif (!item.hasAvailableRetrievalPath) continue;\n\t\t\t\tconst message = messages[item.messageIndex];\n\t\t\t\tif (!message || message.role !== \"toolResult\" || message.toolCallId !== item.toolCallId) continue;\n\t\t\t\tif (message.isError) continue;\n\t\t\t\tconst details = message.details as\n\t\t\t\t\t| { contextGc?: { packed?: unknown }; promptPolicy?: { enforced?: unknown } }\n\t\t\t\t\t| undefined;\n\t\t\t\tif (details?.contextGc?.packed === true || details?.promptPolicy?.enforced === true) continue;\n\t\t\t\tconst text = joinTextPrefix(message.content, 4000);\n\t\t\t\tif (text.length === 0) continue;\n\t\t\t\tthis._brainCurator.enqueue({ kind: \"relevance\", key: item.itemId, content: text, goal });\n\t\t\t}\n\t\t} catch {\n\t\t\t// curation is a sidecar; it must never disrupt a turn\n\t\t}\n\t}\n\n\t/**\n\t * Drain gate: settings on, model configured+authed, and the model has PASSED the digest\n\t * fitness probe on THIS host (design: unfit or unprobed models are refused with a visible\n\t * reason, never silently degraded). Fire-and-forget; never throws into a turn.\n\t */\n\t/**\n\t * Resolve the curation model IFF every gate passes: setting enabled, model configured,\n\t * resolvable+authed, and digest-fitness-proven on THIS host (canonical \"provider/id\" ref —\n\t * runModelFitness stores reports under it, while settings.model may be a bare id or pattern).\n\t * Sets _lastCurationSkipReason on refusal; never throws.\n\t */\n\tprivate _effectiveContextWindowFromFitness(model: Model<Api>): number {\n\t\tconst registered = model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n\t\tconst capacity = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t.getForHost()\n\t\t\t.find((entry) => entry.model === `${model.provider}/${model.id}`)?.report.capacity?.servedContextWindow;\n\t\treturn capacity && capacity > 0 ? Math.min(registered, capacity) : registered;\n\t}\n\n\tresolveCurationModelIfFit(): Model<Api> | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\tif (!settings.enabled) {\n\t\t\t// Never surface a stale refusal reason for a feature the user has since disabled.\n\t\t\tthis._lastCurationSkipReason = undefined;\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!settings.model) {\n\t\t\tthis._lastCurationSkipReason = \"curation_model_unset\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst resolved = resolveCliModel({ cliModel: settings.model, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model || !this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) {\n\t\t\tthis._lastCurationSkipReason = \"curation_model_unresolved\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst canonicalRef = `${resolved.model.provider}/${resolved.model.id}`;\n\t\tconst fitness = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t.getForHost()\n\t\t\t.find((entry) => entry.model === canonicalRef);\n\t\tconst verdict = evaluateSurfaceFitness(\"curation\", fitness?.report);\n\t\tif (!verdict.fit) {\n\t\t\tthis._lastCurationSkipReason =\n\t\t\t\tverdict.reason === \"unprobed\" ? \"curation_model_unprobed\" : \"curation_model_digest_unfit\";\n\t\t\treturn undefined;\n\t\t}\n\t\tthis._lastCurationSkipReason = undefined;\n\t\treturn resolved.model;\n\t}\n\n\tmaybeDrainBrainCuration(): void {\n\t\ttry {\n\t\t\tif (!this._brainCurator.hasWork() || this._brainCurator.isDraining) return;\n\t\t\tconst model = this.resolveCurationModelIfFit();\n\t\t\tif (!model) return;\n\t\t\tconst foregroundModel = this.deps.getModel();\n\t\t\tconst foregroundIsManagedLocal =\n\t\t\t\tforegroundModel?.provider === OLLAMA_PROVIDER || foregroundModel?.provider === HF_TRANSFORMERS_PROVIDER;\n\t\t\tconst curatorIsManagedLocal =\n\t\t\t\tmodel.provider === OLLAMA_PROVIDER || model.provider === HF_TRANSFORMERS_PROVIDER;\n\t\t\tif (foregroundIsManagedLocal && curatorIsManagedLocal) {\n\t\t\t\t// Local foreground accuracy/latency wins. A fire-and-forget curator can otherwise reach\n\t\t\t\t// a single-parallel server first and make the user's request wait behind sidecar work.\n\t\t\t\tthis._lastCurationSkipReason = \"curation_deferred_for_local_foreground\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\t\tvoid this._drainBrainCuration(model, settings.maxJobsPerTurn);\n\t\t} catch {\n\t\t\t// curation is a sidecar; it must never disrupt a turn\n\t\t}\n\t}\n\n\t/**\n\t * Compaction pre-digest gate (design surface 3): everything the drain gate requires PLUS a\n\t * RUNTIME reliability proof — the curator must have run >=5 jobs on this session with a parse\n\t * failure rate <=5% before it is trusted to pre-digest compaction input. Returns undefined\n\t * (verbatim compaction, byte-for-byte today's behavior) whenever any gate refuses.\n\t */\n\tbuildCompactionPreDigest(): ((text: string, signal?: AbortSignal) => Promise<string>) | undefined {\n\t\ttry {\n\t\t\tconst model = this.resolveCurationModelIfFit();\n\t\t\tif (!model) return undefined;\n\t\t\tconst telemetry = this._brainCurator.telemetry();\n\t\t\tif (telemetry.jobsRun < 5 || telemetry.parseFailures / telemetry.jobsRun > 0.05) {\n\t\t\t\tthis._lastPreDigestSkipReason = \"curation_predigest_reliability_unproven\";\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tthis._lastPreDigestSkipReason = undefined;\n\t\t\treturn async (text, signal) => {\n\t\t\t\tconst effectiveWindow = this._effectiveContextWindowFromFitness(model);\n\t\t\t\tconst chunkChars = Number.isFinite(effectiveWindow)\n\t\t\t\t\t? Math.max(1_000, Math.floor((effectiveWindow - 1024) * 4))\n\t\t\t\t\t: undefined;\n\t\t\t\tconst result = await preDigestConversationText({\n\t\t\t\t\ttext,\n\t\t\t\t\tsignal,\n\t\t\t\t\tchunkChars,\n\t\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal: chunkSignal }) => {\n\t\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\t\t\tmaxTokens: 512,\n\t\t\t\t\t\t\tsignal: chunkSignal,\n\t\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (!this.deps.isDisposed() && result.totalChunks > 0) {\n\t\t\t\t\tthis.deps.getSessionManager().appendCustomEntry(\"brain-curation-predigest\", {\n\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\ttotalChunks: result.totalChunks,\n\t\t\t\t\t\tdigested: result.digested,\n\t\t\t\t\t\tfailed: result.failed,\n\t\t\t\t\t\tcharsBefore: text.length,\n\t\t\t\t\t\tcharsAfter: result.text.length,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn result.text;\n\t\t\t};\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate async _drainBrainCuration(model: Model<Api>, maxJobs: number): Promise<void> {\n\t\ttry {\n\t\t\t// ACCUMULATE across all drained jobs (the drain runs the completer once PER job) —\n\t\t\t// keeping only the last job's usage would under-report every multi-job drain.\n\t\t\tlet spentUsage: AssistantMessage[\"usage\"] | undefined;\n\t\t\tconst results = await this._brainCurator.drain({\n\t\t\t\tmaxJobs,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\t\tmaxTokens: 256,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Both curation system prompts are static — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tconst usage = completion.usage;\n\t\t\t\t\tif (!spentUsage) {\n\t\t\t\t\t\tspentUsage = structuredClone(usage);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tspentUsage.input += usage.input;\n\t\t\t\t\t\tspentUsage.output += usage.output;\n\t\t\t\t\t\tspentUsage.cacheRead += usage.cacheRead;\n\t\t\t\t\t\tspentUsage.cacheWrite += usage.cacheWrite;\n\t\t\t\t\t\tspentUsage.totalTokens += usage.totalTokens;\n\t\t\t\t\t\tspentUsage.cost.input += usage.cost.input;\n\t\t\t\t\t\tspentUsage.cost.output += usage.cost.output;\n\t\t\t\t\t\tspentUsage.cost.cacheRead += usage.cost.cacheRead;\n\t\t\t\t\t\tspentUsage.cost.cacheWrite += usage.cost.cacheWrite;\n\t\t\t\t\t\tspentUsage.cost.total += usage.cost.total;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\t\t\t// Honest accounting even for free local models: token visibility is the contract.\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, { label: \"context-curator\" });\n\t\t\t}\n\t\t\tif (this.deps.isDisposed() || results.length === 0) return;\n\t\t\tthis.deps.getSessionManager().appendCustomEntry(\"brain-curation\", {\n\t\t\t\tversion: 1,\n\t\t\t\tresults: results.map((result) => ({\n\t\t\t\t\tkey: result.key,\n\t\t\t\t\tkind: result.kind,\n\t\t\t\t\tok: result.ok,\n\t\t\t\t\tms: result.ms,\n\t\t\t\t\t...(result.digest !== undefined ? { digest: result.digest } : {}),\n\t\t\t\t\t...(result.relevant !== undefined ? { relevant: result.relevant, confidence: result.confidence } : {}),\n\t\t\t\t})),\n\t\t\t\ttelemetry: this._brainCurator.telemetry(),\n\t\t\t});\n\t\t} catch {\n\t\t\t// curation is a sidecar; it must never disrupt a turn\n\t\t}\n\t}\n\n\t/** Curation status for diagnostics/dashboard: settings, live telemetry, last refusal reason. */\n\tgetContextCurationStatus(): {\n\t\tenabled: boolean;\n\t\tmodel?: string;\n\t\ttelemetry: CurationTelemetrySnapshot;\n\t\tlastSkipReason?: string;\n\t\tlastPreDigestSkipReason?: string;\n\t} {\n\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\treturn {\n\t\t\tenabled: settings.enabled,\n\t\t\tmodel: settings.model,\n\t\t\ttelemetry: this._brainCurator.telemetry(),\n\t\t\tlastSkipReason: this._lastCurationSkipReason,\n\t\t\tlastPreDigestSkipReason: this._lastPreDigestSkipReason,\n\t\t};\n\t}\n\n\t/** Read-only inspection of the latest prompt-enforcement report, for tests/debugging. */\n\tgetPromptEnforcementReport(): PromptEnforcementReport {\n\t\treturn this._latestPromptEnforcementReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t}\n\n\tapplyContextGc(\n\t\tmessages: AgentMessage[],\n\t\twritePayloads: boolean,\n\t): { messages: AgentMessage[]; report: ContextGcReport } {\n\t\ttry {\n\t\t\tconst settings = this.deps.getSettingsManager().getContextGcSettings();\n\t\t\t// Merge the ACTIVE memory providers' own page markers (e.g. transcript-recall's\n\t\t\t// \"<memory_context\") into the semantic-memory marker list. The settings default is\n\t\t\t// provider-agnostic and non-empty, so without this merge the recall pages the bundled\n\t\t\t// default provider actually emits are never recognized as semantic-memory pages and\n\t\t\t// accumulate raw for the life of the session — the exact growth Bug #7 GC exists to stop.\n\t\t\tconst providerMarkers = this.deps.getMemoryManager().getContextMarkers();\n\t\t\tconst curationSettings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\t\tconst result = applyContextGc(messages, {\n\t\t\t\t...settings,\n\t\t\t\tsemanticMemory: {\n\t\t\t\t\t...settings.semanticMemory,\n\t\t\t\t\tmarkers: [...new Set([...settings.semanticMemory.markers, ...providerMarkers])],\n\t\t\t\t},\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tstorageDir: this._contextGcStorageDir(),\n\t\t\t\twritePayloads,\n\t\t\t\tcuration: curationSettings.enabled\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tresolveDigest: (digestKey) => {\n\t\t\t\t\t\t\t\tconst digest = this._brainCurator.getDigest(digestKey);\n\t\t\t\t\t\t\t\t// Count serves on the REAL per-turn pass only, never the report path.\n\t\t\t\t\t\t\t\tif (digest !== undefined && writePayloads) this._brainCurator.noteDigestServed();\n\t\t\t\t\t\t\t\treturn digest;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t// Only the real per-turn pass enqueues work; the read-only report path\n\t\t\t\t\t\t\t// (writePayloads=false) stays side-effect free.\n\t\t\t\t\t\t\tonPacked: writePayloads\n\t\t\t\t\t\t\t\t? (record, originalText) => {\n\t\t\t\t\t\t\t\t\t\tthis._brainCurator.enqueue({\n\t\t\t\t\t\t\t\t\t\t\tkind: \"stub_digest\",\n\t\t\t\t\t\t\t\t\t\t\tkey: record.key ?? record.toolCallId,\n\t\t\t\t\t\t\t\t\t\t\tcontent: originalText,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t\tthis._latestContextGcReport = result.report;\n\t\t\t// Only release/reclaim on the real per-turn pass (writePayloads=true), never on\n\t\t\t// the read-only status-report path (getContextGcReport with writePayloads=false),\n\t\t\t// so merely inspecting the report can't have side effects.\n\t\t\tif (writePayloads && result.report.packedCount > 0) {\n\t\t\t\tthis._releaseGcPackedArtifactReferences(messages, result.report);\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch {\n\t\t\tconst report: ContextGcReport = {\n\t\t\t\tenabled: false,\n\t\t\t\tpackedCount: 0,\n\t\t\t\toriginalTokens: 0,\n\t\t\t\tpackedTokens: 0,\n\t\t\t\tsavedTokens: 0,\n\t\t\t\trecords: [],\n\t\t\t};\n\t\t\tthis._latestContextGcReport = report;\n\t\t\treturn { messages, report };\n\t\t}\n\t}\n\n\t/**\n\t * Reference-release + cleanup lifecycle: once context-gc has packed an artifact-producing\n\t * tool result (grep/find/run_toolkit_script) out of the live prompt (the message is no longer current/active working\n\t * context -- see contracts-and-retention.md's \"ephemeral\"/\"expired\" retention\n\t * classes), release the pack-time reference `packToolOutput()` registered for it, and\n\t * opportunistically reclaim now-unreferenced artifacts. This is the other half of the\n\t * D2b-1 gate: artifacts were being registered but never released, so they accumulated\n\t * for the life of the session.\n\t *\n\t * `record.toolCallId` (from context-gc's packed record) is exactly the holder id\n\t * `packToolOutput()` used when it called `addReference()` -- both trace back to the\n\t * same tool call's id -- so no separate bookkeeping is needed to find it.\n\t */\n\tprivate _releaseGcPackedArtifactReferences(messages: AgentMessage[], report: ContextGcReport): void {\n\t\tconst store = this._toolArtifactStore;\n\t\tif (!store) return; // no store was ever constructed, so nothing could have been packed to one\n\n\t\tlet releasedAny = false;\n\t\tfor (const record of report.records) {\n\t\t\tif (record.toolName !== \"grep\" && record.toolName !== \"find\" && record.toolName !== \"run_toolkit_script\")\n\t\t\t\tcontinue;\n\t\t\tconst artifactId = extractArtifactId(messages[record.messageIndex]);\n\t\t\tif (!artifactId) continue;\n\t\t\tif (store.removeReference(artifactId, record.toolCallId)) releasedAny = true;\n\t\t}\n\t\t// Cleanup only runs immediately after a release actually happened in this pass, so\n\t\t// a long session doesn't re-scan the artifact directory on every turn once nothing\n\t\t// new became eligible for release.\n\t\tif (releasedAny) store.cleanup();\n\t}\n\n\tgetContextGcReport(messages?: AgentMessage[]): ContextGcReport {\n\t\tif (messages) return this.applyContextGc(messages, false).report;\n\t\treturn (\n\t\t\tthis._latestContextGcReport ?? {\n\t\t\t\tenabled: this.deps.getSettingsManager().getContextGcSettings().enabled,\n\t\t\t\tpackedCount: 0,\n\t\t\t\toriginalTokens: 0,\n\t\t\t\tpackedTokens: 0,\n\t\t\t\tsavedTokens: 0,\n\t\t\t\trecords: [],\n\t\t\t}\n\t\t);\n\t}\n\n\tobserveProviderUsage(messages: AgentMessage[], usageMessage: AssistantMessage): void {\n\t\tif (usageMessage.stopReason === \"error\" || usageMessage.stopReason === \"aborted\") {\n\t\t\treturn;\n\t\t}\n\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null || messages[estimate.lastUsageIndex] !== usageMessage) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst compactionEntry = this._getLatestCompactionEntry();\n\t\tif (!compactionEntry) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst compactionTimestamp = new Date(compactionEntry.timestamp).getTime();\n\t\tif (usageMessage.timestamp <= compactionTimestamp) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst coveredChars = estimateConversationChars(messages, 0, estimate.lastUsageIndex + 1);\n\t\tif (estimate.usageTokens <= 0 || coveredChars <= 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst anchorKey = `${compactionEntry.id}:${usageMessage.timestamp}:${estimate.usageTokens}:${coveredChars}`;\n\t\tif (anchorKey === this._lastTokenBudgetAnchorKey) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._tokenBudget.anchor(estimate.usageTokens, coveredChars);\n\t\tthis._hasTokenBudgetAnchor = true;\n\t\tthis._tokenBudgetAnchorCompactionId = compactionEntry.id;\n\t\tthis._lastTokenBudgetAnchorKey = anchorKey;\n\t}\n\n\testimateCurrentContextTokens(messages: AgentMessage[]): number {\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) {\n\t\t\treturn this._tokenBudget.estimateDelta(estimateConversationChars(messages));\n\t\t}\n\n\t\tconst usageMessage = messages[estimate.lastUsageIndex];\n\t\tconst compactionEntry = this._getLatestCompactionEntry();\n\t\tif (usageMessage?.role !== \"assistant\" || !compactionEntry) {\n\t\t\treturn estimate.tokens;\n\t\t}\n\t\tconst usageTimestamp = (usageMessage as AssistantMessage).timestamp;\n\t\tconst compactionTimestamp = new Date(compactionEntry.timestamp).getTime();\n\t\tif (usageTimestamp <= compactionTimestamp) {\n\t\t\treturn this._tokenBudget.estimateDelta(estimateConversationChars(messages));\n\t\t}\n\n\t\tif (!this._hasTokenBudgetAnchor || this._tokenBudgetAnchorCompactionId !== compactionEntry.id) {\n\t\t\treturn estimate.tokens;\n\t\t}\n\n\t\tconst deltaChars = estimateConversationChars(messages, estimate.lastUsageIndex + 1, messages.length);\n\t\treturn this._tokenBudget.current(deltaChars, estimate.tokens);\n\t}\n}\n\n/**\n * Estimate covered characters from the provider-visible context messages.\n */\nfunction estimateConversationChars(messages: AgentMessage[], start = 0, end = messages.length): number {\n\tlet total = 0;\n\tfor (let index = Math.max(0, start); index < Math.min(messages.length, end); index++) {\n\t\tconst message = messages[index];\n\t\tif (!message) continue;\n\t\tconst rawContent = (message as { content?: unknown }).content;\n\t\tif (typeof rawContent === \"string\") {\n\t\t\ttotal += rawContent.length;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!Array.isArray(rawContent)) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const block of rawContent) {\n\t\t\tif (typeof block === \"string\") {\n\t\t\t\ttotal += block.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!block || typeof block !== \"object\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (typeof (block as { text?: unknown }).text === \"string\") {\n\t\t\t\ttotal += (block as { text?: string }).text?.length ?? 0;\n\t\t\t}\n\t\t\tif (typeof (block as { thinking?: unknown }).thinking === \"string\") {\n\t\t\t\ttotal += (block as { thinking?: string }).thinking?.length ?? 0;\n\t\t\t}\n\t\t}\n\t}\n\treturn total;\n}\n"]}
@@ -22,7 +22,6 @@
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 { join } from "node:path";
26
25
  import { estimateContextTokens, getLatestCompactionEntry, TokenBudget, } from "@caupulican/pi-agent-core/node";
27
26
  import { BrainCurator, preDigestConversationText } from "./context/brain-curator.js";
28
27
  import { createFileArtifactStore } from "./context/context-artifacts.js";
@@ -113,15 +112,16 @@ export class ContextPipeline {
113
112
  this.deps = deps;
114
113
  }
115
114
  _ensureContextStoreRetention() {
116
- this._contextStoreRetentionLease ??= acquireContextStoreRetention(this.deps.getAgentDir(), this.deps.getSessionManager().getSessionId());
115
+ if (!this._contextStoreRetentionLease) {
116
+ this._contextStoreRetentionLease = acquireContextStoreRetention(this.deps.getAgentDir(), this.deps.getSessionManager().getSessionId());
117
+ }
118
+ return this._contextStoreRetentionLease;
117
119
  }
118
120
  _contextGcStorageDir() {
119
- this._ensureContextStoreRetention();
120
- return join(this.deps.getAgentDir(), "context-gc", this.deps.getSessionManager().getSessionId());
121
+ return this._ensureContextStoreRetention().gcDir;
121
122
  }
122
123
  _toolArtifactsDir() {
123
- this._ensureContextStoreRetention();
124
- return join(this.deps.getAgentDir(), "context-artifacts", this.deps.getSessionManager().getSessionId());
124
+ return this._ensureContextStoreRetention().artifactsDir;
125
125
  }
126
126
  /**
127
127
  * Session-scoped, filesystem-backed artifact store for first-capture-then-bound tool