@octopi-agent/engine 0.98.4 → 0.102.10

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 (301) hide show
  1. package/dist/config-schema/agent.d.ts +35 -5
  2. package/dist/config-schema/agent.js +24 -4
  3. package/dist/config-schema/context.d.ts +6 -36
  4. package/dist/config-schema/context.js +4 -28
  5. package/dist/config-schema/engine.d.ts +57 -160
  6. package/dist/config-schema/engine.js +1 -5
  7. package/dist/config-schema/governance.d.ts +8 -1
  8. package/dist/config-schema/governance.js +8 -1
  9. package/dist/config-schema/models.d.ts +2 -8
  10. package/dist/config-schema/models.js +0 -2
  11. package/dist/config-schema/run.d.ts +2 -2
  12. package/dist/config-schema/run.js +2 -2
  13. package/dist/config-schema/shared.d.ts +0 -3
  14. package/dist/config-schema/shared.js +0 -2
  15. package/dist/config-schema/substrate.d.ts +14 -88
  16. package/dist/config-schema/substrate.js +22 -107
  17. package/dist/config.d.ts +45 -113
  18. package/dist/config.js +8 -2
  19. package/dist/harness/activation/dispatcher.js +7 -0
  20. package/dist/harness/activation/inbox.d.ts +3 -3
  21. package/dist/harness/activation/inbox.js +3 -3
  22. package/dist/harness/activation/runtime.js +13 -5
  23. package/dist/harness/activation/types.d.ts +2 -2
  24. package/dist/harness/agent/builder.d.ts +24 -3
  25. package/dist/harness/agent/builder.js +131 -27
  26. package/dist/harness/agent/config-bridge.js +9 -2
  27. package/dist/harness/agent/config-integrity.js +19 -2
  28. package/dist/harness/agent/wire-agent-builder.d.ts +11 -3
  29. package/dist/harness/agent/wire-agent-builder.js +26 -7
  30. package/dist/harness/capabilities/document/factory.d.ts +5 -0
  31. package/dist/harness/capabilities/document/factory.js +1 -0
  32. package/dist/harness/capabilities/document/port.js +6 -3
  33. package/dist/harness/capabilities/document/types.d.ts +5 -0
  34. package/dist/harness/collaboration/autonomous-subsystem/loader.js +1 -1
  35. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.d.ts +1 -1
  36. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +2 -2
  37. package/dist/harness/collaboration/autonomous-subsystem/sense/input-builder.js +4 -4
  38. package/dist/harness/collaboration/autonomous-subsystem/sense/metrics.d.ts +2 -2
  39. package/dist/harness/collaboration/autonomous-subsystem/sense/metrics.js +2 -2
  40. package/dist/harness/collaboration/autonomous-subsystem/signal/bus.d.ts +6 -0
  41. package/dist/harness/collaboration/autonomous-subsystem/signal/bus.js +25 -4
  42. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +1 -1
  43. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +3 -3
  44. package/dist/harness/collaboration/delegation/child-run.d.ts +1 -1
  45. package/dist/harness/collaboration/delegation/child-run.js +4 -4
  46. package/dist/harness/collaboration/delegation/index.d.ts +1 -1
  47. package/dist/harness/collaboration/delegation/index.js +1 -1
  48. package/dist/harness/collaboration/delegation/notifier.d.ts +6 -1
  49. package/dist/harness/collaboration/delegation/notifier.js +8 -1
  50. package/dist/harness/collaboration/delegation/service.d.ts +2 -0
  51. package/dist/harness/collaboration/delegation/service.js +2 -1
  52. package/dist/harness/collaboration/delegation/store.d.ts +2 -0
  53. package/dist/harness/collaboration/delegation/store.js +2 -1
  54. package/dist/harness/collaboration/delegation/types.d.ts +23 -2
  55. package/dist/harness/collaboration/delegation/types.js +22 -0
  56. package/dist/harness/collaboration/delegation/wiring.js +11 -1
  57. package/dist/harness/context/budget-allocator.d.ts +26 -18
  58. package/dist/harness/context/budget-allocator.js +67 -32
  59. package/dist/harness/context/capabilities/compact/engine.d.ts +0 -6
  60. package/dist/harness/context/capabilities/compact/engine.js +169 -121
  61. package/dist/harness/context/capabilities/compact/handover.d.ts +5 -3
  62. package/dist/harness/context/capabilities/compact/handover.js +7 -5
  63. package/dist/harness/context/capabilities/compact/index.d.ts +5 -1
  64. package/dist/harness/context/capabilities/compact/index.js +4 -0
  65. package/dist/harness/context/capabilities/compact/mechanical.d.ts +130 -0
  66. package/dist/harness/context/capabilities/compact/mechanical.js +268 -0
  67. package/dist/harness/context/capabilities/compact/messages.d.ts +60 -0
  68. package/dist/harness/context/capabilities/compact/messages.js +91 -0
  69. package/dist/harness/context/capabilities/compact/types.d.ts +76 -11
  70. package/dist/harness/context/capabilities/compact/types.js +11 -1
  71. package/dist/harness/context/capabilities/compact/view-split.d.ts +36 -0
  72. package/dist/harness/context/capabilities/compact/view-split.js +72 -0
  73. package/dist/harness/context/capabilities/summary/port.js +0 -1
  74. package/dist/harness/context/capabilities/summary/resolver.d.ts +1 -1
  75. package/dist/harness/context/capabilities/summary/resolver.js +1 -6
  76. package/dist/harness/context/capabilities/summary/tool-binding.d.ts +1 -1
  77. package/dist/harness/context/capabilities/summary/types.d.ts +3 -6
  78. package/dist/harness/context/context-size-ledger.d.ts +143 -0
  79. package/dist/harness/context/context-size-ledger.js +236 -0
  80. package/dist/harness/context/default-context-engine.d.ts +195 -119
  81. package/dist/harness/context/default-context-engine.js +1241 -743
  82. package/dist/harness/context/index.d.ts +2 -2
  83. package/dist/harness/context/index.js +1 -1
  84. package/dist/harness/context/layer-types.d.ts +15 -0
  85. package/dist/harness/context/layer-types.js +14 -1
  86. package/dist/harness/context/layers.d.ts +14 -15
  87. package/dist/harness/context/layers.js +41 -11
  88. package/dist/harness/context/message-selector.d.ts +10 -8
  89. package/dist/harness/context/message-selector.js +49 -27
  90. package/dist/harness/context/summarize.d.ts +2 -2
  91. package/dist/harness/context/summarize.js +9 -2
  92. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  93. package/dist/harness/context/system-prompt-assembler.js +2 -1
  94. package/dist/harness/context/token-constants.d.ts +8 -6
  95. package/dist/harness/context/token-constants.js +8 -7
  96. package/dist/harness/context/token-estimate-fns.d.ts +37 -27
  97. package/dist/harness/context/token-estimate-fns.js +85 -66
  98. package/dist/harness/context/token-estimator.d.ts +27 -12
  99. package/dist/harness/context/token-estimator.js +120 -66
  100. package/dist/harness/context/token-segments.d.ts +88 -0
  101. package/dist/harness/context/token-segments.js +103 -0
  102. package/dist/harness/context/tool-result-aging.d.ts +6 -1
  103. package/dist/harness/context/tool-result-aging.js +16 -5
  104. package/dist/harness/context/tool-result-body.js +2 -0
  105. package/dist/harness/context/transform/anchors.d.ts +66 -0
  106. package/dist/harness/context/transform/anchors.js +125 -0
  107. package/dist/harness/context/transform/fold.d.ts +56 -0
  108. package/dist/harness/context/transform/fold.js +135 -0
  109. package/dist/harness/context/transform/migrate.d.ts +41 -0
  110. package/dist/harness/context/transform/migrate.js +69 -0
  111. package/dist/harness/context/transform/types.d.ts +129 -0
  112. package/dist/harness/context/transform/types.js +19 -0
  113. package/dist/harness/context/turn-envelope.d.ts +6 -3
  114. package/dist/harness/context/types.d.ts +127 -117
  115. package/dist/harness/extension/execution-environment/ops-audit.d.ts +1 -1
  116. package/dist/harness/extension/execution-environment/resource-limits.d.ts +1 -1
  117. package/dist/harness/extension/execution-environment/resource-limits.js +1 -1
  118. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +1 -1
  119. package/dist/harness/extension/plugin-ecosystem/commands/index.d.ts +3 -1
  120. package/dist/harness/extension/plugin-ecosystem/commands/index.js +1 -0
  121. package/dist/harness/extension/plugin-ecosystem/commands/plugin-bridge.d.ts +12 -1
  122. package/dist/harness/extension/plugin-ecosystem/commands/plugin-bridge.js +14 -4
  123. package/dist/harness/extension/plugin-ecosystem/commands/router.d.ts +5 -4
  124. package/dist/harness/extension/plugin-ecosystem/commands/router.js +23 -14
  125. package/dist/harness/extension/plugin-ecosystem/commands/types.d.ts +8 -1
  126. package/dist/harness/extension/plugin-ecosystem/commands/types.js +2 -1
  127. package/dist/harness/extension/plugin-ecosystem/hooks/adapter.d.ts +54 -0
  128. package/dist/harness/extension/plugin-ecosystem/hooks/adapter.js +397 -0
  129. package/dist/harness/extension/plugin-ecosystem/hooks/compaction-integration.d.ts +16 -0
  130. package/dist/harness/extension/plugin-ecosystem/hooks/compaction-integration.js +66 -0
  131. package/dist/harness/extension/plugin-ecosystem/hooks/index.d.ts +4 -0
  132. package/dist/harness/extension/plugin-ecosystem/hooks/index.js +2 -0
  133. package/dist/harness/extension/plugin-ecosystem/hooks/iteration-snapshot.d.ts +11 -0
  134. package/dist/harness/extension/plugin-ecosystem/hooks/iteration-snapshot.js +54 -0
  135. package/dist/harness/extension/plugin-ecosystem/hooks/journal.d.ts +9 -0
  136. package/dist/harness/extension/plugin-ecosystem/hooks/journal.js +22 -0
  137. package/dist/harness/extension/plugin-ecosystem/hooks/policy-error.d.ts +12 -0
  138. package/dist/harness/extension/plugin-ecosystem/hooks/policy-error.js +19 -0
  139. package/dist/harness/extension/plugin-ecosystem/hooks/run-integration.d.ts +36 -0
  140. package/dist/harness/extension/plugin-ecosystem/hooks/run-integration.js +338 -0
  141. package/dist/harness/extension/plugin-ecosystem/hooks/services.d.ts +24 -0
  142. package/dist/harness/extension/plugin-ecosystem/hooks/services.js +139 -0
  143. package/dist/harness/extension/plugin-ecosystem/hooks/types.d.ts +229 -0
  144. package/dist/harness/extension/plugin-ecosystem/hooks/types.js +1 -0
  145. package/dist/harness/extension/plugin-ecosystem/plugins/api.d.ts +83 -249
  146. package/dist/harness/extension/plugin-ecosystem/plugins/api.js +88 -214
  147. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-registry.d.ts +43 -0
  148. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-registry.js +61 -0
  149. package/dist/harness/extension/plugin-ecosystem/plugins/engine-compatibility.d.ts +4 -0
  150. package/dist/harness/extension/plugin-ecosystem/plugins/engine-compatibility.js +18 -0
  151. package/dist/harness/extension/plugin-ecosystem/plugins/entry.d.ts +7 -85
  152. package/dist/harness/extension/plugin-ecosystem/plugins/entry.js +8 -50
  153. package/dist/harness/extension/plugin-ecosystem/plugins/index.d.ts +6 -23
  154. package/dist/harness/extension/plugin-ecosystem/plugins/index.js +3 -23
  155. package/dist/harness/extension/plugin-ecosystem/plugins/loader.d.ts +50 -117
  156. package/dist/harness/extension/plugin-ecosystem/plugins/loader.js +316 -285
  157. package/dist/harness/extension/plugin-ecosystem/plugins/manager.d.ts +23 -490
  158. package/dist/harness/extension/plugin-ecosystem/plugins/manager.js +85 -353
  159. package/dist/harness/extension/plugin-ecosystem/plugins/manifest.d.ts +41 -223
  160. package/dist/harness/extension/plugin-ecosystem/plugins/manifest.js +138 -19
  161. package/dist/harness/extension/plugin-ecosystem/plugins/staging.d.ts +15 -0
  162. package/dist/harness/extension/plugin-ecosystem/plugins/staging.js +15 -0
  163. package/dist/harness/extension/plugin-ecosystem/skills/manager.d.ts +6 -1
  164. package/dist/harness/extension/plugin-ecosystem/skills/manager.js +17 -1
  165. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.d.ts +3 -0
  166. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.js +46 -21
  167. package/dist/harness/extension/plugin-ecosystem/tools/delegation.js +18 -8
  168. package/dist/harness/extension/plugin-ecosystem/tools/plugin-tool.d.ts +11 -0
  169. package/dist/harness/extension/plugin-ecosystem/tools/plugin-tool.js +39 -0
  170. package/dist/harness/extension/plugin-ecosystem/tools/tool-bus.d.ts +1 -1
  171. package/dist/harness/extension/plugin-ecosystem/tools/tool-bus.js +11 -2
  172. package/dist/harness/governance/accounting/usage-ledger.d.ts +13 -1
  173. package/dist/harness/governance/accounting/usage-ledger.js +23 -1
  174. package/dist/harness/governance/human-in-the-loop/decision-cache.d.ts +3 -3
  175. package/dist/harness/governance/human-in-the-loop/decision-cache.js +2 -2
  176. package/dist/harness/governance/security/capability-enforcer.js +1 -2
  177. package/dist/harness/index.d.ts +12 -12
  178. package/dist/harness/index.js +7 -7
  179. package/dist/harness/knowledge/boot-config.d.ts +55 -0
  180. package/dist/harness/knowledge/boot-config.js +50 -0
  181. package/dist/harness/knowledge/catalog-types.d.ts +2 -0
  182. package/dist/harness/knowledge/client.d.ts +24 -2
  183. package/dist/harness/knowledge/client.js +19 -5
  184. package/dist/harness/knowledge/db.js +5 -0
  185. package/dist/harness/knowledge/describe-sample.d.ts +23 -0
  186. package/dist/harness/knowledge/describe-sample.js +58 -0
  187. package/dist/harness/knowledge/describe.d.ts +8 -0
  188. package/dist/harness/knowledge/describe.js +18 -2
  189. package/dist/harness/knowledge/engine-thread.js +6 -0
  190. package/dist/harness/knowledge/grounding.js +3 -1
  191. package/dist/harness/knowledge/http-app.js +35 -4
  192. package/dist/harness/knowledge/http-params.d.ts +18 -0
  193. package/dist/harness/knowledge/http-params.js +24 -0
  194. package/dist/harness/knowledge/index.d.ts +2 -0
  195. package/dist/harness/knowledge/index.js +1 -0
  196. package/dist/harness/knowledge/knowledge-serve-child.js +3 -0
  197. package/dist/harness/knowledge/purge.js +5 -2
  198. package/dist/harness/knowledge/query-service.d.ts +13 -2
  199. package/dist/harness/knowledge/query-service.js +4 -2
  200. package/dist/harness/knowledge/query-worker-client.d.ts +9 -1
  201. package/dist/harness/knowledge/query-worker-client.js +4 -2
  202. package/dist/harness/knowledge/query-worker.js +4 -2
  203. package/dist/harness/knowledge/read-http.js +5 -1
  204. package/dist/harness/knowledge/serve.d.ts +8 -7
  205. package/dist/harness/knowledge/serve.js +9 -0
  206. package/dist/harness/knowledge/source-store.js +26 -3
  207. package/dist/harness/knowledge/start-service-process.d.ts +15 -7
  208. package/dist/harness/knowledge/start-service-process.js +21 -9
  209. package/dist/harness/knowledge/types.d.ts +7 -0
  210. package/dist/harness/knowledge/writer-service.d.ts +37 -9
  211. package/dist/harness/knowledge/writer-service.js +120 -14
  212. package/dist/harness/knowledge/writer-worker-client.d.ts +10 -9
  213. package/dist/harness/knowledge/writer-worker-client.js +20 -2
  214. package/dist/harness/knowledge/writer-worker.js +9 -1
  215. package/dist/harness/memory/sqlite/wisdom-store.js +35 -10
  216. package/dist/harness/memory/types.d.ts +6 -4
  217. package/dist/harness/memory/wisdom-formation.d.ts +14 -3
  218. package/dist/harness/memory/wisdom-formation.js +85 -22
  219. package/dist/harness/memory/wisdom-gates.d.ts +14 -0
  220. package/dist/harness/memory/wisdom-gates.js +59 -19
  221. package/dist/harness/memory/wisdom.js +9 -0
  222. package/dist/harness/observability/observer/hub.js +25 -15
  223. package/dist/harness/observability/observer/types.d.ts +10 -6
  224. package/dist/harness/run/agent/agent.d.ts +40 -21
  225. package/dist/harness/run/agent/agent.js +66 -13
  226. package/dist/harness/run/agent/index.d.ts +1 -1
  227. package/dist/harness/run/budget/budget.d.ts +28 -10
  228. package/dist/harness/run/budget/budget.js +38 -15
  229. package/dist/harness/run/model/index.d.ts +3 -1
  230. package/dist/harness/run/model/index.js +2 -1
  231. package/dist/harness/run/model/resolver.d.ts +4 -1
  232. package/dist/harness/run/model/resolver.js +36 -2
  233. package/dist/harness/run/model/run-scope.d.ts +2 -0
  234. package/dist/harness/run/model/run-scope.js +7 -0
  235. package/dist/harness/run/model/types.d.ts +22 -5
  236. package/dist/harness/run/model/types.js +3 -2
  237. package/dist/harness/run/model/window-truth.d.ts +37 -0
  238. package/dist/harness/run/model/window-truth.js +39 -0
  239. package/dist/harness/run/reliability/context-length-feedback.d.ts +77 -0
  240. package/dist/harness/run/reliability/context-length-feedback.js +128 -0
  241. package/dist/harness/run/reliability/harness-events.d.ts +3 -3
  242. package/dist/harness/run/reliability/model-error-policy.js +4 -0
  243. package/dist/harness/run/reliability/run-agent.d.ts +10 -4
  244. package/dist/harness/run/reliability/run-agent.js +137 -53
  245. package/dist/harness/run/reliability/run-metrics-collector.d.ts +19 -8
  246. package/dist/harness/run/reliability/run-metrics-collector.js +38 -23
  247. package/dist/harness/run/run-guard/default-run-guard.js +8 -8
  248. package/dist/harness/run/run-scope.d.ts +37 -4
  249. package/dist/harness/run/runner.d.ts +44 -29
  250. package/dist/harness/run/runner.js +320 -102
  251. package/dist/harness/session/attachments/index.d.ts +1 -0
  252. package/dist/harness/session/attachments/index.js +1 -0
  253. package/dist/harness/session/attachments/inject.d.ts +21 -10
  254. package/dist/harness/session/attachments/inject.js +76 -24
  255. package/dist/harness/session/attachments/recall-index.d.ts +70 -0
  256. package/dist/harness/session/attachments/recall-index.js +219 -0
  257. package/dist/harness/session/attachments/service.d.ts +21 -0
  258. package/dist/harness/session/attachments/service.js +258 -139
  259. package/dist/harness/session/attachments/types.d.ts +6 -0
  260. package/dist/harness/session/transform-store.d.ts +136 -0
  261. package/dist/harness/session/transform-store.js +302 -0
  262. package/dist/harness/session/types.d.ts +2 -2
  263. package/dist/harness/shared/events/agent-event-map.d.ts +46 -13
  264. package/dist/harness/shared/events/agent-event-map.js +3 -2
  265. package/dist/harness/shared/events/scenario-events.d.ts +6 -6
  266. package/dist/harness/shared/types/agent-definition.d.ts +1 -2
  267. package/dist/index.d.ts +14 -17
  268. package/dist/index.js +7 -9
  269. package/dist/integration/observability/metrics.d.ts +6 -6
  270. package/dist/integration/observability/metrics.js +13 -13
  271. package/dist/integration/observability/observer-bridge.js +2 -2
  272. package/dist/integration/observability/trace-collector.d.ts +5 -5
  273. package/dist/integration/observability/trace-collector.js +34 -35
  274. package/dist/integration/observability/trace-events.d.ts +3 -3
  275. package/dist/integration/observability/trace-events.js +3 -3
  276. package/dist/integration/providers/anthropic.js +14 -1
  277. package/dist/integration/providers/openai.js +7 -1
  278. package/dist/integration/providers/usage.d.ts +1 -1
  279. package/dist/integration/providers/wire-dump.d.ts +1 -1
  280. package/dist/integration/storage/archive-manager.d.ts +6 -0
  281. package/dist/integration/storage/archive-manager.js +10 -0
  282. package/dist/integration/storage/jsonl.d.ts +1 -1
  283. package/dist/integration/storage/jsonl.js +18 -16
  284. package/dist/subsystems/wisdom-steward/formation/SUBSYSTEM.md +8 -1
  285. package/dist/subsystems/wisdom-steward/formation/config.yaml +1 -0
  286. package/dist/subsystems/wisdom-steward/formation/handler.js +27 -5
  287. package/package.json +11 -14
  288. package/dist/harness/context/hybrid-compressor.d.ts +0 -41
  289. package/dist/harness/context/hybrid-compressor.js +0 -159
  290. package/dist/harness/context/llm-summarizer.d.ts +0 -46
  291. package/dist/harness/context/llm-summarizer.js +0 -249
  292. package/dist/harness/context/smart-router.d.ts +0 -75
  293. package/dist/harness/context/smart-router.js +0 -118
  294. package/dist/harness/context/truncate-compressor.d.ts +0 -28
  295. package/dist/harness/context/truncate-compressor.js +0 -107
  296. package/dist/harness/extension/plugin-ecosystem/plugins/capability.d.ts +0 -97
  297. package/dist/harness/extension/plugin-ecosystem/plugins/capability.js +0 -155
  298. package/dist/harness/extension/plugin-ecosystem/plugins/hooks.d.ts +0 -7
  299. package/dist/harness/extension/plugin-ecosystem/plugins/hooks.js +0 -7
  300. package/dist/harness/extension/plugin-ecosystem/plugins/lifecycle.d.ts +0 -86
  301. package/dist/harness/extension/plugin-ecosystem/plugins/lifecycle.js +0 -139
@@ -8,8 +8,12 @@
8
8
  import { getTextContent } from '@octopi-agent/core/types.js';
9
9
  import { isCannedRefusalText } from '@octopi-agent/core/loop/canned-refusal.js';
10
10
  import { HeuristicTokenEstimator } from '../../token-estimator.js';
11
+ import { toolResultBody } from '../../tool-result-body.js';
11
12
  import { buildPolicyRegistry } from '../summary/resolver.js';
12
- import { HANDOVER_SUMMARY_TASK, buildHandoverPrompt, buildHandoverUserContent, clampSummaryProviderCap, } from './handover.js';
13
+ import { buildHandoverPrompt, buildHandoverUserContent, clampSummaryProviderCap, } from './handover.js';
14
+ import { asSummaryMessage, MECHANICAL_NOTICE_STRUCTURAL } from './messages.js';
15
+ import { alignViewSplit } from './view-split.js';
16
+ import { mechanicalDegrade } from './mechanical.js';
13
17
  import { estimateLLMMessages } from '../../token-estimator.js';
14
18
  function defaultEstimator() {
15
19
  const e = new HeuristicTokenEstimator();
@@ -115,14 +119,7 @@ function formatMessagesAsText(messages) {
115
119
  }
116
120
  else if (msg.role === 'tool' && msg.toolResults?.length) {
117
121
  const results = msg.toolResults
118
- .map((tr) => {
119
- const body = tr.error !== undefined
120
- ? JSON.stringify({ error: tr.error })
121
- : typeof tr.result === 'string'
122
- ? tr.result
123
- : JSON.stringify(tr.result ?? null);
124
- return ` - ${tr.name}: ${body}`;
125
- })
122
+ .map((tr) => ` - ${tr.name}: ${toolResultBody(tr)}`)
126
123
  .join('\n');
127
124
  parts.push(`[${role}]\nTool Results:\n${results}`);
128
125
  }
@@ -132,24 +129,26 @@ function formatMessagesAsText(messages) {
132
129
  }
133
130
  return parts.join('\n\n---\n\n');
134
131
  }
135
- function asSummaryMessage(summary) {
136
- const body = summary.includes('[Conversation Summary]')
137
- ? summary
138
- : `[Conversation Summary]\n\n${summary}`;
139
- return {
140
- role: 'user',
141
- content: body,
142
- timestamp: Date.now(),
143
- metadata: { source: 'contextSummary' },
144
- };
145
- }
146
132
  /**
147
133
  * 创建 CompactEngine
148
134
  *
149
- * @param options - 缺省 protect / port / estimator
135
+ * @param options - 缺省 protect / estimator
150
136
  * @returns CompactEngine
151
137
  */
138
+ /**
139
+ * v0.98.10 移除 summaryPort:残留传参必须 fail-loud——与 P0「配置了不生效须出声」同一原则,
140
+ * 禁止静默忽略后走 summarizeFn/截断降级(行为切换必须显式可见)。
141
+ *
142
+ * @param o - 待检配置对象(CompactOptions / CreateCompactEngineOptions)
143
+ * @param where - 报错定位(入口名)
144
+ */
145
+ function rejectRemovedSummaryPort(o, where) {
146
+ if (o !== null && typeof o === 'object' && 'summaryPort' in o) {
147
+ throw new Error(`not_implemented: summaryPort was removed in v0.98.10 (${where}) — inject summarizeFn instead (see CHANGELOG breaking note)`);
148
+ }
149
+ }
152
150
  export function createCompactEngine(options) {
151
+ rejectRemovedSummaryPort(options, 'createCompactEngine');
153
152
  const defaults = {
154
153
  // 能力层缺省与 DefaultContextEngine protectFirstN 同源(5,2026-10-28 拍板交接快照头 5)
155
154
  protectHead: options?.defaultProtectHead ?? 5,
@@ -157,9 +156,9 @@ export function createCompactEngine(options) {
157
156
  targetTokens: options?.defaultTargetTokens,
158
157
  mode: (options?.defaultMode ?? 'structure_only'),
159
158
  };
160
- async function summarizeMiddle(middleText, middleMessages, opts, maxTokens) {
161
- const port = opts.summaryPort ?? options?.summaryPort;
159
+ async function summarizeMiddle(middleText, opts, maxTokens) {
162
160
  const summarizeFn = opts.summarizeFn;
161
+ let summaryOutputTokens;
163
162
  const registry = buildPolicyRegistry();
164
163
  let policy = registry['conversation_default'];
165
164
  if (typeof opts.summarizePolicy === 'string' && registry[opts.summarizePolicy]) {
@@ -171,42 +170,11 @@ export function createCompactEngine(options) {
171
170
  // 中段文本化为空(消息全无正文无工具):不发空摘要请求——空 user / 空 New content
172
171
  // 过不了严格网关,且会让模型凭空产出;按摘要失败降级(onSummarizeFail 接管)
173
172
  if (!middleText.trim()) {
174
- return { error: 'empty_middle' };
175
- }
176
- if (port) {
177
- const unit = {
178
- text: middleText,
179
- structured: middleMessages,
180
- channel: 'pipeline',
181
- source: {},
182
- kind: 'conversation',
183
- policy: opts.summarizePolicy,
184
- task: HANDOVER_SUMMARY_TASK,
185
- };
186
- try {
187
- // 输出闸门与 summarizeFn 路径对齐:污染给一次加严重试,仍污染按失败降级(不静默存坏摘要)
188
- let r = await port.extract(unit, {
189
- signal: opts.signal,
190
- previousSummary: opts.previousSummary,
191
- });
192
- if (detectSummaryContamination(r.text, middleText)) {
193
- r = await port.extract({ ...unit, task: `${HANDOVER_SUMMARY_TASK}${STRICT_RETRY_SUFFIX}` }, { signal: opts.signal, previousSummary: opts.previousSummary });
194
- const again = detectSummaryContamination(r.text, middleText);
195
- if (again) {
196
- return { error: `contaminated_output:${again}` };
197
- }
198
- }
199
- return { summary: r.text, coverage: r.coverage };
200
- }
201
- catch (err) {
202
- // 只吞 port.extract 的抛错(摘要器契约外失败:provider 报错/超时)——转 error
203
- // 通道交给 onSummarizeFail 降级;try 内无其他可抛代码,无其他路径可至此
204
- return { error: err instanceof Error ? err.message : String(err) };
205
- }
173
+ return { error: 'empty_middle', summarizeAttempted: false };
206
174
  }
207
175
  if (summarizeFn) {
208
- // 交接式契约单源(F8 模板统一):模板/指令/合并语义全走 handover.ts——
209
- // 与 LLMSummaryCompressor 逐字同构,previousSummary 只有一种格式在迭代合并
176
+ // 交接式契约单源(F8 模板统一):模板/指令/合并语义全走 handover.ts,
177
+ // previousSummary 只有一种格式在迭代合并(P2 后 manual/proactive/overflow 唯一执行管道)
210
178
  const prompt = buildHandoverPrompt({
211
179
  maxTokens,
212
180
  summarizePolicy: policy,
@@ -232,14 +200,16 @@ export function createCompactEngine(options) {
232
200
  const prefixEchoSource = () => (opts.llmPrefix ?? []).map((m) => String(m.content ?? '')).join('\n');
233
201
  let usePrefix = Boolean(opts.llmPrefix?.length);
234
202
  let llmMessages = usePrefix ? buildPrefixed() : buildTextify();
235
- let echoSource = usePrefix ? prefixEchoSource() : middleText;
203
+ // 回声源:仅前缀分支才用调用方覆盖(前缀含既有摘要占位时,占位正文不得参与判定);
204
+ // textify 分支的比对源必须是它自己发给模型的文本(middleText)
205
+ let echoSource = usePrefix ? (opts.echoSource ?? prefixEchoSource()) : middleText;
236
206
  // 硬顶 = 软目标 4 倍保险丝(P1c 禁硬截断/静默半截),再按窗口钳制(评审 F5):
237
207
  // provider 多按 input+max_tokens ≤ window 校验,压缩恰在会话最满时触发,保险丝可能把
238
208
  // 请求顶出窗口——放不下就改走文本化中段旁路(cache-miss 如实降级),仍放不下则如实失败。
239
209
  const hardCap = (opts.maxSummaryTokens ?? maxTokens) * 4;
240
210
  const windowCapOf = (msgs) => clampSummaryProviderCap({
241
211
  hardCap,
242
- // estimateLLMMessages 口径含 tool_calls/content block/消息开销(同 llm-summarizer)
212
+ // estimateLLMMessages 口径含 tool_calls/content block/消息开销(tool_calls 全量计入)
243
213
  inputTokens: estimateLLMMessages(msgs),
244
214
  contextWindow: opts.contextWindow,
245
215
  maxOutputTokens: opts.maxOutputTokens,
@@ -257,12 +227,15 @@ export function createCompactEngine(options) {
257
227
  opts.emit?.({ type: 'compact.summarize_fallback', reason: 'window_guard', cached: false });
258
228
  }
259
229
  if (providerMaxTokens < 256) {
260
- // F8R-06 可观测:最终失败也是 cache-miss 旁路结果,与 compressor 侧对称上报
230
+ // F8R-06 可观测:最终失败也是 cache-miss 旁路结果,与旁路切换对称上报
261
231
  opts.emit?.({ type: 'compact.summarize_fallback', reason: 'window_exhausted', cached: false });
262
- return { error: 'window_exhausted:summary request cannot fit the model window' };
232
+ return { error: 'window_exhausted:summary request cannot fit the model window', summarizeAttempted: false };
263
233
  }
264
234
  try {
265
235
  const invoke = (strict) => {
236
+ // 重试重置(评审 M1):strict 重试产生的是新响应——被丢弃响应的 outputTokens
237
+ // 不得串给最终摘要;每次 invoke 从零收集
238
+ summaryOutputTokens = undefined;
266
239
  const msgs = strict
267
240
  ? [
268
241
  ...llmMessages.slice(0, -1),
@@ -275,18 +248,28 @@ export function createCompactEngine(options) {
275
248
  return summarizeFn(msgs, {
276
249
  previousSummary: opts.previousSummary,
277
250
  maxTokens: providerMaxTokens,
251
+ ...(opts.signal ? { signal: opts.signal } : {}),
252
+ // outputTokens 真值收集(2026-11-08):摘要产物体量以 provider 实测为准
253
+ onUsage: (u) => {
254
+ summaryOutputTokens = u.outputTokens;
255
+ },
278
256
  });
279
257
  };
280
258
  const text = await invokeGuardedSummarize(invoke, echoSource);
281
- return { summary: text, coverage: 'full' };
259
+ // 空白摘要(空串/纯空白)按失败降级(旧 LLMSummaryCompressor 的 trim 守卫在此收口):
260
+ // 空白冒充 fresh 摘要会把 previousSummary 写成空白并推进覆盖点——静默失忆红线
261
+ if (!text.trim()) {
262
+ return { error: 'empty_output', summarizeAttempted: true };
263
+ }
264
+ return { summary: text, coverage: 'full', summarizeAttempted: true, outputTokens: summaryOutputTokens };
282
265
  }
283
266
  catch (err) {
284
267
  // 吞两类抛错并转 error 通道交 onSummarizeFail 降级:① provider 报错/超时;
285
268
  // ② 闸门二次污染(contaminated_output:*)。try 内无其他可抛代码,无其他路径可至此
286
- return { error: err instanceof Error ? err.message : String(err) };
269
+ return { error: err instanceof Error ? err.message : String(err), summarizeAttempted: true };
287
270
  }
288
271
  }
289
- return { error: 'no_summarizer' };
272
+ return { error: 'no_summarizer', summarizeAttempted: false };
290
273
  }
291
274
  async function compactCore(items, opts) {
292
275
  const isMessages = Array.isArray(items);
@@ -296,6 +279,12 @@ export function createCompactEngine(options) {
296
279
  const tokensBefore = isMessages
297
280
  ? estimator.estimateMessages(messages)
298
281
  : estimator.estimateText(text);
282
+ // 摘要段真值替换(2026-11-08 outputTokens 真值):摘要产物体量以 provider 实测输出
283
+ // tokens 为准,估算只作无回传兜底——压缩计量「放着真值用估算」是三数字核对暴露的
284
+ // 口径缺陷(问题 2 拍板:能用真实值的地方换真实值)。
285
+ const afterWithSummaryTruth = (baseTokens, summaryText, outputTokens) => outputTokens != null && summaryText
286
+ ? baseTokens - estimator.estimateText(summaryText) + outputTokens
287
+ : baseTokens;
299
288
  // 边界归一:负数无契约语义,按 0 处理(slice 对负数是另一套语义,会切出意外视图)
300
289
  const protectHead = Math.max(0, opts.protectHead ?? defaults.protectHead);
301
290
  const protectTail = Math.max(0, opts.protectTail ?? defaults.protectTail);
@@ -304,11 +293,11 @@ export function createCompactEngine(options) {
304
293
  const onFail = opts.onSummarizeFail ?? 'truncate';
305
294
  const unitCount = isMessages ? messages.length : 1;
306
295
  if (unitCount === 0 || (isMessages && messages.length === 0) || (!isMessages && !text.trim())) {
307
- return { ok: true, compacted: false, reason: 'empty', tokensBefore, view: items, summary: opts.previousSummary };
296
+ return { ok: true, compacted: false, reason: 'empty', tokensBefore, summarizeAttempted: false, view: items, summary: opts.previousSummary };
308
297
  }
309
298
  // 已在目标内且非 force 语义:mode auto 时跳过
310
299
  if (mode === 'auto' && targetTokens != null && tokensBefore <= targetTokens) {
311
- return { ok: true, compacted: false, reason: 'within_target', tokensBefore, view: items, summary: opts.previousSummary };
300
+ return { ok: true, compacted: false, reason: 'within_target', tokensBefore, summarizeAttempted: false, view: items, summary: opts.previousSummary };
312
301
  }
313
302
  opts.emit?.({ type: 'compact.start', reason: mode });
314
303
  if (mode === 'head_tail_only') {
@@ -317,7 +306,7 @@ export function createCompactEngine(options) {
317
306
  const tailChars = Math.floor(text.length * 0.2);
318
307
  // 太短无可拆中段(len<5 时 20%×2 皆为 0):原样返回不丢正文(与消息路径 too_short 同语义)
319
308
  if (headChars === 0 && tailChars === 0) {
320
- return { ok: true, compacted: false, reason: 'too_short', tokensBefore, view: text };
309
+ return { ok: true, compacted: false, reason: 'too_short', tokensBefore, summarizeAttempted: false, view: text };
321
310
  }
322
311
  // slice(-0) === slice(0) 返回全量:tailChars=0 时尾段必须显式取空
323
312
  const view = `${text.slice(0, headChars)}\n\n[middle removed]\n\n${tailChars > 0 ? text.slice(-tailChars) : ''}`;
@@ -327,18 +316,35 @@ export function createCompactEngine(options) {
327
316
  reason: 'head_tail_only',
328
317
  tokensBefore,
329
318
  tokensAfter: estimator.estimateText(view),
319
+ summarizeAttempted: false,
330
320
  view,
331
321
  droppedSummary: 'middle removed without LLM',
332
322
  };
333
323
  }
334
324
  if (messages.length <= protectHead + protectTail) {
335
- return { ok: true, compacted: false, reason: 'too_short', tokensBefore, view: messages };
325
+ return { ok: true, compacted: false, reason: 'too_short', tokensBefore, summarizeAttempted: false, view: messages };
336
326
  }
337
- const head = messages.slice(0, protectHead);
338
- // slice(-0) === slice(0) 返回全量:protectTail=0 时 tail 必须显式为空
339
- const tail = protectTail > 0 ? messages.slice(-protectTail) : [];
327
+ // #10 修复:边界对齐(不拆 tool_call/tool_result 对);protectN 为期望条数
328
+ const { headEnd, tailStart } = alignViewSplit(messages, protectHead, protectTail);
329
+ const head = messages.slice(0, headEnd);
330
+ const tail = messages.slice(tailStart);
340
331
  const dropped = messages.length - head.length - tail.length;
341
- const placeholder = asSummaryMessage(`[Structural compact] dropped ${dropped} middle messages (head_tail_only)`);
332
+ // 对齐后无可丢弃(tail 退到 headEnd):不得插占位冒充压缩(tokensAfter 会反涨,评审 P3 F)
333
+ if (dropped <= 0) {
334
+ opts.emit?.({ type: 'compact.end', reason: 'too_short', cached: true });
335
+ return {
336
+ ok: true,
337
+ compacted: false,
338
+ reason: 'too_short',
339
+ tokensBefore,
340
+ tokensAfter: tokensBefore,
341
+ summary: opts.previousSummary,
342
+ fresh: false,
343
+ summarizeAttempted: false,
344
+ view: messages,
345
+ };
346
+ }
347
+ const placeholder = asSummaryMessage(`${MECHANICAL_NOTICE_STRUCTURAL} dropped ${dropped} middle messages (head_tail_only)`);
342
348
  const view = [...head, placeholder, ...tail];
343
349
  return {
344
350
  ok: true,
@@ -347,47 +353,56 @@ export function createCompactEngine(options) {
347
353
  tokensBefore,
348
354
  tokensAfter: estimator.estimateMessages(view),
349
355
  summary: placeholder.content,
356
+ summarizeAttempted: false,
350
357
  view,
351
358
  droppedSummary: `${dropped} messages removed without LLM`,
352
359
  };
353
360
  }
354
361
  if (mode === 'summary_only') {
355
362
  const maxTokens = opts.maxSummaryTokens ?? summarySoftTargetTokens(tokensBefore, opts.summaryBudget);
356
- const summarized = await summarizeMiddle(text, messages, opts, maxTokens);
363
+ const summarized = await summarizeMiddle(text, opts, maxTokens);
357
364
  if (!summarized.summary) {
358
365
  if (onFail === 'keep_partial' && opts.previousSummary && isMessages) {
359
- // slice(-0) === slice(0) 返回全量:protectTail=0 时 tail 必须显式为空
360
- const view = [asSummaryMessage(opts.previousSummary), ...(protectTail > 0 ? messages.slice(-protectTail) : [])];
361
- return { ok: true, compacted: true, reason: 'partial', tokensBefore, tokensAfter: estimator.estimateMessages(view), summary: opts.previousSummary, fresh: false, view };
366
+ // #10 修复:尾段对齐(tail 不得起于孤儿 tool 结果);protectTail=0 时尾段为空
367
+ const { tailStart } = alignViewSplit(messages, 0, protectTail);
368
+ const view = [asSummaryMessage(opts.previousSummary), ...messages.slice(tailStart)];
369
+ return { ok: true, compacted: true, reason: 'partial', tokensBefore, tokensAfter: estimator.estimateMessages(view), summary: opts.previousSummary, fresh: false, summarizeAttempted: summarized.summarizeAttempted, view };
362
370
  }
363
371
  if (isMessages) {
364
- const view = messages.slice(-Math.max(protectTail, 4));
372
+ // 机械降级(单级 purpose 账本):旧摘要留 summary 字段
373
+ // (视图由 sticky 重建注入,覆盖点不推进——宁可胖不丢)。
374
+ // 账本已是最小形态:仍超预算时报 mechanical_over_budget,不再丢条目。
375
+ const degraded = mechanicalDegrade(messages, { targetTokens, estimator });
365
376
  return {
366
377
  ok: true,
367
378
  compacted: true,
368
- reason: 'summarize_failed_truncate',
379
+ reason: degraded.overBudget
380
+ ? `summarize_failed:${summarized.error ?? 'no_output'}:mechanical_over_budget`
381
+ : `summarize_failed:${summarized.error ?? 'no_output'}`,
369
382
  tokensBefore,
370
- tokensAfter: estimator.estimateMessages(view),
371
- // 摘要失败时旧摘要仍有效:summary 字段保留之(与 structure_only 失败兜底同款)
383
+ tokensAfter: degraded.tokensAfter,
384
+ // 摘要失败时旧摘要仍有效:summary 字段保留之(机械占位永不冒充摘要)
372
385
  summary: opts.previousSummary,
373
386
  fresh: false,
374
- view,
375
- droppedSummary: 'middle dropped; summarizer unavailable',
387
+ summarizeAttempted: summarized.summarizeAttempted,
388
+ view: degraded.result,
389
+ droppedSummary: degraded.droppedSummary ?? 'middle degraded; summarizer unavailable',
376
390
  };
377
391
  }
378
392
  const view = text.slice(0, 500);
379
393
  return {
380
394
  ok: true,
381
395
  compacted: true,
382
- reason: 'summarize_failed_truncate',
396
+ reason: `summarize_failed:${summarized.error ?? 'no_output'}`,
383
397
  tokensBefore,
384
398
  summary: opts.previousSummary,
385
399
  fresh: false,
400
+ summarizeAttempted: summarized.summarizeAttempted,
386
401
  view,
387
402
  };
388
403
  }
389
404
  // 摘要即完整更新(previousSummary 已随 prompt 交给 summarizeFn 合并;
390
- // 与 LLMSummaryCompressor / summary executor 同一「迭代式更新」契约),不得再事后拼接
405
+ // 与 summary executor 同一「迭代式更新」契约),不得再事后拼接
391
406
  const summary = summarized.summary;
392
407
  if (!isMessages) {
393
408
  return {
@@ -395,9 +410,11 @@ export function createCompactEngine(options) {
395
410
  compacted: true,
396
411
  reason: 'summary_only',
397
412
  tokensBefore,
398
- tokensAfter: estimator.estimateText(summary),
413
+ tokensAfter: afterWithSummaryTruth(estimator.estimateText(summary), summary, summarized.outputTokens),
399
414
  summary,
400
415
  fresh: true,
416
+ summarizeAttempted: summarized.summarizeAttempted,
417
+ summaryOutputTokens: summarized.outputTokens,
401
418
  coverage: summarized.coverage,
402
419
  view: summary,
403
420
  };
@@ -408,22 +425,25 @@ export function createCompactEngine(options) {
408
425
  compacted: true,
409
426
  reason: 'summary_only',
410
427
  tokensBefore,
411
- tokensAfter: estimator.estimateMessages(view),
428
+ tokensAfter: afterWithSummaryTruth(estimator.estimateMessages(view), summary, summarized.outputTokens),
412
429
  summary,
413
430
  fresh: true,
431
+ summarizeAttempted: summarized.summarizeAttempted,
432
+ summaryOutputTokens: summarized.outputTokens,
414
433
  coverage: summarized.coverage,
415
434
  view,
416
435
  droppedSummary: `Conversation compressed from ${tokensBefore} tokens`,
417
436
  };
418
437
  }
419
- // structure_only(默认)
438
+ // structure_only(默认)。'auto' 无独立执行体:仅在上方做 within_target 短路后
439
+ // 落到这里与 structure_only 同路径(新增 mode 分支时勿误改此隐式契约)
420
440
  if (!isMessages) {
421
441
  const maxTokens = opts.maxSummaryTokens ?? summarySoftTargetTokens(tokensBefore, opts.summaryBudget);
422
- const summarized = await summarizeMiddle(text, [], opts, maxTokens);
442
+ const summarized = await summarizeMiddle(text, opts, maxTokens);
423
443
  if (!summarized.summary) {
424
444
  const head = text.slice(0, Math.max(200, Math.floor(text.length * 0.15)));
425
445
  const tail = text.slice(-Math.max(200, Math.floor(text.length * 0.15)));
426
- const view = `${head}\n\n[Structural compact]\n\n${tail}`;
446
+ const view = `${head}\n\n${MECHANICAL_NOTICE_STRUCTURAL}\n\n${tail}`;
427
447
  return {
428
448
  ok: true,
429
449
  compacted: true,
@@ -433,6 +453,7 @@ export function createCompactEngine(options) {
433
453
  // 摘要失败时旧摘要仍有效:summary 字段保留之(与 messages 失败兜底同款)
434
454
  summary: opts.previousSummary,
435
455
  fresh: false,
456
+ summarizeAttempted: summarized.summarizeAttempted,
436
457
  view,
437
458
  };
438
459
  }
@@ -444,71 +465,98 @@ export function createCompactEngine(options) {
444
465
  compacted: true,
445
466
  reason: 'structure_only',
446
467
  tokensBefore,
447
- tokensAfter: estimator.estimateText(view),
468
+ tokensAfter: afterWithSummaryTruth(estimator.estimateText(view), summary, summarized.outputTokens),
448
469
  summary,
449
470
  fresh: true,
471
+ summarizeAttempted: summarized.summarizeAttempted,
472
+ summaryOutputTokens: summarized.outputTokens,
450
473
  coverage: summarized.coverage,
451
474
  view,
452
475
  };
453
476
  }
454
477
  if (messages.length <= protectHead + protectTail) {
455
- return { ok: true, compacted: false, reason: 'too_short', tokensBefore, view: messages, summary: opts.previousSummary };
478
+ return { ok: true, compacted: false, reason: 'too_short', tokensBefore, summarizeAttempted: false, view: messages, summary: opts.previousSummary };
456
479
  }
457
- const head = messages.slice(0, protectHead);
458
- const middle = messages.slice(protectHead, Math.max(protectHead, messages.length - protectTail));
459
- // slice(-0) === slice(0) 返回全量:protectTail=0 时 tail 必须显式为空
460
- const tail = protectTail > 0 ? messages.slice(-protectTail) : [];
480
+ // #10 修复:head/tail 边界对齐(不拆 tool_call/tool_result 对)——protectN 为期望条数,
481
+ // 对齐后实际条数可能不同(head 缩 / tail 扩);protectTail=0 时尾段自然为空
482
+ const { headEnd, tailStart } = alignViewSplit(messages, protectHead, protectTail);
483
+ const head = messages.slice(0, headEnd);
484
+ const middle = messages.slice(headEnd, tailStart);
485
+ const tail = messages.slice(tailStart);
461
486
  const headTailTokens = estimator.estimateMessages(head) + estimator.estimateMessages(tail);
462
487
  const maxSummaryTokens = opts.maxSummaryTokens ?? summarySoftTargetTokens(tokensBefore, opts.summaryBudget);
463
- const middleText = formatMessagesAsText(middle);
464
- const summarized = await summarizeMiddle(middleText, middle, opts, maxSummaryTokens);
465
- // 摘要即完整更新(previousSummary 已随 prompt 交给 summarizeFn 合并);
466
- // 摘要失败时仍保留旧摘要兜底
467
- let summary = opts.previousSummary ?? '';
468
- let fresh = false;
469
- if (summarized.summary) {
470
- summary = summarized.summary;
471
- fresh = true;
472
- }
473
- else if (!summary) {
474
- const placeholder = `[Structural compact] dropped ${middle.length} middle messages`;
475
- if (onFail === 'keep_partial') {
476
- summary = placeholder;
477
- }
478
- else {
479
- const view = [...head, asSummaryMessage(placeholder), ...tail];
488
+ // 摘要素材(M-4):有 previousSummary + freshMessages 时只文本化未覆盖新消息——
489
+ // 合并契约保证完整性,已覆盖历史不以 raw middle 复发(textify 旁路曾重现 2.13MB
490
+ // 事故形状)。无摘要兜底 = 全量 middle(首次压缩无合并输入,完整性优先)。
491
+ // N2 配套(评审 del-e1ee43ef):空 fresh 段也回退全量 middle——宁可这一次请求胖,
492
+ // 不得丢内容;调用方已有 already_covered 守门,空段常态不达这里。
493
+ const summarizeSource = opts.freshMessages?.length && opts.previousSummary ? opts.freshMessages : middle;
494
+ const middleText = formatMessagesAsText(summarizeSource);
495
+ const summarized = await summarizeMiddle(middleText, opts, maxSummaryTokens);
496
+ // 摘要即完整更新(previousSummary 已随 prompt 交给 summarizeFn 合并)。
497
+ // 失败语义(B′ 机械降级阶梯):旧摘要兜底走 summary 字段/状态(视图由 sticky 重建
498
+ // 注入,覆盖点不推进——宁可胖不丢);keep_partial 显式要求旧摘要进视图;
499
+ // 其余走打码(不丢轮次)→ 账本截断,与自动路径旧 fallbackTruncate 形状一致。
500
+ if (!summarized.summary) {
501
+ if (onFail === 'keep_partial' && opts.previousSummary) {
502
+ const view = [...head, asSummaryMessage(opts.previousSummary), ...tail];
480
503
  return {
481
504
  ok: true,
482
505
  compacted: true,
483
- reason: 'summarize_failed_truncate',
506
+ reason: `summarize_failed:${summarized.error ?? 'no_output'}`,
484
507
  tokensBefore,
485
508
  tokensAfter: estimator.estimateMessages(view),
486
- summary: placeholder,
509
+ summary: opts.previousSummary,
487
510
  fresh: false,
511
+ summarizeAttempted: summarized.summarizeAttempted,
488
512
  view,
489
- droppedSummary: `${middle.length} messages dropped; summarizer failed`,
490
513
  };
491
514
  }
515
+ const degraded = mechanicalDegrade(middle, { targetTokens, estimator });
516
+ const view = [...head, ...degraded.result, ...tail];
517
+ return {
518
+ ok: true,
519
+ compacted: true,
520
+ reason: degraded.overBudget
521
+ ? `summarize_failed:${summarized.error ?? 'no_output'}:mechanical_over_budget`
522
+ : `summarize_failed:${summarized.error ?? 'no_output'}`,
523
+ tokensBefore,
524
+ tokensAfter: estimator.estimateMessages(view),
525
+ // 摘要失败时旧摘要仍有效:summary 字段保留之(机械占位永不冒充摘要)
526
+ summary: opts.previousSummary,
527
+ fresh: false,
528
+ summarizeAttempted: summarized.summarizeAttempted,
529
+ view,
530
+ droppedSummary: degraded.droppedSummary ?? `${middle.length} messages degraded; summarizer failed`,
531
+ };
492
532
  }
533
+ const summary = summarized.summary;
493
534
  const view = [...head, asSummaryMessage(summary), ...tail];
494
- const tokensAfter = estimator.estimateMessages(view);
535
+ const tokensAfter = afterWithSummaryTruth(estimator.estimateMessages(view), summary, summarized.outputTokens);
495
536
  opts.emit?.({ type: 'compact.end', reason: mode, cached: false });
496
537
  return {
497
538
  ok: true,
498
539
  compacted: true,
499
- // fresh=false(摘要失败仅旧摘要兜底)不得报 'structure_only'——调用方据此不推进覆盖
500
- reason: fresh ? 'structure_only' : `summarize_failed:${summarized.error ?? 'no_output'}`,
540
+ reason: 'structure_only',
501
541
  tokensBefore,
502
542
  tokensAfter,
503
543
  summary,
504
- fresh,
544
+ fresh: true,
545
+ summarizeAttempted: summarized.summarizeAttempted,
546
+ summaryOutputTokens: summarized.outputTokens,
505
547
  coverage: summarized.coverage ?? (middle.length > 0 ? 'partial' : 'full'),
506
548
  view,
507
549
  droppedSummary: `Structural compact: head=${head.length} middle=${middle.length} tail=${tail.length}`,
508
550
  };
509
551
  }
510
552
  return {
511
- compactMessages: (messages, opts) => compactCore(messages, opts ?? {}),
512
- compactText: (text, opts) => compactCore(text, opts ?? {}),
553
+ compactMessages: async (messages, opts) => {
554
+ rejectRemovedSummaryPort(opts, 'compactMessages');
555
+ return compactCore(messages, opts ?? {});
556
+ },
557
+ compactText: async (text, opts) => {
558
+ rejectRemovedSummaryPort(opts, 'compactText');
559
+ return compactCore(text, opts ?? {});
560
+ },
513
561
  };
514
562
  }
@@ -2,25 +2,27 @@
2
2
  * 交接式摘要契约(2026-10-28 拍板)——所有摘要路径的**单一指令源**。
3
3
  *
4
4
  * F8 模板统一:手动压缩(compactCore.summarizeMiddle)与 proactive/overflow
5
- * (LLMSummaryCompressor)共用本模板、指令构造与预算语义,保证 previousSummary
5
+ * (summarizeFn 执行器)共用本模板、指令构造与预算语义,保证 previousSummary
6
6
  * 只有一种格式在迭代合并——两套模板轮流并入是压缩行为不可控的根源。
7
7
  *
8
8
  * 模板结构是拍板物(四段式);规则行只约束行为,不改结构。F-d 硬约束
9
9
  * (完成项可核验 + 交接防重做 + 不虚构)以散文形式并入,不另立结构。
10
10
  */
11
11
  import type { SummaryPolicy } from '../summary/types.js';
12
- /** 交接书四段式任务(summaryPort / summarizeFn / LLMSummaryCompressor 共用,保持指令对齐)。
12
+ /** 交接书四段式任务(manual/proactive/overflow 共用同一 summarizeFn 执行管道,保持指令对齐)。
13
13
  * 反回声纪律(评审 F15):指令里不出现任何工具调用/角色标记字面量——负面示例本身会教坏模型
14
14
  * 且引发闸门自命中;证据允许单行短引用(F4:引用≠污染)。 */
15
15
  export declare const HANDOVER_SUMMARY_TASK: string;
16
16
  /** 折叠区间(评审 F7/F3):交接书替换范围与原样保留尾部——计数语义(两路都能精确供给,不编造索引) */
17
17
  export interface HandoverFoldRange {
18
- /** 交接书替换的旧消息条数 */
18
+ /** 本次需要并入交接书的消息条数(既有摘要之后、保护尾之前) */
19
19
  replacedCount: number;
20
20
  /** 会话消息总数 */
21
21
  total: number;
22
22
  /** 原样保留的尾部条数(勿总结它们) */
23
23
  preservedTail: number;
24
+ /** 前缀中上一份交接书已代表的早期消息条数(P2:前缀=折叠视图时 >0) */
25
+ coveredCount?: number;
24
26
  }
25
27
  export interface HandoverPromptOptions {
26
28
  /** 摘要软目标预算(P1c:写进指令当「尽量控制在 N tokens」,禁止作 provider 硬顶) */
@@ -2,7 +2,7 @@
2
2
  * 交接式摘要契约(2026-10-28 拍板)——所有摘要路径的**单一指令源**。
3
3
  *
4
4
  * F8 模板统一:手动压缩(compactCore.summarizeMiddle)与 proactive/overflow
5
- * (LLMSummaryCompressor)共用本模板、指令构造与预算语义,保证 previousSummary
5
+ * (summarizeFn 执行器)共用本模板、指令构造与预算语义,保证 previousSummary
6
6
  * 只有一种格式在迭代合并——两套模板轮流并入是压缩行为不可控的根源。
7
7
  *
8
8
  * 模板结构是拍板物(四段式);规则行只约束行为,不改结构。F-d 硬约束
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import { buildSystemPrompt } from '../summary/executor.js';
12
12
  import { buildPolicyRegistry } from '../summary/resolver.js';
13
- /** 交接书四段式任务(summaryPort / summarizeFn / LLMSummaryCompressor 共用,保持指令对齐)。
13
+ /** 交接书四段式任务(manual/proactive/overflow 共用同一 summarizeFn 执行管道,保持指令对齐)。
14
14
  * 反回声纪律(评审 F15):指令里不出现任何工具调用/角色标记字面量——负面示例本身会教坏模型
15
15
  * 且引发闸门自命中;证据允许单行短引用(F4:引用≠污染)。 */
16
16
  export const HANDOVER_SUMMARY_TASK = [
@@ -59,14 +59,16 @@ export function buildHandoverPrompt(options) {
59
59
  ? Math.max(0, options.foldRange.total - options.foldRange.replacedCount - options.foldRange.preservedTail)
60
60
  : 0;
61
61
  const foldBlock = options.foldRange
62
- ? `\n\nFold boundary: the handoff summarizes ${options.foldRange.replacedCount} older messages of ${options.foldRange.total}; ${preservedHead} earlier and ${options.foldRange.preservedTail} newer messages are preserved verbatim - cover the replaced part in depth and keep the summary off the preserved ones.`
62
+ ? options.foldRange.coveredCount
63
+ ? `\n\nFold boundary: the conversation above already carries your previous handoff, which stands for ${options.foldRange.coveredCount} earlier messages of ${options.foldRange.total}. Fold the ${options.foldRange.replacedCount} newer messages that follow it into that handoff; the last ${options.foldRange.preservedTail} messages are preserved verbatim - keep the summary off them.`
64
+ : `\n\nFold boundary: the handoff summarizes ${options.foldRange.replacedCount} older messages of ${options.foldRange.total}; ${preservedHead} earlier and ${options.foldRange.preservedTail} newer messages are preserved verbatim - cover the replaced part in depth and keep the summary off the preserved ones.`
63
65
  : '';
64
66
  const mergeHint = options.previousSummary ? MERGE_HINT : '';
65
67
  const previousBlock = options.previousSummary
66
68
  ? `\n\nPrevious summary:\n${options.previousSummary}`
67
69
  : '';
68
70
  const taskBlock = options.taskSnapshot?.trim()
69
- ? `\n\nCurrent session task list snapshot (live task store):\n${options.taskSnapshot.trim()}`
71
+ ? `\n\nCurrent session task list snapshot (live task store; supersedes any task list shown earlier in the conversation):\n${options.taskSnapshot.trim()}`
70
72
  : '';
71
73
  return {
72
74
  instruction: `${instruction}${foldBlock}`,
@@ -98,7 +100,7 @@ export function clampSummaryProviderCap(options) {
98
100
  */
99
101
  export function buildHandoverUserContent(options, content) {
100
102
  const taskBlock = options.taskSnapshot?.trim()
101
- ? `\n\nCurrent session task list snapshot (live task store):\n${options.taskSnapshot.trim()}`
103
+ ? `\n\nCurrent session task list snapshot (live task store; supersedes any task list shown earlier in the conversation):\n${options.taskSnapshot.trim()}`
102
104
  : '';
103
105
  if (!options.previousSummary) {
104
106
  return `${content}${taskBlock}`;
@@ -4,6 +4,10 @@
4
4
  * @module harness/context/capabilities/compact
5
5
  */
6
6
  export { createCompactEngine, summarySoftTargetTokens, detectSummaryContamination } from './engine.js';
7
+ export { asSummaryMessage, wrapSummaryText, isMechanicalNotice, SUMMARY_MARKER, MECHANICAL_NOTICE_TRUNCATED, MECHANICAL_NOTICE_COMPRESSED, MECHANICAL_NOTICE_STRUCTURAL, } from './messages.js';
8
+ export { alignViewSplit, semanticHistory } from './view-split.js';
9
+ export { isToolResultMessage, hasToolCall, } from './messages.js';
10
+ export { buildToolCallLedger, asLedgerMessage, ledgerTruncate, mechanicalDegrade, toolExecutionLedgerTrim, } from './mechanical.js';
7
11
  export { HANDOVER_SUMMARY_TASK, buildHandoverPrompt, buildHandoverUserContent, clampSummaryProviderCap, } from './handover.js';
8
12
  export type { HandoverFoldRange, HandoverPromptOptions } from './handover.js';
9
- export type { CompactEngine, CompactMode, CompactOptions, CompactOutcome, CompactSummarizeFn, CompactTokenEstimator, CreateCompactEngineOptions, } from './types.js';
13
+ export type { CompactEngine, CompactMode, CompactOptions, CompactOutcome, CompactTransportOutcome, SummarizeFunction, CompactTokenEstimator, CreateCompactEngineOptions, } from './types.js';
@@ -4,4 +4,8 @@
4
4
  * @module harness/context/capabilities/compact
5
5
  */
6
6
  export { createCompactEngine, summarySoftTargetTokens, detectSummaryContamination } from './engine.js';
7
+ export { asSummaryMessage, wrapSummaryText, isMechanicalNotice, SUMMARY_MARKER, MECHANICAL_NOTICE_TRUNCATED, MECHANICAL_NOTICE_COMPRESSED, MECHANICAL_NOTICE_STRUCTURAL, } from './messages.js';
8
+ export { alignViewSplit, semanticHistory } from './view-split.js';
9
+ export { isToolResultMessage, hasToolCall, } from './messages.js';
10
+ export { buildToolCallLedger, asLedgerMessage, ledgerTruncate, mechanicalDegrade, toolExecutionLedgerTrim, } from './mechanical.js';
7
11
  export { HANDOVER_SUMMARY_TASK, buildHandoverPrompt, buildHandoverUserContent, clampSummaryProviderCap, } from './handover.js';