@markus-global/cli 0.12.4 → 0.12.5-rc.1

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 (159) hide show
  1. package/dist/background-maintenance.d.ts +25 -0
  2. package/dist/background-maintenance.d.ts.map +1 -1
  3. package/dist/background-maintenance.js +61 -0
  4. package/dist/background-maintenance.js.map +1 -1
  5. package/dist/commands/im-inbound-origin.d.ts +38 -0
  6. package/dist/commands/im-inbound-origin.d.ts.map +1 -0
  7. package/dist/commands/im-inbound-origin.js +48 -0
  8. package/dist/commands/im-inbound-origin.js.map +1 -0
  9. package/dist/commands/start.d.ts.map +1 -1
  10. package/dist/commands/start.js +211 -46
  11. package/dist/commands/start.js.map +1 -1
  12. package/dist/markus.mjs +18520 -9886
  13. package/dist/web-ui/assets/{AsyncState-BTLUPIr1.js → AsyncState-fJJNUOXK.js} +1 -1
  14. package/dist/web-ui/assets/ChatComponents-S7d2CAAU.js +14 -0
  15. package/dist/web-ui/assets/{ContentRenderer-BZXRiKE3.js → ContentRenderer-DWqhC0uq.js} +6 -6
  16. package/dist/web-ui/assets/DeliverableShareModal-B7DwzEnt.js +1 -0
  17. package/dist/web-ui/assets/{Deliverables-3Y3zjT_1.js → Deliverables-CueBYYpx.js} +2 -2
  18. package/dist/web-ui/assets/MarkdownMessage-D8BsJzvD.js +4 -0
  19. package/dist/web-ui/assets/{Search-BI3hk-5j.js → Search-CaYXz3u-.js} +1 -1
  20. package/dist/web-ui/assets/{SendToChat-D_5zHO-k.js → SendToChat-_9sm7UBY.js} +1 -1
  21. package/dist/web-ui/assets/Settings-DTL14pY8.js +8 -0
  22. package/dist/web-ui/assets/{Store-B8ksRjHF.js → Store-DpGqUMS2.js} +1 -1
  23. package/dist/web-ui/assets/Switch-NYQTn8wl.js +1 -0
  24. package/dist/web-ui/assets/Team-DB-JytPl.js +93 -0
  25. package/dist/web-ui/assets/Work-sQq-gy3S.js +142 -0
  26. package/dist/web-ui/assets/{arc-VmvI7TpW.js → arc-JtkmqkSR.js} +1 -1
  27. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-CTUtPasm.js → architectureDiagram-3BPJPVTR-B8zM5fky.js} +1 -1
  28. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-xeYAqtZJ.js → blockDiagram-GPEHLZMM-BQgjaOcE.js} +1 -1
  29. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BiFgoGY5.js → c4Diagram-AAUBKEIU-BnZvYRwj.js} +1 -1
  30. package/dist/web-ui/assets/channel-Zno2q8Ba.js +1 -0
  31. package/dist/web-ui/assets/{chunk-2J33WTMH-DueHBqOn.js → chunk-2J33WTMH-KONx1qvt.js} +1 -1
  32. package/dist/web-ui/assets/{chunk-4BX2VUAB-B8zgDfSV.js → chunk-4BX2VUAB-BqkxAkWs.js} +1 -1
  33. package/dist/web-ui/assets/{chunk-55IACEB6-DieD55CP.js → chunk-55IACEB6-DxLiTj85.js} +1 -1
  34. package/dist/web-ui/assets/{chunk-727SXJPM-Do4Z9LQ0.js → chunk-727SXJPM-Dhj-9NIs.js} +1 -1
  35. package/dist/web-ui/assets/{chunk-AQP2D5EJ-qrYsW5ml.js → chunk-AQP2D5EJ-M1vQ4YYc.js} +1 -1
  36. package/dist/web-ui/assets/{chunk-FMBD7UC4-BSz3QT1q.js → chunk-FMBD7UC4-DaXv58SH.js} +1 -1
  37. package/dist/web-ui/assets/{chunk-ND2GUHAM-utDWSydt.js → chunk-ND2GUHAM-Brkz9FCu.js} +1 -1
  38. package/dist/web-ui/assets/{chunk-QZHKN3VN-Cd86CYHV.js → chunk-QZHKN3VN-DIsEGiBf.js} +1 -1
  39. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-hI59DDUw.js +1 -0
  40. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-hI59DDUw.js +1 -0
  41. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-Dc6cP9WW.js → cose-bilkent-S5V4N54A-CSjC_YL5.js} +1 -1
  42. package/dist/web-ui/assets/{dagre-BM42HDAG-4b0Wf_6D.js → dagre-BM42HDAG-BevSxaQN.js} +1 -1
  43. package/dist/web-ui/assets/{diagram-2AECGRRQ-zS_j1Kf4.js → diagram-2AECGRRQ-CT3Hj8jy.js} +1 -1
  44. package/dist/web-ui/assets/{diagram-5GNKFQAL-CPo-_Ime.js → diagram-5GNKFQAL-CAebHy6q.js} +1 -1
  45. package/dist/web-ui/assets/{diagram-KO2AKTUF-CjHOA4_j.js → diagram-KO2AKTUF-BvRWS7BX.js} +1 -1
  46. package/dist/web-ui/assets/{diagram-LMA3HP47-CalZRF6K.js → diagram-LMA3HP47-gR9HBKc4.js} +1 -1
  47. package/dist/web-ui/assets/{diagram-OG6HWLK6-DnLAhsLX.js → diagram-OG6HWLK6-B5HGsfNo.js} +1 -1
  48. package/dist/web-ui/assets/{docx-preview-uRVPnxwM.js → docx-preview-pRjmDg6F.js} +1 -1
  49. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-L0nzlMSn.js → erDiagram-TEJ5UH35-mrPW01aQ.js} +1 -1
  50. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-Bdc3UwtW.js → flowDiagram-I6XJVG4X-BrZ1G-Tt.js} +1 -1
  51. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-CFRmj_qc.js → ganttDiagram-6RSMTGT7-Dq_5mate.js} +1 -1
  52. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-B5hZwcoJ.js → gitGraphDiagram-PVQCEYII-Cb3yTWUy.js} +1 -1
  53. package/dist/web-ui/assets/index-9SXWNIl0.css +1 -0
  54. package/dist/web-ui/assets/index-Bco6UnT7.js +867 -0
  55. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-DVT4RgPd.js → infoDiagram-5YYISTIA-CcnNlnvs.js} +1 -1
  56. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-Bf7pvUY_.js → ishikawaDiagram-YF4QCWOH-BqHTPtO1.js} +1 -1
  57. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-NVRjJlnd.js → journeyDiagram-JHISSGLW-DKBB9B-C.js} +1 -1
  58. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-Co7BKMut.js → kanban-definition-UN3LZRKU-BVO5tbNl.js} +1 -1
  59. package/dist/web-ui/assets/{mermaid.core-CCf28Hq6.js → mermaid.core-bMoKRCj4.js} +5 -5
  60. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-DepMhVEb.js → mindmap-definition-RKZ34NQL-Bk0lFKmi.js} +1 -1
  61. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-Cq9ANaI0.js → pieDiagram-4H26LBE5-BRPnBLeL.js} +1 -1
  62. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CUY0BWhQ.js → quadrantDiagram-W4KKPZXB-CAqdqT5W.js} +1 -1
  63. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-D9fU5rCm.js → requirementDiagram-4Y6WPE33-Vv5YNzCu.js} +1 -1
  64. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-CMHhuSQF.js → sankeyDiagram-5OEKKPKP-Ciq1EgmQ.js} +1 -1
  65. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-Bjx53SID.js → sequenceDiagram-3UESZ5HK-DVRqp161.js} +1 -1
  66. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DVvatKnO.js → stateDiagram-AJRCARHV-zbjDSKA3.js} +1 -1
  67. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-C54VSYn7.js +1 -0
  68. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-9I80LG9m.js → timeline-definition-PNZ67QCA-D0hr0d1U.js} +1 -1
  69. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-B82Deutq.js → vennDiagram-CIIHVFJN-CtuZLcPo.js} +1 -1
  70. package/dist/web-ui/assets/{wardley-L42UT6IY-BKXtp57W.js → wardley-L42UT6IY-nP2-eCDJ.js} +1 -1
  71. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-DzqTzfYa.js → wardleyDiagram-YWT4CUSO-Dxc7OveP.js} +1 -1
  72. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-TowyDWYu.js → xychartDiagram-2RQKCTM6-Bm2LvPhZ.js} +1 -1
  73. package/dist/web-ui/index.html +2 -2
  74. package/docs/README.md +50 -16
  75. package/docs/api/guides/websocket.md +43 -0
  76. package/docs/api/reference.md +657 -0
  77. package/docs/architecture/a2a-communication.md +303 -0
  78. package/docs/architecture/agent-runtime.md +145 -28
  79. package/docs/architecture/architecture.md +30 -11
  80. package/docs/architecture/cognitive-architecture.md +189 -15
  81. package/docs/architecture/concurrent-processing.md +190 -31
  82. package/docs/architecture/context-assembly.md +264 -0
  83. package/docs/architecture/derived-views.md +463 -0
  84. package/docs/architecture/desktop-auto-update.md +185 -0
  85. package/docs/architecture/facts.md +406 -0
  86. package/docs/architecture/learning-loop.md +11 -0
  87. package/docs/architecture/limits.md +79 -0
  88. package/docs/architecture/mailbox-system.md +786 -668
  89. package/docs/architecture/memory-system.md +1 -1
  90. package/docs/architecture/messaging-gateway.md +7 -0
  91. package/docs/architecture/notification-delivery.md +221 -0
  92. package/docs/architecture/notification-sounds.md +177 -0
  93. package/docs/architecture/prompt-engineering.md +171 -700
  94. package/docs/{design/remote-access-contract.md → architecture/remote-access.md} +4 -0
  95. package/docs/architecture/state-machines.md +288 -5
  96. package/docs/architecture/tool-loop-harness.md +362 -0
  97. package/docs/architecture/tool-system.md +40 -16
  98. package/docs/design/background-callback-in-turn-delivery-2026-11-22.md +95 -0
  99. package/docs/design/c10-0b-pick-identity-leak-2026-11-22.md +233 -0
  100. package/docs/design/c10-a-identity-columns-2026-11-22.md +182 -0
  101. package/docs/design/c10-c-trust-boundary-2026-11-23.md +222 -0
  102. package/docs/design/c10-external-adapters-plan-2026-11-19.md +448 -0
  103. package/docs/design/c8-residual-mechanisms-2026-11-15.md +984 -0
  104. package/docs/design/external-signal-decision-loop-2026-11-25.md +579 -0
  105. package/docs/guides/development.md +1 -1
  106. package/docs/{architecture → guides}/mailbox-audit-checklist.md +7 -0
  107. package/docs/guides/remote-access.md +1 -1
  108. package/docs/{design/agent-stop-intent-audit.md → records/agent-stop-intent-audit-2026-11-08.md} +4 -0
  109. package/docs/records/c10-l5-gate-verification-2026-11-26.md +72 -0
  110. package/docs/records/c10-l5-live-verification-2026-11-25.md +117 -0
  111. package/docs/records/cut6-c4-verification-2026-11-12.md +268 -0
  112. package/docs/records/cut6-mailbox-address-envelope-design-2026-11-12.md +871 -0
  113. package/docs/records/cut7-c7a-red-green-evidence-2026-11-13.md +105 -0
  114. package/docs/records/cut7-c7a-workunit-implementation-2026-11-13.md +116 -0
  115. package/docs/records/cut7-c7b-verification-2026-11-14.md +90 -0
  116. package/docs/records/cut7-live-verification-2026-11-14.md +33 -0
  117. package/docs/records/cut7-wiring-negative-cache-2026-11-14.md +64 -0
  118. package/docs/records/cut7-workunit-execution-plan-2026-11-13.md +206 -0
  119. package/docs/records/cut8-a-entity-keys-design-2026-11-14.md +377 -0
  120. package/docs/records/cut8-b-turn-delta-injection-2026-11-14.md +362 -0
  121. package/docs/records/cut8-c-single-clock-2026-11-14.md +119 -0
  122. package/docs/records/cut8-c-single-clock-design-2026-11-14.md +150 -0
  123. package/docs/records/cut8-d-2026-11-14.md +231 -0
  124. package/docs/records/cut8-live-verification-2026-11-14.md +1018 -0
  125. package/docs/records/cut9-adjacent-identity-paths-2026-11-15.md +200 -0
  126. package/docs/records/cut9-identity-declaration-2026-11-15.md +163 -0
  127. package/docs/records/cut9-inbox-dual-run-diff-2026-11-15.md +117 -0
  128. package/docs/records/cut9-live-verification-2026-11-15.md +222 -0
  129. package/docs/records/cut9-runtime-probe-2026-11-19.md +520 -0
  130. package/docs/{design/deliverable-sharing.md → records/deliverable-sharing-2026-08-12.md} +10 -3
  131. package/docs/records/identity-backlog-disposition-2026-11-22.md +143 -0
  132. package/docs/records/marketplace-orphan-freeze-2026-11-22.md +239 -0
  133. package/docs/{architecture/notify-user-context-truth.md → records/notify-user-context-truth-2026-10-28.md} +6 -0
  134. package/docs/{handoff → records}/remote-access-handoff.md +1 -1
  135. package/package.json +1 -1
  136. package/templates/roles/HANDBOOK.md +1 -1
  137. package/templates/skills/agent-building/SKILL.md +1 -1
  138. package/dist/web-ui/assets/ChatComponents-DTB3H_n2.js +0 -12
  139. package/dist/web-ui/assets/DeliverableShareModal-BwZP39nd.js +0 -1
  140. package/dist/web-ui/assets/MarkdownMessage-DVfFMzM9.js +0 -4
  141. package/dist/web-ui/assets/Settings-DTUjLhJY.js +0 -8
  142. package/dist/web-ui/assets/Switch-RmZHA47D.js +0 -1
  143. package/dist/web-ui/assets/Team-BRgI1zM9.js +0 -85
  144. package/dist/web-ui/assets/Work-nah0UYFz.js +0 -142
  145. package/dist/web-ui/assets/channel-s7K3KXLr.js +0 -1
  146. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-B2mHhFY8.js +0 -1
  147. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-B2mHhFY8.js +0 -1
  148. package/dist/web-ui/assets/index-CzHSs0Vd.css +0 -1
  149. package/dist/web-ui/assets/index-TPf50ZeO.js +0 -867
  150. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-92MmE2MZ.js +0 -1
  151. package/docs/api/api.md +0 -353
  152. package/docs/architecture/llm-provider-timeouts.md +0 -60
  153. package/docs/architecture/state-ownership.md +0 -83
  154. /package/docs/architecture/{frontend/team-chat.md → team-chat.md} +0 -0
  155. /package/docs/{analysis → records}/2026-10-29-a2a-cache-hit-rate.md +0 -0
  156. /package/docs/{fixes → records}/2026-11-12-session-expiry-and-mention-thinking.md +0 -0
  157. /package/docs/{handoff → records}/approval-tri-state-handoff.md +0 -0
  158. /package/docs/{design → records}/overview-attention-redesign.md +0 -0
  159. /package/docs/{remote-access/fast-path-plan.md → records/remote-access-fast-path-plan-2026-10-17.md} +0 -0
@@ -1,6 +1,6 @@
1
1
  # Concurrent Processing
2
2
 
3
- > Status: **implemented** · Last updated: 2026-09-11
3
+ > Status: **implemented** · Last updated: 2026-11-22 (sticky entity→worker routing, §3.4)
4
4
  > Scope: how a single agent processes **multiple mailbox items / sessions at once**
5
5
  > through a pool of isolated workers, while preserving factual consistency.
6
6
  > Design origin: the original design memo (rationale, alternatives, phase plan) — superseded by this
@@ -34,10 +34,16 @@ independent consumer of the same mailbox:
34
34
  - Worker activity is made visible to every other worker through a persistent
35
35
  **concurrent handoff log**, injected into the system prompt.
36
36
 
37
- The invariant is simple to state:
37
+ The invariants are simple to state:
38
38
 
39
39
  > **Concurrency only ever happens *between* entities. A single entity is never
40
40
  > processed by two workers at the same time.**
41
+ >
42
+ > **An entity's work is handled by its *owner* worker — the one that first claimed
43
+ > it — across turns, not just within one turn.** Rotating workers inside an entity
44
+ > buys no parallelism (the mutex already serialises it) and only pays costs: context
45
+ > rebuild, cold prompt cache, lost in-flight continuity. Stickiness is the default;
46
+ > liveness overrides it under the explicit rules of §3.4.
41
47
 
42
48
  `maxWorkers = 1` reproduces the pre-concurrency behaviour exactly — that is the
43
49
  compatibility floor and the regression contract.
@@ -154,6 +160,56 @@ deliberately does **not** run triage, LLM deliberation, or interrupt/preempt log
154
160
  Those remain the serial `runLoop`'s job. This keeps the concurrent path small and
155
161
  predictable: a worker only ever dequeues, locks, processes, unlocks, and loops.
156
162
 
163
+ **Skipping judgement does not mean skipping the books.** The original wording let
164
+ "no deliberation" swallow "no recording" as well, and the cost was measured on
165
+ 2026-11-18: a full day of 116 inputs produced 3 ledger rows, all `drop`, while 388
166
+ execution epochs ran. The ledger had become a refusal log — every `pick` was
167
+ recorded inside `runLoop`, which the worker pool never enters.
168
+
169
+ The invariant now is structural rather than per-path: **`processFocusedItem` is the
170
+ single recording execution point**, and both loops call it. A worker cannot process
171
+ an item without leaving a `pick` row, because there is no second place to put it.
172
+
173
+ ```plantuml
174
+ @startuml
175
+ skinparam componentStyle rectangle
176
+ skinparam defaultTextAlignment center
177
+
178
+ title One recording execution point, two loop paths
179
+
180
+ rectangle "runLoop (workerCount = 1)" as Serial {
181
+ card "dequeue" as S1
182
+ card "pre-triage\n(purge + consolidate)" as S2
183
+ card "coalesce window" as S3
184
+ }
185
+
186
+ rectangle "concurrentWorkerLoop × N (workerCount > 1)" as Conc {
187
+ card "dequeueAsync" as C1
188
+ card "lockEntities\n(entity ∪ session keys,\nall-or-nothing)" as C2
189
+ card "conflict → putBack\n+ 250+retry×250ms backoff" as C3
190
+ }
191
+
192
+ rectangle "processFocusedItem" as Shared #LightGreen {
193
+ card "recordDecision('pick', source='rule')\n**only writer**" as P1
194
+ card "delegate.processMailboxItem\n(the LLM turn)" as P2
195
+ card "terminal projection\n(complete / requeue / bounce)" as P3
196
+ }
197
+
198
+ database "agent_decisions" as Ledger
199
+
200
+ S1 --> S2
201
+ S2 --> S3
202
+ S3 --> P1
203
+ C1 --> C2
204
+ C2 --> P1 : lock acquired
205
+ C2 --> C3 : any key held
206
+ C3 --> C1
207
+ P1 --> P2
208
+ P2 --> P3
209
+ P1 --> Ledger
210
+ @enduml
211
+ ```
212
+
157
213
  - `workerCount === 1` → the original `runLoop` is used verbatim (no behavioural drift).
158
214
  - Worker state (current focus, processing start time, in-flight user cancel) is held
159
215
  per worker in `workerStates: Map<number, AttentionWorkerState>`.
@@ -180,7 +236,7 @@ into a per-worker `SessionWorkspace`:
180
236
  | `processingMailboxItemId` | `Agent.processingMailboxItemId` |
181
237
  | `lastInjectedActivityType` | dedup hint for injected activities |
182
238
  | `turnModelOverride` | per-turn model pick |
183
- | `volatileState` / `pendingDeliberationResult` | per-turn transient state |
239
+ | `volatileState` | per-turn volatile prompt tail (time, mailbox summary, status, memories…) — rebuilt deterministically on every turn |
184
240
  | `toolSticky` | `Agent.toolSticky` (recent/activated tool schema names) |
185
241
  | `activatedSkills` | `Agent.activatedSkillInstructions` (skill instruction bodies) |
186
242
 
@@ -246,6 +302,76 @@ Two additions make the queue safe for multiple consumers:
246
302
 
247
303
  <!-- verified-against-code: 2026-09-11, packages/core/src/mailbox.ts:437-489, packages/shared/src/types/mailbox.ts:102-118 -->
248
304
 
305
+ ### 3.4 Sticky entity→worker routing — ownership, not just exclusion
306
+
307
+ **Problem (observed 2026-11-22).** The entity-affinity lock is a *mutex*: it answers
308
+ "may two workers touch this entity **at the same time**?" (no). It does not answer
309
+ "**which** worker should handle this entity's next item?" — `dequeueAsync()` was a
310
+ broadcast race, so any idle worker won. A real conversation (`cs_0203031913ba4072`)
311
+ bounced worker 3 → 1 → 2 across four turns. Every bounce re-orients a fresh worker,
312
+ rebuilds the session context, and risks a cold prompt cache — for zero parallelism
313
+ gain, because the entity was serialised anyway.
314
+
315
+ **First principles.**
316
+
317
+ 1. Workers exist to parallelise *across* entities. Within an entity the mutex already
318
+ serialises, so worker rotation inside an entity is pure cost.
319
+ 2. Therefore ownership must persist **across turns**: first successful claim assigns
320
+ the entity to that worker; later items of the same entity are claimable only by it.
321
+ 3. **Liveness is a hard invariant and beats stickiness.** An item must never starve
322
+ while capacity is idle. Stickiness yields under exactly three conditions (below).
323
+ 4. One fact, one writer, one enforcement point: ownership lives in the mailbox next
324
+ to `entityLocks`, enforced inside `dequeue(workerId)` — the same place the lock
325
+ filter already runs. Worker liveness is owned by the attention controller, which
326
+ supplies a probe; the mailbox never guesses worker state.
327
+
328
+ **Ownership key = the item's *primary* entity key** (`entityKeysOf(item)[0]`), not the
329
+ full key set. `req:` / `user:` are *coordination* dimensions: pinning them would nail
330
+ every task of a requirement (or every session of a user) to one worker and destroy
331
+ cross-entity parallelism. The mutex still locks **all** keys; ownership pins only the
332
+ continuity dimension. A `user:`-primary item (no task/req/conversation resolves) gets
333
+ no owner at all.
334
+
335
+ **Claimability rule** — `dequeue(workerId)` skips an item unless, for its ownership key:
336
+
337
+ | Owner state | Rule |
338
+ |---|---|
339
+ | unowned / self | claimable; a successful claim (re)assigns ownership |
340
+ | owner **idle** | not claimable by others — the owner is awake and will take it |
341
+ | owner **busy**, item waited < `STICKY_STEAL_GRACE_MS` (30 s, from `queuedAt`) | not claimable — wait for the owner |
342
+ | owner **busy**, item waited ≥ grace | **steal**: any idle worker may claim; ownership transfers; logged as `mailbox.sticky_transfer` (reason `steal`) |
343
+ | owner **gone** (not in the live pool) | immediate transfer, no grace (reason `owner-gone`) |
344
+ | no probe installed | claimable (fail-open: liveness first) |
345
+
346
+ **Lifecycle.** Ownership is in-memory and epoch-scoped: `launchWorkerPool()` calls
347
+ `resetEntityOwnership()` and installs a fresh probe (`gone` if the id is not in
348
+ `activeWorkerIds`, else `idle`/`busy` from the worker's state). Persisting ownership
349
+ across restarts would claim a warmth that no longer exists. Serial mode
350
+ (`dequeue()` / `dequeueAsync()` without a `workerId`) neither filters nor records —
351
+ the §6 equivalence contract is untouched.
352
+
353
+ **Wake-up correctness** (three places where stickiness could have introduced stalls):
354
+
355
+ - `idleWaiters` is keyed by worker id, so the unicast wake (`review_request`) prefers
356
+ the **owner's** registered waiter; the deterministic hash remains the fallback.
357
+ - `dequeueAsync(workerId)` arms a **timed wake** at the earliest steal deadline among
358
+ items blocked only by a busy owner — a steal never depends on an unrelated event.
359
+ - The lost-wakeup recheck (`hasRunnableItem(workerId)`) uses the same claimability
360
+ predicate as `dequeue`, so a worker never spins on items it may not claim.
361
+
362
+ **Trade-offs (deliberate, documented).**
363
+
364
+ - Head-of-line latency: while its owner is busy elsewhere, an entity's item waits up
365
+ to the grace window even if other workers are idle. That is the price of continuity;
366
+ 30 s bounds it.
367
+ - A steal transfers continuity — unavoidable when liveness demands it — and is always
368
+ observable (`mailbox.sticky_transfer`), never silent.
369
+ - Items whose entity is *currently locked* are skipped by the pre-existing lock filter
370
+ before ownership is consulted; when the owner finishes, the unlock broadcast lets the
371
+ owner reclaim first (its `dequeue` runs in the same synchronous continuation).
372
+
373
+ <!-- verified-against-code: 2026-11-22, packages/core/src/mailbox.ts (entityOwners/dequeue/dequeueAsync/wakeIdleLoop), packages/core/src/attention.ts (launchWorkerPool/concurrentWorkerLoop) -->
374
+
249
375
  ## 4. Consistency model
250
376
 
251
377
  Concurrency is safe only if every worker can reason about what the others are doing.
@@ -258,18 +384,20 @@ points:
258
384
 
259
385
  | `kind` | When | Purpose |
260
386
  |---|---|---|
261
- | `declared` | worker starts an item | declares intent → prevents duplicate work |
262
- | `fact` | worker establishes a global fact | makes side effects visible |
387
+ | `declared` | worker starts an item | declares intent (history only — **never** read as "still running") |
263
388
  | `done` | worker finishes / fails | summary of result + leftovers |
264
389
  | `conflict` | worker meets a locked entity | surfaces contention |
265
390
 
266
- - Storage: in-memory ring buffer (last `HANDOFF_MAX_KEEP = 64`) **plus** JSONL
267
- persistence under the agent's data dir. `O_APPEND` single writes make concurrent
268
- appends atomic — no interleaving, and history survives restart.
269
- - `inFlight()` reconstructs "who is doing what right now" from `declared`/`fact`
270
- records that have no matching `done`/`conflict`, paired by **(worker, entity)** — a
271
- worker serving several entities keeps *all* of them visible (keying by `workerId`
272
- alone silently dropped all but the last).
391
+ - **This log is history, not state.** A `declared` record means "at some past moment I
392
+ started this"; it never expires on its own, so it cannot answer "who is working on X
393
+ right now". The old `inFlight()` helper tried to reconstruct liveness from
394
+ `declared`/`fact` records without a matching `done`, and the prompt rendered those as
395
+ "in progress" — which is how the same conversation once appeared under both "in
396
+ progress" and "completed" in a single prompt, making a worker announce "another worker
397
+ is handling this" and stop (2026-11-17 incident). `inFlight()` is deleted.
398
+ - **Authoritative liveness lives elsewhere**: `AttentionController.getActiveClaims()`
399
+ returns the live snapshot (workers that hold the entity lock and are mid-turn). No other
400
+ code path may claim that an entity is occupied.
273
401
  - The JSONL file **compacts** once `HANDOFF_COMPACT_THRESHOLD = 512` lines accumulate:
274
402
  the in-memory ring buffer is rewritten wholesale, so the file is bounded by
275
403
  `HANDOFF_MAX_KEEP + threshold` instead of growing without limit for the process
@@ -286,18 +414,25 @@ points:
286
414
  ### 4.2 Prompt injection — `packages/core/src/context-engine.ts`
287
415
 
288
416
  `buildSystemPrompt` appends a **`## Concurrency Context(并发上下文)`** block when
289
- concurrency is active and more than one worker is running. It contains:
290
-
291
- - the current worker id and total worker count;
292
- - other workers' in-flight intents;
293
- - the most recent handoff records (`HANDOFF_CONTEXT_LIMIT = 8`, own records filtered);
294
- - three consistency rules — *do not assume exclusive cognition*, *never process an
295
- entity another worker holds*, *report conflicts instead of overwriting*.
296
-
297
- The block is injected into the **volatile** segment only, so the stable prompt prefix
298
- (and its cache) is untouched. This is precisely the owner's requirement: a worker knows
299
- it is one of several, knows what others finished, and can avoid contradictory or
300
- duplicate actions.
417
+ concurrency is active and more than one worker is running. It contains two clearly
418
+ separated halves:
419
+
420
+ - **who is holding something right now** — `liveClaims`, i.e. the live snapshot from
421
+ `AttentionController.getActiveClaims()`: worker id, the actual lock keys it holds
422
+ (`conv:` / `session:` / `task:` …) and the item type. Deliberately **content-free**:
423
+ occupancy is a structural fact, and shipping the item body would leak one session's
424
+ text into another session's prompt.
425
+ - **handoff history** — the most recent terminal records (`done` / `conflict`, own records
426
+ filtered, capped). Rendered under a heading that says explicitly that history does not
427
+ mean "occupied".
428
+ - three consistency rules — *do not assume exclusive cognition*, *only entities listed
429
+ under "currently held" are off-limits; a name that merely appeared in history is free to
430
+ take*, *report conflicts instead of overwriting*.
431
+
432
+ The block keeps a **fixed shape**: when nothing is held it prints an explicit `(无)` line
433
+ instead of dropping the section, so the prompt never changes template with the data and a
434
+ worker can tell "nothing is held" from "this section was not injected". It is injected into
435
+ the **volatile** segment only, so the stable prompt prefix (and its cache) is untouched.
301
436
 
302
437
  ### 4.3 Tool write lock — `packages/core/src/agent.ts` + `packages/core/src/resource-locks.ts`
303
438
 
@@ -327,7 +462,7 @@ argument so that *different* resources run in parallel:
327
462
  > `packages/core/src/lock-resources.ts` (`AGENT_MEMORY_RESOURCE_DOMAIN = 'agent-memory'`,
328
463
  > `memoryResourceForPath()`, `memoryResourceLock()`). Table entries for memory tools now
329
464
  > carry `{ domain: 'agent-memory', resource: 'knowledge' | 'notebook' }`, and
330
- > `Agent.resourceLocksFor(toolCall, dataDir)` rewrites an `fs`-domain lock into the memory
465
+ > `Agent.resourceLocksFor(toolCall, opts)` rewrites an `fs`-domain lock into the memory
331
466
  > resource lock when the path names an agent memory file (`knowledge.md`, `NOTEBOOK.md`,
332
467
  > `state.md`, `role/ROLE.md`, `role/HEARTBEAT.md`).
333
468
  > Invariant pinned by `packages/core/test/lock-resource-keys.test.ts`: **same resource ⇒ same lock key**
@@ -336,8 +471,9 @@ argument so that *different* resources run in parallel:
336
471
 
337
472
  | Domain | Keyed by | Examples |
338
473
  |---|---|---|
339
- | `'*'` | — (global exclusive) | `shell_execute`, `apply_patch`, `package_install`, `hub_install`, `background_exec`, `process` |
340
- | `fs` | normalized path | `file_write`, `file_edit`, `generate_image`, `office_generate` |
474
+ | `'*'` | — (global exclusive) | `package_install`, `hub_install`, `process` |
475
+ | `shell-session` | shell session key (per execution context, `shellSessionIdFor`) | `shell_execute` |
476
+ | `fs` | normalized path | `file_write`, `file_edit`, `apply_patch` (per `patches[].file`), `shell_execute` / `background_exec` static write targets, `generate_image`, `office_generate` |
341
477
  | `task` / `requirement` / `workflow` / `project` / `deliverable` | entity id | `task_update`, `requirement_update_status`, `workflow_run`, `deliverable_update` |
342
478
  | `terminal` / `browser` | terminal id / page id | `exec_terminal`, `click`, `navigate_page` |
343
479
  | `a2a-out` | target agent / channel | `agent_send_message`, `feishu_send_message` |
@@ -363,6 +499,21 @@ Two important subtleties:
363
499
  `shell_execute` released `'*'`). Lesson: a tool whose own work is nanoseconds must
364
500
  never inherit global serialisation — the reported duration becomes a lie about the
365
501
  tool. Regression: `test/agent-write-lock.test.ts` → "discover_tools 不得排队等全局写锁".
502
+ - **Shell/patch locks are resource-derived, not capability-derived (2026-11-22).**
503
+ `shell_execute` / `apply_patch` / `background_exec` used to take `'*'` for the whole
504
+ command duration. A worker polling CI with `sleep 210` froze every write tool of every
505
+ other worker: `session` rename waited **151.9 s**, `git diff --stat` waited **148.6 s**
506
+ (actual work: 10 ms / 93 ms — DB activity-log evidence, 08:33–08:39 UTC). Now
507
+ `shell_execute` locks its persistent shell process (keyed per execution context via
508
+ `shellSessionIdFor` — the SAME formula the executor uses) plus statically parsed write
509
+ targets (`extractShellWriteTargets`); `apply_patch` locks each `patches[].file`;
510
+ `background_exec` locks its command's write targets at dispatch. The default shell
511
+ session is per-conversation, so concurrent workers no longer share one shell process
512
+ (cap `SHELL_MAX_SESSIONS_PER_AGENT = 16`, one-shot spawn fallback at the cap).
513
+ Residual: implicit writes of arbitrary programs (build output) are statically
514
+ unknowable — the platform guarantees only *decidable* mutual exclusion, exactly as
515
+ with lock-free readers; workspace isolation and branch discipline cover the rest.
516
+ Regression: `test/agent-write-lock.test.ts` → “纯读/纯等待的 shell_execute 不再冻结其他 session 的写工具”.
366
517
  - **Unknown tools get `tool:<name>`, not `'*'`.** MCP/skill/dynamically-registered tools
367
518
  are capability-unknown, but serialising *all* of them against *all* writes would break
368
519
  the platform's "multiple tool calls in one turn run in parallel" contract and stall the
@@ -469,6 +620,7 @@ See [streaming-and-reattach.md](./streaming-and-reattach.md) for the stream life
469
620
  | Loop | original `runLoop` | `concurrentWorkerLoop` × N |
470
621
  | Workspace | shared `rootWorkspace` | one per worker |
471
622
  | Attention/triage/deliberation | full pipeline | not run in worker loops |
623
+ | Decision recording (`pick`) | `processFocusedItem` | `processFocusedItem` — **same execution point** |
472
624
  | Entity lock | no-op (no contention) | enforced |
473
625
  | Handoff log | written on lifecycle (harmless) | injected into prompts |
474
626
  | Status | instance-level | aggregated across workers |
@@ -499,9 +651,13 @@ These are deliberate trade-offs, documented rather than hidden:
499
651
  `shell_execute` even if it mutates the same resources. Builtins are safe because a
500
652
  test asserts every one of them is classified.
501
653
  - **`background_exec` / `process` are protected at *dispatch*, not for the job's
502
- lifetime.** The lock covers registering the job in the process table; the spawned
503
- process then runs outside the lock and may write files concurrently with other
504
- workers. Treat long background jobs as a handoff-log *fact*, not as lock-covered.
654
+ lifetime.** `background_exec` locks its command's static write targets (fs domain)
655
+ at dispatch; `process` keeps `'*'` for the consumption action. The spawned process
656
+ then runs outside the lock and may write files concurrently with other workers.
657
+ Treat long background jobs as a handoff-log *fact*, not as lock-covered.
658
+ `process poll/log` shares the domain: the lock covers the *consumption* action
659
+ (marking the result consumed + resolving the callback entry). In-turn delivery
660
+ (`injectTurnDelta`) consumes the row inside the turn loop, not at tool dispatch.
505
661
 
506
662
  3. **Write-lock nesting is fail-fast.** A call chain that requests a lock conflicting
507
663
  with one it already holds raises `LockNestingConflictError` (§4.3) instead of
@@ -537,11 +693,14 @@ Concurrency-specific suites under `packages/core/test/`:
537
693
  |---|---|
538
694
  | `attention-concurrent.test.ts` | worker pool start/stop, directed cancel, conflict policy |
539
695
  | `mailbox-concurrent.test.ts` | broadcast wake-up, entity lock/unlock, key derivation |
696
+ | `mailbox-sticky-routing.test.ts` | ownership establishment, idle-owner exclusion, busy-owner grace + steal, gone-owner transfer, primary-key-only pinning, unicast owner preference, timed steal wake, serial-mode equivalence |
540
697
  | `agent-concurrent-activity.test.ts` | per-worker `currentActivity` isolation |
541
698
  | `agent-write-lock.test.ts` | domain-lock serialisation, per-path/per-entity parallelism, no-leak on throw, **write-tool classification totality**, lock-free HITL tools, unknown-tool per-name domain |
542
699
  | `resource-locks.test.ts` | domain conflict matrix, FIFO fairness, reentrancy |
543
700
  | `resource-locks-chain.test.ts` | **nested conflicting acquisition fails fast (no self-deadlock)**, cross-chain exclusion not weakened, parallel siblings still serialised |
544
- | `concurrent-handoff.test.ts` | **`clear()` truncates disk**, `inFlight()` pairs by (worker, entity), **file compaction bound**, id uniqueness across instances, corrupt-line tolerance |
701
+ | `concurrent-handoff.test.ts` | **`clear()` truncates disk**, **file compaction bound**, id uniqueness across instances, corrupt-line tolerance |
702
+ | `context-concurrency-notebook.test.ts` | **history never renders as "in progress"**, live claims render with lock keys + item type, notebook snapshot caps |
703
+ | `agent-concurrent-e2e.test.ts` | two chat sessions truly overlap, no session-id bleed, **two items of one session never run in parallel**, no dropped message |
545
704
  | `memory-session-debounce.test.ts` | **per-session debounce isolation** (two workers' sessions both persist) |
546
705
  | `attention-directed-cancel.test.ts` | `cancelActiveStream(target)` routing |
547
706
 
@@ -0,0 +1,264 @@
1
+ # Context Assembly & Compression
2
+
3
+ > **Scope (this file)**: how conversation history and anchors are packed into one request and compressed — token budget, the compression pipeline, task-prompt protection, tool-block compaction, LLM summarization, sanitization, the ContextOS fixed/variable split with SLOT anchors, and the compaction defects with their root-cause analysis.
4
+ > **Split out of** [prompt-engineering.md](./prompt-engineering.md) §3 on **2026-11-15**. Section numbers (§3.x) are unchanged, so an existing `prompt-engineering.md §3.x` reference resolves to the same `§3.x` here.
5
+ > **Siblings**: [prompt-engineering.md](./prompt-engineering.md) — call taxonomy, cache-scope layout, system-prompt architecture (§1–§2), output-token resolution (§6); [tool-loop-harness.md](./tool-loop-harness.md) — tool-loop harness and scenario-specific assembly, incl. the scenario × context matrix (§4–§5).
6
+
7
+ ## 3. Message Assembly & Context Compression
8
+
9
+ `ContextEngine.prepareMessages()` assembles the final message array sent to the LLM. It operates in four stages.
10
+
11
+ ### 3.1 Token Budget Calculation
12
+
13
+ ```
14
+ contextWindow = model's context window (e.g. 200K for Claude Sonnet 4)
15
+ maxOutput = min(model.maxOutputTokens, contextWindow × 40%)
16
+ safetyMargin = ceil(min(contextWindow × 8%, 16000))
17
+ messageBudget = contextWindow − systemTokens − toolDefTokens − maxOutput − safetyMargin
18
+ ```
19
+
20
+ **maxOutput reservation**: Uses the model's actual `maxOutputTokens` from the model catalog (e.g. 64K for Claude Sonnet 4, 128K for Claude Opus 4.6), capped at 40% of the context window. This ensures the budget reserves enough space for the model's full output capability without over-compressing messages.
21
+
22
+ Token estimates use tiktoken when available (model-specific encoding), falling back to `chars / 3.5` heuristic.
23
+
24
+ ### 3.2 Compression Pipeline
25
+
26
+ **Policy: budget-first (model window AND provider afford).** Markus packs against the
27
+ real model window, then further clamps by any OpenRouter prompt-afford hint (from a prior
28
+ `Prompt tokens limit exceeded: X > Y` 402). Compression runs when history exceeds
29
+ `CONTEXT_PROACTIVE_COMPACT_RATIO` (75% — the history-occupancy water level, i.e. the history's
30
+ share of `messageBudget`) — not only when the hard window overflows. Session restore also trims before the first LLM call
31
+ (`SESSION_RESTORE_MAX_MESSAGES` / `SESSION_RESTORE_MAX_MESSAGE_TOKENS`).
32
+
33
+ ```
34
+ Session Messages
35
+ │
36
+ ▼
37
+ Stage 0: Clamp messageBudget by promptAffordTokens − PROMPT_AFFORD_OUTPUT_RESERVE
38
+ │
39
+ ▼
40
+ Stage 1: Pathological single-message shrink ONLY
41
+ └─ shrinkOversizedMessages(cap: CONTEXT_ABSURD_MESSAGE_CHARS = 200k)
42
+ └─ sanitizeMessageSequence()
43
+ │
44
+ ▼
45
+ (runs if totalTokens > messageBudget OR > proactive 75% threshold)
46
+ │
47
+ ▼
48
+ Stage 2: Token-budget-driven compression (progressive)
49
+ ├─ 2a: shrinkOversizedMessages(cap: max(8000, budget/4)) + compactOldTurns()
50
+ ├─ 2b: smartSummarizeAndTruncate(keep: max(24, 55%))
51
+ └─ 2c: stronger summarize(keep: max(16, 40%)) + re-shrink
52
+ │
53
+ ▼
54
+ Stage 3: Last-resort trimming
55
+ └─ trimToFitBudget() — drop oldest, protect index 0 (task prompt)
56
+ │
57
+ ▼
58
+ Final: [system prompt, ...compressed messages]
59
+ Metrics: systemTokens / historyTokens / toolDefTokens / totalPromptTokens / compactStage
60
+ ```
61
+
62
+ - **Safety margin**: `min(contextWindow * 0.08, 16000)` — modest, to prefer packing
63
+ history over reserving unused slack.
64
+ - **Channel history**: `CHANNEL_CONTEXT_MESSAGES = 15` (load, inject, and prompt copy aligned).
65
+ - **Tool result offload**: `TOOL_RESULT_OFFLOAD_CHARS = 12_000` (preview kept in context).
66
+ - **Storage-side compaction** is a separate, high-volume safety net (not a per-call token
67
+ saver): on-disk sessions are compacted only at
68
+ `SESSION_STORAGE_COMPACT_TRIGGER = 2000` messages, keeping
69
+ `SESSION_STORAGE_COMPACT_KEEP = 1000`; oversized on-disk tool results are shrunk at
70
+ `SESSION_STORAGE_TOOL_SHRINK_CHARS = 100k`. See [memory-system.md](./memory-system.md).
71
+
72
+ **Design rationale (Hermes progressive disclosure + afford-aware packing)**: keep cold-start
73
+ system+tools lean (~10k target), activate skill bodies on demand, and never fill a 128k/1M
74
+ window when the provider key can only afford ~37k prompt tokens.
75
+
76
+ **Lightweight sessions**: All interactions (heartbeat, A2A, memory flush, comments) use the same `prepareMessages()` pipeline. Sessions are persisted to JSON files for full traceability. The `scenario` parameter controls what context is included in the system prompt — lightweight scenarios (`heartbeat`, `a2a`, `comment_response`) skip heavy context like assigned tasks, deliverables, and chat session lists.
77
+
78
+ ### 3.3 Task Prompt Protection
79
+
80
+ The first user message in a task session often contains the task description and the `task_submit_review` instruction. This message is **protected** throughout all compression stages:
81
+ - `smartSummarizeAndTruncate()` detects `TASK EXECUTION` or `task_submit_review` markers and preserves the first message verbatim.
82
+ - `compactOldTurns()` skips compaction of block 0 if it matches the task prompt pattern.
83
+ - `trimToFitBudget()` preserves index 0 and only compacts it as a last resort.
84
+
85
+ ### 3.4 Tool Block Compaction
86
+
87
+ `summarizeToolBlock()` compresses an `[assistant+toolCalls, tool, tool, ...]` block into a single assistant message:
88
+ - Preserves tool names and truncated arguments.
89
+ - **Error results** are preserved in full (up to 200 chars) — errors in context help the model self-correct.
90
+ - Research tool results (`web_search`, `file_read`, etc.) retain up to 500 chars of findings.
91
+ - **Serialization diversity**: Uses 4 rotating summary templates to prevent the model from mimicking uniform compaction patterns.
92
+
93
+ ### 3.5 LLM-Powered Summarization
94
+
95
+ When available, `smartSummarizeAndTruncate()` uses an LLM call to summarize older messages:
96
+ - The summarizer LLM call is cheap: truncates each message to 300 chars, total input capped at 8000 chars.
97
+ - No `maxTokens` cap — the router fills in the model's real output limit (the prompt itself bounds output to "under 1500 characters"). Temperature 0.2.
98
+ - Fallback: `buildHeuristicSummary()` extracts key sentences from assistant messages.
99
+ - The summary is **not** persisted to disk — `prepareMessages()` must stay pure (no `writeDailyLog`).
100
+ It is instead carried in-history as a `[SYSTEM] [Conversation history summary …]` message, and the
101
+ durable compaction summary lives in the fixed `[CONTEXT SUMMARY]` segment (the session's `summary` field).
102
+
103
+ ### 3.6 Message Sanitization
104
+
105
+ `sanitizeMessageSequence()` ensures structural correctness before LLM submission:
106
+ - Every `assistant(toolCalls)` must be followed by ALL corresponding `tool` result messages.
107
+ - Orphaned tool messages are dropped.
108
+ - Incomplete assistant+tool blocks are dropped entirely.
109
+ - Consecutive user messages are merged (unless either is a system injection like `[SYSTEM]` or `[Conversation history summary`).
110
+
111
+ ### 3.7 Fixed/Variable Split & Session Anchors (ContextOS)
112
+
113
+ A complement to the compression pipeline above: separate the prompt into a **fixed segment**
114
+ (system + tools + SLOT anchors) that is **never business-compacted**, and a **variable segment**
115
+ (history) that is the only thing compression/truncation touches. Motivation: long-session "loop"
116
+ bugs where compaction discarded the agent's work anchors, so the agent lost its "position" and
117
+ re-read the same files forever (diagnosed on 8/20; deliverable notes are archived in git history).
118
+ Scope: `packages/core/src/context-slot.ts` + `tools/session.ts` + the `prepareMessages` slot
119
+ plumbing.
120
+
121
+ **Fixed vs variable:**
122
+
123
+ - **Fixed (never compacted)**: system prompt, tool definitions, and the **SLOT segment**.
124
+ - **Variable**: conversation history — the only thing shaved/compressed/truncated.
125
+
126
+ **SLOT fixed segment (`[SLOTS]`)** — `context-slot.ts`:
127
+ - Slots are agent-managed named anchors (`goal` / `done` / `next`, or any agent-chosen key)
128
+ persisted on the session (`ConversationSession.slots`).
129
+ - At send time, `prepareMessages` accepts `slotsSegment` (= `serializeSlots(sessionId)`), subtracts
130
+ `slotsTokens` from the budget, and appends it to the system message (`[SLOTS] (agent-managed, not
131
+ compacted)\n· key: text…`). It is **excluded from the compaction/truncation chain** — so after any
132
+ compress or truncate, the agent still sees its current goal/done/next and can continue **without
133
+ re-reading files**.
134
+ - Runtime caps: `CONTEXT_SLOT_MAX_CHARS` (1200).
135
+
136
+ **Session tools (agent-driven compaction + anchors)** — `tools/session.ts` exposes 10 operations so
137
+ the agent can actively manage long sessions instead of relying only on passive auto-compaction:
138
+ `list | get | compact(keepLast, goal?, done?, next?) | pin | unpin | retrieve | include | purge | status | rename`.
139
+ - `compact` folds expired history into structured anchors (`compactWithAnchor`: pin goal/done/next
140
+ into SLOTs, then compress), keeping recent N; raw history is archived to `conversation_fragment`
141
+ (never deleted) and recoverable via `include`.
142
+ - `pin`/`unpin`: write/remove named slot anchors (survive compression + truncation).
143
+ - `include`: place archived fragment back into context precisely.
144
+ - All read/write ops are guarded by `checkOwnership(sessionId, agentId)` — an agent may only manage
145
+ its own session.
146
+
147
+ **Context watermark (`[CONTEXT X% used …]`)** — the agent can observe its own pressure (no more
148
+ silent truncation) and act:
149
+ - `usedPct = (fixedTokens + variableTokens) / effectiveBudget`.
150
+ - `[CONTEXT WARN]` at ≥80%: nudge to `session_compact` or `session_pin` an anchor.
151
+ - `[CONTEXT CRIT]` at ≥95%: warn that the system will hard-truncate oldest turns; instruct to
152
+ immediately `session_compact` + `session_pin`.
153
+ - Injected via the volatile `[SYSTEM] [Live context]` tail (see [prompt-engineering.md](./prompt-engineering.md) §2.1), never into the system prefix.
154
+
155
+ **Why this fixes the loop**: previously compaction dropped anchors → the agent lost position → it
156
+ re-read the same files to re-orient → that re-reading itself grew context → re-truncated → loop.
157
+ With SLOT anchors locked in the fixed segment, a compressed/truncated history still carries
158
+ goal/done/next every turn, so the agent resumes without re-reading — the trigger for the loop is gone.
159
+
160
+ ---
161
+
162
+ ### 3.8 Compaction defects fixed in v2.1 (2026-09-16)
163
+
164
+ Four defects were found by auditing the pipeline against the published designs
165
+ (Anthropic compaction, DeepSeek V3.2 context management, fast-agent).
166
+
167
+ **(a) Fold direction was inverted — `compactOldTurns()`.** It walked blocks
168
+ oldest→newest, kept each verbatim while the budget allowed, then summarised *or
169
+ dropped* the remainder. That preserves the **oldest** conversation and
170
+ summarises/discards the **most recent** past turns — the opposite of "keep the
171
+ recent window verbatim, summarise the distant past" — and it discarded exactly
172
+ the context the model still needed. Now the recency walk accumulates from the END
173
+ and keeps the newest blocks verbatim. Order is preserved, and folding is
174
+ block-wise via `parseIntoBlocks()`, so an assistant tool-call is never separated
175
+ from its tool results. Task prompts (`TASK EXECUTION` / `task_submit_review`) stay
176
+ protected verbatim even though they are the oldest block.
177
+
178
+ **(b) The watermarks could never fire on a large window.**
179
+ `CONTEXT_PROACTIVE_COMPACT_RATIO` / `CONTEXT_WARN_RATIO` are relative to the model
180
+ window, so on the 1311k window Markus runs, proactive compaction sits around
181
+ ~500k tokens. The observed session finished a single turn at 269k input tokens —
182
+ ~12 % of the window — with `compactStage === 'none'` throughout: **no maintenance
183
+ compression ever ran.** Added an absolute ceiling:
184
+
185
+ | Constant | Value | Meaning |
186
+ |---|---|---|
187
+ | `CONTEXT_ABS_HISTORY_TOKENS` | 120 000 | above this, maintenance compression fires regardless of window % |
188
+ | `CONTEXT_ABS_HISTORY_TARGET_TOKENS` | 72 000 | what a fold compresses down to (hysteresis: grow to 120k, fold to 72k) |
189
+
190
+ When the ceiling trips, `historyTarget` replaces the window-derived
191
+ `messageBudget` (which would otherwise authorise keeping everything — a silent
192
+ no-op) and the fold boundary becomes `messages.length`, which is what also covers
193
+ the single-gigantic-turn case.
194
+
195
+ **(c) `smartSummarizeAndTruncate()` reordered history.** Eligible messages were
196
+ sorted by **priority**, and `retained` was then built straight from that sorted
197
+ array — so the summariser received a priority-shuffled transcript and the kept
198
+ older messages were replayed in importance order instead of time order. Both
199
+ `older` and `promoted` are now re-sorted by original index. (Chronological input
200
+ also produces a better summary, and restores determinism, which the prefix cache
201
+ relies on.)
202
+
203
+ **(d) `findCurrentTurnStart()` counted synthetic messages as user turns.**
204
+ Engine-synthesised blocks — the compaction summary, the `[SYSTEM] [Live context]`
205
+ tail, `[Continue from where you left off …]` and `[SYSTEM] Loop detected: …` —
206
+ are `role: 'user'` but are not user turns. Since `findCurrentTurnStart()` decides
207
+ both the turn boundary and the prefix-cache breakpoint, they were placed against
208
+ the wrong boundary. `isSyntheticMessage()` now skips them.
209
+
210
+ > **Why the synthetic blocks cannot simply become `role: 'system'`:** the
211
+ > Anthropic adapter does `find(m => m.role === 'system')` and then
212
+ > `filter(m => m.role !== 'system')`, so any non-first system message is silently
213
+ > dropped there (the summary would vanish). Skipping them during accounting is the
214
+ > provider-safe fix. Revisit only if every adapter is switched to multi-system
215
+ > handling.
216
+
217
+ **Regression guard**: `packages/core/test/context-compaction-v21.test.ts`.
218
+
219
+ ### 3.9 Root cause analysis: why these defects keep returning (2026-09-16)
220
+
221
+ Three rounds of auditing found six defect classes. They are **not six independent
222
+ bugs** — they are six surfaces of four design gaps, which is why fixing one kept
223
+ exposing the next. This section records the gaps so the next fix is aimed at the
224
+ cause rather than the symptom.
225
+
226
+ | # | Root cause | Design or implementation debt | Surfaces it produced |
227
+ |---|---|---|---|
228
+ | RC1 | **The fixed/variable split has no third tier.** Context was modelled as *fixed* (system + tools + slots) vs *variable* (history + volatile tail). Stable-but-large session state — knowledge, notebook, skills catalog, deferred tools, task board — has neither a home nor a delivery contract, so it was dumped into the *per-call* tail. | **Design** | Tail re-sent 66× in one turn; every "make the tail smaller" fix then risked losing the state outright ([prompt-engineering.md](./prompt-engineering.md) §2.1.2) |
229
+ | RC2 | **No harness channel.** Providers accept only system/user/assistant/tool, so the engine synthesises `role:'user'` for state, `[Continue …]` and loop warnings. There is no explicit framing that marks a block as *telemetry, not instruction*. | **Design** | Turn accounting corrupted (`findCurrentTurnStart`); negative priming from stacked \"do not repeat\" prompts; state read as the newest user message and re-announced |
230
+ | RC3 | **No context budget owner.** Each feature pushes into the dynamic array with its own cap; nobody owns the total, the priority order, or eviction. | **Design** | Byte-constant noise lines survive forever (`_(66 completed/closed tasks)_`); knowledge truncated by *document order* mid-sentence; `## Notebook` reached 41 % of the tail |
231
+ | RC4 | **Cache-friendliness was a patch, not an invariant — and was unmeasurable.** Registration-order emission was fixed case-by-case; `discover_tools.description` still embedded per-turn counts *directly under a comment claiming cache-safety*; the documented MUST-NOT in `tool-system.md` was violated by the code. No cache-hit telemetry and a 0.7 heuristic polluting the denominator meant regressions were **invisible**. | **Design (missing guard) + implementation** | Tool prefix silently busted every turn; the same class of bug reappeared across rounds |
232
+ | RC5 | **The toolset is recomputed per turn, not accumulated per session.** `recentToolNames` is an instance-level LRU(10); `activatedExtraTools` is instance-level and never reset. Both drift within a turn **and leak across sessions**. | **Implementation** | Capability surface changes every turn (cache break); one session inherits tools activated in another |
233
+ | RC6 | **Estimated vs reported usage is a dual rail.** Budget and `[CONTEXT x%]` come from the local `TokenCounter`; server-reported `inputTokens` is used only for the audit log, only calibrates the estimator, and is wired on *one* code path (`agent.ts:4373`). | **Implementation** | The displayed water level is an estimate; the cache-hit denominator was back-filled with `totalTokens*0.7` |
234
+
235
+ #### What was fixed in this round
236
+
237
+ | Root cause | Fix | Where |
238
+ |---|---|---|
239
+ | RC1 + RC2 | Durable `[SYSTEM] [State checkpoint]` history message on change (complete + append-only + cache-extending); tail digest names where the content lives; relative-time labels normalised out of the hash | [prompt-engineering.md](./prompt-engineering.md) §2.1.2, `context-engine.ts` |
240
+ | RC3 | Closed-task counters deleted; **team active tasks kept in full** but ranked actionable-first; empty board skipped for converse; `prepareKnowledgeForPrompt(raw, maxChars, query?)` ranks by relevance, selects **whole** sections, and always emits a title index of what was omitted | §3.9.1, `context-engine.ts` |
241
+ | RC4 | `discover_tools.description` is now a pure function of the **registry** (minus `TOOL_DEF_CORE_KEEP`), deterministically sorted; byte-stability guard test added; per-session cache-hit window + `cacheHitRateWindow` / `cacheHitRateSamples` telemetry that returns `null` (not 0) when nothing was reported | `tool-selector.ts`, `agent-metrics.ts` |
242
+
243
+ > **A note on RC3's shape:** the first attempt at the task-board fix collapsed
244
+ > *all* non-actionable team tasks into a count bucket. That was rejected on review
245
+ > — it traded information away for tokens, hiding \"what is my team working on?\"
246
+ > from a manager. Only the genuinely constant counters were removed. **Deleting
247
+ > noise is a win; deleting signal is a regression**, and the two look identical in
248
+ > a token-diff.
249
+
250
+ #### 3.9.1 Open items — status after the cache-scope round (2026-09-16, v4)
251
+
252
+ | # | Item | Status |
253
+ |---|---|---|
254
+ | O1 | **Tool schema drift (RC5).** Session-level monotonic toolset. | **DONE.** `Agent.stickyTools()` keeps `recent`/`activated` in a session-keyed record (`toolSticky`), monotonic within a session (freezes at `STICKY_RECENT_TOOLS_MAX` instead of evicting) and reset on session switch, so the *cross-session leak* is closed as well as the per-turn drift. Remaining (deferred): the call-site inconsistency where the stream/task/risk paths do not pass `extraRecentToolNames`, and `Mask, Don't Remove` decode-time placeholders (not applicable to closed APIs). |
255
+ | O2 | **Reported usage as the single source of truth (RC6).** | **PARTIAL — calibration only.** `calibrateTokenCounter(response.usage.inputTokens)` is now wired on 8 paths, and `extractCacheReadTokens()` already parses DeepSeek's `prompt_cache_hit_tokens` **and** OpenAI/OpenRouter `prompt_tokens_details.cached_tokens`, feeding `cacheHitRateWindow` (reported-only denominator). Still open: using reported tokens to *drive* the budget/water level and marking it `src=reported\|estimated`. Deferred per Owner's call — do DeepSeek-first if pursued. |
256
+ | O3 | **`## Notebook` size (RC3).** Largest single tail section (mean 9 163 chars, 41 % of tail). | **DONE (size + lifecycle).** Added a TOTAL cap (`NOTEBOOK_PROMPT_MAX_CHARS = 6000`) on top of the per-entry cap, keeping the most recent entries and naming any omitted keys — so the block can no longer dominate the tail. Relevance ranking deliberately NOT applied: the notebook is the agent's own workspace, and dropping a note it wrote itself is a correctness risk, not a token win. Follow-up ([memory-system.md](./memory-system.md) §2): the cap alone was not enough — entry count/TTL/single-writer were missing, so a real notebook reached 26 entries / 33 KB and an 18-day-old triage decision was re-injected as current fact. Now: single write path (`Agent.writeNotebookEntry`), per-tier TTL, cross-tier entry cap, normalize-on-load, deterministic ordering, and inline truncation instead of whole-entry omission. |
257
+ | O4 | **`filterSkillsByRelevance` dead code.** | **DONE.** Deleted. It was never called, and the every-turn `## Available Skills` table is ORG context (scope O) — byte-stable for the whole org — so ranking it per query would convert a shared cached block into a per-call one. Rationale recorded in-code. |
258
+
259
+ **Evidence provenance.** All measured figures come from
260
+ `~/.markus/llm-logs/2026-09-16.jsonl` (66-call session; 377 tails) plus a
261
+ read-only audit of `packages/core/src`. The 322 tails taken *before* the gating
262
+ commit are a historical snapshot used to size the problem, **not** a description
263
+ of current `HEAD`.
264
+