pi-braid 0.0.0-stage → 0.40.0

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 (1011) hide show
  1. package/AGENTS.md +195 -0
  2. package/CONTRIBUTING.md +302 -0
  3. package/LICENSE +21 -0
  4. package/README.md +260 -2
  5. package/TOOLS.md +147 -0
  6. package/dist/extensions/cognitive/mars-reflector/index.d.ts +82 -0
  7. package/dist/extensions/cognitive/mars-reflector/index.js +327 -0
  8. package/dist/extensions/cognitive/metacognition/handlers/claim-verification.d.ts +23 -0
  9. package/dist/extensions/cognitive/metacognition/handlers/claim-verification.js +233 -0
  10. package/dist/extensions/cognitive/metacognition/handlers/finalize.d.ts +27 -0
  11. package/dist/extensions/cognitive/metacognition/handlers/finalize.js +557 -0
  12. package/dist/extensions/cognitive/metacognition/handlers/hypothesize.d.ts +19 -0
  13. package/dist/extensions/cognitive/metacognition/handlers/hypothesize.js +291 -0
  14. package/dist/extensions/cognitive/metacognition/handlers/scoring.d.ts +28 -0
  15. package/dist/extensions/cognitive/metacognition/handlers/scoring.js +173 -0
  16. package/dist/extensions/cognitive/metacognition/handlers/think-budget.d.ts +85 -0
  17. package/dist/extensions/cognitive/metacognition/handlers/think-budget.js +164 -0
  18. package/dist/extensions/cognitive/metacognition/handlers/think.d.ts +27 -0
  19. package/dist/extensions/cognitive/metacognition/handlers/think.js +374 -0
  20. package/dist/extensions/cognitive/metacognition/handlers/verify.d.ts +53 -0
  21. package/dist/extensions/cognitive/metacognition/handlers/verify.js +321 -0
  22. package/dist/extensions/cognitive/metacognition/index.d.ts +10 -0
  23. package/dist/extensions/cognitive/metacognition/index.js +90 -0
  24. package/dist/extensions/cognitive/reasoning/index.d.ts +43 -0
  25. package/dist/extensions/cognitive/reasoning/index.js +99 -0
  26. package/dist/extensions/cognitive/sycophancy-detector/index.d.ts +16 -0
  27. package/dist/extensions/cognitive/sycophancy-detector/index.js +203 -0
  28. package/dist/extensions/cognitive/topic-drift/index.d.ts +51 -0
  29. package/dist/extensions/cognitive/topic-drift/index.js +346 -0
  30. package/dist/extensions/cognitive/turn-outcome/index.d.ts +35 -0
  31. package/dist/extensions/cognitive/turn-outcome/index.js +163 -0
  32. package/dist/extensions/context-management/index.d.ts +77 -0
  33. package/dist/extensions/context-management/index.js +339 -0
  34. package/dist/extensions/core/agent-environment/index.d.ts +30 -0
  35. package/dist/extensions/core/agent-environment/index.js +89 -0
  36. package/dist/extensions/core/polyfill/index.d.ts +28 -0
  37. package/dist/extensions/core/polyfill/index.js +474 -0
  38. package/dist/extensions/core/prompt-builder/awareness-whisper.d.ts +74 -0
  39. package/dist/extensions/core/prompt-builder/awareness-whisper.js +116 -0
  40. package/dist/extensions/core/prompt-builder/context-section.d.ts +41 -0
  41. package/dist/extensions/core/prompt-builder/context-section.js +101 -0
  42. package/dist/extensions/core/prompt-builder/custom-sections.d.ts +21 -0
  43. package/dist/extensions/core/prompt-builder/custom-sections.js +11 -0
  44. package/dist/extensions/core/prompt-builder/external-tool-guidelines.d.ts +23 -0
  45. package/dist/extensions/core/prompt-builder/external-tool-guidelines.js +37 -0
  46. package/dist/extensions/core/prompt-builder/identity.d.ts +33 -0
  47. package/dist/extensions/core/prompt-builder/identity.js +77 -0
  48. package/dist/extensions/core/prompt-builder/index.d.ts +33 -0
  49. package/dist/extensions/core/prompt-builder/index.js +496 -0
  50. package/dist/extensions/core/prompt-builder/inspect.d.ts +58 -0
  51. package/dist/extensions/core/prompt-builder/inspect.js +182 -0
  52. package/dist/extensions/core/prompt-builder/instance-composition.d.ts +101 -0
  53. package/dist/extensions/core/prompt-builder/instance-composition.js +416 -0
  54. package/dist/extensions/core/prompt-builder/memory-section.d.ts +20 -0
  55. package/dist/extensions/core/prompt-builder/memory-section.js +60 -0
  56. package/dist/extensions/core/prompt-builder/pi-reference-section.d.ts +17 -0
  57. package/dist/extensions/core/prompt-builder/pi-reference-section.js +11 -0
  58. package/dist/extensions/core/prompt-builder/project-docs-section.d.ts +42 -0
  59. package/dist/extensions/core/prompt-builder/project-docs-section.js +72 -0
  60. package/dist/extensions/core/prompt-builder/section-parity.d.ts +36 -0
  61. package/dist/extensions/core/prompt-builder/section-parity.js +66 -0
  62. package/dist/extensions/core/prompt-builder/section-publish.d.ts +30 -0
  63. package/dist/extensions/core/prompt-builder/section-publish.js +16 -0
  64. package/dist/extensions/core/prompt-builder/section.d.ts +75 -0
  65. package/dist/extensions/core/prompt-builder/section.js +127 -0
  66. package/dist/extensions/core/prompt-builder/surface-discipline-section.d.ts +18 -0
  67. package/dist/extensions/core/prompt-builder/surface-discipline-section.js +20 -0
  68. package/dist/extensions/core/prompt-builder/system-info-tool.d.ts +27 -0
  69. package/dist/extensions/core/prompt-builder/system-info-tool.js +67 -0
  70. package/dist/extensions/core/prompt-builder/tool-description-trim.d.ts +56 -0
  71. package/dist/extensions/core/prompt-builder/tool-description-trim.js +129 -0
  72. package/dist/extensions/core/prompt-builder/tool-guidelines.d.ts +80 -0
  73. package/dist/extensions/core/prompt-builder/tool-guidelines.js +179 -0
  74. package/dist/extensions/core/prompt-builder/tool-pipelines.d.ts +50 -0
  75. package/dist/extensions/core/prompt-builder/tool-pipelines.js +69 -0
  76. package/dist/extensions/core/prompt-builder/top-level-extensions.d.ts +44 -0
  77. package/dist/extensions/core/prompt-builder/top-level-extensions.js +300 -0
  78. package/dist/extensions/core/skills-tool/auto-inject.d.ts +333 -0
  79. package/dist/extensions/core/skills-tool/auto-inject.js +817 -0
  80. package/dist/extensions/core/skills-tool/index.d.ts +56 -0
  81. package/dist/extensions/core/skills-tool/index.js +200 -0
  82. package/dist/extensions/core/skills-tool/loading-guidance.d.ts +50 -0
  83. package/dist/extensions/core/skills-tool/loading-guidance.js +87 -0
  84. package/dist/extensions/core/skills-tool/session-records.d.ts +114 -0
  85. package/dist/extensions/core/skills-tool/session-records.js +268 -0
  86. package/dist/extensions/core/skills-tool/skill-triggers.d.ts +48 -0
  87. package/dist/extensions/core/skills-tool/skill-triggers.js +113 -0
  88. package/dist/extensions/enforcement/detection/malformed.d.ts +9 -0
  89. package/dist/extensions/enforcement/detection/malformed.js +30 -0
  90. package/dist/extensions/enforcement/detection/verification.d.ts +10 -0
  91. package/dist/extensions/enforcement/detection/verification.js +34 -0
  92. package/dist/extensions/enforcement/enforcement-types.d.ts +33 -0
  93. package/dist/extensions/enforcement/enforcement-types.js +24 -0
  94. package/dist/extensions/enforcement/handler-registry.d.ts +12 -0
  95. package/dist/extensions/enforcement/handler-registry.js +196 -0
  96. package/dist/extensions/enforcement/handlers/analysis/bpe-handler.d.ts +10 -0
  97. package/dist/extensions/enforcement/handlers/analysis/bpe-handler.js +37 -0
  98. package/dist/extensions/enforcement/handlers/analysis/dreamer-handler.d.ts +6 -0
  99. package/dist/extensions/enforcement/handlers/analysis/dreamer-handler.js +60 -0
  100. package/dist/extensions/enforcement/handlers/analysis/drift-handler.d.ts +6 -0
  101. package/dist/extensions/enforcement/handlers/analysis/drift-handler.js +75 -0
  102. package/dist/extensions/enforcement/handlers/analysis/feedback-handler.d.ts +6 -0
  103. package/dist/extensions/enforcement/handlers/analysis/feedback-handler.js +19 -0
  104. package/dist/extensions/enforcement/handlers/analysis/mars-handler.d.ts +14 -0
  105. package/dist/extensions/enforcement/handlers/analysis/mars-handler.js +99 -0
  106. package/dist/extensions/enforcement/handlers/analysis/reflection-handler.d.ts +6 -0
  107. package/dist/extensions/enforcement/handlers/analysis/reflection-handler.js +16 -0
  108. package/dist/extensions/enforcement/handlers/blocking.d.ts +16 -0
  109. package/dist/extensions/enforcement/handlers/blocking.js +33 -0
  110. package/dist/extensions/enforcement/handlers/message-analysis.d.ts +25 -0
  111. package/dist/extensions/enforcement/handlers/message-analysis.js +70 -0
  112. package/dist/extensions/enforcement/handlers/orphan-chains.d.ts +14 -0
  113. package/dist/extensions/enforcement/handlers/orphan-chains.js +44 -0
  114. package/dist/extensions/enforcement/handlers/over-correction-gate.d.ts +73 -0
  115. package/dist/extensions/enforcement/handlers/over-correction-gate.js +565 -0
  116. package/dist/extensions/enforcement/handlers/probe-handler.d.ts +31 -0
  117. package/dist/extensions/enforcement/handlers/probe-handler.js +111 -0
  118. package/dist/extensions/enforcement/handlers/register-adherence-meter.d.ts +52 -0
  119. package/dist/extensions/enforcement/handlers/register-adherence-meter.js +158 -0
  120. package/dist/extensions/enforcement/handlers/register-agent-end-api-error.d.ts +3 -0
  121. package/dist/extensions/enforcement/handlers/register-agent-end-api-error.js +69 -0
  122. package/dist/extensions/enforcement/handlers/register-input-handler.d.ts +10 -0
  123. package/dist/extensions/enforcement/handlers/register-input-handler.js +35 -0
  124. package/dist/extensions/enforcement/handlers/register-message-end.d.ts +6 -0
  125. package/dist/extensions/enforcement/handlers/register-message-end.js +388 -0
  126. package/dist/extensions/enforcement/handlers/register-post-cycle-hygiene.d.ts +25 -0
  127. package/dist/extensions/enforcement/handlers/register-post-cycle-hygiene.js +143 -0
  128. package/dist/extensions/enforcement/handlers/register-session-compact.d.ts +50 -0
  129. package/dist/extensions/enforcement/handlers/register-session-compact.js +207 -0
  130. package/dist/extensions/enforcement/handlers/register-session-shutdown-resumption.d.ts +21 -0
  131. package/dist/extensions/enforcement/handlers/register-session-shutdown-resumption.js +116 -0
  132. package/dist/extensions/enforcement/handlers/register-session-shutdown.d.ts +6 -0
  133. package/dist/extensions/enforcement/handlers/register-session-shutdown.js +38 -0
  134. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.d.ts +34 -0
  135. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.js +240 -0
  136. package/dist/extensions/enforcement/handlers/register-session-start.d.ts +16 -0
  137. package/dist/extensions/enforcement/handlers/register-session-start.js +198 -0
  138. package/dist/extensions/enforcement/handlers/register-tool-call.d.ts +6 -0
  139. package/dist/extensions/enforcement/handlers/register-tool-call.js +132 -0
  140. package/dist/extensions/enforcement/handlers/register-tool-result-formatting.d.ts +18 -0
  141. package/dist/extensions/enforcement/handlers/register-tool-result-formatting.js +56 -0
  142. package/dist/extensions/enforcement/handlers/register-tool-result.d.ts +6 -0
  143. package/dist/extensions/enforcement/handlers/register-tool-result.js +91 -0
  144. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.d.ts +35 -0
  145. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +385 -0
  146. package/dist/extensions/enforcement/handlers/routing-handler.d.ts +42 -0
  147. package/dist/extensions/enforcement/handlers/routing-handler.js +135 -0
  148. package/dist/extensions/enforcement/handlers/tool-tracker.d.ts +9 -0
  149. package/dist/extensions/enforcement/handlers/tool-tracker.js +122 -0
  150. package/dist/extensions/enforcement/handlers/turn-analysis.d.ts +41 -0
  151. package/dist/extensions/enforcement/handlers/turn-analysis.js +109 -0
  152. package/dist/extensions/enforcement/handlers/turn-end-handler.d.ts +9 -0
  153. package/dist/extensions/enforcement/handlers/turn-end-handler.js +451 -0
  154. package/dist/extensions/enforcement/index.d.ts +15 -0
  155. package/dist/extensions/enforcement/index.js +22 -0
  156. package/dist/extensions/enforcement/judge-utils.d.ts +73 -0
  157. package/dist/extensions/enforcement/judge-utils.js +83 -0
  158. package/dist/extensions/enforcement/nudge-manager.d.ts +106 -0
  159. package/dist/extensions/enforcement/nudge-manager.js +203 -0
  160. package/dist/extensions/enforcement/self-state-claims.d.ts +79 -0
  161. package/dist/extensions/enforcement/self-state-claims.js +167 -0
  162. package/dist/extensions/enforcement/session-health.d.ts +107 -0
  163. package/dist/extensions/enforcement/session-health.js +251 -0
  164. package/dist/extensions/enforcement/signals.d.ts +54 -0
  165. package/dist/extensions/enforcement/signals.js +47 -0
  166. package/dist/extensions/enforcement/similarity.d.ts +16 -0
  167. package/dist/extensions/enforcement/similarity.js +64 -0
  168. package/dist/extensions/enforcement/state.d.ts +40 -0
  169. package/dist/extensions/enforcement/state.js +74 -0
  170. package/dist/extensions/enforcement/substate/context-hygiene-state.d.ts +88 -0
  171. package/dist/extensions/enforcement/substate/context-hygiene-state.js +119 -0
  172. package/dist/extensions/enforcement/substate/error-tracking-state.d.ts +20 -0
  173. package/dist/extensions/enforcement/substate/error-tracking-state.js +37 -0
  174. package/dist/extensions/enforcement/substate/memory-hygiene-state.d.ts +24 -0
  175. package/dist/extensions/enforcement/substate/memory-hygiene-state.js +37 -0
  176. package/dist/extensions/enforcement/substate/session-state.d.ts +34 -0
  177. package/dist/extensions/enforcement/substate/session-state.js +45 -0
  178. package/dist/extensions/enforcement/substate/thought-chain-state.d.ts +23 -0
  179. package/dist/extensions/enforcement/substate/thought-chain-state.js +43 -0
  180. package/dist/extensions/enforcement/substate/tool-tracking-state.d.ts +71 -0
  181. package/dist/extensions/enforcement/substate/tool-tracking-state.js +99 -0
  182. package/dist/extensions/enforcement/substate/verification-judge-state.d.ts +17 -0
  183. package/dist/extensions/enforcement/substate/verification-judge-state.js +39 -0
  184. package/dist/extensions/enforcement/task-evidence.d.ts +108 -0
  185. package/dist/extensions/enforcement/task-evidence.js +335 -0
  186. package/dist/extensions/enforcement/types.d.ts +35 -0
  187. package/dist/extensions/enforcement/types.js +5 -0
  188. package/dist/extensions/enforcement/validation.d.ts +12 -0
  189. package/dist/extensions/enforcement/validation.js +151 -0
  190. package/dist/extensions/enforcement/verification-judge.d.ts +110 -0
  191. package/dist/extensions/enforcement/verification-judge.js +214 -0
  192. package/dist/extensions/enforcement/whisper.d.ts +46 -0
  193. package/dist/extensions/enforcement/whisper.js +104 -0
  194. package/dist/extensions/heartbeat/analytics/ab-variant.d.ts +19 -0
  195. package/dist/extensions/heartbeat/analytics/ab-variant.js +86 -0
  196. package/dist/extensions/heartbeat/analytics/core.d.ts +12 -0
  197. package/dist/extensions/heartbeat/analytics/core.js +201 -0
  198. package/dist/extensions/heartbeat/analytics/format.d.ts +7 -0
  199. package/dist/extensions/heartbeat/analytics/format.js +111 -0
  200. package/dist/extensions/heartbeat/analytics/index.d.ts +14 -0
  201. package/dist/extensions/heartbeat/analytics/index.js +352 -0
  202. package/dist/extensions/heartbeat/analytics/shared.d.ts +85 -0
  203. package/dist/extensions/heartbeat/analytics/shared.js +69 -0
  204. package/dist/extensions/heartbeat/heartbeat-scheduler/index.d.ts +31 -0
  205. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +881 -0
  206. package/dist/extensions/heartbeat/heartbeat-scheduler/meta-learning.d.ts +10 -0
  207. package/dist/extensions/heartbeat/heartbeat-scheduler/meta-learning.js +49 -0
  208. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/behavioral-drift.d.ts +17 -0
  209. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/behavioral-drift.js +161 -0
  210. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/budget.d.ts +13 -0
  211. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/budget.js +101 -0
  212. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/context-hygiene.d.ts +10 -0
  213. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/context-hygiene.js +221 -0
  214. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/evolver.d.ts +9 -0
  215. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/evolver.js +65 -0
  216. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/measurement.d.ts +8 -0
  217. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/measurement.js +32 -0
  218. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/recaller.d.ts +9 -0
  219. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/recaller.js +75 -0
  220. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/reflection-consolidator.d.ts +9 -0
  221. package/dist/extensions/heartbeat/heartbeat-scheduler/modules/reflection-consolidator.js +98 -0
  222. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +14 -0
  223. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +149 -0
  224. package/dist/extensions/heartbeat/heartbeat-scheduler/state.d.ts +22 -0
  225. package/dist/extensions/heartbeat/heartbeat-scheduler/state.js +82 -0
  226. package/dist/extensions/heartbeat/heartbeat-scheduler/types.d.ts +124 -0
  227. package/dist/extensions/heartbeat/heartbeat-scheduler/types.js +7 -0
  228. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.d.ts +52 -0
  229. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.js +83 -0
  230. package/dist/extensions/manifest.d.ts +32 -0
  231. package/dist/extensions/manifest.js +251 -0
  232. package/dist/extensions/memory/context-lifecycle/helpers.d.ts +55 -0
  233. package/dist/extensions/memory/context-lifecycle/helpers.js +142 -0
  234. package/dist/extensions/memory/context-lifecycle/index.d.ts +17 -0
  235. package/dist/extensions/memory/context-lifecycle/index.js +977 -0
  236. package/dist/extensions/memory/context-lifecycle/policy-engine.d.ts +50 -0
  237. package/dist/extensions/memory/context-lifecycle/policy-engine.js +196 -0
  238. package/dist/extensions/memory/context-lifecycle/signal-detector.d.ts +28 -0
  239. package/dist/extensions/memory/context-lifecycle/signal-detector.js +224 -0
  240. package/dist/extensions/memory/context-lifecycle/state.d.ts +98 -0
  241. package/dist/extensions/memory/context-lifecycle/state.js +90 -0
  242. package/dist/extensions/memory/context-lifecycle/types.d.ts +132 -0
  243. package/dist/extensions/memory/context-lifecycle/types.js +273 -0
  244. package/dist/extensions/memory/context-manager/analysis.d.ts +47 -0
  245. package/dist/extensions/memory/context-manager/analysis.js +264 -0
  246. package/dist/extensions/memory/context-manager/handlers/compaction-chunked.d.ts +159 -0
  247. package/dist/extensions/memory/context-manager/handlers/compaction-chunked.js +658 -0
  248. package/dist/extensions/memory/context-manager/handlers/compaction-retry.d.ts +29 -0
  249. package/dist/extensions/memory/context-manager/handlers/compaction-retry.js +410 -0
  250. package/dist/extensions/memory/context-manager/handlers/compaction-trace.d.ts +74 -0
  251. package/dist/extensions/memory/context-manager/handlers/compaction-trace.js +180 -0
  252. package/dist/extensions/memory/context-manager/handlers/compaction-watchdog.d.ts +69 -0
  253. package/dist/extensions/memory/context-manager/handlers/compaction-watchdog.js +297 -0
  254. package/dist/extensions/memory/context-manager/handlers/compaction.d.ts +37 -0
  255. package/dist/extensions/memory/context-manager/handlers/compaction.js +2150 -0
  256. package/dist/extensions/memory/context-manager/handlers/context-emergency.d.ts +124 -0
  257. package/dist/extensions/memory/context-manager/handlers/context-emergency.js +364 -0
  258. package/dist/extensions/memory/context-manager/handlers/events.d.ts +5 -0
  259. package/dist/extensions/memory/context-manager/handlers/events.js +314 -0
  260. package/dist/extensions/memory/context-manager/handlers/navigation.d.ts +5 -0
  261. package/dist/extensions/memory/context-manager/handlers/navigation.js +86 -0
  262. package/dist/extensions/memory/context-manager/handlers/offload.d.ts +94 -0
  263. package/dist/extensions/memory/context-manager/handlers/offload.js +248 -0
  264. package/dist/extensions/memory/context-manager/handlers/rotation.d.ts +6 -0
  265. package/dist/extensions/memory/context-manager/handlers/rotation.js +304 -0
  266. package/dist/extensions/memory/context-manager/handlers/shared.d.ts +410 -0
  267. package/dist/extensions/memory/context-manager/handlers/shared.js +579 -0
  268. package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.d.ts +55 -0
  269. package/dist/extensions/memory/context-manager/handlers/tool-batch-boundary.js +190 -0
  270. package/dist/extensions/memory/context-manager/handlers/toolresult-capture-cap.d.ts +21 -0
  271. package/dist/extensions/memory/context-manager/handlers/toolresult-capture-cap.js +155 -0
  272. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +90 -0
  273. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +1156 -0
  274. package/dist/extensions/memory/context-manager/handlers/tools/context-inspect.d.ts +16 -0
  275. package/dist/extensions/memory/context-manager/handlers/tools/context-inspect.js +276 -0
  276. package/dist/extensions/memory/context-manager/handlers/tools/context-navigate.d.ts +19 -0
  277. package/dist/extensions/memory/context-manager/handlers/tools/context-navigate.js +378 -0
  278. package/dist/extensions/memory/context-manager/handlers/tools/offload-recover.d.ts +13 -0
  279. package/dist/extensions/memory/context-manager/handlers/tools/offload-recover.js +181 -0
  280. package/dist/extensions/memory/context-manager/index.d.ts +3 -0
  281. package/dist/extensions/memory/context-manager/index.js +88 -0
  282. package/dist/extensions/memory/context-manager/pruning.d.ts +47 -0
  283. package/dist/extensions/memory/context-manager/pruning.js +406 -0
  284. package/dist/extensions/memory/context-manager/semantic-compress.d.ts +71 -0
  285. package/dist/extensions/memory/context-manager/semantic-compress.js +279 -0
  286. package/dist/extensions/memory/memory-agent-bridge/conflict-qa-tool.d.ts +20 -0
  287. package/dist/extensions/memory/memory-agent-bridge/conflict-qa-tool.js +71 -0
  288. package/dist/extensions/memory/memory-agent-bridge/explore-paths.d.ts +30 -0
  289. package/dist/extensions/memory/memory-agent-bridge/explore-paths.js +231 -0
  290. package/dist/extensions/memory/memory-agent-bridge/index.d.ts +28 -0
  291. package/dist/extensions/memory/memory-agent-bridge/index.js +124 -0
  292. package/dist/extensions/memory/memory-agent-bridge/memory-store-tool.d.ts +21 -0
  293. package/dist/extensions/memory/memory-agent-bridge/memory-store-tool.js +194 -0
  294. package/dist/extensions/memory/memory-agent-bridge/memory-tool.d.ts +22 -0
  295. package/dist/extensions/memory/memory-agent-bridge/memory-tool.js +548 -0
  296. package/dist/extensions/memory/scratchpad/format.d.ts +19 -0
  297. package/dist/extensions/memory/scratchpad/format.js +135 -0
  298. package/dist/extensions/memory/scratchpad/handlers.d.ts +53 -0
  299. package/dist/extensions/memory/scratchpad/handlers.js +469 -0
  300. package/dist/extensions/memory/scratchpad/index.d.ts +17 -0
  301. package/dist/extensions/memory/scratchpad/index.js +168 -0
  302. package/dist/extensions/memory/scratchpad/persistence.d.ts +46 -0
  303. package/dist/extensions/memory/scratchpad/persistence.js +343 -0
  304. package/dist/extensions/memory/scratchpad/types.d.ts +124 -0
  305. package/dist/extensions/memory/scratchpad/types.js +8 -0
  306. package/dist/extensions/memory/scratchpad/utils.d.ts +76 -0
  307. package/dist/extensions/memory/scratchpad/utils.js +236 -0
  308. package/dist/extensions/memory/session-recall/analyze.d.ts +58 -0
  309. package/dist/extensions/memory/session-recall/analyze.js +478 -0
  310. package/dist/extensions/memory/session-recall/context-aggregate.d.ts +117 -0
  311. package/dist/extensions/memory/session-recall/context-aggregate.js +315 -0
  312. package/dist/extensions/memory/session-recall/index.d.ts +29 -0
  313. package/dist/extensions/memory/session-recall/index.js +820 -0
  314. package/dist/extensions/memory/session-recall/query.d.ts +15 -0
  315. package/dist/extensions/memory/session-recall/query.js +38 -0
  316. package/dist/extensions/memory/session-recall/rank.d.ts +71 -0
  317. package/dist/extensions/memory/session-recall/rank.js +85 -0
  318. package/dist/extensions/memory/session-recall/search.d.ts +159 -0
  319. package/dist/extensions/memory/session-recall/search.js +682 -0
  320. package/dist/extensions/memory/session-recall/stats.d.ts +34 -0
  321. package/dist/extensions/memory/session-recall/stats.js +67 -0
  322. package/dist/extensions/memory/session-recall/text-utils.d.ts +82 -0
  323. package/dist/extensions/memory/session-recall/text-utils.js +184 -0
  324. package/dist/extensions/memory/three-memory-stores/episodes-disk.d.ts +43 -0
  325. package/dist/extensions/memory/three-memory-stores/episodes-disk.js +125 -0
  326. package/dist/extensions/memory/three-memory-stores/episodes.d.ts +46 -0
  327. package/dist/extensions/memory/three-memory-stores/episodes.js +299 -0
  328. package/dist/extensions/memory/three-memory-stores/handlers/whisper-recall.d.ts +25 -0
  329. package/dist/extensions/memory/three-memory-stores/handlers/whisper-recall.js +112 -0
  330. package/dist/extensions/memory/three-memory-stores/heuristics.d.ts +19 -0
  331. package/dist/extensions/memory/three-memory-stores/heuristics.js +89 -0
  332. package/dist/extensions/memory/three-memory-stores/index.d.ts +34 -0
  333. package/dist/extensions/memory/three-memory-stores/index.js +436 -0
  334. package/dist/extensions/memory/three-memory-stores/tool-reliability.d.ts +11 -0
  335. package/dist/extensions/memory/three-memory-stores/tool-reliability.js +38 -0
  336. package/dist/extensions/memory/three-memory-stores/types.d.ts +69 -0
  337. package/dist/extensions/memory/three-memory-stores/types.js +2 -0
  338. package/dist/extensions/memory/workspace-snapshot/index.d.ts +19 -0
  339. package/dist/extensions/memory/workspace-snapshot/index.js +363 -0
  340. package/dist/extensions/orchestrator/index.d.ts +19 -0
  341. package/dist/extensions/orchestrator/index.js +796 -0
  342. package/dist/extensions/scheduling/timer/fire-timing.d.ts +25 -0
  343. package/dist/extensions/scheduling/timer/fire-timing.js +28 -0
  344. package/dist/extensions/scheduling/timer/index.d.ts +102 -0
  345. package/dist/extensions/scheduling/timer/index.js +1143 -0
  346. package/dist/extensions/scheduling/timer/poller.d.ts +52 -0
  347. package/dist/extensions/scheduling/timer/poller.js +135 -0
  348. package/dist/extensions/scheduling/timer/recovery.d.ts +145 -0
  349. package/dist/extensions/scheduling/timer/recovery.js +445 -0
  350. package/dist/extensions/scheduling/timer/store-file.d.ts +38 -0
  351. package/dist/extensions/scheduling/timer/store-file.js +59 -0
  352. package/dist/extensions/scheduling/timer/timer-manager.d.ts +21 -0
  353. package/dist/extensions/scheduling/timer/timer-manager.js +143 -0
  354. package/dist/extensions/scheduling/timer/wake-retry.d.ts +455 -0
  355. package/dist/extensions/scheduling/timer/wake-retry.js +872 -0
  356. package/dist/extensions/self/auto-recovery/index.d.ts +20 -0
  357. package/dist/extensions/self/auto-recovery/index.js +89 -0
  358. package/dist/extensions/self/error-tracking/index.d.ts +3 -0
  359. package/dist/extensions/self/error-tracking/index.js +244 -0
  360. package/dist/extensions/self/health-maintenance/format.d.ts +3 -0
  361. package/dist/extensions/self/health-maintenance/format.js +60 -0
  362. package/dist/extensions/self/health-maintenance/handlers/session-health-tool.d.ts +23 -0
  363. package/dist/extensions/self/health-maintenance/handlers/session-health-tool.js +158 -0
  364. package/dist/extensions/self/health-maintenance/helpers.d.ts +25 -0
  365. package/dist/extensions/self/health-maintenance/helpers.js +67 -0
  366. package/dist/extensions/self/health-maintenance/index.d.ts +6 -0
  367. package/dist/extensions/self/health-maintenance/index.js +238 -0
  368. package/dist/extensions/self/health-maintenance/types.d.ts +14 -0
  369. package/dist/extensions/self/health-maintenance/types.js +2 -0
  370. package/dist/extensions/self/latent-activator/index.d.ts +12 -0
  371. package/dist/extensions/self/latent-activator/index.js +173 -0
  372. package/dist/extensions/self/latent-activator/mixes.d.ts +9 -0
  373. package/dist/extensions/self/latent-activator/mixes.js +20 -0
  374. package/dist/extensions/self/latent-activator/signals.d.ts +17 -0
  375. package/dist/extensions/self/latent-activator/signals.js +228 -0
  376. package/dist/extensions/self/latent-activator/state.d.ts +43 -0
  377. package/dist/extensions/self/latent-activator/state.js +59 -0
  378. package/dist/extensions/self/latent-activator/types.d.ts +8 -0
  379. package/dist/extensions/self/latent-activator/types.js +8 -0
  380. package/dist/extensions/self/watchdog/config.d.ts +4 -0
  381. package/dist/extensions/self/watchdog/config.js +79 -0
  382. package/dist/extensions/self/watchdog/engine.d.ts +256 -0
  383. package/dist/extensions/self/watchdog/engine.js +935 -0
  384. package/dist/extensions/self/watchdog/index.d.ts +23 -0
  385. package/dist/extensions/self/watchdog/index.js +485 -0
  386. package/dist/index.d.ts +25 -0
  387. package/dist/index.js +81 -0
  388. package/dist/lib/ai/consolidated-claim-critic.d.ts +84 -0
  389. package/dist/lib/ai/consolidated-claim-critic.js +191 -0
  390. package/dist/lib/ai/cost-report.d.ts +83 -0
  391. package/dist/lib/ai/cost-report.js +116 -0
  392. package/dist/lib/ai/critic-cache.d.ts +57 -0
  393. package/dist/lib/ai/critic-cache.js +100 -0
  394. package/dist/lib/ai/critic-fallbacks.d.ts +37 -0
  395. package/dist/lib/ai/critic-fallbacks.js +75 -0
  396. package/dist/lib/ai/critic-gate.d.ts +75 -0
  397. package/dist/lib/ai/critic-gate.js +81 -0
  398. package/dist/lib/ai/critic-helpers.d.ts +26 -0
  399. package/dist/lib/ai/critic-helpers.js +131 -0
  400. package/dist/lib/ai/critic-registry.d.ts +417 -0
  401. package/dist/lib/ai/critic-registry.js +639 -0
  402. package/dist/lib/ai/critic-stats.d.ts +78 -0
  403. package/dist/lib/ai/critic-stats.js +90 -0
  404. package/dist/lib/ai/judge-budget.d.ts +138 -0
  405. package/dist/lib/ai/judge-budget.js +143 -0
  406. package/dist/lib/ai/language-hint.d.ts +21 -0
  407. package/dist/lib/ai/language-hint.js +58 -0
  408. package/dist/lib/ai/llm-call.d.ts +141 -0
  409. package/dist/lib/ai/llm-call.js +745 -0
  410. package/dist/lib/ai/model-resolver.d.ts +90 -0
  411. package/dist/lib/ai/model-resolver.js +185 -0
  412. package/dist/lib/ai/models-init.d.ts +46 -0
  413. package/dist/lib/ai/models-init.js +65 -0
  414. package/dist/lib/ai/payload-hygiene.d.ts +74 -0
  415. package/dist/lib/ai/payload-hygiene.js +240 -0
  416. package/dist/lib/ai/post-loop-classify.d.ts +128 -0
  417. package/dist/lib/ai/post-loop-classify.js +87 -0
  418. package/dist/lib/ai/text-classifier.d.ts +142 -0
  419. package/dist/lib/ai/text-classifier.js +548 -0
  420. package/dist/lib/cognitive/hints.d.ts +33 -0
  421. package/dist/lib/cognitive/hints.js +223 -0
  422. package/dist/lib/cognitive/openspec.d.ts +29 -0
  423. package/dist/lib/cognitive/openspec.js +108 -0
  424. package/dist/lib/config/braid-paths.d.ts +188 -0
  425. package/dist/lib/config/braid-paths.js +340 -0
  426. package/dist/lib/config/braid-settings.d.ts +489 -0
  427. package/dist/lib/config/braid-settings.js +938 -0
  428. package/dist/lib/config/per-tool-settings.d.ts +95 -0
  429. package/dist/lib/config/per-tool-settings.js +161 -0
  430. package/dist/lib/config/session-profiles.d.ts +68 -0
  431. package/dist/lib/config/session-profiles.js +143 -0
  432. package/dist/lib/constants/injection-details.d.ts +30 -0
  433. package/dist/lib/constants/injection-details.js +30 -0
  434. package/dist/lib/constants/session-thresholds.d.ts +42 -0
  435. package/dist/lib/constants/session-thresholds.js +54 -0
  436. package/dist/lib/constants/tool-constants.d.ts +11 -0
  437. package/dist/lib/constants/tool-constants.js +12 -0
  438. package/dist/lib/core/event-names.d.ts +23 -0
  439. package/dist/lib/core/event-names.js +26 -0
  440. package/dist/lib/core/logger.d.ts +102 -0
  441. package/dist/lib/core/logger.js +274 -0
  442. package/dist/lib/detection/compression-strategy.d.ts +38 -0
  443. package/dist/lib/detection/compression-strategy.js +147 -0
  444. package/dist/lib/detection/consolidated-topic-critic.d.ts +51 -0
  445. package/dist/lib/detection/consolidated-topic-critic.js +132 -0
  446. package/dist/lib/detection/context-density.d.ts +70 -0
  447. package/dist/lib/detection/context-density.js +193 -0
  448. package/dist/lib/detection/context-thresholds.d.ts +88 -0
  449. package/dist/lib/detection/context-thresholds.js +107 -0
  450. package/dist/lib/detection/context-tiers.d.ts +80 -0
  451. package/dist/lib/detection/context-tiers.js +144 -0
  452. package/dist/lib/detection/context-usage.d.ts +75 -0
  453. package/dist/lib/detection/context-usage.js +209 -0
  454. package/dist/lib/detection/degradation-detector.d.ts +74 -0
  455. package/dist/lib/detection/degradation-detector.js +454 -0
  456. package/dist/lib/detection/test-burst.d.ts +77 -0
  457. package/dist/lib/detection/test-burst.js +126 -0
  458. package/dist/lib/detection/tool-loop-detector.d.ts +125 -0
  459. package/dist/lib/detection/tool-loop-detector.js +302 -0
  460. package/dist/lib/detection/topic-drift-detector.d.ts +80 -0
  461. package/dist/lib/detection/topic-drift-detector.js +252 -0
  462. package/dist/lib/enforcement/adherence-meter.d.ts +240 -0
  463. package/dist/lib/enforcement/adherence-meter.js +420 -0
  464. package/dist/lib/enforcement/turn-dedup.d.ts +106 -0
  465. package/dist/lib/enforcement/turn-dedup.js +195 -0
  466. package/dist/lib/errors/llm-error.d.ts +79 -0
  467. package/dist/lib/errors/llm-error.js +241 -0
  468. package/dist/lib/events/consolidation-channel.d.ts +109 -0
  469. package/dist/lib/events/consolidation-channel.js +374 -0
  470. package/dist/lib/events/consolidation-scoring.d.ts +59 -0
  471. package/dist/lib/events/consolidation-scoring.js +95 -0
  472. package/dist/lib/events/event-bus.d.ts +123 -0
  473. package/dist/lib/events/event-bus.js +108 -0
  474. package/dist/lib/events/event-types.d.ts +39 -0
  475. package/dist/lib/events/event-types.js +30 -0
  476. package/dist/lib/events/timer-bus.d.ts +21 -0
  477. package/dist/lib/events/timer-bus.js +41 -0
  478. package/dist/lib/events/timer-types.d.ts +64 -0
  479. package/dist/lib/events/timer-types.js +8 -0
  480. package/dist/lib/events/turn-end-coordinator.d.ts +52 -0
  481. package/dist/lib/events/turn-end-coordinator.js +89 -0
  482. package/dist/lib/harness/failure-trace-collector.d.ts +31 -0
  483. package/dist/lib/harness/failure-trace-collector.js +114 -0
  484. package/dist/lib/harness/index.d.ts +20 -0
  485. package/dist/lib/harness/index.js +21 -0
  486. package/dist/lib/harness/types.d.ts +85 -0
  487. package/dist/lib/harness/types.js +20 -0
  488. package/dist/lib/harness/weakness-miner.d.ts +29 -0
  489. package/dist/lib/harness/weakness-miner.js +165 -0
  490. package/dist/lib/memory/constants.d.ts +11 -0
  491. package/dist/lib/memory/constants.js +29 -0
  492. package/dist/lib/memory/index.d.ts +147 -0
  493. package/dist/lib/memory/index.js +564 -0
  494. package/dist/lib/memory/lifecycle.d.ts +50 -0
  495. package/dist/lib/memory/lifecycle.js +139 -0
  496. package/dist/lib/memory/past-insights.d.ts +35 -0
  497. package/dist/lib/memory/past-insights.js +189 -0
  498. package/dist/lib/memory/storage.d.ts +38 -0
  499. package/dist/lib/memory/storage.js +167 -0
  500. package/dist/lib/memory/store-lock.d.ts +23 -0
  501. package/dist/lib/memory/store-lock.js +69 -0
  502. package/dist/lib/memory/store-merge.d.ts +38 -0
  503. package/dist/lib/memory/store-merge.js +73 -0
  504. package/dist/lib/memory/types.d.ts +65 -0
  505. package/dist/lib/memory/types.js +5 -0
  506. package/dist/lib/memory/utils.d.ts +35 -0
  507. package/dist/lib/memory/utils.js +156 -0
  508. package/dist/lib/memory/write-log.d.ts +85 -0
  509. package/dist/lib/memory/write-log.js +124 -0
  510. package/dist/lib/memory/write-quality.d.ts +197 -0
  511. package/dist/lib/memory/write-quality.js +314 -0
  512. package/dist/lib/orchestrator/branch.d.ts +63 -0
  513. package/dist/lib/orchestrator/branch.js +192 -0
  514. package/dist/lib/orchestrator/index.d.ts +14 -0
  515. package/dist/lib/orchestrator/index.js +11 -0
  516. package/dist/lib/orchestrator/locks.d.ts +46 -0
  517. package/dist/lib/orchestrator/locks.js +122 -0
  518. package/dist/lib/orchestrator/slop-scanner.d.ts +31 -0
  519. package/dist/lib/orchestrator/slop-scanner.js +207 -0
  520. package/dist/lib/orchestrator/workers.d.ts +453 -0
  521. package/dist/lib/orchestrator/workers.js +1001 -0
  522. package/dist/lib/public.d.ts +18 -0
  523. package/dist/lib/public.js +23 -0
  524. package/dist/lib/reasoning/advice-tracker.d.ts +51 -0
  525. package/dist/lib/reasoning/advice-tracker.js +177 -0
  526. package/dist/lib/reasoning/belief-policy-engine.d.ts +48 -0
  527. package/dist/lib/reasoning/belief-policy-engine.js +268 -0
  528. package/dist/lib/reasoning/belief-types.d.ts +32 -0
  529. package/dist/lib/reasoning/belief-types.js +8 -0
  530. package/dist/lib/reasoning/classifier-offline.d.ts +72 -0
  531. package/dist/lib/reasoning/classifier-offline.js +75 -0
  532. package/dist/lib/reasoning/dreamer.d.ts +37 -0
  533. package/dist/lib/reasoning/dreamer.js +169 -0
  534. package/dist/lib/reasoning/nudge-analytics.d.ts +18 -0
  535. package/dist/lib/reasoning/nudge-analytics.js +62 -0
  536. package/dist/lib/reasoning/policy-rules.d.ts +18 -0
  537. package/dist/lib/reasoning/policy-rules.js +153 -0
  538. package/dist/lib/reasoning/reasoning-metrics.d.ts +42 -0
  539. package/dist/lib/reasoning/reasoning-metrics.js +174 -0
  540. package/dist/lib/reasoning/reasoning-summary.d.ts +34 -0
  541. package/dist/lib/reasoning/reasoning-summary.js +122 -0
  542. package/dist/lib/reasoning/tool-usage-analyzer.d.ts +50 -0
  543. package/dist/lib/reasoning/tool-usage-analyzer.js +188 -0
  544. package/dist/lib/state/async-storage.d.ts +52 -0
  545. package/dist/lib/state/async-storage.js +171 -0
  546. package/dist/lib/state/extension-state.d.ts +184 -0
  547. package/dist/lib/state/extension-state.js +373 -0
  548. package/dist/lib/state/global-state.d.ts +358 -0
  549. package/dist/lib/state/global-state.js +741 -0
  550. package/dist/lib/state/metacognitive-state.d.ts +21 -0
  551. package/dist/lib/state/metacognitive-state.js +50 -0
  552. package/dist/lib/state/session-manager.d.ts +32 -0
  553. package/dist/lib/state/session-manager.js +11 -0
  554. package/dist/lib/state/session-start-queue.d.ts +42 -0
  555. package/dist/lib/state/session-start-queue.js +105 -0
  556. package/dist/lib/state/state-checkpoint.d.ts +72 -0
  557. package/dist/lib/state/state-checkpoint.js +252 -0
  558. package/dist/lib/state/telegram-poller-liveness.d.ts +54 -0
  559. package/dist/lib/state/telegram-poller-liveness.js +67 -0
  560. package/dist/lib/state/tool-provenance.d.ts +22 -0
  561. package/dist/lib/state/tool-provenance.js +25 -0
  562. package/dist/lib/state/workspace-snapshot.d.ts +111 -0
  563. package/dist/lib/state/workspace-snapshot.js +372 -0
  564. package/dist/lib/store/belief-store.d.ts +112 -0
  565. package/dist/lib/store/belief-store.js +252 -0
  566. package/dist/lib/store/bidirectional-verifier.d.ts +87 -0
  567. package/dist/lib/store/bidirectional-verifier.js +242 -0
  568. package/dist/lib/store/claim-tracker.d.ts +66 -0
  569. package/dist/lib/store/claim-tracker.js +276 -0
  570. package/dist/lib/store/conflict-qa.d.ts +96 -0
  571. package/dist/lib/store/conflict-qa.js +283 -0
  572. package/dist/lib/store/evidence-pool.d.ts +185 -0
  573. package/dist/lib/store/evidence-pool.js +598 -0
  574. package/dist/lib/telemetry/context-heartbeat.d.ts +122 -0
  575. package/dist/lib/telemetry/context-heartbeat.js +449 -0
  576. package/dist/lib/telemetry/drift-signals.d.ts +46 -0
  577. package/dist/lib/telemetry/drift-signals.js +75 -0
  578. package/dist/lib/telemetry/rss-telemetry.d.ts +41 -0
  579. package/dist/lib/telemetry/rss-telemetry.js +53 -0
  580. package/dist/lib/types/episode-types.d.ts +31 -0
  581. package/dist/lib/types/episode-types.js +9 -0
  582. package/dist/lib/types/standard-result.d.ts +32 -0
  583. package/dist/lib/types/standard-result.js +22 -0
  584. package/dist/lib/utils/async-fs.d.ts +17 -0
  585. package/dist/lib/utils/async-fs.js +22 -0
  586. package/dist/lib/utils/bounded.d.ts +38 -0
  587. package/dist/lib/utils/bounded.js +59 -0
  588. package/dist/lib/utils/dedup.d.ts +40 -0
  589. package/dist/lib/utils/dedup.js +43 -0
  590. package/dist/lib/utils/error-guard.d.ts +15 -0
  591. package/dist/lib/utils/error-guard.js +22 -0
  592. package/dist/lib/utils/extension-utils.d.ts +36 -0
  593. package/dist/lib/utils/extension-utils.js +65 -0
  594. package/dist/lib/utils/extract-json.d.ts +23 -0
  595. package/dist/lib/utils/extract-json.js +90 -0
  596. package/dist/lib/utils/file-mutation-queue.d.ts +33 -0
  597. package/dist/lib/utils/file-mutation-queue.js +150 -0
  598. package/dist/lib/utils/filter-safe-to-remove.d.ts +26 -0
  599. package/dist/lib/utils/filter-safe-to-remove.js +256 -0
  600. package/dist/lib/utils/format-tool-result.d.ts +47 -0
  601. package/dist/lib/utils/format-tool-result.js +88 -0
  602. package/dist/lib/utils/id.d.ts +44 -0
  603. package/dist/lib/utils/id.js +59 -0
  604. package/dist/lib/utils/injection-tracker.d.ts +317 -0
  605. package/dist/lib/utils/injection-tracker.js +840 -0
  606. package/dist/lib/utils/local-time.d.ts +57 -0
  607. package/dist/lib/utils/local-time.js +181 -0
  608. package/dist/lib/utils/memory-fence.d.ts +55 -0
  609. package/dist/lib/utils/memory-fence.js +66 -0
  610. package/dist/lib/utils/sop-extractor.d.ts +75 -0
  611. package/dist/lib/utils/sop-extractor.js +259 -0
  612. package/dist/lib/utils/sop-suggestion.d.ts +34 -0
  613. package/dist/lib/utils/sop-suggestion.js +336 -0
  614. package/dist/lib/utils/wake-gate.d.ts +151 -0
  615. package/dist/lib/utils/wake-gate.js +265 -0
  616. package/dist/lib/utils/whisper-format.d.ts +95 -0
  617. package/dist/lib/utils/whisper-format.js +115 -0
  618. package/dist/lib/verification/coordination-checker.d.ts +72 -0
  619. package/dist/lib/verification/coordination-checker.js +126 -0
  620. package/dist/loader/api.d.ts +19 -0
  621. package/dist/loader/api.js +114 -0
  622. package/dist/loader/loader.d.ts +85 -0
  623. package/dist/loader/loader.js +534 -0
  624. package/docs/BEGINNERS.md +144 -0
  625. package/docs/COMPACTION-LOSS-INVESTIGATION.md +179 -0
  626. package/docs/CONTEXT-MAP.md +220 -0
  627. package/docs/CONTEXT-POLICY.md +86 -0
  628. package/docs/HISTORY.md +110 -0
  629. package/docs/LOCAL_DEV.md +246 -0
  630. package/docs/ROADMAP.md +107 -0
  631. package/docs/SETUP.md +459 -0
  632. package/package.json +97 -4
  633. package/skills/agent-testing/SKILL.md +214 -0
  634. package/skills/braid-reference/SKILL.md +88 -0
  635. package/skills/code-refactoring/SKILL.md +211 -0
  636. package/skills/code-search/SKILL.md +14 -0
  637. package/skills/documentation/SKILL.md +89 -0
  638. package/skills/dox/AGENTS.md.template +83 -0
  639. package/skills/dox/SKILL.md +86 -0
  640. package/skills/healthcheck/SKILL.md +65 -0
  641. package/skills/herdr-topology/SKILL.md +269 -0
  642. package/skills/meta-cognition/SKILL.md +24 -0
  643. package/skills/meta-improvement/SKILL.md +180 -0
  644. package/skills/misdirection-audit/SKILL.md +66 -0
  645. package/skills/pi-reference/SKILL.md +104 -0
  646. package/skills/placement-discipline/SKILL.md +69 -0
  647. package/skills/probe-evaluation/SKILL.md +85 -0
  648. package/skills/release-pipeline/SKILL.md +191 -0
  649. package/skills/research/SKILL.md +166 -0
  650. package/skills/skill-usage/SKILL.md +81 -0
  651. package/skills/software-engineer/SKILL.md +83 -0
  652. package/skills/subagent-orchestration/SKILL.md +454 -0
  653. package/skills/subagent-orchestration/scripts/workers.mjs +283 -0
  654. package/skills/subagent-verification/SKILL.md +127 -0
  655. package/skills/tone-quality/SKILL.md +176 -0
  656. package/skills/voice-replies/SKILL.md +125 -0
  657. package/src/AGENTS.md +111 -0
  658. package/src/extensions/cognitive/AGENTS.md +29 -0
  659. package/src/extensions/cognitive/mars-reflector/index.ts +415 -0
  660. package/src/extensions/cognitive/metacognition/handlers/AGENTS.md +30 -0
  661. package/src/extensions/cognitive/metacognition/handlers/claim-verification.ts +295 -0
  662. package/src/extensions/cognitive/metacognition/handlers/finalize.ts +648 -0
  663. package/src/extensions/cognitive/metacognition/handlers/hypothesize.ts +368 -0
  664. package/src/extensions/cognitive/metacognition/handlers/scoring.ts +242 -0
  665. package/src/extensions/cognitive/metacognition/handlers/think-budget.ts +199 -0
  666. package/src/extensions/cognitive/metacognition/handlers/think.ts +489 -0
  667. package/src/extensions/cognitive/metacognition/handlers/verify.ts +440 -0
  668. package/src/extensions/cognitive/metacognition/index.ts +109 -0
  669. package/src/extensions/cognitive/reasoning/index.ts +168 -0
  670. package/src/extensions/cognitive/sycophancy-detector/index.ts +286 -0
  671. package/src/extensions/cognitive/topic-drift/index.ts +429 -0
  672. package/src/extensions/cognitive/turn-outcome/index.ts +209 -0
  673. package/src/extensions/context-management/README.md +102 -0
  674. package/src/extensions/context-management/index.ts +383 -0
  675. package/src/extensions/core/AGENTS.md +34 -0
  676. package/src/extensions/core/agent-environment/index.ts +135 -0
  677. package/src/extensions/core/polyfill/index.ts +617 -0
  678. package/src/extensions/core/prompt-builder/AGENTS.md +151 -0
  679. package/src/extensions/core/prompt-builder/awareness-whisper.ts +162 -0
  680. package/src/extensions/core/prompt-builder/context-section.ts +120 -0
  681. package/src/extensions/core/prompt-builder/custom-sections.ts +27 -0
  682. package/src/extensions/core/prompt-builder/external-tool-guidelines.ts +41 -0
  683. package/src/extensions/core/prompt-builder/identity.ts +98 -0
  684. package/src/extensions/core/prompt-builder/index.ts +602 -0
  685. package/src/extensions/core/prompt-builder/inspect.ts +227 -0
  686. package/src/extensions/core/prompt-builder/instance-composition.ts +515 -0
  687. package/src/extensions/core/prompt-builder/memory-section.ts +76 -0
  688. package/src/extensions/core/prompt-builder/pi-reference-section.ts +26 -0
  689. package/src/extensions/core/prompt-builder/project-docs-section.ts +105 -0
  690. package/src/extensions/core/prompt-builder/section-parity.ts +108 -0
  691. package/src/extensions/core/prompt-builder/section-publish.ts +43 -0
  692. package/src/extensions/core/prompt-builder/section.ts +150 -0
  693. package/src/extensions/core/prompt-builder/surface-discipline-section.ts +21 -0
  694. package/src/extensions/core/prompt-builder/system-info-tool.ts +87 -0
  695. package/src/extensions/core/prompt-builder/tool-description-trim.ts +127 -0
  696. package/src/extensions/core/prompt-builder/tool-guidelines.ts +226 -0
  697. package/src/extensions/core/prompt-builder/tool-pipelines.ts +78 -0
  698. package/src/extensions/core/prompt-builder/top-level-extensions.ts +338 -0
  699. package/src/extensions/core/skills-tool/auto-inject.ts +1004 -0
  700. package/src/extensions/core/skills-tool/index.ts +240 -0
  701. package/src/extensions/core/skills-tool/loading-guidance.ts +89 -0
  702. package/src/extensions/core/skills-tool/session-records.ts +328 -0
  703. package/src/extensions/core/skills-tool/skill-triggers.ts +119 -0
  704. package/src/extensions/enforcement/AGENTS.md +69 -0
  705. package/src/extensions/enforcement/detection/malformed.ts +42 -0
  706. package/src/extensions/enforcement/detection/verification.ts +52 -0
  707. package/src/extensions/enforcement/enforcement-types.ts +42 -0
  708. package/src/extensions/enforcement/handler-registry.ts +225 -0
  709. package/src/extensions/enforcement/handlers/AGENTS.md +68 -0
  710. package/src/extensions/enforcement/handlers/analysis/AGENTS.md +40 -0
  711. package/src/extensions/enforcement/handlers/analysis/bpe-handler.ts +53 -0
  712. package/src/extensions/enforcement/handlers/analysis/dreamer-handler.ts +73 -0
  713. package/src/extensions/enforcement/handlers/analysis/drift-handler.ts +100 -0
  714. package/src/extensions/enforcement/handlers/analysis/feedback-handler.ts +22 -0
  715. package/src/extensions/enforcement/handlers/analysis/mars-handler.ts +121 -0
  716. package/src/extensions/enforcement/handlers/analysis/reflection-handler.ts +22 -0
  717. package/src/extensions/enforcement/handlers/blocking.ts +50 -0
  718. package/src/extensions/enforcement/handlers/message-analysis.ts +95 -0
  719. package/src/extensions/enforcement/handlers/orphan-chains.ts +53 -0
  720. package/src/extensions/enforcement/handlers/over-correction-gate.ts +634 -0
  721. package/src/extensions/enforcement/handlers/probe-handler.ts +133 -0
  722. package/src/extensions/enforcement/handlers/register-adherence-meter.ts +216 -0
  723. package/src/extensions/enforcement/handlers/register-agent-end-api-error.ts +82 -0
  724. package/src/extensions/enforcement/handlers/register-input-handler.ts +36 -0
  725. package/src/extensions/enforcement/handlers/register-message-end.ts +477 -0
  726. package/src/extensions/enforcement/handlers/register-post-cycle-hygiene.ts +166 -0
  727. package/src/extensions/enforcement/handlers/register-session-compact.ts +248 -0
  728. package/src/extensions/enforcement/handlers/register-session-shutdown-resumption.ts +138 -0
  729. package/src/extensions/enforcement/handlers/register-session-shutdown.ts +46 -0
  730. package/src/extensions/enforcement/handlers/register-session-start-discoverability.ts +270 -0
  731. package/src/extensions/enforcement/handlers/register-session-start.ts +240 -0
  732. package/src/extensions/enforcement/handlers/register-tool-call.ts +160 -0
  733. package/src/extensions/enforcement/handlers/register-tool-result-formatting.ts +73 -0
  734. package/src/extensions/enforcement/handlers/register-tool-result.ts +108 -0
  735. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +456 -0
  736. package/src/extensions/enforcement/handlers/routing-handler.ts +191 -0
  737. package/src/extensions/enforcement/handlers/tool-tracker.ts +145 -0
  738. package/src/extensions/enforcement/handlers/turn-analysis.ts +156 -0
  739. package/src/extensions/enforcement/handlers/turn-end-handler.ts +538 -0
  740. package/src/extensions/enforcement/index.ts +28 -0
  741. package/src/extensions/enforcement/judge-utils.ts +106 -0
  742. package/src/extensions/enforcement/nudge-manager.ts +298 -0
  743. package/src/extensions/enforcement/self-state-claims.ts +204 -0
  744. package/src/extensions/enforcement/session-health.ts +317 -0
  745. package/src/extensions/enforcement/signals.ts +88 -0
  746. package/src/extensions/enforcement/similarity.ts +76 -0
  747. package/src/extensions/enforcement/state.ts +115 -0
  748. package/src/extensions/enforcement/substate/context-hygiene-state.ts +212 -0
  749. package/src/extensions/enforcement/substate/error-tracking-state.ts +50 -0
  750. package/src/extensions/enforcement/substate/memory-hygiene-state.ts +54 -0
  751. package/src/extensions/enforcement/substate/session-state.ts +79 -0
  752. package/src/extensions/enforcement/substate/thought-chain-state.ts +62 -0
  753. package/src/extensions/enforcement/substate/tool-tracking-state.ts +166 -0
  754. package/src/extensions/enforcement/substate/verification-judge-state.ts +52 -0
  755. package/src/extensions/enforcement/task-evidence.ts +436 -0
  756. package/src/extensions/enforcement/types.ts +38 -0
  757. package/src/extensions/enforcement/validation.ts +194 -0
  758. package/src/extensions/enforcement/verification-judge.ts +317 -0
  759. package/src/extensions/enforcement/whisper.ts +120 -0
  760. package/src/extensions/heartbeat/AGENTS.md +47 -0
  761. package/src/extensions/heartbeat/analytics/AGENTS.md +57 -0
  762. package/src/extensions/heartbeat/analytics/ab-variant.ts +106 -0
  763. package/src/extensions/heartbeat/analytics/core.ts +222 -0
  764. package/src/extensions/heartbeat/analytics/format.ts +144 -0
  765. package/src/extensions/heartbeat/analytics/index.ts +373 -0
  766. package/src/extensions/heartbeat/analytics/shared.ts +149 -0
  767. package/src/extensions/heartbeat/heartbeat-scheduler/AGENTS.md +84 -0
  768. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +1095 -0
  769. package/src/extensions/heartbeat/heartbeat-scheduler/meta-learning.ts +75 -0
  770. package/src/extensions/heartbeat/heartbeat-scheduler/modules/behavioral-drift.ts +200 -0
  771. package/src/extensions/heartbeat/heartbeat-scheduler/modules/budget.ts +113 -0
  772. package/src/extensions/heartbeat/heartbeat-scheduler/modules/context-hygiene.ts +288 -0
  773. package/src/extensions/heartbeat/heartbeat-scheduler/modules/evolver.ts +88 -0
  774. package/src/extensions/heartbeat/heartbeat-scheduler/modules/measurement.ts +47 -0
  775. package/src/extensions/heartbeat/heartbeat-scheduler/modules/recaller.ts +99 -0
  776. package/src/extensions/heartbeat/heartbeat-scheduler/modules/reflection-consolidator.ts +114 -0
  777. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +193 -0
  778. package/src/extensions/heartbeat/heartbeat-scheduler/state.ts +88 -0
  779. package/src/extensions/heartbeat/heartbeat-scheduler/types.ts +128 -0
  780. package/src/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.ts +98 -0
  781. package/src/extensions/manifest.ts +293 -0
  782. package/src/extensions/memory/AGENTS.md +93 -0
  783. package/src/extensions/memory/context-lifecycle/AGENTS.md +62 -0
  784. package/src/extensions/memory/context-lifecycle/helpers.ts +167 -0
  785. package/src/extensions/memory/context-lifecycle/index.ts +1232 -0
  786. package/src/extensions/memory/context-lifecycle/policy-engine.ts +287 -0
  787. package/src/extensions/memory/context-lifecycle/signal-detector.ts +293 -0
  788. package/src/extensions/memory/context-lifecycle/state.ts +165 -0
  789. package/src/extensions/memory/context-lifecycle/types.ts +441 -0
  790. package/src/extensions/memory/context-manager/analysis.ts +344 -0
  791. package/src/extensions/memory/context-manager/handlers/AGENTS.md +37 -0
  792. package/src/extensions/memory/context-manager/handlers/compaction-chunked.ts +800 -0
  793. package/src/extensions/memory/context-manager/handlers/compaction-retry.ts +556 -0
  794. package/src/extensions/memory/context-manager/handlers/compaction-trace.ts +243 -0
  795. package/src/extensions/memory/context-manager/handlers/compaction-watchdog.ts +366 -0
  796. package/src/extensions/memory/context-manager/handlers/compaction.ts +2552 -0
  797. package/src/extensions/memory/context-manager/handlers/context-emergency.ts +470 -0
  798. package/src/extensions/memory/context-manager/handlers/events.ts +430 -0
  799. package/src/extensions/memory/context-manager/handlers/navigation.ts +94 -0
  800. package/src/extensions/memory/context-manager/handlers/offload.ts +330 -0
  801. package/src/extensions/memory/context-manager/handlers/rotation.ts +363 -0
  802. package/src/extensions/memory/context-manager/handlers/shared.ts +961 -0
  803. package/src/extensions/memory/context-manager/handlers/tool-batch-boundary.ts +219 -0
  804. package/src/extensions/memory/context-manager/handlers/toolresult-capture-cap.ts +176 -0
  805. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +1333 -0
  806. package/src/extensions/memory/context-manager/handlers/tools/context-inspect.ts +343 -0
  807. package/src/extensions/memory/context-manager/handlers/tools/context-navigate.ts +423 -0
  808. package/src/extensions/memory/context-manager/handlers/tools/offload-recover.ts +234 -0
  809. package/src/extensions/memory/context-manager/index.ts +111 -0
  810. package/src/extensions/memory/context-manager/pruning.ts +479 -0
  811. package/src/extensions/memory/context-manager/semantic-compress.ts +321 -0
  812. package/src/extensions/memory/memory-agent-bridge/AGENTS.md +62 -0
  813. package/src/extensions/memory/memory-agent-bridge/conflict-qa-tool.ts +106 -0
  814. package/src/extensions/memory/memory-agent-bridge/explore-paths.ts +283 -0
  815. package/src/extensions/memory/memory-agent-bridge/index.ts +163 -0
  816. package/src/extensions/memory/memory-agent-bridge/memory-store-tool.ts +284 -0
  817. package/src/extensions/memory/memory-agent-bridge/memory-tool.ts +746 -0
  818. package/src/extensions/memory/scratchpad/AGENTS.md +148 -0
  819. package/src/extensions/memory/scratchpad/format.ts +161 -0
  820. package/src/extensions/memory/scratchpad/handlers.ts +601 -0
  821. package/src/extensions/memory/scratchpad/index.ts +230 -0
  822. package/src/extensions/memory/scratchpad/persistence.ts +374 -0
  823. package/src/extensions/memory/scratchpad/types.ts +149 -0
  824. package/src/extensions/memory/scratchpad/utils.ts +268 -0
  825. package/src/extensions/memory/session-recall/AGENTS.md +104 -0
  826. package/src/extensions/memory/session-recall/analyze.ts +605 -0
  827. package/src/extensions/memory/session-recall/context-aggregate.ts +381 -0
  828. package/src/extensions/memory/session-recall/index.ts +956 -0
  829. package/src/extensions/memory/session-recall/query.ts +44 -0
  830. package/src/extensions/memory/session-recall/rank.ts +121 -0
  831. package/src/extensions/memory/session-recall/search.ts +801 -0
  832. package/src/extensions/memory/session-recall/stats.ts +93 -0
  833. package/src/extensions/memory/session-recall/text-utils.ts +209 -0
  834. package/src/extensions/memory/three-memory-stores/AGENTS.md +66 -0
  835. package/src/extensions/memory/three-memory-stores/episodes-disk.ts +138 -0
  836. package/src/extensions/memory/three-memory-stores/episodes.ts +371 -0
  837. package/src/extensions/memory/three-memory-stores/handlers/whisper-recall.ts +132 -0
  838. package/src/extensions/memory/three-memory-stores/heuristics.ts +109 -0
  839. package/src/extensions/memory/three-memory-stores/index.ts +549 -0
  840. package/src/extensions/memory/three-memory-stores/tool-reliability.ts +58 -0
  841. package/src/extensions/memory/three-memory-stores/types.ts +74 -0
  842. package/src/extensions/memory/workspace-snapshot/AGENTS.md +19 -0
  843. package/src/extensions/memory/workspace-snapshot/index.ts +455 -0
  844. package/src/extensions/orchestrator/index.ts +1141 -0
  845. package/src/extensions/scheduling/AGENTS.md +26 -0
  846. package/src/extensions/scheduling/timer/AGENTS.md +259 -0
  847. package/src/extensions/scheduling/timer/fire-timing.ts +46 -0
  848. package/src/extensions/scheduling/timer/index.ts +1331 -0
  849. package/src/extensions/scheduling/timer/poller.ts +138 -0
  850. package/src/extensions/scheduling/timer/recovery.ts +462 -0
  851. package/src/extensions/scheduling/timer/store-file.ts +59 -0
  852. package/src/extensions/scheduling/timer/timer-manager.ts +161 -0
  853. package/src/extensions/scheduling/timer/wake-retry.ts +1057 -0
  854. package/src/extensions/self/AGENTS.md +30 -0
  855. package/src/extensions/self/auto-recovery/index.ts +112 -0
  856. package/src/extensions/self/error-tracking/AGENTS.md +38 -0
  857. package/src/extensions/self/error-tracking/index.ts +299 -0
  858. package/src/extensions/self/health-maintenance/AGENTS.md +42 -0
  859. package/src/extensions/self/health-maintenance/format.ts +87 -0
  860. package/src/extensions/self/health-maintenance/handlers/session-health-tool.ts +182 -0
  861. package/src/extensions/self/health-maintenance/helpers.ts +78 -0
  862. package/src/extensions/self/health-maintenance/index.ts +308 -0
  863. package/src/extensions/self/health-maintenance/types.ts +14 -0
  864. package/src/extensions/self/latent-activator/AGENTS.md +64 -0
  865. package/src/extensions/self/latent-activator/index.ts +206 -0
  866. package/src/extensions/self/latent-activator/mixes.ts +22 -0
  867. package/src/extensions/self/latent-activator/signals.ts +237 -0
  868. package/src/extensions/self/latent-activator/state.ts +79 -0
  869. package/src/extensions/self/latent-activator/types.ts +47 -0
  870. package/src/extensions/self/watchdog/AGENTS.md +27 -0
  871. package/src/extensions/self/watchdog/config.ts +73 -0
  872. package/src/extensions/self/watchdog/engine.ts +1246 -0
  873. package/src/extensions/self/watchdog/index.ts +577 -0
  874. package/src/index.ts +93 -0
  875. package/src/lib/AGENTS.md +39 -0
  876. package/src/lib/ai/AGENTS.md +37 -0
  877. package/src/lib/ai/consolidated-claim-critic.ts +287 -0
  878. package/src/lib/ai/cost-report.ts +206 -0
  879. package/src/lib/ai/critic-cache.ts +122 -0
  880. package/src/lib/ai/critic-fallbacks.ts +74 -0
  881. package/src/lib/ai/critic-gate.ts +135 -0
  882. package/src/lib/ai/critic-helpers.ts +135 -0
  883. package/src/lib/ai/critic-registry.ts +754 -0
  884. package/src/lib/ai/critic-stats.ts +158 -0
  885. package/src/lib/ai/judge-budget.ts +241 -0
  886. package/src/lib/ai/language-hint.ts +70 -0
  887. package/src/lib/ai/llm-call.ts +975 -0
  888. package/src/lib/ai/model-resolver.ts +224 -0
  889. package/src/lib/ai/models-init.ts +68 -0
  890. package/src/lib/ai/payload-hygiene.ts +265 -0
  891. package/src/lib/ai/post-loop-classify.ts +185 -0
  892. package/src/lib/ai/text-classifier.ts +746 -0
  893. package/src/lib/cognitive/AGENTS.md +40 -0
  894. package/src/lib/cognitive/hints.ts +254 -0
  895. package/src/lib/cognitive/openspec.ts +124 -0
  896. package/src/lib/config/AGENTS.md +17 -0
  897. package/src/lib/config/braid-paths.ts +401 -0
  898. package/src/lib/config/braid-settings.ts +1442 -0
  899. package/src/lib/config/per-tool-settings.ts +197 -0
  900. package/src/lib/config/session-profiles.ts +165 -0
  901. package/src/lib/constants/AGENTS.md +15 -0
  902. package/src/lib/constants/injection-details.ts +32 -0
  903. package/src/lib/constants/session-thresholds.ts +64 -0
  904. package/src/lib/constants/tool-constants.ts +16 -0
  905. package/src/lib/core/AGENTS.md +23 -0
  906. package/src/lib/core/event-names.ts +31 -0
  907. package/src/lib/core/logger.ts +334 -0
  908. package/src/lib/detection/AGENTS.md +21 -0
  909. package/src/lib/detection/compression-strategy.ts +183 -0
  910. package/src/lib/detection/consolidated-topic-critic.ts +188 -0
  911. package/src/lib/detection/context-density.ts +237 -0
  912. package/src/lib/detection/context-thresholds.ts +132 -0
  913. package/src/lib/detection/context-tiers.ts +201 -0
  914. package/src/lib/detection/context-usage.ts +270 -0
  915. package/src/lib/detection/degradation-detector.ts +583 -0
  916. package/src/lib/detection/test-burst.ts +170 -0
  917. package/src/lib/detection/tool-loop-detector.ts +364 -0
  918. package/src/lib/detection/topic-drift-detector.ts +323 -0
  919. package/src/lib/enforcement/AGENTS.md +20 -0
  920. package/src/lib/enforcement/adherence-meter.ts +578 -0
  921. package/src/lib/enforcement/turn-dedup.ts +246 -0
  922. package/src/lib/errors/llm-error.ts +288 -0
  923. package/src/lib/events/AGENTS.md +23 -0
  924. package/src/lib/events/consolidation-channel.ts +493 -0
  925. package/src/lib/events/consolidation-scoring.ts +112 -0
  926. package/src/lib/events/event-bus.ts +213 -0
  927. package/src/lib/events/event-types.ts +53 -0
  928. package/src/lib/events/timer-bus.ts +53 -0
  929. package/src/lib/events/timer-types.ts +64 -0
  930. package/src/lib/events/turn-end-coordinator.ts +108 -0
  931. package/src/lib/harness/AGENTS.md +20 -0
  932. package/src/lib/harness/failure-trace-collector.ts +157 -0
  933. package/src/lib/harness/index.ts +41 -0
  934. package/src/lib/harness/types.ts +122 -0
  935. package/src/lib/harness/weakness-miner.ts +209 -0
  936. package/src/lib/memory/AGENTS.md +36 -0
  937. package/src/lib/memory/constants.ts +34 -0
  938. package/src/lib/memory/index.ts +705 -0
  939. package/src/lib/memory/lifecycle.ts +159 -0
  940. package/src/lib/memory/past-insights.ts +221 -0
  941. package/src/lib/memory/storage.ts +187 -0
  942. package/src/lib/memory/store-lock.ts +70 -0
  943. package/src/lib/memory/store-merge.ts +100 -0
  944. package/src/lib/memory/types.ts +82 -0
  945. package/src/lib/memory/utils.ts +173 -0
  946. package/src/lib/memory/write-log.ts +174 -0
  947. package/src/lib/memory/write-quality.ts +383 -0
  948. package/src/lib/orchestrator/branch.ts +193 -0
  949. package/src/lib/orchestrator/index.ts +78 -0
  950. package/src/lib/orchestrator/locks.ts +160 -0
  951. package/src/lib/orchestrator/slop-scanner.ts +258 -0
  952. package/src/lib/orchestrator/workers.ts +1382 -0
  953. package/src/lib/public.ts +43 -0
  954. package/src/lib/reasoning/AGENTS.md +25 -0
  955. package/src/lib/reasoning/advice-tracker.ts +244 -0
  956. package/src/lib/reasoning/belief-policy-engine.ts +342 -0
  957. package/src/lib/reasoning/belief-types.ts +45 -0
  958. package/src/lib/reasoning/classifier-offline.ts +111 -0
  959. package/src/lib/reasoning/dreamer.ts +215 -0
  960. package/src/lib/reasoning/nudge-analytics.ts +85 -0
  961. package/src/lib/reasoning/policy-rules.ts +172 -0
  962. package/src/lib/reasoning/reasoning-metrics.ts +202 -0
  963. package/src/lib/reasoning/reasoning-summary.ts +154 -0
  964. package/src/lib/reasoning/tool-usage-analyzer.ts +248 -0
  965. package/src/lib/state/AGENTS.md +192 -0
  966. package/src/lib/state/async-storage.ts +189 -0
  967. package/src/lib/state/extension-state.ts +419 -0
  968. package/src/lib/state/global-state.ts +1046 -0
  969. package/src/lib/state/metacognitive-state.ts +65 -0
  970. package/src/lib/state/session-manager.ts +43 -0
  971. package/src/lib/state/session-start-queue.ts +135 -0
  972. package/src/lib/state/state-checkpoint.ts +352 -0
  973. package/src/lib/state/telegram-poller-liveness.ts +75 -0
  974. package/src/lib/state/tool-provenance.ts +26 -0
  975. package/src/lib/state/workspace-snapshot.ts +466 -0
  976. package/src/lib/store/AGENTS.md +24 -0
  977. package/src/lib/store/belief-store.ts +325 -0
  978. package/src/lib/store/bidirectional-verifier.ts +316 -0
  979. package/src/lib/store/claim-tracker.ts +382 -0
  980. package/src/lib/store/conflict-qa.ts +385 -0
  981. package/src/lib/store/evidence-pool.ts +779 -0
  982. package/src/lib/telemetry/AGENTS.md +28 -0
  983. package/src/lib/telemetry/context-heartbeat.ts +555 -0
  984. package/src/lib/telemetry/drift-signals.ts +105 -0
  985. package/src/lib/telemetry/rss-telemetry.ts +57 -0
  986. package/src/lib/types/AGENTS.md +21 -0
  987. package/src/lib/types/episode-types.ts +31 -0
  988. package/src/lib/types/standard-result.ts +40 -0
  989. package/src/lib/utils/AGENTS.md +30 -0
  990. package/src/lib/utils/async-fs.ts +23 -0
  991. package/src/lib/utils/bounded.ts +58 -0
  992. package/src/lib/utils/dedup.ts +44 -0
  993. package/src/lib/utils/error-guard.ts +27 -0
  994. package/src/lib/utils/extension-utils.ts +72 -0
  995. package/src/lib/utils/extract-json.ts +89 -0
  996. package/src/lib/utils/file-mutation-queue.ts +172 -0
  997. package/src/lib/utils/filter-safe-to-remove.ts +301 -0
  998. package/src/lib/utils/format-tool-result.ts +109 -0
  999. package/src/lib/utils/id.ts +64 -0
  1000. package/src/lib/utils/injection-tracker.ts +1014 -0
  1001. package/src/lib/utils/local-time.ts +196 -0
  1002. package/src/lib/utils/memory-fence.ts +70 -0
  1003. package/src/lib/utils/sop-extractor.ts +329 -0
  1004. package/src/lib/utils/sop-suggestion.ts +426 -0
  1005. package/src/lib/utils/wake-gate.ts +318 -0
  1006. package/src/lib/utils/whisper-format.ts +120 -0
  1007. package/src/lib/verification/coordination-checker.ts +183 -0
  1008. package/src/loader/AGENTS.md +32 -0
  1009. package/src/loader/api.ts +138 -0
  1010. package/src/loader/loader.ts +600 -0
  1011. package/src/types/extension-context.d.ts +85 -0
@@ -0,0 +1,2150 @@
1
+ // Compaction handler: session_before_compact, session_compact (parking +
2
+ // outcome stages), session_compact_failed, and retry logic. pi-core 0.85.1
3
+ // has no `compaction_end` extension event - the cycle's outcome stages are
4
+ // wired to the events pi-core actually fires. This is the core of context
5
+ // management - compaction quality directly affects agent performance on long
6
+ // sessions.
7
+ import { addEvidence } from "../../../../lib/store/evidence-pool.js";
8
+ import { eventBus } from "../../../../lib/events/event-bus.js";
9
+ import { recordAdvice } from "../../../../lib/reasoning/advice-tracker.js";
10
+ import { appendFileSync, mkdirSync } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
+ import { createHash } from "node:crypto";
13
+ import { analyzeSession } from "../analysis.js";
14
+ import { getSessionIdSafe, getLeafIdSafe, getExtensionState, getFullSessionManager, } from "../../../../lib/state/extension-state.js";
15
+ import { log, getCmState, isTransientCompactionError, isContextWindowError, isCompactionActive, setCompactionActive, recordCompactionOutcome, recordCompactionHealth, compactionRetryState, overflowRetryState, noteCompactionNoProgress, clearCompactionFailsafe, armCompactionFailsafeCut, consumeCompactionFailsafeCut, settleCompactionRetry, settleOverflowRetry, resetCompactionRetry, resetOverflowRetry, COMPACTION_NO_PROGRESS_LIMIT, } from "./shared.js";
16
+ import { snapBoundaryOutsideToolBatch } from "./tool-batch-boundary.js";
17
+ import { filterSafeToRemove } from "../../../../lib/utils/filter-safe-to-remove.js";
18
+ import { determineCompressionLevel } from "../../../../lib/detection/compression-strategy.js";
19
+ import { CONTEXT_COMPACT_REFUSE_PERCENT, USAGE_WHISPER_CRITICAL, } from "../../../../lib/detection/context-thresholds.js";
20
+ import { estimateMessagesTokens, resolveWindow } from "../../../../lib/detection/context-usage.js";
21
+ import { semanticCompress } from "../semantic-compress.js";
22
+ import { onEvent } from "../../../../lib/events/event-types.js";
23
+ import { SESSION_SHUTDOWN, SESSION_COMPACT, SESSION_COMPACT_FAILED, SESSION_BEFORE_COMPACT, MESSAGE_END, AGENT_SETTLED, INPUT, } from "../../../../lib/core/event-names.js";
24
+ import { handleOverflowFailure, handleTransientError, handleContextWindowError, handleThresholdFailure, handleSummaryCapFailure, triggerFailsafeCompaction, } from "./compaction-retry.js";
25
+ import { COMPACTION_STALL_THRESHOLD_MS, armCompactionWatchdog, clearCompactionWatchdog, getCompactionWatchdogArmedAt, handleSummaryCapAbort, } from "./compaction-watchdog.js";
26
+ import { classifyCompactionFailure, countSpanMessages, writeCompactionTrace, } from "./compaction-trace.js";
27
+ import { summarizeSpanInChunks } from "./compaction-chunked.js";
28
+ import { trackInjection } from "../../../../lib/utils/injection-tracker.js";
29
+ // Deduplication Guard
30
+ // NOTE: registerTurnEndRetryReset is registered in compaction-retry.ts and
31
+ // wired from index.ts. Test checks it's mentioned here.
32
+ // session_before_compact fires from TWO call sites in pi core:
33
+ // (1) compact() - manual /pi compact command
34
+ // (2) _runAutoCompaction() - auto-compaction triggered by context pressure
35
+ // Without a guard, our handler fires twice per compaction cycle.
36
+ const MAX_PROCESSED_COMPACTS = 200;
37
+ const _processedCompacts = new Map();
38
+ /**
39
+ * Cooldown window for the dedup guard. A later compaction cycle on the same
40
+ * session+leaf that begins AFTER this window — or once compaction is no longer
41
+ * in-flight — is NOT a duplicate; it must run. The guard only ever blocks the
42
+ * in-cycle double-fire from pi-core's two call sites (compact() + _runAutoCompaction()).
43
+ */
44
+ const COMPACT_COOLDOWN_MS = 20000;
45
+ // Summarizer thinking-off switch: pi-core forwards the session thinking level
46
+ // into its own summarization call
47
+ // (agent-session.js:1844 -> compaction.js createSummarizationOptions), and
48
+ // effort-based providers bill reasoning inside max_tokens — the same budget
49
+ // the summary needs; xhigh reasoning on a large span length-stops the summary.
50
+ // When a cycle is about to hand its span to pi-core's summarizer, switch the
51
+ // level off for the call and restore it at the cycle outcome (both outcome
52
+ // events fire on every cycle that armed the switch; shutdown is the
53
+ // backstop). Summaries are mechanical merges; xhigh is actively harmful
54
+ // there. Extension-owned chunked calls (range branch, recovery branch) pass
55
+ // reasoning "off" per call and never arm this.
56
+ function armSummarizerThinkingOff(pi, ctx) {
57
+ try {
58
+ const cmState = getCmState(ctx);
59
+ if (cmState.pendingSummarizerThinkingLevel !== undefined)
60
+ return; // already armed
61
+ const model = ctx.model;
62
+ if (!model?.reasoning)
63
+ return; // nothing to strip
64
+ const previous = pi.getThinkingLevel();
65
+ if (previous === "off")
66
+ return; // no change, no session entry
67
+ cmState.pendingSummarizerThinkingLevel = previous;
68
+ // "off" is accepted at runtime by pi-ai's clampThinkingLevel (it maps to
69
+ // the model's lowest level or disables thinking), but the public union
70
+ // doesn't list it yet — same boundary cast callLlm centralizes for its
71
+ // reasoning option.
72
+ pi.setThinkingLevel("off");
73
+ log.info(`[context-manager] Summarizer thinking off: level ${previous} -> off for the ` +
74
+ `summarization call (restored at cycle outcome)`);
75
+ }
76
+ catch (e) {
77
+ log.warn("[context-manager] thinking switch unavailable - summarizer runs at the session level:", e);
78
+ }
79
+ }
80
+ function restoreSummarizerThinkingLevel(pi, ctx) {
81
+ try {
82
+ const cmState = getCmState(ctx);
83
+ const previous = cmState.pendingSummarizerThinkingLevel;
84
+ if (previous === undefined)
85
+ return;
86
+ cmState.pendingSummarizerThinkingLevel = undefined;
87
+ pi.setThinkingLevel(previous);
88
+ log.info(`[context-manager] Summarizer thinking restored: level ${previous}`);
89
+ }
90
+ catch (e) {
91
+ log.warn("[context-manager] thinking restore failed - level may stay switched:", e);
92
+ }
93
+ }
94
+ /**
95
+ * Concurrency-scoped dedup guard. Returns true when the compaction should
96
+ * proceed, false when it is a duplicate of a compaction already in-flight for
97
+ * this leaf (same cycle).
98
+ *
99
+ * The dedupe covers only the in-cycle double-fire — when a compaction was
100
+ * already in-flight as this firing began (captured before the handler marks
101
+ * this cycle active) AND it was already seen within the cooldown window. A
102
+ * persistent whole-session key would starve legitimate later compactions on
103
+ * the same leaf ("duplicate - skipping"); once the cycle completes
104
+ * (active=false) or the cooldown lapses, a fresh cycle on the same leaf runs.
105
+ */
106
+ function markCompactProcessed(sessionId, leafId, ctx, inFlightBefore) {
107
+ const key = `${sessionId}::${leafId}`;
108
+ const now = Date.now();
109
+ const last = _processedCompacts.get(key);
110
+ const fresh = last !== undefined && now - last < COMPACT_COOLDOWN_MS;
111
+ // Dedupe only if a compaction was ALREADY in-flight when this firing began
112
+ // (the in-cycle double-fire from pi-core's compact() + _runAutoCompaction())
113
+ // AND we already saw this leaf within the cooldown window. A new cycle that
114
+ // begins after completion — or after the cooldown lapses — must run.
115
+ if (inFlightBefore && fresh) {
116
+ return false;
117
+ }
118
+ // LRU: remove oldest half when over limit
119
+ if (_processedCompacts.size >= MAX_PROCESSED_COMPACTS) {
120
+ const oldest = [..._processedCompacts.entries()]
121
+ .sort((a, b) => a[1] - b[1])
122
+ .slice(0, Math.floor(MAX_PROCESSED_COMPACTS / 2));
123
+ for (const [k] of oldest)
124
+ _processedCompacts.delete(k);
125
+ }
126
+ _processedCompacts.set(key, now);
127
+ return true;
128
+ }
129
+ function clearProcessedCompacts(sessionId, leafId) {
130
+ _processedCompacts.delete(`${sessionId}::${leafId}`);
131
+ }
132
+ /**
133
+ * Extract the messages in a declared archive span [startIndex..endIndex] from
134
+ * the session branch, mirroring pi-core's compaction message extraction.
135
+ */
136
+ function collectRangeMessages(branch, startIndex, endIndex) {
137
+ const messages = [];
138
+ const lo = Math.max(0, startIndex);
139
+ const hi = Math.min(branch.length - 1, endIndex);
140
+ for (let i = lo; i <= hi; i++) {
141
+ const entry = branch[i];
142
+ if (entry?.type === "message" && entry.message) {
143
+ messages.push(entry.message);
144
+ }
145
+ }
146
+ return messages;
147
+ }
148
+ /**
149
+ * Count of messages in this cycle's RAW summarization input —
150
+ * the captured originals JSON (what the compaction summary replaced). Returns
151
+ * undefined when the capture is absent/unparseable — telemetry degrades to
152
+ * absent, never wrong.
153
+ */
154
+ function countSummarizedMessages(originals) {
155
+ if (!originals)
156
+ return undefined;
157
+ try {
158
+ const parsed = JSON.parse(originals);
159
+ return Array.isArray(parsed) ? parsed.length : undefined;
160
+ }
161
+ catch {
162
+ return undefined;
163
+ }
164
+ }
165
+ /**
166
+ * Count the messages that remain LIVE in context after a compaction with the
167
+ * given firstKeptEntryId anchor: message entries from the anchor (inclusive)
168
+ * to the branch end, minus any the recovery path omitted. A `context_edit`
169
+ * with `replacement === null` removes the TARGET from model context without
170
+ * removing it from the branch, so counting branch messages alone overcounts by
171
+ * the omitted attempts (exactly the entries overflow recovery appends after
172
+ * the anchor). Returns undefined when the anchor is missing from the branch
173
+ * (degrade - telemetry is never wrong, at worst absent).
174
+ */
175
+ function countKeptMessages(branch, firstKeptEntryId) {
176
+ if (!firstKeptEntryId)
177
+ return undefined;
178
+ const anchorIndex = branch.findIndex((entry) => entry.id === firstKeptEntryId);
179
+ if (anchorIndex < 0)
180
+ return undefined;
181
+ // Effective omissions, last edit per target wins (pi keeps a Map keyed by
182
+ // targetId): a later non-null replacement re-includes the target.
183
+ const omitted = new Set();
184
+ for (const entry of branch) {
185
+ if (entry?.type !== "context_edit" || !entry.targetId)
186
+ continue;
187
+ if (entry.replacement === null)
188
+ omitted.add(entry.targetId);
189
+ else
190
+ omitted.delete(entry.targetId);
191
+ }
192
+ let kept = 0;
193
+ for (let i = anchorIndex; i < branch.length; i++) {
194
+ const entry = branch[i];
195
+ if (entry?.type === "message" && entry.message && !omitted.has(entry.id))
196
+ kept++;
197
+ }
198
+ return kept;
199
+ }
200
+ /**
201
+ * Stable fingerprint over the compaction INPUT (Pattern 8 delta-only borrow):
202
+ * sha256(branchLength + "|" + entryIds(messagesToSummarize).join(",") + "|" +
203
+ * firstKeptEntryId). Entry ids are stable across turns; timestamps and token
204
+ * counts are excluded because they drift and would defeat the skip.
205
+ *
206
+ * Messages in messagesToSummarize are the same object references as
207
+ * branch[i].message (pi-core's prepareCompaction pushes entry.message), so
208
+ * entry ids are recovered by identity, in branch order.
209
+ */
210
+ function computeCompactionFingerprint(branch, messagesToSummarize, firstKeptEntryId) {
211
+ const summarizeSet = new Set(messagesToSummarize);
212
+ const ids = [];
213
+ for (const entry of branch) {
214
+ if (entry?.type === "message" && entry.message && summarizeSet.has(entry.message)) {
215
+ ids.push(entry.id);
216
+ }
217
+ }
218
+ return createHash("sha256")
219
+ .update(`${branch.length}|${ids.join(",")}|${firstKeptEntryId ?? ""}`)
220
+ .digest("hex");
221
+ }
222
+ // Verify / rollback stage (light path).
223
+ // A compaction that "succeeds" can still destroy context silently: an
224
+ // empty/boilerplate summary (the STEP 0.75 defect class), a summary larger than
225
+ // the dropped span (budget not recovered), or a branch left incoherent (missing
226
+ // first-kept anchor). Recording "success" on any truthy result with no
227
+ // coherence or budget validation is exactly that silent destruction.
228
+ //
229
+ // Light path: validation + honest failure feedback. NO destructive rollback —
230
+ // pi-core 0.84.2 has no snapshot mechanism; the branch file is append-only and
231
+ // originals are recoverable via context_navigate/archive (the append-only
232
+ // archive preserves every compaction's originals batch).
233
+ /**
234
+ * Verify a completed compaction BEFORE recording success.
235
+ *
236
+ * - Coherence: compactionEntry must exist with a non-empty summary (trim
237
+ * length > 0) and firstKeptEntryId must be present. An empty summary is the
238
+ * STEP 0.75 defect class — caught here even though prevents it at the
239
+ * source.
240
+ * - Budget: post-compaction usage (recomputed via analyzeSession) must be
241
+ * strictly below the pre-compaction usage captured at session_before_compact
242
+ * (<= 1pp slack: a drop of 1pp or less is a no-op treadmill). Only enforced
243
+ * when a pre-compaction value was captured; analysis failure degrades to
244
+ * coherence-only and never fails a compaction on missing telemetry.
245
+ *
246
+ * Returns { ok: true } when verification passes, or { ok: false, reason } with a
247
+ * specific reason ("coherence..." vs "budget...").
248
+ */
249
+ function verifyCompactionResult(event, ctx, preCompactionUsagePercent) {
250
+ // Coherence: non-empty summary + first-kept anchor present.
251
+ const summary = event.compactionEntry?.summary?.trim() ?? "";
252
+ if (summary.length === 0) {
253
+ return {
254
+ ok: false,
255
+ reason: "coherence: compaction summary is empty (STEP 0.75 defect class)",
256
+ };
257
+ }
258
+ if (!event.firstKeptEntryId) {
259
+ return {
260
+ ok: false,
261
+ reason: "coherence: firstKeptEntryId missing — branch anchor lost",
262
+ };
263
+ }
264
+ // Budget: post-compaction usage must be strictly below the pre-compaction
265
+ // usage captured at session_before_compact (<= 1pp slack).
266
+ if (preCompactionUsagePercent !== undefined) {
267
+ let postUsagePercent = 0;
268
+ try {
269
+ postUsagePercent = analyzeSession(ctx).usage.percent;
270
+ }
271
+ catch {
272
+ /* analysis unavailable - cannot verify budget; do not fail the compaction */
273
+ }
274
+ if (postUsagePercent >= preCompactionUsagePercent - 1) {
275
+ return {
276
+ ok: false,
277
+ reason: `budget: post-compaction usage ${postUsagePercent.toFixed(1)}% did not drop ` +
278
+ `below pre-compaction ${preCompactionUsagePercent.toFixed(1)}% (<=1pp slack)`,
279
+ };
280
+ }
281
+ }
282
+ return { ok: true };
283
+ }
284
+ // Append-only originals archive.
285
+ // A compaction that "succeeded" but destroyed context needs recovery, not
286
+ // just detection: the dropped originals stay buried in the append-only session
287
+ // file in a way the live branch can't navigate to. EVERY compaction that
288
+ // proceeded writes its raw originals (captured at session_before_compact,
289
+ // pre-compression) into an explicit on-disk archive (pi-condense's post-hoc
290
+ // recovery-archive pattern; no new dependency), so originals are never
291
+ // silently discarded from the live branch just because verification happened
292
+ // to pass.
293
+ /**
294
+ * Write the append-only originals archive. Called from BOTH the
295
+ * session_compact outcome stage's success path (reason "compact") and the
296
+ * verify-failure path (reason = verify.reason). Always-on per (lossless
297
+ * default): whenever
298
+ * originals were captured (a compaction actually proceeded), the exact
299
+ * pre-compression originals are appended as one JSON line to
300
+ * <sessionDir>/archives/<sessionId>-<leafId>-<epoch>.jsonl (mkdir -p
301
+ * archives) and the recovery path is logged. VerifyFailed +
302
+ * pendingCompactionOriginals are ALWAYS cleared in finally here (the archive
303
+ * write owns the flag lifecycle) so no stale flag or capture lingers on
304
+ * success or failure.
305
+ *
306
+ * Each line also carries the compacted-vs-kept message counter
307
+ * (compactedMessages = this cycle's raw summarization input, keptMessages =
308
+ * messages still live from the firstKeptEntryId anchor), so post-hoc loss
309
+ * questions are answerable from the durable per-compaction record. Counts are
310
+ * omitted (undefined) when their source degraded — absent, never wrong.
311
+ *
312
+ * Session file access is READ-ONLY (rotation.ts statSync pattern): the session
313
+ * file path is read from ctx.sessionManager (getSessionFile(), backed by the
314
+ * private sessionFile field) and never written.
315
+ */
316
+ function writeOriginalsArchive(ctx, reason, originals, counts) {
317
+ try {
318
+ // Always-on / lossless default: the archive is written whenever originals
319
+ // were captured (a compaction actually proceeded), on BOTH the healthy and
320
+ // verify-failed path (the !originals no-op below covers abort /
321
+ // fingerprint-skip). Future opt-out extension point: a config toggle keyed
322
+ // on getCmState(ctx) would re-introduce a gate here (e.g.
323
+ // archiveOriginals === false).
324
+ if (!originals)
325
+ return; // nothing captured — nothing to archive
326
+ const sm = ctx.sessionManager;
327
+ const sessionFilePath = sm.sessionFile ?? sm.getSessionFile?.();
328
+ if (!sessionFilePath) {
329
+ log.warn("[context-manager] No session file path — originals archive skipped");
330
+ return;
331
+ }
332
+ const sessionDir = dirname(sessionFilePath);
333
+ const archivesDir = join(sessionDir, "archives");
334
+ mkdirSync(archivesDir, { recursive: true });
335
+ const sessionId = getSessionIdSafe(ctx);
336
+ const leafId = getLeafIdSafe(ctx);
337
+ const epoch = Date.now();
338
+ const archivePath = join(archivesDir, `${sessionId}-${leafId}-${epoch}.jsonl`);
339
+ const line = JSON.stringify({
340
+ sessionId,
341
+ leafId,
342
+ reason,
343
+ timestamp: new Date().toISOString(),
344
+ compactedMessages: counts?.compactedMessages,
345
+ keptMessages: counts?.keptMessages,
346
+ originals,
347
+ });
348
+ appendFileSync(archivePath, `${line}\n`);
349
+ // A: count coverage on a successful append only — an
350
+ // archive write that threw must not inflate the coverage counter.
351
+ recordCompactionHealth("totalArchivesWritten");
352
+ log.info(`[context-manager] Originals archived to ${archivePath} (verify: ${reason}) — ` +
353
+ `recover via context_navigate/read`);
354
+ }
355
+ catch (e) {
356
+ log.error("[context-manager] Originals archive write failed:", e);
357
+ }
358
+ finally {
359
+ // Owns the flag lifecycle: verifyFailed must never linger after the
360
+ // write attempt (success or failure), and the capture is consumed.
361
+ try {
362
+ const cmState = getCmState(ctx);
363
+ cmState.verifyFailed = false;
364
+ cmState.pendingCompactionOriginals = undefined;
365
+ }
366
+ catch {
367
+ /* state unavailable */
368
+ }
369
+ }
370
+ }
371
+ /**
372
+ * Source stamped on the durable seat record. A reader that has to recover
373
+ * owner input after a crash looks for this value in the branch's
374
+ * `braid_injection` entries.
375
+ */
376
+ export const OWNER_INPUT_SEAT_SOURCE = "context-manager/owner-input-seat";
377
+ /** Bounded ring so a long session's delivery confirmations stay small. */
378
+ const MAX_DELIVERED_OWNER_INPUTS = 32;
379
+ const EMPTY_INTERCEPT_STATE = {
380
+ queuedDuringCompaction: undefined,
381
+ preAppendedEntryId: undefined,
382
+ origAppendMessage: undefined,
383
+ interceptActive: false,
384
+ interceptedSmRef: undefined,
385
+ holdQueuedPrompt: false,
386
+ heldQueuedText: undefined,
387
+ pendingOwnerInputs: [],
388
+ deliveredOwnerInputs: [],
389
+ };
390
+ function getInterceptState(ctx) {
391
+ return getExtensionState(ctx, "context-manager/compaction-intercept", () => ({
392
+ ...EMPTY_INTERCEPT_STATE,
393
+ // Fresh arrays: the spread above copies the const's references, and a
394
+ // push into a shared array would leak one session's seats into the next.
395
+ pendingOwnerInputs: [],
396
+ deliveredOwnerInputs: [],
397
+ }));
398
+ }
399
+ /**
400
+ * Create a wrapper for sessionManager.appendMessage that skips the duplicate
401
+ * when flushCompactionQueue's session.prompt() fires after our pre-append.
402
+ *
403
+ * SAFETY: Captures the original appendMessage in the closure at creation time.
404
+ * This prevents self-recursion (max call stack) if intercept state is cleared
405
+ * while the wrapper is still in place — the fallback still delegates to the
406
+ * original function rather than calling sessionManager.appendMessage (which
407
+ * IS the wrapper itself).
408
+ *
409
+ * Returns the pre-appended entry ID to avoid creating a duplicate entry.
410
+ */
411
+ function createSkipDuplicateWrapper(sessionManager, ctx, originalAppendMessage) {
412
+ return (msg) => {
413
+ const st = getInterceptState(ctx);
414
+ // Safety: if intercept was deactivated (e.g., the outcome stage closing a
415
+ // cycle with no queued messages), pass through to the original without any
416
+ // duplicate detection.
417
+ if (!st.interceptActive) {
418
+ return originalAppendMessage.call(sessionManager, msg);
419
+ }
420
+ // Only messages with content[] can be the duplicate user message.
421
+ // BashExecutionMessage has NO `content` field - must pass through.
422
+ const content = msg?.content;
423
+ if (Array.isArray(content)) {
424
+ const text = content[0]?.text;
425
+ if (typeof text === "string" && text === st.queuedDuringCompaction) {
426
+ // Skip - this is the duplicate from session.prompt()'s message_end handler.
427
+ // The original from session_compact is already in sessionManager.
428
+ // Return the pre-appended entry ID so the caller gets a valid ID.
429
+ return st.preAppendedEntryId ?? "";
430
+ }
431
+ }
432
+ // Not a duplicate — delegate to original (captured in closure).
433
+ return originalAppendMessage.call(sessionManager, msg);
434
+ };
435
+ }
436
+ /**
437
+ * Attempt to restore sessionManager.appendMessage from the intercept.
438
+ * Called wherever the intercept window can close without the flush replay:
439
+ * the input hook that spends the manual-compaction hold, the message_end
440
+ * backup, session_compact_failed, and session shutdown.
441
+ */
442
+ export function tryRestoreAppendMessage(ctx) {
443
+ const st = getInterceptState(ctx);
444
+ if (!st.interceptActive || !st.origAppendMessage)
445
+ return;
446
+ // The install side wraps the manager ctx exposes (getFullSessionManager),
447
+ // so the restore must read the same handle for the same-instance guard
448
+ // below to mean anything. pi's ExtensionAPI carries no sessionManager.
449
+ const sm = getFullSessionManager(ctx);
450
+ if (!sm) {
451
+ // No sessionManager available - clear intercept state.
452
+ st.interceptActive = false;
453
+ st.origAppendMessage = undefined;
454
+ st.interceptedSmRef = undefined;
455
+ return;
456
+ }
457
+ // Only restore if the sessionManager is the same one we intercepted.
458
+ // After session replacement (reload/newSession), sm is a new instance
459
+ // and the old st.origAppendMessage is stale - DO NOT restore.
460
+ if (sm !== st.interceptedSmRef) {
461
+ log.debug("[context-manager] Skipped intercept restore - sessionManager replaced");
462
+ st.interceptActive = false;
463
+ st.origAppendMessage = undefined;
464
+ st.interceptedSmRef = undefined;
465
+ return;
466
+ }
467
+ // Verify appendMessage is still our wrapper (not further mutated).
468
+ // If it's no longer the wrapper, someone else already restored it.
469
+ if (typeof sm.appendMessage !== "function" || sm.appendMessage === st.origAppendMessage) {
470
+ // Not wrapped or already restored - nothing to do.
471
+ st.interceptActive = false;
472
+ st.origAppendMessage = undefined;
473
+ st.interceptedSmRef = undefined;
474
+ return;
475
+ }
476
+ sm.appendMessage = st.origAppendMessage;
477
+ st.origAppendMessage = undefined;
478
+ st.interceptActive = false;
479
+ st.interceptedSmRef = undefined;
480
+ log.debug("[context-manager] AppendMessage intercept restored");
481
+ }
482
+ export function clearInterceptState(ctx) {
483
+ // Unwrap before clearing: the bookkeeping below is what the restore path
484
+ // reads, so clearing first would strand the wrapper on the session manager.
485
+ tryRestoreAppendMessage(ctx);
486
+ const st = getInterceptState(ctx);
487
+ st.queuedDuringCompaction = undefined;
488
+ st.preAppendedEntryId = undefined;
489
+ st.origAppendMessage = undefined;
490
+ st.interceptActive = false;
491
+ st.interceptedSmRef = undefined;
492
+ st.holdQueuedPrompt = false;
493
+ st.heldQueuedText = undefined;
494
+ setCompactionActive(false, ctx);
495
+ }
496
+ /**
497
+ * Force-persist the session to disk.
498
+ * This is needed because sessionManager._persist() has a no-assistant guard that
499
+ * returns early without writing if there's no assistant message yet.
500
+ * When we pre-append a user message during compaction (before any assistant response),
501
+ * _persist() silently ignores it, causing the message to be lost on session reload.
502
+ *
503
+ * This function manually writes all pending entries to disk, bypassing the guard.
504
+ */
505
+ function forcePersistSession(sm) {
506
+ try {
507
+ if (!sm?.sessionFile || !sm?.persist)
508
+ return;
509
+ const flushed = sm.flushed;
510
+ const fileEntries = sm.fileEntries;
511
+ // The force-write reaches pi-core's private buffer by design (its own
512
+ // _persist() guards on a landed user/assistant message). A rename of
513
+ // either private field would otherwise silently turn this loss-prevention
514
+ // write into a no-op, or re-append entries that were already persisted.
515
+ // Verify the private shape before writing.
516
+ if (typeof flushed !== "boolean" || !Array.isArray(fileEntries)) {
517
+ log.warn("[context-manager] Force-persist skipped: sessionManager private layout changed " +
518
+ "(expected flushed:boolean, fileEntries:array)");
519
+ return;
520
+ }
521
+ if (!flushed && fileEntries.length > 0) {
522
+ // Write all entries to establish the session file with all content
523
+ for (const entry of fileEntries) {
524
+ appendFileSync(sm.sessionFile, `${JSON.stringify(entry)}\n`);
525
+ }
526
+ sm.flushed = true;
527
+ log.debug(`[context-manager] Force-persisted ${fileEntries.length} entries to ${sm.sessionFile}`);
528
+ }
529
+ }
530
+ catch (e) {
531
+ log.error("[context-manager] Force-persist failed:", e);
532
+ }
533
+ }
534
+ // Durable owner-input seat.
535
+ // The intercept state above is an in-memory seat, and a failed compaction
536
+ // wipes it (clearInterceptState) while the text exists nowhere else: the
537
+ // TUI's compaction queue lives in the TUI process, non-TUI callers have none,
538
+ // and a steer parked in pi's in-memory steering queue is invisible to the
539
+ // session tree. Owner text therefore gets a durable copy at receipt, written
540
+ // through the same store every tracked injection uses (`braid_injection`
541
+ // session entries; injection-tracker owns that write path), and delivery is
542
+ // confirmed by the session's own message events.
543
+ //
544
+ // The seat is a COPY, never a second queue: text pi still holds in its own
545
+ // queue is not re-delivered (a settled run's unconsumed steer is drained by
546
+ // the next run's start), and a text confirmed delivered is never delivered
547
+ // again.
548
+ /** Record owner text in the durable seat, once per undelivered text. */
549
+ function seatOwnerInput(ctx, text, kind) {
550
+ try {
551
+ const st = getInterceptState(ctx);
552
+ if (st.deliveredOwnerInputs.includes(text))
553
+ return;
554
+ if (st.pendingOwnerInputs.some((item) => item.text === text))
555
+ return;
556
+ st.pendingOwnerInputs.push({ text, kind, seatedAt: Date.now() });
557
+ trackInjection({
558
+ type: "context",
559
+ source: OWNER_INPUT_SEAT_SOURCE,
560
+ content: text,
561
+ display: true,
562
+ steer: kind === "steer",
563
+ fullContent: true,
564
+ });
565
+ }
566
+ catch (e) {
567
+ log.warn("[context-manager] owner-input seat write failed:", e);
568
+ }
569
+ }
570
+ /**
571
+ * Confirm delivery and drop the pending seat. `remember` also suppresses
572
+ * re-seating a replay of this text: a park is followed by the TUI flush
573
+ * replay, which is a second receipt of text already in the session.
574
+ */
575
+ function markOwnerInputDelivered(ctx, text, remember = false) {
576
+ const st = getInterceptState(ctx);
577
+ const index = st.pendingOwnerInputs.findIndex((item) => item.text === text);
578
+ if (index >= 0)
579
+ st.pendingOwnerInputs.splice(index, 1);
580
+ if (index < 0 && !remember)
581
+ return;
582
+ st.deliveredOwnerInputs.push(text);
583
+ while (st.deliveredOwnerInputs.length > MAX_DELIVERED_OWNER_INPUTS) {
584
+ st.deliveredOwnerInputs.shift();
585
+ }
586
+ }
587
+ /**
588
+ * Write one owner text into the session as a user message and force-persist
589
+ * it - the delivery the successful compaction path pre-appends, reused by the
590
+ * failure and settle paths. Returns false when no session manager is
591
+ * reachable; the durable seat still holds the text.
592
+ */
593
+ function parkOwnerTextInSession(ctx, text) {
594
+ const sm = getFullSessionManager(ctx);
595
+ if (!sm || typeof sm.appendMessage !== "function")
596
+ return false;
597
+ try {
598
+ const st = getInterceptState(ctx);
599
+ const messageObj = {
600
+ role: "user",
601
+ content: [{ type: "text", text }],
602
+ timestamp: Date.now(),
603
+ };
604
+ // Append through the original when the intercept wrapper is already
605
+ // installed for THIS session manager, so the wrapper's duplicate skip
606
+ // cannot swallow this write. A replaced manager (session reload) must
607
+ // never receive the write through the stale binding.
608
+ const reuseWrapper = Boolean(st.interceptActive && st.origAppendMessage && st.interceptedSmRef === sm);
609
+ const append = reuseWrapper && st.origAppendMessage ? st.origAppendMessage : sm.appendMessage.bind(sm);
610
+ st.preAppendedEntryId = append(messageObj);
611
+ if (!reuseWrapper) {
612
+ // Fresh intercept window: wrap appendMessage so the flush replay of this
613
+ // text is skipped instead of creating a duplicate entry.
614
+ st.origAppendMessage = sm.appendMessage.bind(sm);
615
+ sm.appendMessage = createSkipDuplicateWrapper(sm, ctx, st.origAppendMessage);
616
+ st.interceptedSmRef = sm;
617
+ st.interceptActive = true;
618
+ }
619
+ forcePersistSession(sm);
620
+ markOwnerInputDelivered(ctx, text, true);
621
+ log.info(`[context-manager] Owner input parked in the session (entry: ${st.preAppendedEntryId})`);
622
+ return true;
623
+ }
624
+ catch (e) {
625
+ log.error("[context-manager] Failed to park owner input in the session:", e);
626
+ return false;
627
+ }
628
+ }
629
+ /**
630
+ * Re-deliver owner inputs still pending at a lifecycle boundary.
631
+ *
632
+ * - "failure": the compaction cycle landed no entry. Deliver now only when the
633
+ * session is idle; a live run must not receive a raw session write mid-run
634
+ * (message order), so the text waits for the settle boundary.
635
+ * - "settle": the run has settled. Texts pi still holds in its own queue are
636
+ * skipped - the next run's start drains them (the agent loop polls the
637
+ * steering queue at run start), and delivering here would duplicate that.
638
+ * - "shutdown": last chance to persist; deliver everything still pending.
639
+ */
640
+ export function flushPendingOwnerInputs(ctx, phase) {
641
+ let pending;
642
+ try {
643
+ pending = [...getInterceptState(ctx).pendingOwnerInputs];
644
+ }
645
+ catch {
646
+ return;
647
+ }
648
+ if (pending.length === 0)
649
+ return;
650
+ if (phase === "failure" && !readIdle(ctx))
651
+ return;
652
+ if (phase === "settle" && readHasPendingMessages(ctx))
653
+ return;
654
+ for (const item of pending) {
655
+ parkOwnerTextInSession(ctx, item.text);
656
+ }
657
+ }
658
+ /** Live idle read, fail-open to delivery (a missed delivery loses owner text). */
659
+ function readIdle(ctx) {
660
+ try {
661
+ return typeof ctx.isIdle === "function" ? ctx.isIdle() : true;
662
+ }
663
+ catch {
664
+ return true;
665
+ }
666
+ }
667
+ /**
668
+ * Live queued-messages read. Fail-closed: an unreadable queue must not make
669
+ * the settle flush re-deliver text pi may still be holding.
670
+ */
671
+ function readHasPendingMessages(ctx) {
672
+ try {
673
+ return typeof ctx.hasPendingMessages === "function" ? ctx.hasPendingMessages() : false;
674
+ }
675
+ catch {
676
+ return false;
677
+ }
678
+ }
679
+ /**
680
+ * Drop the seat bookkeeping. For shutdown (after the flush above) and for
681
+ * fixtures; the durable entries stay in the session either way.
682
+ */
683
+ export function clearOwnerInputSeats(ctx) {
684
+ const st = getInterceptState(ctx);
685
+ st.pendingOwnerInputs.length = 0;
686
+ st.deliveredOwnerInputs.length = 0;
687
+ }
688
+ // Compaction Instructions Builder
689
+ // Generates smarter instructions for the summarization model.
690
+ // The key insight: tell the model WHAT to preserve, not just "summarize".
691
+ function buildCompactionInstructions(audit) {
692
+ const instructions = [];
693
+ // 1. Task state preservation
694
+ if (audit.tagCount > 0) {
695
+ instructions.push(`Session has ${audit.tagCount} checkpoint(s): preserve tag labels for navigation.`);
696
+ }
697
+ // 2. Prune candidates - tell model what to cut
698
+ const highPriorityPrune = audit.candidates?.filter((c) => c.score >= 0.6) ?? [];
699
+ if (highPriorityPrune.length > 3) {
700
+ instructions.push(`${highPriorityPrune.length} entries are prune candidates with low semantic value - summarize briefly.`);
701
+ }
702
+ // 3. Context pressure - tell model how aggressive to be
703
+ if (audit.usage.percent > 85) {
704
+ instructions.push(`CRITICAL: Context at ${audit.usage.percent.toFixed(0)}% - aggressively summarize. ` +
705
+ `Preserve: (1) active task/goals, (2) key file paths and edits, (3) error states. ` +
706
+ `Discard: verbose tool outputs, repeated reads, exploration logs.`);
707
+ }
708
+ else if (audit.usage.percent > CONTEXT_COMPACT_REFUSE_PERCENT) {
709
+ instructions.push(`Context at ${audit.usage.percent.toFixed(0)}% - moderate summarization. ` +
710
+ `Keep: task context, recent decisions, pending work. Summarize: older tool outputs.`);
711
+ }
712
+ // 4. Semantic preservation rules
713
+ instructions.push("Preserve tool-call/result pairs together - never split a tool call from its result. " +
714
+ "If a tool call produced an error, keep both the call and the error.");
715
+ // 5. Memory hint
716
+ instructions.push("After compaction: consider storing key learnings in memory for cross-session continuity.");
717
+ return instructions;
718
+ }
719
+ // Session before compact: custom instructions before compaction for
720
+ // smarter LLM summarization.
721
+ //
722
+ // The path always uses LLM summarization - it's fast (a few seconds) and
723
+ // produces better summaries than hard truncation; pi-core handles its own
724
+ // last-resort safety net.
725
+ //
726
+ // Flow:
727
+ // 1. Deduplicate - prevent two compaction entries from manual+auto call sites
728
+ // 2. Pre-filter - remove 100%-safe-to-remove items (STEP 1)
729
+ // 3. Instruct - inject smart summarization instructions (STEP 2)
730
+ // pi core then calls LLM summarization with our instructions
731
+ /**
732
+ * Capture the messages a deterministic cut drops as this cycle's originals
733
+ * capture, so the trace's span size and the originals archive describe the cut
734
+ * that actually landed rather than pi-core's default token-cut span. Degrades
735
+ * to the existing capture, never to a wrong one.
736
+ */
737
+ function captureDroppedSpanBefore(ctx, cutEntryId) {
738
+ try {
739
+ const sm = ctx.sessionManager;
740
+ const branch = typeof sm.getBranch === "function"
741
+ ? (sm.getBranch() ?? [])
742
+ : [];
743
+ const cutIndex = branch.findIndex((entry) => entry?.id === cutEntryId);
744
+ if (cutIndex < 0)
745
+ return;
746
+ const droppedMessages = [];
747
+ for (const entry of branch.slice(0, cutIndex)) {
748
+ const message = entry.message;
749
+ if (entry.type === "message" && message)
750
+ droppedMessages.push(message);
751
+ }
752
+ getCmState(ctx).pendingCompactionOriginals = JSON.stringify(droppedMessages);
753
+ }
754
+ catch {
755
+ /* capture replacement unavailable - telemetry degrades to the default snapshot */
756
+ }
757
+ }
758
+ /**
759
+ * Deterministic no-LLM cut point: the last rung of the summary-cap ladder.
760
+ * Persists an extension compaction result that drops the oldest entries and
761
+ * keeps the recent tail live - the same cut shape the high-context guard
762
+ * persists, reused here so a bounded summarizer failure can never leave a
763
+ * session unable to compact. Returns null when no cut point resolves (the
764
+ * caller then cancels as before).
765
+ *
766
+ * `reason` and `detail` are the landed summary's own account of why the cut was
767
+ * taken; the defaults describe the bounded-summarizer failure this rung was
768
+ * first built for, and the fail-safe rung passes its own.
769
+ */
770
+ function buildDeterministicCut(ctx, prep, account = {}) {
771
+ const reason = account.reason ?? "after a bounded summarizer failure";
772
+ const detail = account.detail ?? "(the chunked summarizer exhausted its bounded budget on this span)";
773
+ try {
774
+ const sm = ctx.sessionManager;
775
+ const branch = typeof sm.getBranch === "function"
776
+ ? (sm.getBranch() ?? [])
777
+ : [];
778
+ const keepCount = Math.min(50, Math.max(10, Math.floor(branch.length * 0.3)));
779
+ // The deterministic cut is a supplied boundary: snap it out of any tool
780
+ // batch it lands in (HTTP 400: a kept slice that opens with a tool result
781
+ // has no preceding tool_calls).
782
+ const cutIndex = snapBoundaryOutsideToolBatch(branch, Math.max(0, branch.length - keepCount));
783
+ const cutEntryId = branch[cutIndex]?.id;
784
+ if (!cutEntryId || cutIndex <= 0)
785
+ return null;
786
+ const keptCount = branch.length - cutIndex;
787
+ const cmState = getCmState(ctx);
788
+ cmState.slideMode = {
789
+ active: true,
790
+ cutEntryId,
791
+ keepCount: keptCount,
792
+ droppedCount: cutIndex,
793
+ timestamp: Date.now(),
794
+ };
795
+ captureDroppedSpanBefore(ctx, cutEntryId);
796
+ return {
797
+ compaction: {
798
+ summary: `Deterministic cut ${reason}: dropped the ${cutIndex} entries ` +
799
+ `before the cut without LLM summarization ${detail}. The last ${keptCount} entries ` +
800
+ `remain live; dropped content stays in the append-only session file and the originals archive.`,
801
+ firstKeptEntryId: cutEntryId,
802
+ tokensBefore: typeof prep?.tokensBefore === "number" ? prep.tokensBefore : 0,
803
+ details: { readFiles: [], modifiedFiles: [] },
804
+ },
805
+ };
806
+ }
807
+ catch (err) {
808
+ log.error("[context-manager] deterministic cut failed:", err);
809
+ return null;
810
+ }
811
+ }
812
+ export function registerBeforeCompactHandler(pi) {
813
+ // Input hook: capture user's queued message during compaction
814
+ // When the user sends a message while compaction is running, it is queued in
815
+ // TUI's compactionQueuedMessages (not persisted to sessionManager yet).
816
+ // We capture the text here so we can pre-append it to sessionManager in
817
+ // session_compact (before TUI's rebuildChatFromMessages runs).
818
+ pi.on(INPUT, (event, ctx) => {
819
+ if (!event?.text)
820
+ return;
821
+ // Durable seat at receipt: text entering a queue this extension cannot
822
+ // verify drains (the compaction capture window, or a steer/follow-up into
823
+ // a run) gets its durable copy before any cycle can consume the capture.
824
+ // An idle prompt is delivered by definition and is not seated.
825
+ // Per-session active read: the ctx-less fallback is a single-session
826
+ // shortcut, and this hook's ctx is the session the text belongs to.
827
+ const compactionActive = isCompactionActive(ctx);
828
+ if (compactionActive || event.streamingBehavior !== undefined) {
829
+ seatOwnerInput(ctx, event.text, compactionActive ? "compaction" : "steer");
830
+ }
831
+ // Guard: only capture messages typed DURING active compaction.
832
+ // Messages typed before compaction starts are already in sessionManager
833
+ // and should NOT be pre-appended (would create a duplicate).
834
+ if (compactionActive) {
835
+ const st = getInterceptState(ctx);
836
+ if (st.queuedDuringCompaction === undefined) {
837
+ st.queuedDuringCompaction = event.text;
838
+ }
839
+ }
840
+ // Manual-compaction hold (armed in session_compact): a manual compaction is
841
+ // a full stop: the TUI's post-compaction flush replays the parked message
842
+ // via session.prompt(text, {streamingBehavior}), which would start a fresh
843
+ // assistant turn from pre-compaction input. The hold is one-shot: the first
844
+ // post-compaction input event spends it. Swallow only the exact replay:
845
+ // held text arriving as a queued prompt (streamingBehavior set, the flush's
846
+ // call shape; a genuinely new idle submit carries no streamingBehavior).
847
+ // Any other input disarms without swallowing. Either way the parked text
848
+ // stays in the session (pre-appended at session_compact) and the intercept
849
+ // wrapper is restored, since the flush it guarded can no longer duplicate.
850
+ const st = getInterceptState(ctx);
851
+ if (st.holdQueuedPrompt) {
852
+ const isFlushReplay = event.text === st.heldQueuedText && event.streamingBehavior !== undefined;
853
+ st.holdQueuedPrompt = false;
854
+ st.heldQueuedText = undefined;
855
+ st.queuedDuringCompaction = undefined;
856
+ tryRestoreAppendMessage(ctx);
857
+ if (isFlushReplay) {
858
+ log.info("[context-manager] Manual compaction: flush replay of parked message swallowed - no turn from pre-compaction input");
859
+ return { action: "handled" };
860
+ }
861
+ }
862
+ });
863
+ pi.on(SESSION_BEFORE_COMPACT, async (event, ctx) => {
864
+ try {
865
+ const sessionId = getSessionIdSafe(ctx);
866
+ const leafId = getLeafIdSafe(ctx);
867
+ // Capture whether a compaction is ALREADY in-flight when this firing
868
+ // begins (a same-cycle double-fire), BEFORE we mark this cycle active.
869
+ const wasCompactionInFlight = isCompactionActive(ctx);
870
+ // P2a: carry the in-flight capture to the outcome stage so an abort of
871
+ // this cycle can be tagged with whether another compaction was
872
+ // in-flight. Store before the dedup early-return so even a second
873
+ // (deduped) firing leaves
874
+ // the tag for the abort path.
875
+ try {
876
+ getCmState(ctx).inFlightBeforeCapture = wasCompactionInFlight;
877
+ }
878
+ catch {
879
+ /* state unavailable - abort tagging degrades to untagged */
880
+ }
881
+ setCompactionActive(true, ctx);
882
+ // Arm the stall watchdog: an in-flight cycle that never reaches an
883
+ // outcome (a summarization stream stalled mid-flight) must not freeze
884
+ // the agent. Re-firings of the same cycle just refresh the deadline.
885
+ armCompactionWatchdog(pi, ctx, { reason: event.reason });
886
+ // Cycle identity for post-hoc pairing: one monotonic counter per
887
+ // session_before_compact firing, written into every trace as `cycleId`
888
+ // so an outcome names the attempt it belongs to rather than being
889
+ // reconstructable only by entry ordering. Mirrors the watchdog's
890
+ // per-arm counter.
891
+ try {
892
+ const cmc = getCmState(ctx);
893
+ cmc.compactionCycleId = (cmc.compactionCycleId ?? 0) + 1;
894
+ }
895
+ catch {
896
+ /* state unavailable - cycle id degrades to absent in the trace */
897
+ }
898
+ if (!markCompactProcessed(sessionId, leafId, ctx, wasCompactionInFlight)) {
899
+ log.info("[context-manager] session_before_compact duplicate - skipping");
900
+ return;
901
+ }
902
+ // Fresh cycle: the previous cycle's capture and manual-compaction hold
903
+ // are spent. Clearing here keeps the capture keyed to THIS cycle (a stale
904
+ // text would be pre-appended as a duplicate at this cycle's session_compact
905
+ // and would arm the hold against the wrong message), and disarms a hold
906
+ // that survived its flush window unspent (e.g. a queue replayed entirely
907
+ // as commands/steers produced no input event). The new cycle re-arms at
908
+ // session_compact if it parks a message. The stale cancel source is
909
+ // cleared too: an unattributed abort of THIS cycle must not inherit the
910
+ // previous cycle's attribution.
911
+ try {
912
+ const ist = getInterceptState(ctx);
913
+ ist.queuedDuringCompaction = undefined;
914
+ ist.holdQueuedPrompt = false;
915
+ ist.heldQueuedText = undefined;
916
+ // The replay suppression is cycle-scoped: a text parked by the cycle
917
+ // that just closed must not suppress a seat for the same text typed
918
+ // into a later cycle.
919
+ ist.deliveredOwnerInputs = [];
920
+ }
921
+ catch {
922
+ /* intercept state unavailable - fresh-cycle hygiene degrades to no-op */
923
+ }
924
+ try {
925
+ getCmState(ctx).cancelSource = undefined;
926
+ getCmState(ctx).summaryCapCancelError = undefined;
927
+ }
928
+ catch {
929
+ /* state unavailable - abort attribution degrades to untagged */
930
+ }
931
+ // Reset the pre-compaction usage capture so a stale
932
+ // value from a previous cycle can never trigger a false budget failure at
933
+ // the outcome stage. A fresh value is stashed below wherever an existing
934
+ // analyzeSession runs (fingerprint block + STEP 0.75 guard).
935
+ try {
936
+ getCmState(ctx).preCompactionUsagePercent = undefined;
937
+ }
938
+ catch {
939
+ /* state unavailable - budget verify degrades to coherence-only */
940
+ }
941
+ const prep = event.preparation;
942
+ // Read once, before any branch that may rewrite event.customInstructions:
943
+ // the SLIDE_MODE marker decides whether this cycle is the operator's own
944
+ // deterministic cut (below).
945
+ const customInstructions = event.customInstructions;
946
+ const isOperatorSlide = typeof customInstructions === "string" && customInstructions.includes("SLIDE_MODE");
947
+ // Fail-safe rung: the previous cycles each ended with no landed entry
948
+ // while this session sat above the critical usage band, and the failure
949
+ // routing armed a deterministic cut rather than trying the summarizer
950
+ // again. Land it here, BEFORE the blocks below can cancel or hand a span
951
+ // to a summarizer: pi-core consumes an extension compaction result
952
+ // verbatim and skips its own call, so this cycle compacts with no LLM
953
+ // request at all. An operator's own slide keeps precedence and leaves the
954
+ // cut armed for the next cycle.
955
+ if (prep && !isOperatorSlide) {
956
+ const armed = consumeCompactionFailsafeCut(ctx);
957
+ if (armed) {
958
+ const cut = buildDeterministicCut(ctx, prep, {
959
+ reason: armed.reason,
960
+ detail: "(no summarizer call was attempted for this cut)",
961
+ });
962
+ if (cut) {
963
+ log.error(`[context-manager] Fail-safe cut landing: ${armed.reason} - persisting the ` +
964
+ `deterministic cut (no LLM summarization)`);
965
+ return cut;
966
+ }
967
+ // No cut point resolves (branch too short to drop anything). Reset the
968
+ // ladder instead of re-dispatching per failure, so the next arm needs
969
+ // a fresh sequence of no-progress cycles.
970
+ log.error(`[context-manager] Fail-safe cut armed but no cut point resolves ` +
971
+ `(branch has nothing to drop) - continuing with the normal path`);
972
+ clearCompactionFailsafe(ctx);
973
+ }
974
+ }
975
+ // If the compaction INPUT is identical to the last SUCCESSFUL compaction
976
+ // on this leaf, re-summarizing it is pure waste ("silent re-prime
977
+ // starvation"): the agent keeps receiving the same summary and the
978
+ // redundant steering (pre-filter, semantic compression, summarization)
979
+ // burns tokens for zero new value.
980
+ //
981
+ // pi-core 0.83.0 (installed) cancel contract — verified:
982
+ // runner.js:570/586-588 — a session-before handler returning an object
983
+ // with a truthy `.cancel` short-circuits the event emit.
984
+ // agent-session.js:1396/1400-1402 (manual compact()) — event.reason ===
985
+ // "manual"; result?.cancel throws "Compaction cancelled".
986
+ // agent-session.js:1615-1629 (_runAutoCompaction) — event.reason is the
987
+ // auto reason ("threshold"|"overflow"); extensionResult?.cancel emits
988
+ // the internal compaction_end(aborted) plus the extension-visible
989
+ // session_compact_failed, and returns false (clean no-op, no branch
990
+ // mutation). So auto vs manual IS distinguishable and the cancel path
991
+ // is safe for auto.
992
+ //
993
+ // Decision rule: cancel ONLY the auto path (reason !== "manual"), and
994
+ // ONLY when usage < 85 — critical pressure must still compact to avoid
995
+ // overflow, and manual/agent-initiated compaction is explicit intent that
996
+ // is never skipped.
997
+ if (prep?.messagesToSummarize?.length) {
998
+ const cmState = getCmState(ctx);
999
+ const leafKey = `${sessionId}::${leafId}`;
1000
+ const branch = typeof ctx.sessionManager?.getBranch === "function"
1001
+ ? (ctx.sessionManager.getBranch() ?? [])
1002
+ : [];
1003
+ const currentFp = computeCompactionFingerprint(branch, prep.messagesToSummarize, prep.firstKeptEntryId);
1004
+ if (cmState.lastCompactionFingerprints?.[leafKey] === currentFp) {
1005
+ let usagePercent = 0;
1006
+ try {
1007
+ usagePercent = analyzeSession(ctx).usage.percent;
1008
+ // Capture pre-compaction usage for the
1009
+ // outcome-stage budget verify — reuses this analyzeSession (
1010
+ // code path). The STEP 0.75 guard below re-stashes the same value
1011
+ // for the standard path.
1012
+ cmState.preCompactionUsagePercent = usagePercent;
1013
+ }
1014
+ catch {
1015
+ /* non-fatal - analysis unavailable */
1016
+ }
1017
+ const isManual = event.reason === "manual";
1018
+ if (!isManual && usagePercent < 85) {
1019
+ log.info(`[context-manager] Input unchanged since last compaction — skipping ` +
1020
+ `(leaf ${leafKey}, usage ${usagePercent.toFixed(1)}%)`);
1021
+ // Cancel the auto-compaction: pi-core emits the internal
1022
+ // compaction_end(aborted) plus the extension-visible
1023
+ // session_compact_failed, and returns false — a clean no-op that
1024
+ // leaves the branch untouched. Attribute the cancel so the failed
1025
+ // handler records a deliberate skip, not an unexplained abort.
1026
+ try {
1027
+ getCmState(ctx).cancelSource = "extension";
1028
+ }
1029
+ catch {
1030
+ /* state unavailable - cancel attribution degrades to untagged */
1031
+ }
1032
+ return { cancel: true, reason: "input unchanged since last compaction" };
1033
+ }
1034
+ log.info(`[context-manager] Input unchanged since last compaction but NOT skipping: ` +
1035
+ `${isManual ? "manual intent" : `critical usage ${usagePercent.toFixed(1)}%`}`);
1036
+ }
1037
+ // Stash the current input fingerprint so session_compact can record it
1038
+ // on success — the branch is mutated by then, so it can't be recomputed.
1039
+ cmState.pendingCompactionFingerprint = currentFp;
1040
+ }
1041
+ // Capture the RAW originals for the recovery
1042
+ // archive. Placed AFTER the fingerprint block (which may cancel) and
1043
+ // BEFORE the semantic-compression block (STEP 1.5 replaces
1044
+ // prep.messagesToSummarize in place — capture must see the RAW originals,
1045
+ // byte-exact, independent of later in-place mutation). Serialized to JSON
1046
+ // so the snapshot is immutable; serialization failure degrades the
1047
+ // archive to off and never breaks the compaction path.
1048
+ if (prep?.messagesToSummarize?.length) {
1049
+ try {
1050
+ getCmState(ctx).pendingCompactionOriginals = JSON.stringify(prep.messagesToSummarize);
1051
+ }
1052
+ catch {
1053
+ log.warn("[context-manager] Failed to capture compaction originals for recovery archive");
1054
+ }
1055
+ }
1056
+ // Slide mode arrives via customInstructions, set by context_compress action="slide".
1057
+ // When slide mode is active, respond with pi-core's extension-compaction
1058
+ // result: compact() skips the default LLM summarization entirely and
1059
+ // appends this result verbatim (fromExtension=true). Steering
1060
+ // prep.messagesToSummarize=[] alone would still route the stale summary
1061
+ // through the UPDATE prompt — an LLM call re-rendering old content from
1062
+ // an empty conversation, costing output tokens and minutes for zero new
1063
+ // value.
1064
+ if (isOperatorSlide && prep) {
1065
+ const cmState = getCmState(ctx);
1066
+ const slide = cmState.slideMode;
1067
+ if (slide?.active && slide.cutEntryId) {
1068
+ // The stored cut is a supplied boundary: re-snap it against the
1069
+ // branch as it stands at consumption (the armer may have read the
1070
+ // branch before the batch's later results landed). HTTP 400: a kept
1071
+ // slice that opens with a tool result has no preceding tool_calls.
1072
+ const slideBranch = typeof ctx.sessionManager?.getBranch === "function"
1073
+ ? (ctx.sessionManager.getBranch() ?? [])
1074
+ : [];
1075
+ const storedIndex = slideBranch.findIndex((entry) => entry?.id === slide.cutEntryId);
1076
+ const cutIndex = storedIndex >= 0 ? snapBoundaryOutsideToolBatch(slideBranch, storedIndex) : -1;
1077
+ const cutEntryId = cutIndex >= 0
1078
+ ? (slideBranch[cutIndex]?.id ?? slide.cutEntryId)
1079
+ : slide.cutEntryId;
1080
+ const droppedCount = cutIndex >= 0 ? cutIndex : slide.droppedCount;
1081
+ const keptCount = cutIndex >= 0 ? slideBranch.length - cutIndex : slide.keepCount;
1082
+ log.info(`[context-manager] Slide mode: keeping last ${keptCount} entries, ` +
1083
+ `dropping ${droppedCount}`);
1084
+ // Telemetry honesty: the originals capture above snapshotted
1085
+ // pi-core's DEFAULT token-cut summarize set, not the deterministic
1086
+ // span this cycle actually drops. Replace it with the dropped span
1087
+ // so the compacted/kept counters and the originals archive describe
1088
+ // THIS cut, not the token-budget cut pi-core would have made.
1089
+ captureDroppedSpanBefore(ctx, cutEntryId);
1090
+ // One-shot consumption so a later normal compaction is unaffected.
1091
+ cmState.slideMode = null;
1092
+ return {
1093
+ compaction: {
1094
+ summary: `Sliding window compaction: dropped the ${droppedCount} entries before the ` +
1095
+ `cut; the last ${keptCount} entries remain live. Deterministic entry cut — ` +
1096
+ `dropped content is preserved in the append-only session file and the originals archive.`,
1097
+ firstKeptEntryId: cutEntryId,
1098
+ tokensBefore: typeof prep.tokensBefore === "number" ? prep.tokensBefore : 0,
1099
+ details: { readFiles: [], modifiedFiles: [] },
1100
+ },
1101
+ };
1102
+ }
1103
+ else {
1104
+ log.warn("[context-manager] SLIDE_MODE marker found but slide state is missing or inactive");
1105
+ }
1106
+ }
1107
+ // Set by context_compress(action="archive"): the user declared a range
1108
+ // [startIndex..endIndex] plus a summary that must anchor the compaction.
1109
+ // Apply firstKeptEntryId = <entry after endIndex> so the declared range is
1110
+ // the real compaction boundary, keep messagesToSummarize = the declared
1111
+ // span (it SHOULD be summarized), and render the user summary as an anchor
1112
+ // in the compaction instructions so the LLM carries intent, changes,
1113
+ // decisions, and next steps forward (the research-grounded anchor model).
1114
+ const rangeMode = getCmState(ctx).rangeMode;
1115
+ if (prep && rangeMode?.active) {
1116
+ const branch = typeof ctx.sessionManager?.getBranch === "function"
1117
+ ? (ctx.sessionManager.getBranch() ?? [])
1118
+ : [];
1119
+ const spanMessages = collectRangeMessages(branch, rangeMode.startIndex, rangeMode.endIndex);
1120
+ // The declared boundary is a supplied one: snap it out of any tool
1121
+ // batch it lands in (HTTP 400: a kept slice that opens with a tool
1122
+ // result has no preceding tool_calls), against the branch as it
1123
+ // stands at consumption.
1124
+ let boundaryId = rangeMode.firstKeptEntryId;
1125
+ if (boundaryId) {
1126
+ const storedIndex = branch.findIndex((entry) => entry.id === boundaryId);
1127
+ if (storedIndex >= 0) {
1128
+ const snappedIndex = snapBoundaryOutsideToolBatch(branch, storedIndex);
1129
+ boundaryId = branch[snappedIndex]?.id ?? boundaryId;
1130
+ }
1131
+ prep.firstKeptEntryId = boundaryId;
1132
+ }
1133
+ prep.messagesToSummarize = spanMessages;
1134
+ // No split-turn prefix summary — the declared span IS the summarize set.
1135
+ prep.turnPrefixMessages = [];
1136
+ prep.isSplitTurn = false;
1137
+ // Telemetry honesty (same convention as the slide branch): the capture
1138
+ // above snapshotted pi-core's default token-cut span, not the declared
1139
+ // range this cycle actually summarizes. Replace it with the span.
1140
+ try {
1141
+ getCmState(ctx).pendingCompactionOriginals = JSON.stringify(spanMessages);
1142
+ }
1143
+ catch {
1144
+ /* capture replacement unavailable - telemetry degrades to the default snapshot */
1145
+ }
1146
+ // Anchor the user summary into the compaction instructions. pi-core
1147
+ // does not read this channel back (see the dead-code gap note below);
1148
+ // the chunked takeover below folds the anchor into its own prompts.
1149
+ event.customInstructions = [
1150
+ `Declared archive range for this compaction: entries [${rangeMode.startIndex}..${rangeMode.endIndex}] (topic: "${rangeMode.topic}").`,
1151
+ `The user supplied the following anchor summary — fold its intent, changes made, decisions, and next steps into the new compaction summary; keep this substance intact:`,
1152
+ `---ANCHOR---`,
1153
+ rangeMode.summary,
1154
+ `---END ANCHOR---`,
1155
+ ].join("\n");
1156
+ // Stash the declaration so a failed cycle can re-arm it on its
1157
+ // summary-cap retry (retry cycles recompute pi-core's default span,
1158
+ // which would silently drop the declared range).
1159
+ getCmState(ctx).pendingRangeArchive = { ...rangeMode };
1160
+ // Reset range mode so subsequent compactions are unaffected.
1161
+ getCmState(ctx).rangeMode = null;
1162
+ log.info(`[context-manager] Range mode: archiving entries [${rangeMode.startIndex}..${rangeMode.endIndex}], ` +
1163
+ `${spanMessages.length} messages to summarize, boundary ${boundaryId ?? "branch-end"}`);
1164
+ // Bounded takeover: summarize the declared span in chunked calls
1165
+ // (reasoning off, fixed per-call output budget, previous summary and
1166
+ // anchor merged) and hand pi-core the finished summary as an extension
1167
+ // compaction result. The declared range never reaches a summarizer as
1168
+ // one giant call — that is the range-archive shape: a single
1169
+ // 185-message call length-stops and the archive lands
1170
+ // with no summary at all.
1171
+ const chunked = await summarizeSpanInChunks({
1172
+ ctx,
1173
+ span: spanMessages,
1174
+ anchor: { topic: rangeMode.topic, summary: rangeMode.summary },
1175
+ previousSummary: prep.previousSummary,
1176
+ signal: event.signal,
1177
+ logPrefix: "Range archive summary",
1178
+ });
1179
+ if (!("error" in chunked)) {
1180
+ // Landed: the stash is consumed (the success handler also clears it,
1181
+ // this just avoids a window where a stale stash outlives the cycle).
1182
+ getCmState(ctx).pendingRangeArchive = undefined;
1183
+ return {
1184
+ compaction: {
1185
+ summary: chunked.summary,
1186
+ firstKeptEntryId: prep.firstKeptEntryId,
1187
+ tokensBefore: typeof prep.tokensBefore === "number" ? prep.tokensBefore : 0,
1188
+ details: { readFiles: [], modifiedFiles: [] },
1189
+ ...(chunked.usage ? { usage: chunked.usage } : {}),
1190
+ },
1191
+ };
1192
+ }
1193
+ // Summary-cap class: a bounded failure must stay bounded. Handing the
1194
+ // span to pi-core's default summarizer is the one recovery that cannot
1195
+ // work for the class that made the bounded path necessary — an
1196
+ // observed failure (a 750-message span) shows the shape: chunk
1197
+ // capped -> fall-through -> pi-core's single unbounded call capped too
1198
+ // -> retry ladder burned on calls that could never complete. Cancel
1199
+ // the cycle instead; the failed routing attributes the cancel
1200
+ // (cancelSource "summary-cap") and re-arms the bounded recovery, with
1201
+ // the stash surviving to re-arm the declared range.
1202
+ if (chunked.failureClass === "summary-cap") {
1203
+ log.error(`[context-manager] Range archive chunked summary failed (${chunked.error}) — ` +
1204
+ `bounded failure, cancelling the cycle (no fall-through to pi-core's unbounded summarizer)`);
1205
+ const cmState = getCmState(ctx);
1206
+ cmState.cancelSource = "summary-cap";
1207
+ cmState.summaryCapCancelError = chunked.error;
1208
+ // A cancelled cycle never fires session_compact, so the retry guard
1209
+ // it set stays true and the ladder then answers "already active" for
1210
+ // every later retry — the armed bounded recovery starves. This
1211
+ // cycle is over; release the guard.
1212
+ const wasRetryCycle = cmState.compactionRetryActive === true;
1213
+ cmState.compactionRetryActive = false;
1214
+ if (wasRetryCycle) {
1215
+ // Never block: the bounded summarizer already had its retry cycle,
1216
+ // so the next move is deterministic instead of a third cancel that
1217
+ // leaves the session unable to compact at all.
1218
+ const cut = buildDeterministicCut(ctx, prep);
1219
+ if (cut) {
1220
+ log.error(`[context-manager] Range archive chunked summary failed twice - persisting the ` +
1221
+ `deterministic cut (no LLM summarization)`);
1222
+ return cut;
1223
+ }
1224
+ }
1225
+ return { cancel: true };
1226
+ }
1227
+ log.error(`[context-manager] Range archive chunked summary failed (${chunked.error}) — ` +
1228
+ `falling through to pi-core's default summarization`);
1229
+ // Fall through: the span stays replaced; pi-core summarizes it. That
1230
+ // call is pi-core's own, so arm the thinking-off switch for it. The
1231
+ // stash STAYS: if pi-core's call dies with a summary-cap failure, the
1232
+ // failed routing re-arms the declared range on the retry cycle.
1233
+ armSummarizerThinkingOff(pi, ctx);
1234
+ return;
1235
+ }
1236
+ // When context exceeds CONTEXT_COMPACT_REFUSE_PERCENT (owner:
1237
+ // lib/detection/context-thresholds.ts), ANY compaction path (manual context_compress or
1238
+ // pi-core auto-compaction) can cause "max call stack" crashes that corrupt
1239
+ // session state and lead to 403 provider errors. We auto-redirect to a
1240
+ // deterministic entry-based CUT POINT (slide-mode behavior). The cut is
1241
+ // applied to pi-core's boundary-aware preparation: the guard never widens
1242
+ // messagesToSummarize back to the raw branch head, and it never hands the
1243
+ // summarizer a span that pi-ai's request clamp would strangle (that span is
1244
+ // persisted as a deterministic cut instead). The normal summarization
1245
+ // machinery below (STEP 1/1.5/2) still produces a substantive summary
1246
+ // whenever the prepared span fits the window.
1247
+ //
1248
+ // This covers both compaction paths because both fire session_before_compact.
1249
+ // The existing guard in context_compress(action="compact") only covers the
1250
+ // manual tool path. Auto-compaction bypasses that guard entirely.
1251
+ if (prep?.messagesToSummarize?.length) {
1252
+ try {
1253
+ let usagePercent = 0;
1254
+ try {
1255
+ const audit = analyzeSession(ctx);
1256
+ usagePercent = audit.usage.percent;
1257
+ // Capture pre-compaction usage for the
1258
+ // outcome-stage budget verify — reuses this analyzeSession (the
1259
+ // first unconditional one in the handler).
1260
+ try {
1261
+ getCmState(ctx).preCompactionUsagePercent = usagePercent;
1262
+ }
1263
+ catch {
1264
+ /* state unavailable - budget verify degrades to coherence-only */
1265
+ }
1266
+ }
1267
+ catch {
1268
+ // Non-fatal - analysis unavailable
1269
+ }
1270
+ if (usagePercent > CONTEXT_COMPACT_REFUSE_PERCENT &&
1271
+ !event.customInstructions?.includes("SLIDE_MODE")) {
1272
+ const sm = ctx.sessionManager;
1273
+ const branch = typeof sm.getBranch === "function" ? sm.getBranch() : [];
1274
+ const keepCount = Math.min(50, Math.max(10, Math.floor(branch.length * 0.3)));
1275
+ // The guard arms a supplied boundary: snap it out of any tool batch
1276
+ // it lands in (HTTP 400: a kept slice that opens with a tool result
1277
+ // has no preceding tool_calls).
1278
+ const cutIndex = snapBoundaryOutsideToolBatch(branch, Math.max(0, branch.length - keepCount));
1279
+ const cutEntryId = branch[cutIndex]?.id;
1280
+ const keptCount = branch.length - cutIndex;
1281
+ if (cutEntryId && cutIndex > 0) {
1282
+ // Store slide state for audit trail (session_compact handler reads it).
1283
+ const cmState = getCmState(ctx);
1284
+ cmState.slideMode = {
1285
+ active: true,
1286
+ cutEntryId,
1287
+ keepCount: keptCount,
1288
+ droppedCount: cutIndex,
1289
+ timestamp: Date.now(),
1290
+ };
1291
+ // pi-core's preparation is boundary-aware: messagesToSummarize starts
1292
+ // after the last persisted compaction boundary and ends at pi-core's own
1293
+ // cut point. Replacing it with the raw branch head re-summarizes content
1294
+ // the persisted summaries already cover and can push the span past the
1295
+ // window (the strangle class this guard exists for). Keep the prepared
1296
+ // span; shrink it only when it overlaps the entries this deterministic
1297
+ // cut keeps live, shrinking in place so the boundary-aware start survives.
1298
+ // A span lying entirely inside the kept region is left alone: trimming it
1299
+ // to the cut would empty the summarize set (the defect class this guard
1300
+ // exists for).
1301
+ // The messages are the same object references as branch[i].message
1302
+ // (pi-core's prepareCompaction pushes entry.message), so the span's
1303
+ // branch indices are recoverable by identity.
1304
+ const spanMessages = prep.messagesToSummarize;
1305
+ const spanRefs = new Set(spanMessages);
1306
+ let spanStart = -1;
1307
+ let spanLast = -1;
1308
+ for (let i = 0; i < branch.length; i++) {
1309
+ const entry = branch[i];
1310
+ if (entry?.type === "message" && entry.message && spanRefs.has(entry.message)) {
1311
+ if (spanStart < 0)
1312
+ spanStart = i;
1313
+ spanLast = i;
1314
+ }
1315
+ }
1316
+ // Exclusive end of the prepared span: pi-core's kept-region anchor when
1317
+ // it resolves in the branch (it can sit past the span on split turns),
1318
+ // else the entry after the span's last message.
1319
+ const preparedKeepEntryId = prep.firstKeptEntryId;
1320
+ const preparedKeepIndex = typeof preparedKeepEntryId === "string"
1321
+ ? branch.findIndex((entry) => entry.id === preparedKeepEntryId)
1322
+ : -1;
1323
+ const spanEnd = preparedKeepIndex >= 0 ? preparedKeepIndex : spanLast + 1;
1324
+ const spanResolved = spanStart >= 0;
1325
+ const shrinksSpan = spanResolved && spanStart <= cutIndex - 1 && spanEnd > cutIndex;
1326
+ const summarySpan = shrinksSpan
1327
+ ? collectRangeMessages(branch, spanStart, cutIndex - 1)
1328
+ : spanMessages;
1329
+ // Mirror pi-ai's request-side clamp (simple-options.js:6-12:
1330
+ // available = window - estimate(prompt) - 4096). A span whose estimate
1331
+ // no longer fits leaves max_tokens at its 1-token floor, the provider
1332
+ // returns an empty length-stopped summary, and pi-core refuses to
1333
+ // persist it - the compaction aborts and re-fires every turn. Never
1334
+ // hand the summarizer such a span: persist the deterministic cut
1335
+ // instead (pi-core consumes an extension compaction result verbatim
1336
+ // and skips its summarization call).
1337
+ const window = resolveWindow(ctx?.model?.contextWindow).contextWindow;
1338
+ const spanEstimate = estimateMessagesTokens(summarySpan);
1339
+ if (spanEstimate + 4096 >= window) {
1340
+ // Telemetry honesty, same convention as the slide branch: the
1341
+ // originals capture above snapshotted pi-core's default span, not
1342
+ // the deterministic cut this cycle persists.
1343
+ captureDroppedSpanBefore(ctx, cutEntryId);
1344
+ log.warn(`[context-manager] High-context guard: dropped-span estimate ${spanEstimate} ` +
1345
+ `+ 4096 safety >= window ${window} - deterministic cut without LLM ` +
1346
+ `summarization (keep ${keptCount}/${branch.length}, dropped ${cutIndex} ` +
1347
+ `entries before ${cutEntryId}).`);
1348
+ return {
1349
+ compaction: {
1350
+ summary: `High-context deterministic cut: dropped the ${cutIndex} entries before the cut ` +
1351
+ `without LLM summarization (the summary span would not fit the configured ` +
1352
+ `context window: estimated ${spanEstimate} tokens plus 4096 safety >= ${window}). ` +
1353
+ `The last ${keptCount} entries remain live; dropped content stays in the ` +
1354
+ `append-only session file and the originals archive.`,
1355
+ firstKeptEntryId: cutEntryId,
1356
+ tokensBefore: typeof prep.tokensBefore === "number" ? prep.tokensBefore : 0,
1357
+ details: { readFiles: [], modifiedFiles: [] },
1358
+ },
1359
+ };
1360
+ }
1361
+ if (shrinksSpan) {
1362
+ prep.messagesToSummarize = summarySpan;
1363
+ prep.turnPrefixMessages = [];
1364
+ prep.isSplitTurn = false;
1365
+ prep.firstKeptEntryId = cutEntryId;
1366
+ log.warn(`[context-manager] High-context compact guard triggered: ` +
1367
+ `${usagePercent.toFixed(1)}% > ${CONTEXT_COMPACT_REFUSE_PERCENT}%. ` +
1368
+ `Deterministic cut: keep ${keptCount}/${branch.length} entries; prepared ` +
1369
+ `span trimmed to [${spanStart}..${cutIndex - 1}].`);
1370
+ }
1371
+ else {
1372
+ log.warn(`[context-manager] High-context compact guard triggered: ` +
1373
+ `${usagePercent.toFixed(1)}% > ${CONTEXT_COMPACT_REFUSE_PERCENT}%. ` +
1374
+ `Prepared boundary-aware span preserved unchanged ` +
1375
+ `(the deterministic cut [..${cutIndex - 1}] requires no trim).`);
1376
+ }
1377
+ }
1378
+ else {
1379
+ // Edge case: can't determine cut point - log and fall through.
1380
+ log.warn(`[context-manager] High-context guard: context at ${usagePercent.toFixed(1)}% ` +
1381
+ `but could not determine cut point (branch=${branch.length}, cutEntryId=${cutEntryId}). ` +
1382
+ `Falling through to normal compaction path.`);
1383
+ }
1384
+ }
1385
+ }
1386
+ catch (err) {
1387
+ // If guard itself fails, fall through to normal compaction without modifying prep.
1388
+ log.error("[context-manager] High-context guard error, falling through:", err);
1389
+ }
1390
+ }
1391
+ // Removes duplicate reads, resolved errors, oversized non-critical outputs.
1392
+ // Reduces context before LLM call so LLM summarization has an easier job.
1393
+ if (prep?.messagesToSummarize?.length) {
1394
+ // Type bridge: filterSafeToRemove uses its own AgentMessage interface;
1395
+ // pi's messagesToSummarize uses pi's AgentMessage. Structurally compatible.
1396
+ const { filtered, stats } = filterSafeToRemove(prep.messagesToSummarize);
1397
+ if (stats.totalRemoved > 0) {
1398
+ const pct = Math.round((1 - stats.afterTokens / stats.beforeTokens) * 100);
1399
+ log.info(`[context-manager] Pre-filter: removed ${stats.totalRemoved} messages ` +
1400
+ `(from ${stats.beforeTokens} to ${stats.afterTokens} tokens, saved ~${pct}%)`);
1401
+ prep.messagesToSummarize = filtered;
1402
+ }
1403
+ }
1404
+ // Compresses semantic units (redundant tool results, bloated reasoning chains,
1405
+ // low-value exchanges) before LLM summarization.
1406
+ // Uses adaptive compression level based on session state (turn count,
1407
+ // context usage %) to control how aggressively we compress.
1408
+ if (prep?.messagesToSummarize?.length) {
1409
+ try {
1410
+ // Determine adaptive compression level from session metrics
1411
+ const audit = analyzeSession(ctx);
1412
+ // Use current session context usage instead of cross-session peak
1413
+ // (getPeakUsagePercent leaked peakUsage across sessions, causing
1414
+ // aggressive compression in sessions that never hit high usage).
1415
+ const currentUsage = audit.usage.percent;
1416
+ // ExtensionContext has no turnCount - use audit.branchLength as proxy
1417
+ const proxyTurnCount = audit.branchLength ?? 0;
1418
+ const decision = await determineCompressionLevel(ctx, {
1419
+ turnCount: proxyTurnCount,
1420
+ turnsSinceCompression: proxyTurnCount - (getCmState(ctx).lastCompressionStats?.turnRange?.to ?? 0),
1421
+ consecutiveFailures: 0,
1422
+ reasoningChainDepth: audit.recommendations.length > 3 ? 4 : 1,
1423
+ messageCount: prep.messagesToSummarize.length,
1424
+ });
1425
+ const baseLevel = decision.level;
1426
+ // Escalate compression level when current context is near-full
1427
+ const compressionLevel = currentUsage > 85
1428
+ ? baseLevel === "short-term"
1429
+ ? "medium-term"
1430
+ : "long-term"
1431
+ : baseLevel;
1432
+ const { compressed, stats: scStats } = semanticCompress(prep.messagesToSummarize, compressionLevel);
1433
+ if (scStats.messagesOut < scStats.messagesIn) {
1434
+ log.info(`[context-manager] Semantic compress[${compressionLevel}]: ` +
1435
+ `${scStats.messagesIn}->${scStats.messagesOut} msgs ` +
1436
+ `(${scStats.unitsCollapsed} collapsed, ${scStats.unitsDropped} dropped)`);
1437
+ prep.messagesToSummarize = compressed;
1438
+ // Store compression metadata for retrieval quality scoring
1439
+ try {
1440
+ const state = getCmState(ctx);
1441
+ state.lastCompressionStats = {
1442
+ ...scStats,
1443
+ turnRange: {
1444
+ from: proxyTurnCount,
1445
+ to: proxyTurnCount,
1446
+ },
1447
+ timestamp: Date.now(),
1448
+ };
1449
+ }
1450
+ catch {
1451
+ log.warn("[context-manager] failed to emit end-of-turn context signal");
1452
+ }
1453
+ }
1454
+ }
1455
+ catch (err) {
1456
+ log.error("session_before_compact semantic compression error:", err);
1457
+ }
1458
+ }
1459
+ // Bounded recovery for a summary token-cap failure (class "summary-cap"):
1460
+ // the retry cycle re-enters here, and instead of replaying the same
1461
+ // oversized single call, the span is summarized in bounded chunks with
1462
+ // reasoning off (compaction-chunked.ts), then handed to pi-core as an
1463
+ // extension compaction result. Requires the armed recovery flag AND an
1464
+ // active retry cycle — a stale flag never hijacks a user compaction.
1465
+ if (prep?.messagesToSummarize?.length) {
1466
+ try {
1467
+ const cmState = getCmState(ctx);
1468
+ const recovery = cmState.pendingSummaryCapRecovery;
1469
+ if (recovery && cmState.compactionRetryActive) {
1470
+ cmState.pendingSummaryCapRecovery = undefined;
1471
+ log.info(`[context-manager] Summary-cap recovery (attempt ${recovery.attempt}): ` +
1472
+ `summarizing the ${prep.messagesToSummarize.length}-message span in bounded chunks, reasoning off`);
1473
+ const chunked = await summarizeSpanInChunks({
1474
+ ctx,
1475
+ span: prep.messagesToSummarize,
1476
+ anchor: recovery.anchor,
1477
+ previousSummary: prep.previousSummary,
1478
+ signal: event.signal,
1479
+ logPrefix: `Summary-cap recovery (attempt ${recovery.attempt})`,
1480
+ });
1481
+ if (!("error" in chunked)) {
1482
+ return {
1483
+ compaction: {
1484
+ summary: chunked.summary,
1485
+ firstKeptEntryId: prep.firstKeptEntryId,
1486
+ tokensBefore: typeof prep.tokensBefore === "number" ? prep.tokensBefore : 0,
1487
+ details: { readFiles: [], modifiedFiles: [] },
1488
+ ...(chunked.usage ? { usage: chunked.usage } : {}),
1489
+ },
1490
+ };
1491
+ }
1492
+ if (chunked.failureClass === "summary-cap") {
1493
+ log.error(`[context-manager] Summary-cap recovery chunked summary failed (${chunked.error}) — ` +
1494
+ `bounded failure, cancelling the cycle (no fall-through to pi-core's unbounded summarizer)`);
1495
+ const cmState = getCmState(ctx);
1496
+ cmState.cancelSource = "summary-cap";
1497
+ cmState.summaryCapCancelError = chunked.error;
1498
+ // This cycle IS the retry (the recovery only runs on one), so the
1499
+ // ladder ends here: release the guard and take the deterministic
1500
+ // cut instead of cancelling into a session that cannot compact.
1501
+ cmState.compactionRetryActive = false;
1502
+ const cut = buildDeterministicCut(ctx, prep);
1503
+ if (cut) {
1504
+ log.error(`[context-manager] Summary-cap recovery failed - persisting the deterministic ` +
1505
+ `cut (no LLM summarization)`);
1506
+ return cut;
1507
+ }
1508
+ return { cancel: true };
1509
+ }
1510
+ log.error(`[context-manager] Summary-cap recovery chunked summary failed (${chunked.error}) — ` +
1511
+ `falling through to pi-core's default summarization`);
1512
+ // Fall through to pi-core's own call — arm the thinking switch.
1513
+ armSummarizerThinkingOff(pi, ctx);
1514
+ }
1515
+ }
1516
+ catch (err) {
1517
+ log.error("[context-manager] summary-cap recovery error:", err);
1518
+ }
1519
+ }
1520
+ // pi core passes these to the LLM summarization call. The LLM handles all
1521
+ // chunking - we just tell it WHAT to preserve.
1522
+ // NOTE (pi-core 0.84.2 dead-code gap): event.customInstructions is NOT read
1523
+ // back by pi-core (verified agent-session.js:1422/1665) — preparation
1524
+ // steering (messagesToSummarize, firstKeptEntryId, turnPrefixMessages,
1525
+ // isSplitTurn) is the only channel that takes effect. Kept for forward
1526
+ // compatibility with pi-core versions that do read it.
1527
+ const audit = analyzeSession(ctx);
1528
+ const instructions = buildCompactionInstructions(audit);
1529
+ if (instructions.length > 0) {
1530
+ event.customInstructions = instructions.join(" ");
1531
+ }
1532
+ try {
1533
+ eventBus.emit({
1534
+ type: "memory_evict",
1535
+ reason: "context compaction",
1536
+ count: prep?.messagesToSummarize?.length ?? 0,
1537
+ });
1538
+ }
1539
+ catch {
1540
+ log.warn("[context-manager] failed to emit memory_evict event");
1541
+ }
1542
+ // This cycle hands its span to pi-core's summarizer: keep reasoning out
1543
+ // of the summary budget (switch helper above).
1544
+ if (prep?.messagesToSummarize?.length) {
1545
+ armSummarizerThinkingOff(pi, ctx);
1546
+ }
1547
+ }
1548
+ catch (err) {
1549
+ log.error("session_before_compact error:", err);
1550
+ }
1551
+ });
1552
+ }
1553
+ // Session Compact (success only)
1554
+ // session_compact fires ONLY on successful compaction. pi-core 0.85.1 has no
1555
+ // `compaction_end` extension event: the post-compaction outcome handling lives
1556
+ // in registerSessionCompactOutcomeHandler (a second, deliberately separate
1557
+ // session_compact stage below) and the failure handling in
1558
+ // registerSessionCompactFailedHandler on session_compact_failed.
1559
+ export function registerSessionCompactHandler(pi) {
1560
+ pi.on(SESSION_COMPACT, async (event, ctx) => {
1561
+ try {
1562
+ // The compaction completed: the cycle's dedup-relevant in-flight phase is
1563
+ // over. A later cycle on the same leaf must run (no lifetime block) while
1564
+ // the in-cycle double-fire stays deduped — see markCompactProcessed.
1565
+ setCompactionActive(false, ctx);
1566
+ // Cycle outcome arrived: disarm the stall watchdog.
1567
+ clearCompactionWatchdog(ctx);
1568
+ // The cycle LANDED an entry: that is progress, so the fail-safe ladder is
1569
+ // broken and the retry dispatch (if any) is over. Cleared here, before the
1570
+ // parking work below can throw, so a landed compaction can never leave a
1571
+ // cut armed against an unrelated later cycle.
1572
+ try {
1573
+ clearCompactionFailsafe(ctx);
1574
+ settleCompactionRetry();
1575
+ settleOverflowRetry();
1576
+ }
1577
+ catch {
1578
+ /* state unavailable - fail-safe bookkeeping degrades to the failure path */
1579
+ }
1580
+ const entry = event.compactionEntry;
1581
+ // Pattern 8: record the compaction-input fingerprint for this leaf so a
1582
+ // later auto-compaction with an identical input can be skipped. The
1583
+ // fingerprint was stashed at session_before_compact (before the branch
1584
+ // was mutated) and is only recorded here, on SUCCESS.
1585
+ try {
1586
+ const cmState = getCmState(ctx);
1587
+ if (cmState.pendingCompactionFingerprint) {
1588
+ const key = `${getSessionIdSafe(ctx)}::${getLeafIdSafe(ctx)}`;
1589
+ cmState.lastCompactionFingerprints ??= {};
1590
+ cmState.lastCompactionFingerprints[key] = cmState.pendingCompactionFingerprint;
1591
+ cmState.pendingCompactionFingerprint = undefined;
1592
+ }
1593
+ }
1594
+ catch {
1595
+ /* state unavailable - fingerprint skip degrades to off */
1596
+ }
1597
+ if (entry) {
1598
+ addEvidence(ctx, "context_compacted", "session", `Context compressed: ${entry.summary?.slice(0, 80) ?? "no summary"}`, 0.8);
1599
+ }
1600
+ // FIX: Pre-append the user's queued message to sessionManager BEFORE
1601
+ // compaction_end fires (which triggers TUI's rebuildChatFromMessages).
1602
+ // Intercept appendMessage to skip the duplicate from flushCompactionQueue's
1603
+ // session.prompt() -> message_end -> appendMessage call.
1604
+ const st = getInterceptState(ctx);
1605
+ if (st.queuedDuringCompaction) {
1606
+ // Delivery through the shared park path: session write + force-persist
1607
+ // + the appendMessage wrapper that dedups the flush replay. The text
1608
+ // leaves the pending seat here - a landed cycle delivered it.
1609
+ const parked = parkOwnerTextInSession(ctx, st.queuedDuringCompaction);
1610
+ if (parked) {
1611
+ // Manual compaction: full stop. Arm the one-shot hold so the TUI
1612
+ // flush's replay prompt is swallowed in the input hook instead of
1613
+ // starting a turn from pre-compaction input. Auto reasons keep the
1614
+ // flush replay as their resume and are never armed. Snapshot the
1615
+ // text so later capture clears cannot retarget the hold.
1616
+ if (event?.reason === "manual") {
1617
+ st.holdQueuedPrompt = true;
1618
+ st.heldQueuedText = st.queuedDuringCompaction;
1619
+ log.info("[context-manager] Manual compaction: hold armed - queued message will not resume the turn");
1620
+ }
1621
+ }
1622
+ else {
1623
+ // The cycle landed but the write path was unavailable. The seat keeps
1624
+ // the text for the settle flush; it must not be cleared here.
1625
+ log.error("[context-manager] Failed to park the queued message - it stays seated for the settle flush");
1626
+ }
1627
+ // NOTE: st.queuedDuringCompaction stays set after intercept setup.
1628
+ // It must survive until flushCompactionQueue's session.prompt()
1629
+ // fires AFTER session_compact returns, so skipDuplicateAppend can
1630
+ // detect the duplicate user message. Cleared on turn_end or abort.
1631
+ }
1632
+ // NOTE: Do NOT inject a resume steer here.
1633
+ // The queued message's lifecycle after a manual compaction is: parked via
1634
+ // the pre-append above, its flush replay swallowed by the input-hook hold
1635
+ // (no turn from pre-compaction input; the operator sends the next input
1636
+ // themselves). After an auto compaction (threshold/overflow) the flush
1637
+ // replay IS the resume: it fires message_start/message_end, is persisted
1638
+ // by sessionManager, and renders in the TUI. The steer from agent.steer()
1639
+ // is delivered via agent-loop _steeringMessages, never emits message_start/
1640
+ // message_end events, never reaches sessionManager.appendMessage(), and is
1641
+ // invisible in both the TUI and session tree. Adding it would only add noise
1642
+ // to agent context without any user-visible benefit.
1643
+ // Clear overflow notification flag and retry guards on success.
1644
+ const cmState = getCmState(ctx);
1645
+ cmState.overflowNotified = false;
1646
+ cmState.compactionRetryActive = false;
1647
+ cmState.overflowRetryActive = false;
1648
+ // A landed compaction consumes the range stash and any armed recovery
1649
+ // (normally already consumed by the owning branch), and restores the
1650
+ // summarizer thinking switch this cycle armed.
1651
+ cmState.pendingRangeArchive = undefined;
1652
+ cmState.pendingSummaryCapRecovery = undefined;
1653
+ restoreSummarizerThinkingLevel(pi, ctx);
1654
+ }
1655
+ catch (err) {
1656
+ log.error("session_compact error:", err);
1657
+ }
1658
+ });
1659
+ }
1660
+ /**
1661
+ * Concatenated text of a user message's content parts ("" when none). Used as
1662
+ * the delivery proof for a seated owner input, so the comparison is exact.
1663
+ */
1664
+ function userMessageText(content) {
1665
+ if (typeof content === "string")
1666
+ return content;
1667
+ if (!Array.isArray(content))
1668
+ return "";
1669
+ return content
1670
+ .filter((part) => typeof part === "object" && part !== null)
1671
+ .map((part) => (typeof part.text === "string" ? part.text : ""))
1672
+ .join("");
1673
+ }
1674
+ export function registerSessionCompactOutcomeHandler(pi) {
1675
+ onEvent(pi, SESSION_COMPACT, async (event, _ctx) => {
1676
+ try {
1677
+ // Cycle outcome (intermediate or final): restore the summarizer
1678
+ // thinking switch this cycle may have armed. Idempotent no-op when
1679
+ // the switch was never armed.
1680
+ restoreSummarizerThinkingLevel(pi, _ctx);
1681
+ const entry = event.compactionEntry;
1682
+ if (!entry)
1683
+ return;
1684
+ // A stale originals capture must never leak into a later cycle. Snapshot it into a local for the always-on archive
1685
+ // write below, then clear the session state; the archive write
1686
+ // consumes and clears it in finally.
1687
+ let pendingCompactionOriginals;
1688
+ try {
1689
+ const cmState = getCmState(_ctx);
1690
+ pendingCompactionOriginals = cmState.pendingCompactionOriginals;
1691
+ cmState.pendingCompactionOriginals = undefined;
1692
+ }
1693
+ catch {
1694
+ /* state unavailable - archive write degrades to off */
1695
+ }
1696
+ // Compacted-vs-kept message counter, snapped once per cycle so
1697
+ // post-hoc loss questions are answerable from telemetry. compacted =
1698
+ // this cycle's raw summarization input (the originals capture — what
1699
+ // the summary replaced); kept = messages still live from the
1700
+ // firstKeptEntryId anchor to the branch end. Both degrade to undefined
1701
+ // — absent, never wrong.
1702
+ const compactedMessages = countSummarizedMessages(pendingCompactionOriginals);
1703
+ let keptMessages;
1704
+ try {
1705
+ const sm = _ctx.sessionManager;
1706
+ const branch = typeof sm?.getBranch === "function" ? (sm.getBranch() ?? []) : [];
1707
+ keptMessages = countKeptMessages(branch, entry.firstKeptEntryId);
1708
+ }
1709
+ catch {
1710
+ /* branch unavailable - kept count degrades to absent */
1711
+ }
1712
+ // Verify the completed compaction BEFORE recording success. Coherence
1713
+ // (non-empty summary + first-kept anchor) and budget (post-compaction
1714
+ // usage dropped below pre-compaction usage) must both pass; otherwise
1715
+ // the "success" is a silent context destroyer and must be reported
1716
+ // honestly as a failure. No destructive rollback — originals remain in
1717
+ // the append-only branch and are recoverable via context_navigate/archive.
1718
+ let preCompactionUsagePercent;
1719
+ try {
1720
+ preCompactionUsagePercent = getCmState(_ctx).preCompactionUsagePercent;
1721
+ }
1722
+ catch {
1723
+ /* state unavailable - budget verify degrades to coherence-only */
1724
+ }
1725
+ let cycleId;
1726
+ try {
1727
+ cycleId = getCmState(_ctx).compactionCycleId;
1728
+ }
1729
+ catch {
1730
+ /* state unavailable - cycle id degrades to absent */
1731
+ }
1732
+ const verify = verifyCompactionResult({ compactionEntry: entry, firstKeptEntryId: entry.firstKeptEntryId }, _ctx, preCompactionUsagePercent);
1733
+ if (!verify.ok) {
1734
+ recordCompactionOutcome("failure", {
1735
+ errorMessage: `verify: ${verify.reason}`,
1736
+ });
1737
+ // Feed outcome into advice-tracker for retry strategy adjustment
1738
+ recordAdvice("compaction", "failure", 0);
1739
+ log.error(`[context-manager] Compaction verify FAILED — ${verify.reason}; ` +
1740
+ `originals preserved in branch, use context_navigate/archive to recover`);
1741
+ // Durable trace: the session file gains one entry naming the
1742
+ // verify class (coherence/budget), the span size, and the retry
1743
+ // count, so the rollback is visible after the fact.
1744
+ writeCompactionTrace(pi, _ctx, {
1745
+ event: "verify-failed",
1746
+ reason: event.reason,
1747
+ failureClass: String(verify.reason).startsWith("coherence:")
1748
+ ? "verify-coherence"
1749
+ : "verify-budget",
1750
+ errorMessage: `verify: ${verify.reason}`,
1751
+ spanMessages: compactedMessages,
1752
+ retryAttempt: 0,
1753
+ willRetry: false,
1754
+ cycleId,
1755
+ });
1756
+ try {
1757
+ const cmState = getCmState(_ctx);
1758
+ cmState.verifyFailed = true;
1759
+ // A verify rejection is a rollback (loss) — count it distinctly
1760
+ // from generic failures so the telemetry can measure the
1761
+ // verify/rollback stage.
1762
+ recordCompactionHealth("totalVerifyFailures");
1763
+ // The append-only originals archive also writes on the
1764
+ // verify-failure path (always-on / lossless default), with the
1765
+ // verify rejection as the reason. WriteOriginalsArchive clears
1766
+ // verifyFailed + pendingCompactionOriginals in finally.
1767
+ writeOriginalsArchive(_ctx, verify.reason, pendingCompactionOriginals, {
1768
+ compactedMessages,
1769
+ keptMessages,
1770
+ });
1771
+ }
1772
+ catch {
1773
+ /* state unavailable - archive write degrades to off */
1774
+ }
1775
+ return;
1776
+ }
1777
+ log.info("[context-manager] Compaction completed successfully");
1778
+ // The outcome carries the compacted-vs-kept message counter.
1779
+ // entriesRemoved (existing CompactionHealth field) records the
1780
+ // compacted side cumulatively; the kept side + both counts land in the
1781
+ // per-compaction archive line below. The same counters also surface as
1782
+ // the lastCompactedMessages/lastKeptMessages health fields, rendered by
1783
+ // formatCompactionLossLine in context_inspect.
1784
+ recordCompactionOutcome("success", {
1785
+ entriesRemoved: compactedMessages,
1786
+ compactedMessages,
1787
+ keptMessages,
1788
+ });
1789
+ log.info(`[context-manager] Compaction outcome: ` +
1790
+ `${compactedMessages ?? "?"} message(s) compacted into summary, ` +
1791
+ `${keptMessages ?? "?"} kept live (anchor ${entry.firstKeptEntryId ?? "none"})`);
1792
+ // Always-on append-only originals archive on the healthy path too:
1793
+ // the raw originals this compaction replaced are preserved
1794
+ // even when verification passes (lossless default). reason="compact"
1795
+ // (the healthy path has no verify reason).
1796
+ writeOriginalsArchive(_ctx, "compact", pendingCompactionOriginals, {
1797
+ compactedMessages,
1798
+ keptMessages,
1799
+ });
1800
+ // Feed outcome into advice-tracker for retry strategy adjustment
1801
+ recordAdvice("compaction", "success", 0);
1802
+ }
1803
+ catch (err) {
1804
+ log.error("session_compact outcome error:", err);
1805
+ }
1806
+ });
1807
+ // message_end backup cleanup
1808
+ // Catches edge cases where turn_end is missed (no tools called that turn).
1809
+ // Ensures intercept state is always cleaned up before the next assistant turn.
1810
+ onEvent(pi, MESSAGE_END, async (_event, _ctx) => {
1811
+ // Delivery proof for a seated owner input: a consumed steer and a flush
1812
+ // replay both land as user messages, while text pi never consumed never
1813
+ // appears.
1814
+ const message = _event?.message;
1815
+ if (message?.role === "user") {
1816
+ const text = userMessageText(message.content);
1817
+ if (text) {
1818
+ let confirmed = false;
1819
+ let parked = false;
1820
+ try {
1821
+ const st = getInterceptState(_ctx);
1822
+ confirmed = st.pendingOwnerInputs.some((i) => i.text === text);
1823
+ parked = st.deliveredOwnerInputs.includes(text);
1824
+ if (confirmed)
1825
+ markOwnerInputDelivered(_ctx, text);
1826
+ }
1827
+ catch {
1828
+ /* state unavailable - confirmation degrades to the settle flush */
1829
+ }
1830
+ // Do NOT unwrap on the delivery of a text this extension parked: pi
1831
+ // persists this message right after extension handlers run, and the
1832
+ // wrapper is what skips the duplicate entry. The next unrelated
1833
+ // message_end (or input) restores it.
1834
+ if (confirmed || parked)
1835
+ return;
1836
+ }
1837
+ }
1838
+ tryRestoreAppendMessage(_ctx);
1839
+ });
1840
+ // Settle reconciliation
1841
+ // The run has settled: deliver seated owner input that no queue will carry
1842
+ // any further. pi's own queue is checked first, so an unconsumed steer
1843
+ // (drained by the next run's start) is never double-delivered.
1844
+ onEvent(pi, AGENT_SETTLED, async (_event, _ctx) => {
1845
+ try {
1846
+ flushPendingOwnerInputs(_ctx, "settle");
1847
+ }
1848
+ catch (err) {
1849
+ log.error("session settle owner-input flush error:", err);
1850
+ }
1851
+ });
1852
+ }
1853
+ export function registerSessionCompactFailedHandler(pi) {
1854
+ onEvent(pi, SESSION_COMPACT_FAILED, async (event, _ctx) => {
1855
+ try {
1856
+ setCompactionActive(false, _ctx);
1857
+ // Cycle outcome arrived: restore the summarizer thinking switch this
1858
+ // cycle may have armed, and disarm the stall watchdog. Read the armed
1859
+ // timestamp and the cycle id BEFORE clearing the watchdog: the failure
1860
+ // trace below carries both (only the watchdog stall path
1861
+ // populates durationMs).
1862
+ restoreSummarizerThinkingLevel(pi, _ctx);
1863
+ let cycleId;
1864
+ try {
1865
+ cycleId = getCmState(_ctx).compactionCycleId;
1866
+ }
1867
+ catch {
1868
+ /* state unavailable - cycle id degrades to absent */
1869
+ }
1870
+ let durationMs;
1871
+ try {
1872
+ const armedAt = getCompactionWatchdogArmedAt(_ctx);
1873
+ if (typeof armedAt === "number")
1874
+ durationMs = Date.now() - armedAt;
1875
+ }
1876
+ catch {
1877
+ /* state unavailable - duration degrades to absent */
1878
+ }
1879
+ clearCompactionWatchdog(_ctx);
1880
+ // The cycle never landed an entry: clear the dedup guard so the next
1881
+ // compaction can run, and drop the pending fingerprint (the input was
1882
+ // never compacted, so it must not be recorded as processed).
1883
+ clearProcessedCompacts(getSessionIdSafe(_ctx), getLeafIdSafe(_ctx));
1884
+ try {
1885
+ getCmState(_ctx).pendingCompactionFingerprint = undefined;
1886
+ }
1887
+ catch {
1888
+ /* state unavailable */
1889
+ }
1890
+ // Span size for the trace: read the pending originals capture BEFORE
1891
+ // the clear below consumes it. Degrades to absent, never wrong.
1892
+ let spanMessages;
1893
+ try {
1894
+ spanMessages = countSpanMessages(getCmState(_ctx).pendingCompactionOriginals);
1895
+ }
1896
+ catch {
1897
+ /* state unavailable - span degrades to absent */
1898
+ }
1899
+ // Resolve who cancelled the cycle (extension skip vs watchdog vs
1900
+ // external), then consume the marker so it never leaks into a later
1901
+ // cycle's abort attribution.
1902
+ let cancelSource;
1903
+ let cancelSummaryCapError;
1904
+ try {
1905
+ cancelSource = getCmState(_ctx).cancelSource;
1906
+ getCmState(_ctx).cancelSource = undefined;
1907
+ // Carried with the "summary-cap" cancel: the bounded path's real
1908
+ // error text (names the capped chunk). Consumed with the source so
1909
+ // it never outlives the cycle.
1910
+ cancelSummaryCapError = getCmState(_ctx).summaryCapCancelError;
1911
+ getCmState(_ctx).summaryCapCancelError = undefined;
1912
+ }
1913
+ catch {
1914
+ /* state unavailable - untagged */
1915
+ }
1916
+ // Non-destructive failure: a cycle that landed no entry must not
1917
+ // consume parked owner text. It is delivered now when the session is
1918
+ // idle (re-queued through the same session write the success path
1919
+ // uses) or kept pending for the settle boundary; the durable seat
1920
+ // already holds it either way. clearInterceptState drops only the
1921
+ // intercept window - the seat list survives it.
1922
+ flushPendingOwnerInputs(_ctx, "failure");
1923
+ // Restore intercept state: flushCompactionQueue won't fire on failure,
1924
+ // so message_end won't trigger the normal restoration path. If we
1925
+ // don't clean up here, the wrapper stays in place and a future message
1926
+ // with matching text would be incorrectly skipped.
1927
+ tryRestoreAppendMessage(_ctx);
1928
+ clearInterceptState(_ctx);
1929
+ // A stale originals capture must never leak into a later cycle. The
1930
+ // compaction failed, so the branch still carries the originals -
1931
+ // there is nothing to archive, just clear the capture.
1932
+ try {
1933
+ getCmState(_ctx).pendingCompactionOriginals = undefined;
1934
+ }
1935
+ catch {
1936
+ /* state unavailable */
1937
+ }
1938
+ // Durable trace on EVERY failed/aborted/cancelled firing. On 1.0.1
1939
+ // pi sends willRetry:false on all three emit sites, so this is the
1940
+ // final outcome of a cycle, never an intermediate retry; the field
1941
+ // stays recorded because it is pi's contract. The post-mortem triad
1942
+ // (failure class, span size, retry count) plus fromExtension and the
1943
+ // cycle id are only reconstructable from the entry sequence. The entry
1944
+ // is a plain custom entry: it lands in the session file and never
1945
+ // participates in the LLM context.
1946
+ // A "summary-cap" cancelSource is an extension cancel (no
1947
+ // errorMessage, aborted=true by pi-core's shape), which classifies as
1948
+ // "aborted"; the honest class is the one that caused the cancel.
1949
+ let failureClass = classifyCompactionFailure(event);
1950
+ if (failureClass === "aborted" && cancelSource === "summary-cap") {
1951
+ failureClass = "summary-cap";
1952
+ }
1953
+ writeCompactionTrace(pi, _ctx, {
1954
+ event: event.aborted ? "aborted" : "failure",
1955
+ reason: event.reason,
1956
+ failureClass,
1957
+ errorMessage: event.errorMessage ??
1958
+ (failureClass === "summary-cap" ? cancelSummaryCapError : undefined),
1959
+ spanMessages,
1960
+ retryAttempt: event.reason === "overflow" ? overflowRetryState.attempt : compactionRetryState.attempt,
1961
+ willRetry: event.willRetry,
1962
+ fromExtension: event.fromExtension,
1963
+ cycleId,
1964
+ cancelSource,
1965
+ durationMs,
1966
+ });
1967
+ // pi core is retrying - nothing to do, let pi handle it. On 1.0.1
1968
+ // willRetry is always false here (a returned compaction snapshot is
1969
+ // the only setter, and a returned compaction does not fail), so this
1970
+ // branch is unreachable today; it stays because it is pi's contract.
1971
+ if (event.willRetry)
1972
+ return;
1973
+ // This cycle is over and it landed no entry. Release the dispatch
1974
+ // guards the cycle held: they exist to stop a second compaction being
1975
+ // dispatched INTO a live cycle; releasing them only on success leaves
1976
+ // the first failed retry guarding the session for good - every later
1977
+ // dispatch then logs "already active"
1978
+ // and reset the ladder, so the exhausted rungs were unreachable.
1979
+ settleCompactionRetry();
1980
+ settleOverflowRetry();
1981
+ try {
1982
+ const cmState = getCmState(_ctx);
1983
+ cmState.compactionRetryActive = false;
1984
+ cmState.overflowRetryActive = false;
1985
+ }
1986
+ catch {
1987
+ /* state unavailable - the next dispatch's own guard check decides */
1988
+ }
1989
+ // Fail-safe accounting: a cycle that lands no entry while the session
1990
+ // sits above the critical band is one turn of a loop, not an incident.
1991
+ // Count it and, once the loop is established, arm the deterministic cut
1992
+ // for the next cycle - the per-cycle routing below has no view of the
1993
+ // repetition, and at this usage every rung it can reach either asks the
1994
+ // operator to act (emergency rotation) or tries a summarizer that has
1995
+ // just failed. An extension cancel is the operator's own decision to
1996
+ // skip (unchanged input), so it is not counted as no progress.
1997
+ if (cancelSource !== "extension") {
1998
+ try {
1999
+ const noProgress = noteCompactionNoProgress(_ctx);
2000
+ if (noProgress >= COMPACTION_NO_PROGRESS_LIMIT) {
2001
+ const usagePercent = getCmState(_ctx).preCompactionUsagePercent;
2002
+ if (typeof usagePercent === "number" && usagePercent >= USAGE_WHISPER_CRITICAL) {
2003
+ const failSafeReason = `fail-safe after ${noProgress} consecutive compaction cycles landed no entry ` +
2004
+ `at ${usagePercent.toFixed(0)}% context`;
2005
+ if (armCompactionFailsafeCut(_ctx, failSafeReason)) {
2006
+ log.error(`[context-manager] Compaction fail-safe armed: ${failSafeReason} - the next cycle ` +
2007
+ `compacts deterministically (no LLM summarization)`);
2008
+ triggerFailsafeCompaction(_ctx);
2009
+ }
2010
+ }
2011
+ }
2012
+ }
2013
+ catch {
2014
+ /* state unavailable - a session without fail-safe bookkeeping keeps
2015
+ the pre-existing per-cycle routing */
2016
+ }
2017
+ }
2018
+ const { reason, aborted, errorMessage } = event;
2019
+ // Aborted - user cancelled. Record the abort in loss telemetry, tagged
2020
+ // with whether a compaction was in-flight when the aborted cycle began
2021
+ // (the inFlightBefore capture from session_before_compact). Aborts are
2022
+ // counted distinctly from failures and successes.
2023
+ if (aborted) {
2024
+ // A watchdog cancel is a stall, not an operator abort: the cycle
2025
+ // died on a hung summarization stream and was killed by the stall
2026
+ // watchdog's ctx.abort(). Record it as a failure and re-issue a
2027
+ // bounded retry through the existing machinery, so a recoverable
2028
+ // stream cut does not leave the context uncompacted and the turn
2029
+ // stuck above its threshold.
2030
+ if (cancelSource === "watchdog") {
2031
+ const watchdogMessage = errorMessage ??
2032
+ `watchdog: compaction stalled >${Math.round(COMPACTION_STALL_THRESHOLD_MS / 1000)}s`;
2033
+ recordCompactionOutcome("failure", { errorMessage: watchdogMessage });
2034
+ recordAdvice("compaction", "failure", 0);
2035
+ if (reason === "overflow") {
2036
+ handleOverflowFailure(pi, event, _ctx, watchdogMessage);
2037
+ }
2038
+ else {
2039
+ handleThresholdFailure(pi, event, _ctx, watchdogMessage);
2040
+ }
2041
+ return;
2042
+ }
2043
+ // A summary-cap cancel came from this extension's bounded path
2044
+ // (chunked split failed with the summary-cap class and the cycle was
2045
+ // cancelled instead of falling through to pi-core's unbounded
2046
+ // summarizer). Route it exactly like a pi-core summary-cap failure:
2047
+ // the bounded recovery re-arms (with the range stash folded in) and
2048
+ // the retry ladder advances. A cancel is not a user abort — the
2049
+ // agent never pressed ESC here.
2050
+ if (cancelSource === "summary-cap") {
2051
+ recordCompactionOutcome("failure", { errorMessage: cancelSummaryCapError });
2052
+ recordAdvice("compaction", "failure", 0);
2053
+ // Watchdog rule: a summary-cap abort at the critical band lands one
2054
+ // deterministic slide, so the class can never be terminal (the
2055
+ // bounded retry can wedge on "already active"). Runs before the
2056
+ // retry arms, so the armed cut is visible to that retry cycle.
2057
+ handleSummaryCapAbort(pi, _ctx, {
2058
+ errorMessage: cancelSummaryCapError,
2059
+ spanMessages,
2060
+ });
2061
+ handleSummaryCapFailure(pi, event, _ctx, cancelSummaryCapError);
2062
+ return;
2063
+ }
2064
+ let inFlightBeforeAbort = false;
2065
+ try {
2066
+ inFlightBeforeAbort = getCmState(_ctx).inFlightBeforeCapture ?? false;
2067
+ }
2068
+ catch {
2069
+ /* state unavailable - untagged abort */
2070
+ }
2071
+ recordCompactionOutcome("aborted", { inFlight: inFlightBeforeAbort });
2072
+ return;
2073
+ }
2074
+ // Summary token-cap failure: the generation hit its output budget
2075
+ // before the summary completed (class "summary-cap"). Not a context
2076
+ // emergency — recover with a
2077
+ // bounded chunked summary on the retry cycle. Checked before the
2078
+ // context-window branch: a cap failure is about the OUTPUT budget,
2079
+ // not the input fit, and must not be routed into window-error advice.
2080
+ if (classifyCompactionFailure(event) === "summary-cap") {
2081
+ recordCompactionOutcome("failure", { errorMessage });
2082
+ recordAdvice("compaction", "failure", 0);
2083
+ // Watchdog rule (see the cancel branch above): one deterministic
2084
+ // slide per cooldown window at the critical band.
2085
+ handleSummaryCapAbort(pi, _ctx, { errorMessage, spanMessages });
2086
+ handleSummaryCapFailure(pi, event, _ctx, errorMessage);
2087
+ return;
2088
+ }
2089
+ // Context window error - context too large even for LLM summarization
2090
+ if (isContextWindowError(errorMessage)) {
2091
+ recordCompactionOutcome("failure", { errorMessage });
2092
+ // Feed outcome into advice-tracker for retry strategy adjustment
2093
+ recordAdvice("compaction", "failure", 0);
2094
+ handleContextWindowError(pi, event, _ctx, errorMessage);
2095
+ return;
2096
+ }
2097
+ // Threshold/manual compaction failure
2098
+ if (reason === "threshold" || reason === "manual") {
2099
+ handleThresholdFailure(pi, event, _ctx, errorMessage);
2100
+ return;
2101
+ }
2102
+ // Overflow recovery failure
2103
+ if (reason === "overflow") {
2104
+ handleOverflowFailure(pi, event, _ctx, errorMessage);
2105
+ return;
2106
+ }
2107
+ // Transient server error (529, 500, network)
2108
+ if (isTransientCompactionError(errorMessage)) {
2109
+ handleTransientError(pi, event, _ctx, errorMessage);
2110
+ return;
2111
+ }
2112
+ // The failed cycle's range stash was consumed by the summary-cap
2113
+ // routing (re-armed as range mode) or is stale — never outlive the
2114
+ // cycle.
2115
+ try {
2116
+ getCmState(_ctx).pendingRangeArchive = undefined;
2117
+ }
2118
+ catch {
2119
+ /* state unavailable */
2120
+ }
2121
+ }
2122
+ catch (err) {
2123
+ log.error("session_compact_failed error:", err);
2124
+ }
2125
+ });
2126
+ // Session lifecycle cleanup
2127
+ // Prevents _processedCompacts memory leak across sessions. Module-level state
2128
+ // must be explicitly cleared; LRU eviction alone is insufficient for
2129
+ // long-running agent processes with many session rotations.
2130
+ onEvent(pi, SESSION_SHUTDOWN, (_event, ctx) => {
2131
+ _processedCompacts.clear();
2132
+ // The retry ladders and the fail-safe are module-level and session-scoped
2133
+ // respectively: neither may outlive the session that armed it. A stale
2134
+ // in-flight marker would block the next session's turn-end resets, and an
2135
+ // armed cut belongs to the session that earned it.
2136
+ resetCompactionRetry();
2137
+ resetOverflowRetry();
2138
+ // A shutdown must not leave a stall timer holding a dying session's ctx,
2139
+ // nor a switched summarizer thinking level armed across the crash.
2140
+ try {
2141
+ clearCompactionWatchdog(ctx);
2142
+ clearCompactionFailsafe(ctx);
2143
+ restoreSummarizerThinkingLevel(pi, ctx);
2144
+ }
2145
+ catch {
2146
+ /* state unavailable */
2147
+ }
2148
+ });
2149
+ }
2150
+ //# sourceMappingURL=compaction.js.map