@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,29 @@
1
1
  # Mailbox & Attention System
2
2
 
3
- > Last updated: 2026-07
3
+ > Last updated: 2026-11-15 — the A2A chapter (§11) and the user-notification chapters
4
+ > (§12/§13) were extracted to [a2a-communication.md](./a2a-communication.md) and
5
+ > [notification-delivery.md](./notification-delivery.md). Only pointers remain here.
6
+
7
+ ---
8
+
9
+ ## 本文件范围 — Scope of this file
10
+
11
+ **This document owns the mailbox queue and the attention controller, and nothing else.** It is
12
+ the single source of truth for *how a signal enters, waits, is merged, is claimed, is retried
13
+ and is finally delivered to an agent*: the item-type registry (§3), the attention controller
14
+ (§4), the enqueue API (§5), persistence (§6), state-machine integration (§7), enqueue-time
15
+ deduplication (§14), restart/retry (§17/§18), the attention decision rules (§21), and the
16
+ address/envelope/bounce layer (§28). Priorities and the delivery invariants stated here are
17
+ binding for every producer.
18
+
19
+ - **Agent-to-agent (A2A)** — DM/group channels, the one-message-one-delivery-fact invariant,
20
+ the reply sink, tools & transport, `PendingCallbackRegistry`, heartbeat integration: see
21
+ [a2a-communication.md](./a2a-communication.md) (was §11; §11 below is a pointer).
22
+ - **User notification / IM delivery** — in-app notification store, `notify_user` vs
23
+ `request_user_input`, destination resolution and approval cards: see
24
+ [notification-delivery.md](./notification-delivery.md) (was §12/§13; §12/§13 below are pointers).
25
+ - The mailbox is the **transport** for both: it guarantees enqueue, priority and serialised
26
+ attention; it does not define *what* a notification means or *who* should receive it.
4
27
 
5
28
  ---
6
29
 
@@ -13,7 +36,7 @@ This is implemented through two core abstractions:
13
36
  - **Agent Mailbox** — A priority queue that serialises all incoming stimuli.
14
37
  - **Attention Controller** — An event-driven focus manager that processes mailbox items one at a time, with interrupt handling at safe yield points.
15
38
 
16
- **Concurrent processing (default on, opt-out).** The attention loop can instead run as a pool of N isolated **worker loops** so the agent handles several *independent* entities at once — see [concurrent-processing.md](./concurrent-processing.md). Serialisation is preserved **per entity**: an entity-affinity lock in the mailbox guarantees a given task / requirement / conversation / user is never processed by two workers simultaneously, and each worker holds its own `SessionWorkspace`, so the "one thing at a time" guarantee still holds for any single line of work. Setting `agent.concurrent.enabled = false` (or `maxWorkers = 1`) restores a strictly single-worker loop with identical behaviour to the original design.
39
+ **Concurrent processing (default on, opt-out).** The attention loop can instead run as a pool of N isolated **worker loops** so the agent handles several *independent* entities at once — see [concurrent-processing.md](./concurrent-processing.md). Serialisation is preserved **per entity**: an entity-affinity lock in the mailbox guarantees a given task / requirement / conversation / user is never processed by two workers simultaneously, and each worker holds its own `SessionWorkspace`, so the "one thing at a time" guarantee still holds for any single line of work. Setting `agent.concurrent.enabled = false` (or `maxWorkers = 1`) restores a strictly single-worker loop with identical behaviour to the original design. Beyond exclusion, the mailbox also keeps **sticky entity→worker ownership**: an entity's items are claimable across turns only by the worker that first claimed them, with explicit liveness overrides (busy-owner grace steal / gone-owner transfer / pool-epoch reset) — see [concurrent-processing.md §3.4](./concurrent-processing.md).
17
40
 
18
41
  ### Why was processing originally serialised?
19
42
 
@@ -25,7 +48,7 @@ Early Markus let an agent handle multiple messages simultaneously, which caused:
25
48
  The mailbox model fixed this by treating the agent's attention as a scarce, serial resource. Concurrent processing re-introduces parallelism **only *between* entities**, and addresses each of these three failures directly:
26
49
 
27
50
  - **Memory contamination** → per-worker [`SessionWorkspace`](../../packages/core/src/session-workspace.ts) isolation via `AsyncLocalStorage`.
28
- - **Cognitive interference** → concurrent worker loops are pure consumers; triage / deliberation / preempt logic runs only in the serial loop.
51
+ - **Cognitive interference** → concurrent worker loops are pure consumers; decide / preempt logic runs only in the serial loop.
29
52
  - **Non-deterministic races** → entity-affinity lock in the mailbox + an agent-level tool write-lock.
30
53
 
31
54
  See [concurrent-processing.md](./concurrent-processing.md) for the full guarantees, configuration, and known limitations.
@@ -91,6 +114,38 @@ All mailbox item types, their metadata, and their processing behaviour **should*
91
114
  drifted (e.g. the sets were cited as lines 1493-1500 but live at 1595-1597), and a
92
115
  stale line number is worse than none because it looks authoritative.
93
116
 
117
+ ### 3.2 Identity on every enqueue
118
+
119
+ Every `AgentMailbox.enqueue` must declare **where the item came from**. Otherwise the
120
+ identity column is silently NULL and the item cannot be attributed to a turn — which is
121
+ what produced the 2026-11-15 incident where terminal gates required a fact that the
122
+ executing turn could not attribute.
123
+
124
+ | Field | Meaning |
125
+ |---|---|
126
+ | `workUnitRef` | The turn that produced the item: `session:<id>:r<N>` for a chat turn, `task_<taskId>_r<N>` for a task execution, `a2a:<entity>` for agent-to-agent. This is the intended normal case — measured coverage was 0.18% before the enqueue gate became mandatory (2026-11-18); see §6.7. |
127
+ | `refOrigin` | The caller's declaration of where identity comes from: `"entity"` / `"turn"` (a ref is present), or `"platform-internal"` (the platform itself, not an agent turn). **Required whenever `workUnitRef` is absent** — see §6.7 for why an undeclared NULL is rejected rather than logged. C10-0B removed the former `"pending-link"` declaration: identity must exist at enqueue (memory + DB, one writer); a post-enqueue link wrote only the DB column and left the in-memory item null. |
128
+
129
+ Enforcement is in `AgentMailbox.enqueue` (`packages/core/src/mailbox.ts`): an item carrying
130
+ neither field logs an ERROR and is **rejected**, rather than being stored with a NULL
131
+ identity. Adding a new caller means declaring one of the two — not adding a carve-out.
132
+
133
+ **Ensure at assembly (C10-0A).** A declared ref is a promise that the entity exists.
134
+ At the same enqueue assembly point, `AgentMailbox` calls the identity port
135
+ (`MailboxIdentityPort.ensureIdentity`, wired by `APIServer.wireWorkUnits`) to
136
+ insert-or-nothing the `work_units` row **before** the item is stored — a reference
137
+ without an entity is the dangling-identity defect this gate exists to prevent.
138
+ Owner resolution belongs to org-manager (task → assignee, requirement → creator,
139
+ fallback: the recipient); core never guesses entity semantics. Ensure failure does
140
+ not break the business path: it is counted (`takeIdentityEnsureFailedCount`) and
141
+ surfaced, never silent. Entity refs (`requirement:<id>`, `task_<taskId>_r<N>`) are
142
+ constructed only via `WORK_UNIT_REF` in `packages/shared/src/work-unit.ts`.
143
+
144
+ A WU pre-created `idle` by a notification is transitioned to `running` by
145
+ `TaskService.linkExecutionEpoch` when execution actually starts (an
146
+ `execution_started` row in `status_transitions`) — a turn must never run on an
147
+ idle WU, and the transition reuses the same row (ensure is insert-or-nothing).
148
+
94
149
  <!-- verified-against-code: 2026-10-25, packages/core/src/attention.ts (USER_INTERACTION_TYPES, PEER_INTERACTION_TYPES, heuristicDecision) -->
95
150
 
96
151
  **Definition of record**: `packages/shared/src/types/mailbox.ts` — `MAILBOX_TYPE_REGISTRY`,
@@ -275,7 +330,7 @@ Registration flow: when an agent starts an async operation the completion is reg
275
330
 
276
331
  On completion/firing the registry entry is resolved and delivered via the shared `Agent.deliverCallback()` helper according to its `deliveryMode`.
277
332
 
278
- See §11.3 for the full `PendingCallbackRegistry` specification.
333
+ See [a2a-communication.md](./a2a-communication.md) §11.3 for the full `PendingCallbackRegistry` specification.
279
334
 
280
335
  ---
281
336
 
@@ -301,7 +356,7 @@ There is **no polling**. When a new item arrives while the agent is focused:
301
356
  1. The mailbox emits `mailbox:new-item` via the EventBus.
302
357
  2. The `AttentionController` sets an **interrupt signal**.
303
358
  3. At the next **safe yield point** (between LLM turns in the tool loop), the agent calls `checkYieldPoint()`.
304
- 4. The controller evaluates the pending item using **heuristics first** (fast, no LLM call), then optionally falls back to an **LLM interrupt judge** for ambiguous cases where heuristics return `continue`. The LLM judge sees both the current work context and the full content of the new message, enabling it to understand semantic intent (e.g., "stop publishing" → cancel, "hold off for now" → preempt).
359
+ 4. The controller evaluates the pending item with `heuristicDecision()` — a **pure rule table** (priority + type + session identity), no LLM call at any point. There is no "ask a model when the table says `continue`" fallback: the table's `continue` is final.
305
360
 
306
361
  ### Decision Types
307
362
 
@@ -323,7 +378,7 @@ These two decisions handle fundamentally different situations:
323
378
  - **Preempt (pause)**: "暂停" — The current work is saved. The mailbox item is moved to `deferred` status and will automatically resurface when the agent is idle. Session context (conversation history) is preserved by `sessionId`, so processing continues from where it left off.
324
379
  - **Cancel (stop)**: "取消" — The current work is permanently abandoned. The mailbox item is marked as `completed` and will NOT be resumed. Used when the incoming message explicitly revokes or invalidates the current work.
325
380
 
326
- The heuristic interrupt rules (`heuristicDecision`) never produce `cancel` — only the **LLM interrupt judge** can make this semantic distinction, since it requires understanding message content (e.g., distinguishing "wait before deploying" from "cancel the deployment entirely").
381
+ The heuristic interrupt rules (`heuristicDecision`) never produce `cancel`, and nothing else in the decision path does either — there is no model in the loop to infer "the user meant stop". Cancellation is an **explicit act** (the user aborts, or the item is cancelled through its own terminal path); an ambiguous instruction like "wait before deploying" lands as `continue` or `preempt`, never as a silent irreversible cancel.
327
382
 
328
383
  ### Priority Invariant: User Interactions First
329
384
 
@@ -333,7 +388,7 @@ Only user chat (`human_chat`) is assigned **priority 0 (critical)** — the high
333
388
  2. **R1**: If a new `human_chat` arrives while the agent is focused on any non-user work, the agent **always preempts** to handle it immediately. Only `human_chat` is in `USER_INTERACTION_TYPES`, so comments do **not** preempt this way — a `task_comment` / `requirement_comment` on the focused task/requirement is **merged** into context instead (R2 / R3).
334
389
  3. When idle with multiple items queued, the priority queue ensures user interactions are dequeued first.
335
390
  4. The agent's system prompt includes a **summary** of the mailbox queue — the pending count plus the top items, each truncated to `SYSTEM_MAILBOX_ITEM_PREVIEW_CHARS` (`ContextEngine.buildMailboxSection`). It is deliberately a truncated view. An earlier revision claimed the opposite ("the full mailbox queue, not a truncated view"); the code has always sliced.
336
- 5. **Deliberation abort**: If a `human_chat` arrives during active deliberation, the deliberation is aborted immediately and the user message is processed first. Deliberation results are discarded; items remain in queue for next cycle.
391
+ 5. **Preemption is resumable**: if a `human_chat` arrives while the agent is working, R1 returns `preempt` — the running item is parked with `deferDequeued()` and the user message is processed first; the parked item keeps its session and resumes on the next idle cycle (§22). Nothing is discarded.
337
392
 
338
393
  <!-- verified-against-code: 2026-10-25, packages/shared/src/types/mailbox.ts (category tables), packages/core/src/attention.ts (USER_INTERACTION_TYPES, heuristicDecision, checkYieldPoint) -->
339
394
 
@@ -671,11 +726,81 @@ Historical activities without `mailbox_item_id` remain valid but lack the causal
671
726
  6. **Completed** → `mailbox_items.status = 'completed'`, `completed_at` set; activity `ended_at` set
672
727
  7. If **deferred** → `status = 'deferred'` with optional `deferred_until`
673
728
  8. If **merged** → `status = 'merged'` with `merged_into` pointing to the absorbing item
674
- 9. If **abandoned** → `status = 'dropped'`. This includes stale rows that recovery
675
- refused to requeue, retry-exhausted background items, and duplicates spliced out
676
- by dedup. `dropped` is a first-class terminal state, not an error case — the
677
- earlier revision of this list omitted it even though it is the most frequent
678
- terminal status written by `mailbox.ts`.
729
+ 9. If **abandoned** → `status = 'bounced'` with a mandatory `drop_reason`, then collected into
730
+ `catch_all` with `bounce_target`. This includes stale rows that recovery refused to
731
+ requeue, retry-exhausted background items, duplicates spliced out by dedup, and explicit
732
+ cancel decisions (see §28.5). `dropped` **is not in the status value domain** — historical
733
+ rows carrying it are read-only and normalised to `bounced` on the read path.
734
+ A bounce is a first-class terminal state, not an error case — and never a silent one.
735
+
736
+ ### 6.6 Item state machine
737
+
738
+ ```plantuml
739
+ @startuml
740
+ skinparam defaultTextAlignment center
741
+ hide empty description
742
+
743
+ title mailbox_items — states and the transitions that write them
744
+
745
+ [*] --> queued : enqueue()\n**identity gate**: ref or refOrigin,\nelse rejected
746
+
747
+ queued --> processing : dequeue / dequeueAsync\n+ lease claimed
748
+ queued --> merged : dedup / consolidateByEntity\nmerged_into → survivor
749
+ queued --> deferred : deferItem()\ndeferred_until
750
+ queued --> bounced : bounceSignal / duplicate /\nstale purge — **drop_reason mandatory**
751
+
752
+ deferred --> queued : resurfaceDue()
753
+
754
+ processing --> completed : turn produced a reply\nor typed end_turn
755
+ processing --> queued : requeue()\nabnormal reply, retries left
756
+ processing --> bounced : retry exhausted /\norphan abandoned /\ncancel — with reason
757
+ processing --> catch_all : bounce collected\nbounce_target set
758
+
759
+ merged --> [*]
760
+ completed --> [*]
761
+ bounced --> [*]
762
+ catch_all --> [*]
763
+
764
+ note right of bounced
765
+ `dropped` is **not** in the value domain.
766
+ Historical rows are read-only and
767
+ normalised to `bounced` on read.
768
+ Rows with no reason are labelled
769
+ `legacy_unexplained` by migration —
770
+ unexplained is a fact, not a blank.
771
+ end note
772
+
773
+ note right of processing
774
+ Entering this state always leaves a
775
+ `pick` row in agent_decisions:
776
+ processFocusedItem is the single
777
+ recording point for both loop paths.
778
+ end note
779
+ @enduml
780
+ ```
781
+
782
+ ### 6.7 Identity is mandatory at enqueue
783
+
784
+ An item carries either a `workUnitRef` or an explicit `refOrigin` declaration:
785
+
786
+ | Declaration | Meaning |
787
+ |---|---|
788
+ | `entity` / `turn` | a ref is present (entity identity / current turn identity) |
789
+ | `platform-internal` | genuinely no entity (receipts, internal events) |
790
+
791
+ (C10-0B deleted `pending-link`: "identity arrives later" licensed a second writer
792
+ that UPDATE-ed only the DB column — the in-memory item the decision ledger reads
793
+ stayed null. Identity is built before enqueue and lands with the enqueue itself.)
794
+
795
+ Neither present ⇒ **`enqueue()` rejects** with an actionable message. The guard is
796
+ not opt-in: an optional strictness guards nothing. Under the previous
797
+ `MARKUS_STRICT_IDENTITY=1` opt-in, production took the "log and let it through"
798
+ branch and 242,496 inputs ended up with 0.18% identity coverage (measured
799
+ 2026-11-18). `MARKUS_LENIENT_IDENTITY=1` is an explicit, auditable escape hatch —
800
+ used by the test harness for synthetic fixtures, never the default.
801
+
802
+ The distinction that matters: **"no entity yet" and "forgot to pass it" must not be
803
+ the same value.** Both are NULL in the column; only the declaration tells them apart.
679
804
 
680
805
  ---
681
806
 
@@ -749,7 +874,7 @@ The Agent Mind tab provides a unified view of the agent's cognitive state and hi
749
874
  `callback_result`. Labels stay in i18n: copying English labels here would fight
750
875
  the translation layer.
751
876
  4. **Expandable detail** — clicking a mailbox item shows: (a) decision badge(s), (b) activity summary, (c) lazy-loaded activity logs.
752
- 5. **Status indicators**: `completed` (green), `processing` (blue pulse), `merged` (blue), `deferred` (purple), `dropped` (red), `queued` (amber).
877
+ 5. **Status indicators**: `completed` (green), `processing` (blue pulse), `merged` (blue), `deferred` (purple), `bounced` (red), `catch_all` (amber-red, bounces awaiting collection), `queued` (amber).
753
878
 
754
879
  ---
755
880
 
@@ -761,9 +886,9 @@ All paths that invoke the LLM are routed through the mailbox:
761
886
  - **Task execution** (runTask / runTaskFresh) → `sendTaskExecution`
762
887
  - **Post-task comment reply** → `sendSessionReply`
763
888
  - **Daily report** (API trigger) → `generateDailyReport` → `sendMessage(sourceType: 'daily_report')`
764
- - **Heartbeat** (periodic timer) → `heartbeat:trigger` event → `mailbox.enqueue('heartbeat')` — includes active goals review and timed-out callback checks (§11.4)
889
+ - **Heartbeat** (periodic timer) → `heartbeat:trigger` event → `mailbox.enqueue('heartbeat')` — includes active goals review and timed-out callback checks ([a2a-communication.md](./a2a-communication.md) §11.4)
765
890
  - **Memory consolidation** (dream cycle) → `dreamConsolidateMemory` → `sendMessage(sourceType: 'memory_consolidation')`
766
- - **Cross-agent messages** (A2A / delegation) → DM channel → `enqueueToMailbox('a2a_message')` (§11)
891
+ - **Cross-agent messages** (A2A / delegation) → DM channel → `enqueueToMailbox('a2a_message')` ([a2a-communication.md](./a2a-communication.md) §11)
767
892
  - **Async operation completions** (`background_exec`, etc.) → `PendingCallbackRegistry` → `enqueueToMailbox('callback_result')`
768
893
  - **Notifications** (task status, requirement, comments) → `enqueueToMailbox`
769
894
 
@@ -771,452 +896,40 @@ No LLM call is made outside this architecture.
771
896
 
772
897
  ---
773
898
 
774
- ## 11. Agent-to-Agent Communication (A2A via Mailbox)
775
-
776
- Inter-agent messaging is fully consolidated into the Mailbox system. The legacy `A2ABus` class has been retired — it added a redundant routing layer when the mailbox already provides serialised attention handling.
777
-
778
- ### 11.1 A2A DM Channels
779
-
780
- A2A messages now route through **deterministic DM channels** that reuse the group-chat infrastructure for persistence, WebSocket delivery, and mailbox enqueue:
781
-
782
- ```
783
- Channel key: dm:a2a:{sorted_id_1}:{sorted_id_2}
784
- (agent IDs sorted lexicographically — one channel per pair)
785
- ```
786
-
787
- ```
788
- Agent A Agent B
789
- ──────── ────────
790
- tool: agent_send_message ──► AgentManager.sendMessage()
791
- │
792
- ▼
793
- ensureDmChannel(dm:a2a:...)
794
- │
795
- ▼
796
- sendGroupMessage(channelKey, ...)
797
- ├─ persist to channel_messages
798
- ├─ WebSocket broadcast
799
- └─ enqueueToMailbox('a2a_message', { extra: { channelKey } })
800
- │
801
- ▼
802
- AttentionController picks it up
803
- (stable session: channel_{channelKey}_{agentId})
804
- ```
805
-
806
- Benefits over ephemeral session IDs:
807
-
808
- - **Persistent history** — both agents recall past exchanges via `recall_context` with `scope: "channel"` and `channel_key`. Personal user↔agent DM **chat sessions** (`chat_sessions` table) use `recall_context` with `scope: "chat_session"` and `session_id` (pagination via `before` / `limit`) — see [learning-loop.md](./learning-loop.md) §9.3.
809
- - **Stable sessions** — all messages in a pair share one session ID derived from the channel key
810
- - **Enqueue-time dedup** — messages from the same `channelKey` coalesce (§14)
811
- - **Group chat parity** — DM channels use the same `groupChatRepo`, member resolution, and API paths as custom group chats
812
-
813
- When `groupChatHandlers` are not wired (e.g., unit tests), A2A falls back to direct `sendMessage()` with `sourceType: 'a2a_message'` and the same `channelKey` in `extra`.
814
-
815
- ### 11.1.1 Delivery invariant — one message, one delivery fact
816
-
817
- > **Normative.** This section is the contract; the code must not have a second way
818
- > to reach another agent. It replaces the previous, unwritten arrangement in which
819
- > some paths persisted + woke the peer directly and others enqueued (see §14.5).
820
-
821
- 1. **Exactly one delivery mechanism.** Every inter-agent message — DM
822
- (`dm:a2a:*`), group/team channel, `@mention`, review/comment notification — MUST
823
- reach the recipient as a mailbox item:
824
- `enqueueToMailbox('a2a_message', { extra: { channelKey } })`.
825
- `channel_messages` is a **projection** (UI history + the context slice the
826
- recipient reads when it processes the item). It is **not** a delivery channel:
827
- persisting a row has never delivered anything and must never be reported as if
828
- it had.
829
-
830
- 2. **No half-state.** Either a pending mailbox item exists for the recipient
831
- (possibly merged with siblings, §14) or the message was never sent. The state
832
- `delivered-but-not-awake` is forbidden — it is invisible to the sender and to
833
- the UI, and it was the direct cause of the 2026-10-25 repeat-notification
834
- incident.
835
-
836
- 3. **Reply generation is not delivery.** `processGroupChatReply` exists to produce
837
- a reply for an item the peer is **already** processing. It MUST NOT be used to
838
- hand a new message to a peer; that is the mailbox's job.
839
-
840
- 4. **Storm control is causal, never temporal.**
841
- - *Chain*: `chainId` propagates trace-style. When an item is processed its
842
- `extra.chainId` becomes the turn's current chain (per-worker
843
- `SessionWorkspace.chainId`, so concurrent workers never share one); anything
844
- the turn sends inherits it, and `sendGroupMessage` hands the parent to
845
- `deliver()` with `depth + 1`. A fresh id is minted only when a delivery truly
846
- starts a conversation. The context is cleared in the processing `finally` so
847
- it cannot leak into the next turn.
848
-
849
- > **Failure mode worth remembering**: this shipped once and did nothing,
850
- > because the send logic existed **twice** in `AgentManager` — two
851
- > near-identical `sendMessage` closures in different tool-context factories —
852
- > and only one forwarded the chain. The A2A tools received the other one, so
853
- > every delivery still minted a fresh id while the code read correctly. Both
854
- > copies are now deleted in favour of one private `deliverA2AMessage()`.
855
- > Reading either copy alone could not have revealed it: only the pair did.
856
- - *Coalescing*: messages on the same `channelKey` merge into **one** mailbox
857
- item at enqueue time (§14), with the full text preserved in the channel.
858
- - Wall-clock throttles MUST NOT drop a wake. `a2aCooldowns` (per-channel 30 s)
859
- and `wakeBudget` (global per-agent quota) were removed for exactly this
860
- reason — both could answer "sent" for a message the peer never received.
861
-
862
- 5. **The sender is told the truth.** `agent_send_message` returns
863
- `{ deliveryState: 'queued' | 'coalesced', deliveryId, peerPendingItems,
864
- coalescedCount }`. `coalesced` means "your message is part of the item the peer
865
- will process next" — it is a delivery outcome, not a silent drop.
866
-
867
- 6. **One place decides.** `AgentDelivery.deliver()` is the only caller of the
868
- mailbox enqueue for inter-agent traffic. Any new feature that wants to reach
869
- another agent calls it; it must not re-implement "persist + wake".
870
-
871
- ### 11.1.2 Reply sink — one writer for "an agent said something in a channel"
872
-
873
- A2A has two facts, and each needs exactly one writer:
874
-
875
- | Fact | Writer | Never |
876
- |---|---|---|
877
- | "A message is addressed to agent X" | `AgentDelivery.deliver()` → `mailbox.enqueue('a2a_message')` | never a direct `getAgent(...).handleMessage(...)` |
878
- | "Agent Y produced a reply in channel C" | `AgentDelivery.postReply()` — persists to `channel_messages`, broadcasts, and **does not** auto-trigger anyone | never a second persist/broadcast path |
879
-
880
- `processGroupChatReply` used to be **both** — it woke the peer *and* wrote the
881
- reply — which is why an A2A message had two possible lifecycles depending on which
882
- branch produced it. Under this contract it has no role: the mailbox item wakes the
883
- agent (with its own lease/retry/merge semantics), and the reply returns through
884
- `responsePromise` to the single sink.
885
-
886
- **No automatic reply chain.** A reply never triggers the peer. If the other side
887
- has something to add it must call `agent_send_message` — a deliberate act. This
888
- removes the class of incident in which two agents re-replied for 43 turns /
889
- 35 minutes after a single proactive message.
890
-
891
- ### 11.1.3 Replies are a decision, never a chain
892
-
893
- The platform does not decide that an agent should answer. It delivers the message
894
- and the agent decides:
895
-
896
- * **Perception is automatic, response is optional.** A delivered message wakes the
897
- agent (mailbox semantics); whether it says anything back is its own call. Ending
898
- a turn without replying (`end_turn`) is a legitimate, expected outcome — for
899
- human messages too.
900
- * **No automatic reply chain.** A reply never triggers the peer. If the
901
- conversation should continue, the replying agent calls `agent_send_message`
902
- itself — a deliberate act with its own cost. There is therefore no "reflection"
903
- to bound: without a chain, `DM_MAX_DEPTH`, per-round `respondedAgents`,
904
- `shouldChainDmReply`'s regex, the 30 s `a2aCooldowns` and `wakeBudget` have **no
905
- subject matter left**. They existed only to bound a chain the platform itself
906
- was creating.
907
- * **`chainId` is correlation, not a guard.** It is inherited from the inbound item
908
- (§11.1.1 point 4), so a request and the answer it provokes share one id; it is
909
- never used to throttle or to drop.
910
- * **Nothing is lost when someone stays silent.** The message is in the channel and
911
- in the recipient's mailbox history; silence is observable, not a delivery failure.
912
-
913
- Rationale (learned the hard way, 2026-10): every storm guard we ever added was a
914
- consequence of the platform auto-replying on the agent's behalf. Removing the
915
- auto-reply removes the storm; keeping it forced us to invent judges (wall clock,
916
- quota, regex) that had to guess "does this reply need an answer?" — and when they
917
- guessed wrong they discarded the wake while still reporting success.
918
-
919
- ### 11.1.4 Entry-point inventory (nothing may bypass the delivery service)
920
-
921
- | Entry | Path | Notes |
922
- |---|---|---|
923
- | `agent_send_message` (DM) | `AgentDelivery.deliver` | one item per `channelKey`, mergeable |
924
- | group chat, no @mention | `AgentDelivery.deliver` (`throttled` when a chain is hot) | awareness, not a reply request |
925
- | group chat, @mention | `AgentDelivery.deliver` with `mentions` + `chainId` | the chain decision happens **after** delivery |
926
- | `agent_delegate_task` | delegation manager → `deliver` | protocol on top of the same transport |
927
- | review / comment / requirement notifications | `task-service` mailbox items | their own item types, not A2A; they must not invent a second wake path |
928
-
929
- **Addressedness** (who is this message for): a message aimed at a specific agent —
930
- a DM, or a group message where the agent was `@mentioned` — is delivered with a
931
- one-line `[MENTIONED] This message is addressed to you …` prefix so the recipient
932
- knows it is the target. Open/broadcast messages carry no marker. Single writer:
933
- `DeliveryRequest.addressedTargetIds` (a list of the target ids that are actually
934
- addressed) in `AgentDelivery.deliver()`; callers must not construct the marker
935
- themselves.
936
-
937
- The prefix also carries the **count**: `… Others also addressed: N.` Knowing that
938
- nobody else was addressed ("this is yours to handle") is a different action from
939
- knowing two others were ("whoever picks it up first"). The count is emitted
940
- always, including `0`, for two reasons:
941
-
942
- - **One template, one stable prefix.** The marker line is a prompt prefix shared by
943
- every a2a message. Two shapes (with/without the clause) would fork that prefix and
944
- degrade prompt-cache hits; a fixed template with only the trailing number varying
945
- keeps the common prefix intact. Put variable content at the **end** of a stable
946
- template, never by making the template conditional.
947
- - **It is the decision-relevant part, and only that.** Names are deliberately not
948
- included: the list would grow the line without bound and would expose unrelated
949
- agents' identities to a third party. A count answers "must I act" without leaking.
950
-
951
- It is an id list, deliberately, not a boolean. One group message can address two
952
- of ten members: with a boolean a caller can only mark the whole batch (bystanders
953
- think they were singled out) or none of it (the mentioned agent never learns it
954
- was the target). With a list the ambiguous state is not expressible — which is
955
- the point.
956
-
957
- **Origin** (who sent it): `DeliveryRequest.origin` — `[FROM HUMAN] <name> … humans can
958
- see this channel` versus `[FROM AGENT] … no human is waiting on this`. Produced
959
- only in `deliver()`, like the addressedness marker. It is load-bearing: a human
960
- group message delivered as a bare `a2a_message` would be read under the a2a prompt
961
- section ("humans do NOT see this conversation"), so the agent misjudges the context
962
- and answers the wrong audience.
963
-
964
- **Machine-checkable**: `enqueueToMailbox('a2a_message'` may appear only inside
965
- `agent-delivery.ts`; a direct `handleMessage`/`processGroupChatReply` used to hand a
966
- message to another agent is a regression.
967
-
968
- ### 11.2 Tools & Transport
969
-
970
- - **`agent_send_message`**: Always asynchronous — returns immediately with `conversation_id` and `channel_key`. Messages are tagged `[conversation:...]` for multi-turn correlation.
971
- - **`agent_delegate_task`**: Uses `DelegationManager` for protocol orchestration; transport goes through the DM channel path above.
972
- - **`agent_broadcast_status`**: Lightweight path — writes to target agent's daily log without an LLM call. Does not use DM channels.
973
- - **`agent_send_group_message`**: Team/custom group channels (`group:<teamId>`, `group:custom:<id>`). @mentions control which peer agents receive `a2a_message` mailbox items.
974
-
975
- The `@markus/a2a` package retains `DelegationManager` and protocol types. `A2ABus` is exported with a `@deprecated` annotation for backward compatibility only.
976
-
977
- ### 11.3 PendingCallbackRegistry
978
-
979
- `PendingCallbackRegistry` (`packages/core/src/pending-callback.ts`) tracks async operations that must report results back through the mailbox rather than injecting directly into an active session.
980
-
981
- ```typescript
982
- type CallbackType = 'background_exec' | 'wakeup' | 'a2a_reply';
983
- type CallbackDelivery = 'in_session' | 'mailbox';
984
-
985
- interface PendingCallback {
986
- id: string; // Unique callback ID (e.g., background session ID, a2a_<conversation_id>)
987
- agentId: string; // Originating agent
988
- originSessionId: string; // Session to resume on completion (in_session mode)
989
- type: CallbackType; // Operation type
990
- deliveryMode?: CallbackDelivery; // in_session (default) → callback_result; mailbox → system_event
991
- command?: string; // Optional context (shell command, etc.)
992
- note?: string; // Free-text label (wakeup reason, delegation goal)
993
- correlationId?: string; // Correlates an external event (conversation_id)
994
- wakeAt?: number; // Scheduled wakeups: epoch ms when due
995
- recurringMs?: number; // Recurring wakeups: re-arm interval
996
- registeredAt: number; // Epoch ms
997
- timeoutMs: number; // 10 min for background_exec; 30 min for a2a_reply; effectively ∞ for wakeup
998
- }
999
- ```
1000
-
1001
- **Lifecycle:**
1002
-
1003
- 1. **Register** — An async operation is registered as a `PendingCallback` and persisted via `SqlitePendingCallbackRepo`:
1004
- - `background_exec` → `registerBackgroundSession()` (called from `Agent.executeTool` on the tool result).
1005
- - `agent_send_message` with `reply_in_session` (alias `await_in_session`) → an `a2a_reply` callback keyed by `conversation_id`.
1006
- - `schedule_wakeup` → a `wakeup` callback with `wakeAt` (+ optional `recurringMs`).
1007
- 2. **Complete / fire** — On completion (`background_exec`, `a2a_reply`) or when a wakeup is due, the entry is resolved and delivered via the shared `Agent.deliverCallback()` helper: `in_session` → `callback_result` (bound to `originSessionId`); `mailbox` → `system_event`. Recurring wakeups re-arm.
1008
- 3. **Timeout** — Heartbeat calls `getTimedOut()` to find expired callbacks, then `expireTimedOut(id)` removes each from the registry. Timed-out operations are surfaced in the heartbeat prompt (§11.4) for agent investigation — they do not silently disappear. (Wakeups use an effectively infinite timeout and are never flagged.)
1009
-
1010
- **Wakeup scheduler:** each agent runs a coarse (~1-minute) sweep (`Agent.sweepDueWakeups`) that fires any `wakeup` callbacks whose `wakeAt` has passed. This lets an agent register precise time-based follow-ups (`schedule_wakeup`) and stay idle in between, rather than relying on the periodic heartbeat.
1011
-
1012
- **Heartbeat as coarse safety-net:** the periodic heartbeat is a fallback patrol (`DEFAULT_HEARTBEAT_INTERVAL_MS`, 6h), not the primary timing mechanism — `schedule_wakeup` is. The interval is configurable live by the user (Heartbeat tab / `PATCH /api/agents/:id/config`) and by the agent itself via the `set_heartbeat_interval` tool (clamped 5min–24h). Both paths go through `Agent.setHeartbeatInterval()`, which restarts the scheduler immediately; agent-initiated changes persist via the `agent:heartbeat-interval-changed` event → `agentRepo.updateConfig`.
1013
-
1014
- The registry is a process singleton (`pendingCallbackRegistry`), restored from SQLite on startup so callbacks survive server restarts.
1015
-
1016
- ### 11.4 Heartbeat Integration
1017
-
1018
- Periodic heartbeat items (`priority: 3 — low`) drive proactive agent patrol. Beyond the standard checklist, heartbeat now integrates:
1019
-
1020
- **Active goals review** — When `goalFetcher` is wired (from org-manager requirement service), the heartbeat prompt includes an **Active Goals** section listing each goal's title, status, iteration count (`currentIteration` / `maxIterations`), and completion criteria. The agent is instructed to:
1021
-
1022
- 1. Check linked tasks for progress
1023
- 2. Create follow-up tasks if needed
1024
- 3. Mark requirements complete when criteria are met
1025
- 4. Escalate or adjust approach if stuck
1026
-
1027
- **Callback timeout handling** — Before building the heartbeat prompt, `handleHeartbeat()` calls `pendingCallbackRegistry.getTimedOut()`. For each expired callback:
899
+ ## 11. Agent-to-Agent Communication (A2A) — moved
1028
900
 
1029
- 1. `expireTimedOut(id)` removes it from the registry (and persistence)
1030
- 2. Details are injected into the heartbeat prompt under **Timed-Out Async Operations** (background exec or an awaited A2A delegation whose reply never arrived)
1031
- 3. The agent investigates and takes corrective action during the heartbeat LLM session
901
+ A2A messages reach another agent as `a2a_message` **mailbox items** and nothing else;
902
+ `channel_messages` is only a projection (UI history + the context slice the recipient reads),
903
+ never a delivery channel, and "persisted but not awake" is a forbidden state. The mailbox is the
904
+ single delivery mechanism, `AgentDelivery.deliver()` is its only inter-agent caller, and a reply
905
+ never triggers the peer — there is no automatic reply chain.
1032
906
 
1033
- This ensures orphaned async operations are surfaced even when the completion handler never fires (process crash, hung command, etc.).
1034
-
1035
- Background process completions that *do* finish normally are still routed as separate `callback_result` mailbox items (priority 1) — the heartbeat section only handles the timeout case.
1036
-
1037
- ### 11.5 Async-Only A2A (Deadlock Prevention)
1038
-
1039
- The `wait_for_reply=true` parameter is **deprecated and ignored**. All A2A messaging is non-blocking. This eliminates deadlocks that occurred when two agents simultaneously awaited each other's reply.
1040
-
1041
- **Correlation pattern**: Each message carries a `conversation_id` (auto-generated UUID). Agents record pending questions in working memory and recognize replies by the `[conversation:...]` tag prepended to the message content. Multi-turn exchanges use the same `conversation_id` for context continuity.
907
+ The full contract lives in [a2a-communication.md](./a2a-communication.md) §11 — DM channels
908
+ `dm:a2a:{sorted_ids}` (§11.1), the delivery invariant (§11.1.1), the reply sink (§11.1.2), the
909
+ entry-point inventory (§11.1.4), tools & transport (§11.2), `PendingCallbackRegistry` (§11.3),
910
+ heartbeat integration (§11.4) and async-only correlation (§11.5).
1042
911
 
1043
912
  ---
1044
913
 
1045
- ## 12. User Notifications (Human Mailbox)
1046
-
1047
- Just as agents have a mailbox for incoming stimuli, users have a **persistent notification system** for events that require their attention. This is the user-facing counterpart to the agent mailbox.
1048
-
1049
- ### 12.1 Storage
1050
-
1051
- ```sql
1052
- CREATE TABLE user_notifications (
1053
- id TEXT PRIMARY KEY,
1054
- user_id TEXT NOT NULL,
1055
- type TEXT NOT NULL, -- UserNotificationType
1056
- title TEXT NOT NULL,
1057
- body TEXT DEFAULT '',
1058
- priority TEXT DEFAULT 'normal', -- 'low' | 'normal' | 'high' | 'urgent'
1059
- read INTEGER DEFAULT 0,
1060
- action_type TEXT, -- 'navigate' | 'open_chat' | null
1061
- action_target TEXT, -- JSON: { path } or { agentId, sessionId }
1062
- metadata TEXT DEFAULT '{}',
1063
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
1064
- );
1065
- ```
1066
-
1067
- ### 12.2 Notification Type Registry
1068
-
1069
- Analogous to `MAILBOX_TYPE_REGISTRY`, user notification types are defined in `USER_NOTIFICATION_TYPE_REGISTRY` in `@markus/shared`:
1070
-
1071
- | Type | Label | Icon | Default Priority | Action | Category |
1072
- |------|-------|------|-----------------|--------|----------|
1073
- | `approval_request` | Approval Request | 🔐 | high | navigate | approval |
1074
- | `task_created` | Task Created | 📋 | normal | navigate | task |
1075
- | `task_completed` | Task Completed | ✅ | normal | navigate | task |
1076
- | `task_review` | Task Review | 👁️ | normal | navigate | task |
1077
- | `task_failed` | Task Failed | ❌ | high | navigate | task |
1078
- | `requirement_created` | Requirement Proposed | 📝 | high | navigate | task |
1079
- | `requirement_decision` | Requirement Decision | ⚖️ | normal | navigate | task |
1080
- | `agent_report` | Agent Report | 📊 | normal | none | agent |
1081
- | `system` | System | ⚙️ | normal | none | system |
1082
-
1083
- ### 12.3 Action Types
1084
-
1085
- Notifications can be **actionable** — clicking them navigates the user to the relevant context:
1086
-
1087
- | `action_type` | `action_target` format | Behaviour |
1088
- |---------------|----------------------|-----------|
1089
- | `navigate` | `{ "path": "/work?task=T123" }` | Navigate to the specified route |
1090
- | `open_chat` | `{ "agentId": "...", "sessionId": "..." }` | Open chat with agent, resume session |
1091
- | `none` | — | Notification only, no navigation |
914
+ ## 12. User Notifications (human mailbox) — moved
1092
915
 
1093
- ### 12.4 REST API
1094
-
1095
- | Method | Path | Description |
1096
- |--------|------|-------------|
1097
- | GET | `/api/notifications?type=...&limit=...&offset=...` | List notifications with filtering, returns `totalCount` and `unreadCount` |
1098
- | POST | `/api/notifications/:id/read` | Mark single notification as read |
1099
- | POST | `/api/notifications/mark-all-read` | Mark all notifications as read |
1100
-
1101
- ### 12.5 Real-Time Delivery
1102
-
1103
- When a notification is created (via `HITLService.notify()`), a WebSocket `notification` event is broadcast. The frontend `App.tsx` listens for this and dispatches a `markus:notifications-changed` custom DOM event, which triggers the `NotificationBell` component to refresh.
916
+ The delivery contract for user notifications is defined in
917
+ [notification-delivery.md](./notification-delivery.md) §12 (storage, type registry, action
918
+ types, REST API, real-time delivery). **The mailbox only owns enqueueing and priority**: it
919
+ carries the resulting items — type, default priority, merge with siblings — but it does not
920
+ define what a notification means or how it reaches a person.
1104
921
 
1105
922
  ---
1106
923
 
1107
- ## 13. Agent-to-User Communication
1108
-
1109
- Agents have two distinct modes for communicating with users. **They are not
1110
- interchangeable** — the choice is decided by one question: *do I need an answer
1111
- before I can continue?*
1112
-
1113
- | I need… | Tool | Semantics |
1114
- |---|---|---|
1115
- | to inform (status, report, alert, finding) | `notify_user` | **one-way**; do NOT expect a reply; must not wait for it |
1116
- | an answer / authorization / a decision | `request_user_input` | **blocks** until the human responds; returns the answer |
1117
-
1118
- A question asked through `notify_user` does not block, brings no answer back, and
1119
- leaves the agent permanently blocked — which in practice produces repeated
1120
- notifications of the same ask (2026-10-25: 12 identical sends in 3 minutes). A
1121
- notification sent through `request_user_input` would hold a turn open for an
1122
- answer nobody needs to give. Each tool's own description states this boundary;
1123
- it is enforced by the tools' contracts, not by caller discipline.
1124
-
1125
- ### 13.1 `notify_user` — Proactive Chat Message + Notification
1126
-
1127
- Proactive messages that appear in the agent's chat **and** the user's notification bell. The user can reply in chat, and the agent has full context of what it sent.
1128
-
1129
- ```typescript
1130
- // Tool schema
1131
- {
1132
- name: 'notify_user',
1133
- parameters: {
1134
- title: string, // Short headline (1 line)
1135
- body: string, // Full message content (visible in chat)
1136
- priority: 'low' | 'normal' | 'high' | 'urgent', // optional, default 'normal'
1137
- related_task_id?: string, // deep-link to task if applicable
1138
- target_user_id?: string // target specific user (defaults to currentInteractingUserId)
1139
- }
1140
- }
1141
- ```
1142
-
1143
- **When to use**: Status updates, task completion notices, FYI messages, findings, alerts — any proactive communication where the user may want to reply.
1144
-
1145
- **Flow**: `agent.executeTool('notify_user')` → builds formatted message with embedded context → `memory.appendMessage()` (in-memory session) → `eventBus.emit('agent:notify-user')` → `start.ts` handler: `chatSessionRepo.appendMessage()` (with `notifyUser` metadata) + `ws.broadcastProactiveMessage()` (with metadata) + `hitlService.notify()`
924
+ ## 13. Agent-to-User Communication — moved
1146
925
 
1147
- **Notification routing**: With `related_task_id` → `actionType: 'navigate'` to Work page. Without task → `actionType: 'open_chat'` with `sessionId` to agent's chat.
1148
-
1149
- #### Message Metadata & Context Embedding
1150
-
1151
- Every `notify_user` message is persisted with **two layers of context**:
1152
-
1153
- 1. **DB metadata** (`metadata` column): `{ notifyUser: true, priority, taskId?, requirementId? }` — used by the frontend to display context links and badges.
1154
-
1155
- 2. **Embedded context comment** (appended to message content): `<!-- notify_context: task_id=xxx, requirement_id=yyy -->` — survives through `restoreSessionFromHistory()` (which only reads `role` + `content`), ensuring the agent retains context about what it notified the user about when the user replies.
1156
-
1157
- The agent's `chat` scenario system prompt instructs it to parse these `notify_context` references and use tools like `recall_activity` or `search_tasks` to retrieve full context before responding to user follow-ups.
1158
-
1159
- > **Referencing resources in the body**: `notify_user` bodies (and any chat/comment/report markdown) should reference Markus resources using the conventions in [prompt-engineering.md §2.2 "Referencing Markus Resources"](./prompt-engineering.md#referencing-markus-resources) — bare IDs (`tsk_…`, `dlv_…`, …), titled links `[Title](task:tsk_…)`, or a reference alone on its own line to render a card. This is separate from the `related_task_id` metadata (which drives the notification's deep-link badge).
1160
-
1161
- #### Real-time Visibility
1162
-
1163
- All `notify_user` messages are buffered in the frontend for every agent conversation immediately upon WebSocket receipt — regardless of whether the user is currently viewing that agent's chat. This ensures messages are visible as soon as the user navigates to the agent, without requiring a page reload.
1164
-
1165
- ### 13.2 `request_user_input` — Blocking Decision Request
1166
-
1167
- Requests input or a decision from the user. The tool **blocks** until the user
1168
- responds — no timeout. Supports multiple questions, default Approve/Reject
1169
- options, custom options, and optional freeform text input.
1170
- `request_user_approval` is a deprecated alias with identical behaviour, kept only
1171
- so older prompts keep working.
1172
-
1173
- **Use it whenever you cannot continue without an answer** — an authorization, a
1174
- scope call, an ambiguous choice, a fact only the human has ("I am blocked, I need
1175
- one line of approval"). Asking through `notify_user` instead leaves the turn
1176
- unblocked, brings no answer back, and produces repeated notifications of the same
1177
- ask; the blocking tool is the only correct choice for a question that needs an
1178
- answer.
1179
-
1180
- ```typescript
1181
- // Tool schema
1182
- {
1183
- name: 'request_user_input',
1184
- parameters: {
1185
- title: string, // Short headline
1186
- description: string, // Detailed context
1187
- options?: Array<{ // Custom options (defaults to Approve/Reject)
1188
- id: string,
1189
- label: string,
1190
- description?: string
1191
- }>,
1192
- allow_freeform?: boolean, // Allow user to type custom text
1193
- related_task_id?: string,
1194
- priority?: 'normal' | 'high' | 'urgent'
1195
- }
1196
- }
1197
- // Returns: { status: 'ok', approved: boolean, selected_option: string, comment: string }
1198
- ```
1199
-
1200
- **When to use**: Approval requests, design decisions, choosing between approaches, anything requiring user input or decision.
1201
-
1202
- **Flow**: `agent.executeTool('request_user_input')` → `attentionController.setWaitingForApproval(true)` → `HITLService.requestApprovalAndWait(options)` → notification + WebSocket → NotificationBell renders options → user responds → `HITLService.respondToApproval(selectedOption)` → promise resolves → agent receives result
1203
-
1204
- The attention controller uses `APPROVAL_WAIT_TIMEOUT_MS` (24h) instead of the normal 45-minute backstop (`MAILBOX_PROCESSING_TIMEOUT_MS`) while waiting for approval, preventing the mailbox item from being requeued prematurely.
1205
-
1206
- ### 13.3 Prompt Guidance
1207
-
1208
- The system prompt includes scenario-specific guidance on which tool to use:
1209
-
1210
- | Situation | Tool |
1211
- |-----------|------|
1212
- | Status report, progress update, FYI alert | `notify_user` — one-way; the user may reply, but do not wait |
1213
- | Task completed notification | `notify_user` with `related_task_id` |
1214
- | **Blocked: needs an authorization / decision to continue** | **`request_user_input`** (blocks, returns the answer) |
1215
- | Need user to approve/reject something | `request_user_input` (default options) |
1216
- | Need user to choose between approaches | `request_user_input` with custom `options` |
1217
- | Need user freeform input | `request_user_input` with `allow_freeform: true` |
1218
- | Want to discuss interactively | Mention user via task/requirement comment |
1219
- | Need to review past execution details | `recall_activity` (list activities or get logs) |
926
+ The `notify_user` (one-way, non-blocking) versus `request_user_input` (blocking, returns the
927
+ answer) contract, the `notify_context` metadata rules and the prompt guidance are defined in
928
+ [notification-delivery.md](./notification-delivery.md) §13. Mailbox-side, all that stays here is
929
+ the enqueue and priority of the produced items, plus one timing fact: while an item waits for
930
+ approval the attention controller uses `APPROVAL_WAIT_TIMEOUT_MS` (24 h) instead of the normal
931
+ 45-minute backstop (`MAILBOX_PROCESSING_TIMEOUT_MS`), so the item is not requeued prematurely
932
+ (§4).
1220
933
 
1221
934
  ---
1222
935
 
@@ -1248,7 +961,7 @@ This prevents scenarios where 5 rapid-fire comments on the same task each trigge
1248
961
 
1249
962
  ### Channel Coalescing
1250
963
 
1251
- Group chat and A2A messages from the same `channelKey` are coalesced both at enqueue time and during pre-triage consolidation. The merged item carries a `messages` array providing structured context:
964
+ Group chat and A2A messages from the same `channelKey` are coalesced both at enqueue time and during entity consolidation. The merged item carries a `messages` array providing structured context:
1252
965
 
1253
966
  ```typescript
1254
967
  payload.messages: Array<{
@@ -1261,7 +974,7 @@ payload.messages: Array<{
1261
974
 
1262
975
  ### Burst Coalescing Window
1263
976
 
1264
- After dequeuing a non-user item, the attention loop pauses for `MAILBOX_COALESCE_WINDOW_MS` (default 200ms) before starting triage. This gives rapid-fire messages time to arrive and merge via enqueue-time dedup, reducing redundant processing for burst scenarios (e.g., multiple agents posting to the same group chat within milliseconds).
977
+ After dequeuing a non-user item, the attention loop pauses for `MAILBOX_COALESCE_WINDOW_MS` (default 200ms) before purge/consolidation. This gives rapid-fire messages time to arrive and merge via enqueue-time dedup, reducing redundant processing for burst scenarios (e.g., multiple agents posting to the same group chat within milliseconds).
1265
978
 
1266
979
  **Execution-trigger safety**: Items with `extra.triggerExecution` (task execution triggers) are **never merged** — neither as the incoming item nor as the merge target. Execution items carry critical callbacks (`onLog`, `cancelToken`, `taskProjectContext`) in their `extra` field that would be lost during a content merge. They must always remain standalone queue entries.
1267
980
 
@@ -1273,7 +986,7 @@ stayed persisted:
1273
986
 
1274
987
  | Guard | Where | Judgement | Outcome on match |
1275
988
  |---|---|---|---|
1276
- | ~~`DM_MAX_DEPTH`~~ | ~~reply chain~~ | **deleted** | bounded a chain that no longer exists (§11.1.3) |
989
+ | ~~`DM_MAX_DEPTH`~~ | ~~reply chain~~ | **deleted** | bounded a chain that no longer exists ([a2a-communication.md](./a2a-communication.md) §11.1.3) |
1277
990
  | `a2aCooldowns` | api-server, per (channel, peer) | 30 s wall clock | **drop the wake, keep the row** |
1278
991
  | `wakeBudget` | api-server, per agent | global quota | **drop the wake, keep the row** |
1279
992
  | mailbox coalescing | enqueue (§14) | same `channelKey` | merge into one item |
@@ -1289,7 +1002,7 @@ question twelve times" (must be coalesced) from "twelve different messages" (all
1289
1002
  must arrive), so it thinned real information while doing nothing about the
1290
1003
  duplicate asks themselves.
1291
1004
 
1292
- Hence the rule in §11.1.1: **coalescing is the only thinning mechanism for a
1005
+ Hence the rule in [a2a-communication.md](./a2a-communication.md) §11.1.1: **coalescing is the only thinning mechanism for a
1293
1006
  channel**, and the chain guard may only prevent a chain from growing — it must
1294
1007
  never discard an addressed message. Regression detector: a `suppressed by
1295
1008
  cooldown` log line or a `wakeBudget.tryConsume` call existing anywhere in the tree
@@ -1332,7 +1045,8 @@ The frontend Agent Mind view supports filtering by both **category** and **statu
1332
1045
  | `completed` | Green | Successfully processed |
1333
1046
  | `merged` | Blue | Absorbed into another item |
1334
1047
  | `deferred` | Purple | Postponed for later |
1335
- | `dropped` | Red | Discarded |
1048
+ | `bounced` | Red | Delivery failed — `drop_reason` is mandatory |
1049
+ | `catch_all` | Amber-red | Bounce collected into the overview, awaiting collection |
1336
1050
 
1337
1051
  Both category and status filters are passed as query parameters to the mailbox API endpoint.
1338
1052
 
@@ -1361,7 +1075,7 @@ agent_id = ? AND status = 'processing'
1361
1075
  Those carry work that cannot be recreated from scratch, so dropping them would lose
1362
1076
  it. After requeue the row no longer matches the predicate, so the next step leaves
1363
1077
  it alone.
1364
- 3. **Drop the remainder** (`UPDATE ... SET status='dropped'`).
1078
+ 3. **Bounce the remainder** (`status='bounced'` + `drop_reason='stale_signal'` → `catch_all`).
1365
1079
 
1366
1080
  If the candidate SELECT or the payload parse throws, the method logs and **falls back
1367
1081
  to drop-only** — the conservative pre-existing behaviour — rather than proceeding with
@@ -1370,13 +1084,13 @@ a half-computed split.
1370
1084
  This is safe because:
1371
1085
  - `resumeInProgressTasks()` already re-creates execution items for any tasks that need to continue.
1372
1086
  - The stale items' callbacks (`onLog`, `cancelToken`, etc.) are garbage-collected references that cannot be resumed.
1373
- - Marking as `dropped` (not `completed`) preserves the audit trail — these items did not complete successfully.
1087
+ - Marking as `bounced` (not `completed`) preserves the audit trail — these items did not complete successfully, and the reason is queryable.
1374
1088
 
1375
1089
  ### Post-Recovery Deduplication
1376
1090
 
1377
1091
  After all queued items are restored from the database, `recoverStaleItems()` runs `deduplicateQueue()` to collapse redundant entries that accumulated before the restart:
1378
1092
 
1379
- 1. **Heartbeat collapse**: Multiple queued heartbeats are reduced to a single entry (the most recent). Older heartbeats are marked `dropped`.
1093
+ 1. **Heartbeat collapse**: Multiple queued heartbeats are reduced to a single entry (the most recent). Older heartbeats are marked `bounced` with a `drop_reason` (`dropped` is not in the status value domain — see §28.5).
1380
1094
  2. **Comment merging**: `task_comment` items with the same `taskId` are merged. Same for `requirement_comment` by `requirementId`.
1381
1095
  3. **Channel coalescing**: `a2a_message` items with the same `extra.channelKey` are merged (`CHANNEL_DEDUP_TYPES`). This rule was missing from earlier revisions of this list at §17 (it appeared only in §14).
1382
1096
  4. **Priority escalation**: When merging, the survivor inherits the highest priority of all merged items.
@@ -1448,7 +1162,6 @@ task:failed ──────────► task:failed ─
1448
1162
  mailbox:new-item ──────────► mailbox:new-item ──────► agent:mailbox WS event
1449
1163
  attention:decision ──────────► attention:decision ──────► agent:decision WS event
1450
1164
  attention:state-changed ──────► attention:state-changed ──► agent:attention WS event
1451
- attention:triage ──────────► attention:triage ──────► agent:triage WS event
1452
1165
  ```
1453
1166
 
1454
1167
  Events emitted directly on the manager's bus (no forwarding needed):
@@ -1550,210 +1263,181 @@ finish cleanly.
1550
1263
 
1551
1264
  ---
1552
1265
 
1553
- ## 21. Mailbox Triage System
1554
-
1555
- When an agent dequeues a mailbox item and additional items remain in the queue, the Attention Controller triggers an LLM-driven **triage phase** before processing. This ensures the agent considers all pending work holistically rather than blindly following priority order.
1556
-
1557
- ### Pre-Triage Entity Consolidation
1558
-
1559
- Before triage (or processing), the system automatically consolidates queued items that share the same `taskId` or `requirementId` — regardless of `sourceType`. This is a cross-type merge: a `task_status_update`, `a2a_message`, `mention`, and `task_comment` all referencing `tsk_abc123` are collapsed into a single rich-context item.
1266
+ ## 21. Attention Decision: One Rule Table, Zero Model Calls
1267
+
1268
+ When an agent dequeues a mailbox item while other items are still queued, **nothing is
1269
+ "triaged"**. There is exactly one decision surface, and it is a deterministic rule table in
1270
+ `packages/core/src/attention.ts`. There is no second model call, no batch decision phase,
1271
+ no decision protocol the agent must answer before it is allowed to work, and no prompt that
1272
+ turns "what should I do next?" into a paid inference question. An earlier revision of this
1273
+ document described a three-tier model (Tier 0 reflex / Tier 1 LLM classifier / Tier 2
1274
+ full-session deliberation, with a `[DELIBERATION MODE]` prompt and a structured
1275
+ decision-tool result); that whole stack has been deleted. What follows is what the code
1276
+ does today.
1277
+
1278
+ ### 21.1 The single entry point: `heuristicDecision(current, new)`
1279
+
1280
+ `AttentionController.heuristicDecision()` (`packages/core/src/attention.ts`, ~:1515) is a
1281
+ top-to-bottom rule table — **first match wins**, zero model calls:
1282
+
1283
+ | Rule | Condition | Decision |
1284
+ |------|-----------|----------|
1285
+ | R0 | Same sender, same session, both `human_chat` | `merge` |
1286
+ | R0x | New `human_chat` is an explicit NEW session | `continue` |
1287
+ | R1 | New is `human_chat`, current is not | `preempt` |
1288
+ | R1.5 | New is `a2a_message`, current is background | `preempt` |
1289
+ | R2 | `task_comment` on the same `taskId` as current | `merge` |
1290
+ | R3 | Requirement update/comment on the same requirement | `merge` |
1291
+ | R4 | New priority is `critical`, current is not | `preempt` |
1292
+ | R6 | New has strictly higher priority (lower number) | `preempt` |
1293
+ | R8 | Same priority, current is background/system | `preempt` |
1294
+ | R9 | New is a mention, current priority ≥ normal | `preempt` |
1295
+ | — | Otherwise | `continue` |
1296
+
1297
+ The production delegate (`agent.ts` → `evaluateInterrupt`) returns exactly
1298
+ `heuristicDecision(current, new)`; the model-based interrupt judge it once consulted is
1299
+ gone, so no interrupt can cost a model call. Note also what the table does **not** produce:
1300
+ `cancel`. The heuristic never cancels, and nothing else in the decision path infers a
1301
+ cancel either — cancellation is an explicit terminal act.
1302
+
1303
+ Every decision is recorded (`recordDecision` → `attention:decision` ledger row with the
1304
+ rule's reasoning), which makes the whole surface reproducible and testable: same queue
1305
+ state, same decision.
1306
+
1307
+ ### 21.2 Entity consolidation before processing
1308
+
1309
+ Before anything is decided, a non-user item's queue is cleaned up:
1310
+
1311
+ - **Stale purge** — `purgeStaleItems()` drops expired informational items (old heartbeats,
1312
+ superseded status updates) that would only cost a turn.
1313
+ - **Cross-type entity merge** — the head item is temporarily put back
1314
+ (`putBack(headItem)`), `consolidateByEntity()` collapses queued items sharing the same
1315
+ `taskId` / `requirementId` (and `a2a_message`s sharing a `channelKey`) into a single
1316
+ rich-context item, and the head is re-dequeued.
1560
1317
 
1561
1318
  This differs from enqueue-time dedup (which only merges same-type comments):
1562
1319
  - **Enqueue-time**: `task_comment` + `task_comment` for same task → merged (fast, prevents accumulation)
1563
- - **Pre-triage**: `task_comment` + `a2a_message` + `task_status_update` for same task → consolidated (comprehensive, gives agent full entity context)
1564
-
1565
- The headItem is temporarily put back into the queue so it participates in consolidation, then re-dequeued.
1566
-
1567
- ### Three-Tier Cognitive Model
1568
-
1569
- The triage system implements a three-tier cognitive model inspired by Dual Process Theory (Kahneman, 2011):
1320
+ - **Pre-processing**: `task_comment` + `a2a_message` + `task_status_update` for same task → consolidated (comprehensive, gives agent full entity context)
1570
1321
 
1571
- - **Tier 0 (Reflexive / System 1)**: Queue depth = 0 after consolidation, or priorities clearly separate items → no LLM call needed. Process immediately.
1572
- - **Tier 1 (Quick Classification / System 1+)**: Interrupt arrives during focused work, heuristic says "continue" but LLM may disagree → single LLM call returning one word (`continue`/`preempt`/`cancel`/`merge`/`defer`).
1573
- - **Tier 2 (Full Deliberation / System 2)**: Multiple items with overlapping priorities AND `performDeliberation` configured → full agent session with complete tool access and memory.
1322
+ Strict state items are never used as merge targets (see §21.4), so a formal task execution
1323
+ cannot be folded into a neighbour's context.
1574
1324
 
1575
- ### Triage Flow
1325
+ ### 21.3 Decision flow
1576
1326
 
1577
1327
  ```
1578
- dequeueAsync() → headItem
1328
+ dequeueAsync() → item
1579
1329
  │
1580
- ├─ queue empty? → TIER 0: record 'pick' → process(headItem)
1330
+ ├─ USER INTERACTION (human_chat)? → skip cleanup, process immediately
1581
1331
  │
1582
- └─ queue non-empty?
1583
- ├─ CONSOLIDATION: putBack(headItem) → consolidateByEntity() → dequeue()
1584
- │ (items sharing same taskId/requirementId merged cross-type)
1585
- │
1586
- ├─ queue empty after consolidation? → TIER 0
1587
- │
1588
- └─ priorities clearly separate? → TIER 0
1589
- │
1590
- └─ ambiguous priorities AND (performDeliberation OR triageJudge)?
1332
+ └─ otherwise
1333
+ ├─ COALESCE WINDOW: MAILBOX_COALESCE_WINDOW_MS pause when the queue is non-empty
1334
+ │ (lets rapid-fire messages merge via enqueue-time dedup)
1335
+ ├─ putBack(item) → purgeStaleItems() → consolidateByEntity() → dequeue()
1336
+ ├─ record 'pick' — which item is next is decided by the priority queue alone
1337
+ └─ processFocusedItem(item)
1591
1338
  │
1592
- ├─ performDeliberation available?
1593
- │ → TIER 2: Full-session deliberation (scenario='deliberation')
1594
- │ ├─ Agent deliberates AS ITSELF with full identity
1595
- │ ├─ Access to memory, recall_activity, task tools
1596
- │ ├─ Can handle simple items INLINE (notify, comment, message)
1597
- │ ├─ Calls complete_deliberation tool with decision
1598
- │ ├─ Apply inline-completed / defer / drop / choose
1599
- │ └─ Working memory updated (`deliberation` key from situational awareness)
1600
- │
1601
- └─ triageJudge only (fallback)?
1602
- → Mini triage loop (up to TRIAGE_MAX_TOOL_ITERATIONS rounds)
1603
- ├─ Build prompt with candidates + context
1604
- ├─ LLM calls read-only tools to gather context
1605
- ├─ Returns JSON: { processItemId, deferItemIds, dropItemIds }
1606
- └─ Apply decisions
1339
+ └─ new item arrives mid-processing?
1340
+ → heuristicDecision(current, new) ← one rule table, first match wins
1341
+ ├─ merge / continue → keep working (merge injects context)
1342
+ ├─ preempt → suspend current (deferDequeued → resumes
1343
+ │ with its session context when idle)
1344
+ └─ defer → park the NEW item (refused for strict state)
1607
1345
  ```
1608
1346
 
1609
- ### Full-Session Deliberation (Tier 2)
1610
-
1611
- When `delegate.performDeliberation` is available (always in production), the attention controller delegates triage to a full agent session:
1612
-
1613
- 1. The agent receives all queued items formatted as a `[DELIBERATION MODE]` prompt.
1614
- 2. It uses `handleMessage()` with `scenario: 'deliberation'` — the same code path as chat/task but with restricted tool access (`DELIBERATION_ALLOWED_TOOLS`).
1615
- 3. The agent deliberates **as itself** (full system prompt, identity, memory access).
1616
- 4. It can handle simple items **inline** (e.g., send a quick notification, post a comment).
1617
- 5. It calls `complete_deliberation` with its structured decision.
1618
- 6. The attention controller applies the decision: mark inline items completed, defer/drop others, choose the focus item.
1347
+ There is no third branch to take: ordering is not a judgement call. The priority queue
1348
+ (priority + enqueue sequence) is the only producer of "which item is next", and the rule
1349
+ table is the only producer of "should this one interrupt that one".
1619
1350
 
1620
- **Deliberation is atomic**: yield points are suppressed during deliberation (new mail sets the interrupt signal but is not evaluated until deliberation completes).
1351
+ ### 21.4 Strict state items are never deferred
1621
1352
 
1622
- **Strict state items are excluded from deliberation (critical safety)**:
1623
-
1624
- Items carrying formal task/requirement/workflow state transitions — collectively **strict state items** (predicate `isStrictStateItem` in `@markus/shared`):
1353
+ Items carrying formal task/requirement/workflow state transitions — collectively **strict
1354
+ state items** (predicate `isStrictStateItem` in `@markus/shared`):
1625
1355
  - `task_status_update` with `extra.triggerExecution` (formal task execution)
1626
1356
  - `review_request` (review request)
1627
1357
  - `requirement_update` / `workflow_update` with `extra.actionRequired` (closure action)
1628
1358
 
1629
- are **filtered out of the deliberation view entirely**:
1630
-
1631
- 1. **They are invisible to the LLM during deliberation** — `performDeliberation` receives only non-strict items; the optionality prompt (`[DELIBERATION MODE]`) and tool docs instruct the agent that `isStrictState: true` items seen via `check_mailbox` may only be reordered, never deferred/dropped/batched/inline-completed.
1632
- 2. **They never trigger deliberation** — `needsLLMTriage` returns false when the head or any queued item is strict, so tasks/reviews are processed by the normal single-item execution path with the full tool set (including `task_update` / `task_submit_review` / shell / file).
1633
- 3. **Yield-point defer is refused** — if the interrupt evaluator returns `defer` for a strict item, it falls back to the heuristic (high-priority task execution → `preempt` → executed as its own item).
1634
- 4. **Mailbox tools refuse them** — `defer_mailbox_item` / `drop_mailbox_item` return an error for strict items (defense in depth), and `complete_deliberation` rejects results that list strict items in `defer/drop/inline/batch`. The orphan-completeness check **excludes** strict items (they are not part of the deliberation view).
1635
- 5. **Lost-closure recovery** — if a task execution item ever resurfaces from persistence **without its callback closures** (e.g. deferred before start, then resurfaced after restart), the agent no longer silently completes it: it emits an `agent:incomplete` event with `reason: resurfaced-task-execution-lost-closures`, and the org-manager `TaskService` subscribes to that event and calls `recoverLostTaskExecution(taskId)` — re-dispatches the task via `runTask` (with proper closures) if it is still `in_progress` and has no active execution. This prevents tasks from hanging in `in_progress` forever.
1636
-
1637
- Why this matters: task execution, review, and requirement/workflow finalization must run through their dedicated state machines (`executeTask(taskId, onLog)` with live `onLog`/`cancelToken`/`responsePromise` closures). If they were deferred/dropped/merged/batched by deliberation, the closures are lost with persistence, task logs never land under the task, and the task can remain `in_progress` with nobody working it.
1638
-
1639
- ### Tool Access During Deliberation
1640
-
1641
- Defined by `DELIBERATION_ALLOWED_TOOLS` in `@markus/shared`:
1642
-
1643
- | Category | Tools |
1644
- |----------|-------|
1645
- | Context gathering | `task_list`, `task_get`, `requirement_list`, `requirement_get`, `list_projects`, `team_list`, `team_status`, `recall_activity`, `memory_search` |
1646
- | Inline communication | `notify_user`, `task_comment`, `requirement_comment`, `agent_send_message`, `agent_send_group_message`, `agent_create_group_chat`, `agent_list_group_chats` |
1647
- | Mailbox management | `check_mailbox`, `defer_mailbox_item`, `drop_mailbox_item`, `prioritize_mailbox_item` |
1648
- | Working memory | `notebook_upsert`, `notebook_clear`, `notebook_read` |
1649
- | Memory | `memory_save`, `memory_update`, `memory_update_longterm` |
1650
- | Decision output | `complete_deliberation` |
1651
-
1652
- **Excluded**: `task_create`, `task_update`, `requirement_propose`, code/shell tools, `spawn_subagent`. These are heavy side-effect tools that belong in the processing phase.
1653
-
1654
- ### Agent Mailbox Management Tools
1655
-
1656
- In addition to the batch decision via `complete_deliberation`, agents can manage
1657
- individual mailbox items using dedicated tools:
1658
-
1659
- | Tool | Available In | Purpose |
1660
- |------|-------------|---------|
1661
- | `check_mailbox` | All scenarios | Read-only queue inspection |
1662
- | `defer_mailbox_item` | Deliberation + focused processing | Postpone an item |
1663
- | `drop_mailbox_item` | Deliberation + focused processing | Discard stale item |
1664
- | `prioritize_mailbox_item` | Deliberation only | Re-prioritize item |
1665
- | `notebook_upsert` | All scenarios | Update situational awareness |
1666
- | `notebook_clear` | All scenarios | Clear stale awareness |
1359
+ are protected at four points:
1360
+
1361
+ 1. **`defer` is refused and falls back to the table** — if the evaluated decision is
1362
+ `defer` for a strict item, the controller logs the refusal and re-runs
1363
+ `heuristicDecision` (`attention.ts` ~:1442-1465). A high-priority task execution comes
1364
+ back `preempt`, i.e. it is executed as its own item.
1365
+ 2. **Mailbox tools refuse them** — `defer_mailbox_item` / `drop_mailbox_item` return an
1366
+ error (defense in depth); only `prioritize_mailbox_item` may change their priority.
1367
+ 3. **Consolidation never swallows them** — `consolidateByEntity()` skips strict items, so
1368
+ they cannot be merged away into another item's context.
1369
+ 4. **Lost-closure recovery** — if a task execution item ever resurfaces from persistence
1370
+ **without its callback closures** (e.g. deferred before start, then resurfaced after
1371
+ restart), the agent no longer silently completes it: it emits an `agent:incomplete`
1372
+ event with `reason: resurfaced-task-execution-lost-closures`, and the org-manager
1373
+ `TaskService` subscribes to that event and calls `recoverLostTaskExecution(taskId)` —
1374
+ re-dispatches the task via `runTask` (with proper closures) if it is still `in_progress`
1375
+ and has no active execution. This prevents tasks from hanging in `in_progress` forever.
1376
+
1377
+ Why this matters: task execution, review, and requirement/workflow finalization must run
1378
+ through their dedicated state machines (`executeTask(taskId, onLog)` with live
1379
+ `onLog`/`cancelToken`/`responsePromise` closures). Deferral persists the item and loses the
1380
+ closures with it, so task logs never land under the task and the task can remain
1381
+ `in_progress` with nobody working it.
1382
+
1383
+ **Preemption is a pause, not a loss.** When a running item is preempted, the controller
1384
+ parks it with `mailbox.deferDequeued(item)`; the payload keeps its `sessionId`, so when it
1385
+ resurfaces on the next idle cycle it resumes where it left off (§22). Only an explicit
1386
+ cancel resolves an item as `dropped` — and even then it is recorded as a bounce with a
1387
+ reason and collected into the catch-all overview (§28), never silently erased.
1388
+
1389
+ ### 21.5 Mailbox management tools
1390
+
1391
+ The agent manages its own queue with per-item tools (registered in the `mailbox-admin`
1392
+ domain, available in every scenario):
1393
+
1394
+ | Tool | Purpose |
1395
+ |------|---------|
1396
+ | `check_mailbox` | Read-only queue inspection |
1397
+ | `defer_mailbox_item` | Postpone an item (optional `defer_minutes`) |
1398
+ | `drop_mailbox_item` | Discard a stale item — recorded as a `stale_signal` bounce, not a silent drop |
1399
+ | `prioritize_mailbox_item` | Re-prioritize an item (0-4) |
1400
+ | `notebook_upsert` | Update situational awareness |
1401
+ | `notebook_clear` | Clear stale awareness |
1667
1402
 
1668
1403
  **Safety**: `human_chat` items are protected — they cannot be deferred, dropped,
1669
1404
  or reprioritized by tool calls. **Strict state items** (formal task execution / review /
1670
- requirement·workflow closure actions — see above) are protected too: `defer_mailbox_item` /
1405
+ requirement·workflow closure actions — see §21.4) are protected too: `defer_mailbox_item` /
1671
1406
  `drop_mailbox_item` return an error, and only `prioritize_mailbox_item` may change their priority;
1672
1407
  they are ultimately executed one at a time by the normal dequeue path.
1673
1408
 
1674
- **Relationship to `complete_deliberation`**: The individual tools take immediate
1675
- effect. `complete_deliberation` handles remaining items in bulk. They are additive.
1676
-
1677
- ### DeliberationResult
1678
-
1679
- ```typescript
1680
- interface DeliberationResult {
1681
- processItemId: string; // Primary item (backward compat)
1682
- processItemIds?: string[]; // Batch: multiple items to process together
1683
- batchContext?: string; // Synthesis/instruction for batch processing
1684
- deferItemIds: string[]; // Postpone for later
1685
- dropItemIds: string[]; // Discard (stale/redundant)
1686
- inlineCompletedIds: string[]; // Already handled during deliberation
1687
- reasoning: string;
1688
- situationalAwareness?: string; // Agent-authored metacognitive summary
1689
- memoryUpdates?: Array<{ // Memory operations applied after deliberation
1690
- type: 'working' | 'longterm';
1691
- key: string;
1692
- content: string;
1693
- }>;
1694
- }
1695
- ```
1696
-
1697
- ### Batch Processing
1409
+ Each tool takes effect immediately on the queue. There is no second, batched interface to
1410
+ pair them with — one item, one call, observable in the queue right away.
1698
1411
 
1699
- When `processItemIds` contains more than one item, the attention controller dequeues all of them and composes their content into a single LLM session. This is efficient for:
1700
- - Multiple `a2a_message` items from the same channel (already partially merged by dedup)
1701
- - Related notifications about the same project/topic
1702
- - Multiple low-priority items that can be acknowledged together
1703
-
1704
- All batch items share one LLM call. If processing is interrupted (preempt/cancel/timeout), all batch items are requeued.
1705
-
1706
- ### Memory Updates During Deliberation
1707
-
1708
- Deliberation can produce `memoryUpdates` — both working memory (volatile, per-session) and long-term memory (curated, persisted to MEMORY.md). This enables the agent to:
1709
- - Record team decisions observed in merged messages
1710
- - Note user preferences inferred from multiple interactions
1711
- - Build context continuity across processing cycles
1712
-
1713
- Tools `memory_save` and `memory_update_longterm` are also available during deliberation for immediate effect.
1714
- ```
1715
-
1716
- ### Working Memory Injection
1412
+ ### 21.6 Notebook (keyed working memory)
1717
1413
 
1718
1414
  The agent maintains a **keyed working memory store** (`workingMemory` Map) that
1719
1415
  replaces the former `currentCognition` string. Each entry has:
1720
- - A key (agent-chosen label, e.g., "deliberation", "task-priorities")
1416
+ - A key (agent-chosen label, e.g., "task-priorities")
1721
1417
  - Content text
1722
1418
  - Update timestamp
1723
1419
 
1724
- Working memory is populated from three sources:
1725
- 1. **Deliberation**: `situationalAwareness` → key `"deliberation"`
1726
- 2. **Triage**: reasoning → key `"triage-decision"`
1727
- 3. **Agent tools**: `notebook_upsert` / `notebook_clear`
1420
+ Entries have exactly two writers: the agent itself through `notebook_upsert` /
1421
+ `notebook_clear`, and a one-shot import of the retired `state.md` (`legacy-state` key).
1422
+ The former machine-written `deliberation` / `triage-decision` keys disappeared with the
1423
+ mechanisms that produced them — nothing writes a decision summary into the notebook behind
1424
+ the agent's back.
1728
1425
 
1729
1426
  All entries are injected into every system prompt as a `## Notebook` block with
1730
1427
  age labels per entry. (The internal field is still named `workingMemory`; the prompt
1731
1428
  heading was renamed to `## Notebook`, so the old name survives only in code.) The agent decides what to keep, update, or expire.
1732
1429
 
1733
- ### Mini Triage Loop (Fallback)
1734
-
1735
- When `performDeliberation` is unavailable, the system falls back to the legacy mini triage loop:
1736
- - Triage LLM uses the agent's name and role in its system prompt.
1737
- - Can call tools from `TRIAGE_ALLOWED_TOOLS` (including `recall_activity`, `memory_search`) up to `TRIAGE_MAX_TOOL_ITERATIONS` (6) rounds.
1738
- - Returns a structured JSON decision (same as `TriageResult`).
1739
-
1740
- ### Key Methods
1430
+ ### 21.7 Key methods
1741
1431
 
1742
1432
  | Method | Location | Purpose |
1743
1433
  |--------|----------|---------|
1744
- | `performDeliberation()` | `agent.ts` | Full-session deliberation via handleMessage(scenario='deliberation') |
1745
- | `applyDeliberationResult()` | `attention.ts` | Applies inline/defer/drop/choose from deliberation |
1746
- | `complete_deliberation` (tool) | `agent.ts` executeTool | Captures structured decision during deliberation |
1747
- | `applyTriageResult()` | `attention.ts` | Applies defer/drop/choose from mini triage (fallback) |
1748
- | `performTriage()` | `attention.ts` | Mini triage loop (fallback path) |
1749
- | `buildTriagePrompt()` | `attention.ts` | Constructs the triage prompt with candidates + context |
1750
- | `consolidateByEntity()` | `mailbox.ts` | Merges items sharing same taskId/requirementId (cross-type) |
1751
- | `updateCognitionFromDeliberation()` | `agent.ts` | Writes deliberation `situationalAwareness` into `workingMemory` under key `"deliberation"` |
1752
- | `evaluateWithLLMFallback()` | `attention.ts` | Heuristic-first interrupt decision with optional LLM fallback |
1753
-
1754
- ### Triage Prompt Identity
1755
-
1756
- Both deliberation (Tier 2) and the mini triage loop (fallback) use first-person perspective: "You are {agentName}." The agent deliberates **as itself** with its role context, not as an external "attention manager."
1434
+ | `heuristicDecision()` | `attention.ts` (~:1515) | The entire decision surface: top-to-bottom rule table, first match wins |
1435
+ | `evaluateInterrupt()` (delegate) | `agent.ts` | Returns `heuristicDecision(current, new)` unchanged — no model call |
1436
+ | `consolidateByEntity()` | `mailbox.ts` | Merges items sharing same taskId/requirementId (cross-type); skips strict state items |
1437
+ | `purgeStaleItems()` | `mailbox.ts` | Drops expired informational items before consolidation |
1438
+ | `deferDequeued()` | `mailbox.ts` | Parks a preempted item so it can resume; only an explicit cancel drops |
1439
+ | `recordDecision()` | `attention.ts` | Writes the `attention:decision` ledger row (reasoning + queue context) |
1440
+ | `defer_mailbox_item` / `drop_mailbox_item` / `prioritize_mailbox_item` | `tools/mailbox-tools.ts` | Per-item queue management; refuse strict state items |
1757
1441
 
1758
1442
  ---
1759
1443
 
@@ -1773,30 +1457,47 @@ Deferred mailbox items are automatically resurfaced when the agent is idle:
1773
1457
  - **→ `review`**: Notifies reviewer (agent via mailbox, or human via approval request)
1774
1458
  - **Terminal states**: Checks and unblocks dependent tasks
1775
1459
 
1776
- Agents do NOT need to take action on these notifications — they serve as episodic memory and triage decision context. Agents should NOT send A2A messages to duplicate what the side-effect system already does.
1460
+ Agents do NOT need to take action on these notifications — they serve as episodic memory and processing context. Agents should NOT send A2A messages to duplicate what the side-effect system already does.
1777
1461
 
1778
- ## 24. Cognitive Science Foundation
1462
+ ## 24. Why a Rule Table (and not a model)
1779
1463
 
1780
- The three-tier triage model (§21) is grounded in established cognitive science:
1464
+ §21's decision surface is a lookup table on purpose. The earlier three-tier framing
1465
+ (Kahneman's System 1 / System 2) described a mechanism that no longer exists in the code:
1466
+ there is one tier, it costs zero tokens, and it is decidable from the queue alone.
1781
1467
 
1782
- | Theory | Application in Markus |
1783
- |--------|----------------------|
1784
- | **Dual Process Theory** (Kahneman, 2011) | Tier 0/1 = System 1 (fast, automatic); Tier 2 = System 2 (slow, deliberative) |
1785
- | **Situational Awareness** (Endsley, 1995) | Full deliberation achieves Level 2+3 SA (comprehension + projection) via memory access |
1786
- | **Working Memory / Episodic Buffer** (Baddeley, 2000) | `recall_activity` and `memory_search` serve as the episodic buffer linking current stimuli to long-term memory |
1787
- | **Metacognition** (Flavell, 1979) | `situationalAwareness` field in `DeliberationResult` enables agent self-monitoring |
1788
- | **Prospective Memory** (Einstein & McDaniel, 2005) | During deliberation, agents can check pending commitments and proactively notify users |
1789
- | **Cognitive Load Theory** (Sweller, 1988) | Unified identity in deliberation eliminates task-switching cost between "triage assistant" and "agent self" |
1468
+ | Concern | How the rule table answers it |
1469
+ |--------|------------------------------|
1470
+ | **Dual Process Theory** (Kahneman, 2011) | The fast path *is* the only path — an interrupt is decided by priority and type, never by reflection |
1471
+ | **Determinism** | Same queue state ⇒ same decision; no sampling, no model variance, no unrepeatable ordering |
1472
+ | **Observability** | Every decision lands in the `attention:decision` ledger with the rule's reasoning and the queue context that produced it |
1473
+ | **Interaction cost** | 0 model calls and 0 added latency per interrupt — the agent's budget goes to the work, not to deciding what the work is |
1474
+ | **Working Memory / Episodic Buffer** (Baddeley, 2000) | The `## Notebook` block carries keyed, agent-authored context across processing cycles |
1475
+ | **Prospective Memory** (Einstein & McDaniel, 2005) | `rest(wakeOn)` declares a wait and gets a turn back when it matches or expires — the mailbox, not a poll loop, is the reminder |
1790
1476
 
1791
1477
  ### Design Rationale
1792
1478
 
1793
- - **Why not always use Tier 2?** Cost and latency. Tier 2 deliberation costs 5-15K tokens vs 0 for Tier 0. Now with `TRIAGE_BACKLOG_THRESHOLD = 2`, deliberation fires whenever 2+ items are queued (non-user head). The cost increase is acceptable because:
1794
- - (a) most single-item processing still takes the fast path,
1795
- - (b) deliberation with 2-3 items is much cheaper than with 5+, and
1796
- - (c) the agent can now use `drop_mailbox_item` during deliberation to clean up before committing to expensive processing.
1797
- - **Why allow inline handling?** Cognitive science shows humans handle simple items (quick email replies) during triage rather than queuing them separately. This reduces total cognitive load and latency.
1798
- - **Why suppress yield points during deliberation?** Deliberation is a metacognitive process — interrupting it would break the agent's reasoning coherence (analogous to interrupting someone mid-thought during planning).
1799
- - **Why inject working memory into future prompts?** This implements **metacognitive regulation** — keyed summaries (deliberation, triage, agent-authored entries) persist across processing contexts, maintaining behavioral consistency.
1479
+ - **Why not let a model reorder the queue?** Because it is a decidable question. Priority +
1480
+ enqueue sequence already produce the order; paying a full tool-enabled turn for it bought
1481
+ nothing and made the order unobservable (the decision only landed in a log). The original
1482
+ motivation — several messages about the same entity — is absorbed structurally by the
1483
+ merge layers (enqueue-time dedup, coalescing window, `consolidateByEntity`), not by a
1484
+ smarter judge.
1485
+ - **Why not let a model classify interrupts?** Same reason: "is a `human_chat` more
1486
+ important than a status update?" is answered by the rule table without inference. An
1487
+ interrupt that costs a model call is an interrupt that can be delayed by the very work it
1488
+ is meant to interrupt.
1489
+ - **Why keep the per-item tools?** `defer` / `drop` / `prioritize` are still the agent's own
1490
+ judgement about its queue — but expressed one item at a time, immediately, and visibly in
1491
+ the queue. That is the opposite trade-off from a bulk model decision: local, cheap,
1492
+ auditable.
1493
+ - **Why does `preempt` defer instead of drop?** Because "interrupted" is not "finished":
1494
+ the paused item keeps its session and resumes (§22).
1495
+ - **Why is `defer` refused for strict state items?** Persistence loses the closures a task
1496
+ execution runs on; a resurfaced execution cannot actually execute and the task hangs in
1497
+ `in_progress` (§21.4).
1498
+ - **Why inject the notebook into future prompts?** This is **metacognitive regulation** —
1499
+ keyed, agent-authored summaries persist across processing contexts and keep behaviour
1500
+ consistent without a machine-written decision trail.
1800
1501
 
1801
1502
  ---
1802
1503
 
@@ -1818,7 +1519,7 @@ The three-tier triage model (§21) is grounded in established cognitive science:
1818
1519
  | Notification bell | **Yes** — `HITLService.notify()` creates persistent notification |
1819
1520
  | Target specific user by ID | **Yes** — `target_user_id` parameter (optional) |
1820
1521
  | Fallback when no target specified | Uses `currentInteractingUserId` (last human who chatted), then team owner |
1821
- | Initiate first-ever conversation with user | **Yes** — via `target_user_id` during deliberation or heartbeat |
1522
+ | Initiate first-ever conversation with user | **Yes** — via `target_user_id` during any processing turn |
1822
1523
 
1823
1524
  **Flow**:
1824
1525
  ```
@@ -1846,11 +1547,10 @@ Agent calls notify_user(title, body, target_user_id?)
1846
1547
  | Message visible to all channel members | **Yes** — persisted + WebSocket broadcast |
1847
1548
  | Triggers other agents in channel | **Yes** — enqueues `a2a_message` to peer agents |
1848
1549
  | Create new group chat | **Yes** — `agent_create_group_chat` tool |
1849
- | Available during deliberation | **Yes** — in `DELIBERATION_ALLOWED_TOOLS` |
1850
1550
 
1851
1551
  ### 25.3 Agent-to-Agent (A2A)
1852
1552
 
1853
- A2A messages route through persistent DM channels (`dm:a2a:{sorted_ids}`) — see §11.1.
1553
+ A2A messages route through persistent DM channels (`dm:a2a:{sorted_ids}`) — see [a2a-communication.md](./a2a-communication.md) §11.1.
1854
1554
 
1855
1555
  | Tool | Capability |
1856
1556
  |------|-----------|
@@ -1858,37 +1558,32 @@ A2A messages route through persistent DM channels (`dm:a2a:{sorted_ids}`) — se
1858
1558
  | `agent_broadcast_status` | Status update to all colleagues (lightweight, no LLM) |
1859
1559
  | `agent_delegate_task` | Formal task delegation with protocol |
1860
1560
 
1861
- ### 25.4 Proactive Messaging During Deliberation
1561
+ ### 25.4 Proactive Messaging During Focused Processing
1862
1562
 
1863
- During full-session deliberation (Tier 2), agents can handle simple items inline by calling communication tools directly:
1563
+ There is no separate decision turn in which to speak: every proactive message is sent from
1564
+ the item's own processing turn, where the agent already has memory, activity recall and the
1565
+ task/requirement tools.
1864
1566
 
1865
1567
  ```
1866
- Deliberation session starts (5 items queued)
1568
+ Focused turn starts (item #1 dequeued)
1867
1569
  → Agent calls memory_search to check commitments
1868
- → Agent calls notify_user(target_user_id="usr_alice", ...) — handles item #3 inline
1869
- → Agent calls task_comment(...) — handles item #5 inline
1870
- → Agent calls complete_deliberation({
1871
- process_item_id: "item_1",
1872
- inline_completed_ids: ["item_3", "item_5"],
1873
- defer_item_ids: ["item_4"],
1874
- drop_item_ids: ["item_2"],
1875
- reasoning: "Item 1 is an urgent review request; handled notifications inline"
1876
- })
1570
+ → Agent calls notify_user(target_user_id="usr_alice", ...) — the notification this item called for
1571
+ → Agent calls task_comment(...) — records the finding on the task
1572
+ → Agent calls defer_mailbox_item("item_4", reason) — parks unrelated work (refused for strict items)
1877
1573
  ```
1878
1574
 
1879
- This collapses what would have been 5 separate triage+process cycles into a single deliberation + 1 processing cycle.
1575
+ One item, one turn, one LLM call. Work that needs its own turn gets its own turn — that is
1576
+ what the queue is for, and there is no protocol by which the agent can declare other items
1577
+ "handled inline".
1880
1578
 
1881
1579
  ---
1882
1580
 
1883
1581
  ## 26. Future Work
1884
1582
 
1885
- - **Proactive messaging scheduler** *(implemented)*: Agents schedule time-based follow-ups via `schedule_wakeup` (one-shot or recurring); a coarse per-agent sweep fires due wakeups into the mailbox. See §11.3.
1583
+ - **Proactive messaging scheduler** *(implemented)*: Agents schedule time-based follow-ups via `schedule_wakeup` (one-shot or recurring); a coarse per-agent sweep fires due wakeups into the mailbox. See [a2a-communication.md](./a2a-communication.md) §11.3.
1886
1584
  - **Cross-agent priority coordination**: Allow a manager agent to influence subordinate agents' mailbox priorities.
1887
1585
  - **Decision pattern learning**: Use long-term decision history to adaptively tune heuristic thresholds.
1888
- - **Deliberation cost optimization**: Implement adaptive deliberation depth — use cheaper models or shorter budgets for simple multi-item scenarios, full budget only for genuinely complex triage.
1889
1586
  - **Working memory persistence**: Persist keyed working memory across agent restarts (currently volatile).
1890
- - **Adaptive deliberation model selection**: Use cheaper models for simple 2-item queues; reserve fuller budgets for genuinely complex triage.
1891
- - **Recursive deliberation**: Allow deliberation to trigger sub-deliberation for complex multi-step planning (with depth limits).
1892
1587
 
1893
1588
  ---
1894
1589
 
@@ -1910,10 +1605,10 @@ This collapses what would have been 5 separate triage+process cycles into a sing
1910
1605
 
1911
1606
  ### 27.2 Known gaps (no-timeout awaits)
1912
1607
 
1913
- - **GAP-A — triage deliberation is NOT inside the backstop**: `deliberate` (Tier-2 full
1914
- deliberation) can await the model with no timeout — the **closest existing path to a
1915
- permanent block**. Mitigation today: only reachable with a non-empty queue; still, it
1916
- deserves a timeout + fail-loud.
1608
+ - **GAP-A — ~~triage deliberation is NOT inside the backstop~~ (stale, closed)**: the
1609
+ Tier-2 decision-model await was deleted with LLM triage (§21). The decision path is a
1610
+ pure rule table with no model call, so the only unbounded model work in a mailbox turn
1611
+ is the item's own processing turn — covered by the 45-min watchdog above.
1917
1612
  - **GAP-B — ~~task-queue has no per-task timeout~~ (stale, closed)**: `TaskService.checkTimeouts()`
1918
1613
  enforces `task.timeoutMs` against `startedAt` and fails the task with an explicit message.
1919
1614
  Do not spend time "adding" this — it exists.
@@ -1930,6 +1625,429 @@ visibility-first invariant as §4.1 — a failure must never look like success.
1930
1625
  ### 27.4 Design intent
1931
1626
 
1932
1627
  The chain is allowed to **stall (bounded) but never to block silently forever**. Any new
1933
- `await` inserted into the main loop or attention/triage path must be either (a) bounded by
1628
+ `await` inserted into the main loop or attention path must be either (a) bounded by
1934
1629
  a timeout/backstop, or (b) explicitly justified as blocking by design. Watchdog + backstop
1935
1630
  values are single-source constants in `packages/core/src/` — do not fork them per caller.
1631
+
1632
+ ---
1633
+
1634
+ ## 28. Addresses, Envelopes and Bounces
1635
+
1636
+ > Last updated: 2026-11-12. This is the **canonical description of current behaviour**.
1637
+ > Execution narrative and evidence live in
1638
+ > [records/cut6-mailbox-address-envelope-design-2026-11-12.md](../records/cut6-mailbox-address-envelope-design-2026-11-12.md)
1639
+ > and [records/cut6-c4-verification-2026-11-12.md](../records/cut6-c4-verification-2026-11-12.md).
1640
+
1641
+ ### 28.1 The problem this layer removes
1642
+
1643
+ Before this layer, "who is this signal from, and who is it for" existed only as an
1644
+ **inference** over `payload.extra` flags and a handful of `sourceType === '…'` branches,
1645
+ and a signal that could not be routed was written as `status = 'dropped'` — a terminal
1646
+ state with no reason field, no echo, and no reader. The production DB held ≥28,621 such
1647
+ rows. Structure was being derived from payload; nothing was queryable.
1648
+
1649
+ Three structural rules replace that:
1650
+
1651
+ 1. **Structure is never inferred from payload.** Identity is a column, not a guess.
1652
+ 2. **A signal that cannot be delivered is never silently discarded.** It becomes a
1653
+ *bounce*: a row with a structured reason, collected into a catch-all overview that a
1654
+ human or agent can claim.
1655
+ 3. **One fact, one writer.** One address format writer, one envelope builder, one
1656
+ resolver, one status-transition execution point.
1657
+
1658
+ ### 28.2 Address format (v1)
1659
+
1660
+ An internal mailbox address is `<local>.<org>@markus.global`: exactly one dot, lowercase
1661
+ ASCII `[a-z0-9-]`, no leading/trailing/doubled hyphens, `local` ≤ 32 chars, `org` ≤ 30.
1662
+ The dot count defines the namespace: **0 dots = platform-reserved**, **1 dot = org**,
1663
+ **≥2 dots = external domain (kept opaque)**.
1664
+
1665
+ | Rule | Enforcement point |
1666
+ |---|---|
1667
+ | `formatAddress()` / `parseAddress()` are the **only** format entry points | `packages/shared/src/address.ts`; no other module may `split('.')` an address |
1668
+ | Reserved names (platform + ops/host names) are a **closed set** | `PLATFORM_RESERVED_ADDRESSES` / `LOCAL_RESERVED` / `ORG_RESERVED`, locked by tests |
1669
+ | Out-of-range input is **rejected with an actionable hint**, never silently rewritten | `AddressResult` carries `{ ok: false, reason, hint }` |
1670
+ | A string that looks like an internal address is **not** an identity | `parseAddress()` returns `MailAddressRef`, which cannot produce `agent` / `im` |
1671
+ | Human `users.email` may not be an org-format `markus.global` address | single guard in `SqliteUserRepo.assertHumanEmail()` (all three write paths) |
1672
+
1673
+ `AddressRef` (the envelope's `from`/`to` type) is a discriminated union wider than
1674
+ `MailAddressRef`: it adds `{ kind: 'agent', agentId }` and
1675
+ `{ kind: 'im', platform, nativeUserId }` — **delivery-party identities, not mailboxes**.
1676
+ `fromVerified` rides on the envelope, not on the address object, so an external string
1677
+ can never be mistaken for a verified internal identity.
1678
+
1679
+ ### 28.3 Bindings and the resolver
1680
+
1681
+ Addresses are bound to targets in `channel_bindings` (`address` + `revoked_at`, plus the
1682
+ `address_bindings` view). The unique index is
1683
+ `uq_channel_bindings_address_active ON channel_bindings(address) WHERE revoked_at IS NULL`
1684
+ — **`org_id` is deliberately absent from the key**: the org slug is already encoded in the
1685
+ address, and scoping by the *current* org would make `cto.acme@markus.global` unresolvable
1686
+ from any other org's instance. Revoking stamps `revoked_at`; rows are never deleted.
1687
+
1688
+ **C10-A slug ownership.** `organizations.org_slug` (nullable, partial unique index
1689
+ `uq_organizations_org_slug`) is the registry fact "which org owns this slug". `bind()`
1690
+ checks the address's org segment — taken from the single parser, never a second split —
1691
+ against the binding org's declared slug: no declared slug ⇒ `bounced/org_slug_unset`
1692
+ (fail closed), mismatch ⇒ `bounced/org_slug_mismatch` (anti-squatting: the global unique
1693
+ index prevents collisions, not squatting). Slugs are owned by markus.global:
1694
+ `createOrg` and the one-time upgrade backfill share the single derivation point
1695
+ `registryOrgSlug(id) = local-<hash>` — **never derived from `name`** — and the real
1696
+ slug arrives from the Hub (`bindHubOrg` / `syncHubOrgIdentity`). There is deliberately
1697
+ no local write entry point: global uniqueness can only be adjudicated by the Hub's
1698
+ unique index. `revoke()` deliberately has no ownership
1699
+ gate: releasing your own historical binding must not be locked out by registry state.
1700
+ The `address_bindings` view is **recreated on every init** (`DROP VIEW IF EXISTS` +
1701
+ `CREATE VIEW`; a view holds zero rows, so this is non-destructive) and exposes `kind`
1702
+ (frozen closed set `{agent, role, platform}`, metadata only); `bind()` writes
1703
+ `kind='agent'`. Bind/revoke record `status_transitions` rows with `entity_type='address'`
1704
+ through the single transition execution point.
1705
+
1706
+ `resolveEnvelopeTarget(envelope, catchAllOwner, lookup?)` is the **single resolver** and
1707
+ reads the envelope only — its signature makes `payload` / `sourceType` physically
1708
+ unreachable (rule 1 expressed as a type boundary, not a comment). It returns exactly two
1709
+ shapes: `{ matched: true, targetRef, agentId }` or
1710
+ `{ matched: false, reason, catchAll }`. There is no third "quietly undefined" outcome.
1711
+
1712
+ | `to.kind` | Behaviour |
1713
+ |---|---|
1714
+ | `agent` | Direct internal delivery — the target identity is already given |
1715
+ | `markus` | Look up the address book; hit ⇒ unique active target, miss ⇒ `no_active_target` |
1716
+ | `platform` / `external` / `im` | Not a delivery recipient in v1 ⇒ `unresolved_address` (platform addresses are senders, external mail is not implemented, `im` is a sender identity) |
1717
+
1718
+ ### 28.4 The delivery envelope
1719
+
1720
+ Every inbound signal carries a `DeliveryEnvelope` persisted in `mailbox_items.envelope`
1721
+ (JSON). `buildDeliveryEnvelope()` in `packages/shared/src/mail.ts` is the **only** shape
1722
+ writer; no module may hand-write the object literal.
1723
+
1724
+ | Field | Role |
1725
+ |---|---|
1726
+ | `from` / `to` | `AddressRef` — identity, queryable |
1727
+ | `messageId` | Idempotency identity. Projected into `mailbox_items.message_id` because uniqueness must be adjudicated by an **index**, not by parsing a JSON blob |
1728
+ | `intent` | `deliver` \| `trigger_execution` \| `action_required` — promoted out of `payload.extra.{triggerExecution,actionRequired}` |
1729
+ | `signalClass` | `chat` \| `a2a` \| `callback` \| `governance_event` \| `record` \| `system` — assigned by the single routing decision |
1730
+ | `externalThreadRef` | Causal chain (In-Reply-To / References). **Read-only**: never routes, never dedups |
1731
+ | `auth` / `replyTo` / `workUnitRef` | Reserved slots, **always `null`** until a writer exists. C10-A froze `auth` as four nullable fields `{spf, dkim, dmarc, verified}`; values are written only by an adapter that actually verifies (C10-D). `auth.verified` is the authentication verdict — not `fromVerified` (the routing trust bit) |
1732
+
1733
+ Reserved slots are written as explicit `null`s rather than omitted: omitting makes the
1734
+ JSON shape vary with the input, which forces a branch per shape on the read side.
1735
+ `parseEnvelope()` returns `undefined` for NULL / empty / malformed JSON and **never
1736
+ synthesises** a plausible-looking envelope.
1737
+
1738
+ Three delivery points supply only what they actually know; assembly happens once, in
1739
+ `AgentMailbox.enqueue()`:
1740
+
1741
+ | # | Delivery point | Supplies |
1742
+ |---|---|---|
1743
+ | 1 | IM inbound (`cli/src/commands/start.ts` `messageRouter.setAgentHandler`) | `from = im:<platform>:<senderId>`, `messageId = message.id` (adapter re-delivery lands one row) |
1744
+ | 2 | Gateway `createTask()` (`org-manager/src/api-server.ts`) | `from = agent:<createdBy>`, `messageId = gateway-task:<taskId>` |
1745
+ | 3 | A2A `AgentDelivery.deliver()` | `from = agent:<fromAgentId>`, `messageId = deliveryId`, `externalThreadRef = chainId` |
1746
+
1747
+ A2A deliberately does **not** dedup on `chainId`: two different messages in the same chain
1748
+ at the same hop are both legitimate, and deduping on the chain would silently swallow one.
1749
+
1750
+ ### 28.5 Bounces and the catch-all overview
1751
+
1752
+ `dropped` is **no longer in the status value domain**. Historical rows are read-only and
1753
+ are normalised to `bounced` on the read path by `normalizeSignalStatus()`; no `UPDATE` is
1754
+ ever run against them.
1755
+
1756
+ ```
1757
+ queued ─▶ processing ─▶ completed | deferred | merged
1758
+ │ │
1759
+ └────────────┴──▶ bounced ──▶ catch_all ──▶ queued (claimed by a human/agent)
1760
+ ▲ ▲
1761
+ reason + why bounce_target
1762
+ ```
1763
+
1764
+ `drop_reason` is mandatory and draws from a **closed set** — six producible reasons plus
1765
+ one reserved:
1766
+
1767
+ | Reason | Meaning |
1768
+ |---|---|
1769
+ | `unresolved_address` | The `to` kind is not a delivery recipient in v1 |
1770
+ | `no_active_target` | Org address has no active binding |
1771
+ | `lease_expired` | Claim expired mid-flight |
1772
+ | `duplicate_message_id` | Same `(agent, messageId)` delivered twice |
1773
+ | `stale_signal` | Superseded / TTL-expired / deliberately discarded. **Only** this meaning |
1774
+ | `payload_invalid` | The signal cannot be read as a turn at all — request-shape validation rejected it (`SignalPayloadInvalidError`) |
1775
+ | `processing_error` | The platform threw while handling a signal it *could* read. Not the sender's fault, and not a decision: this is the platform's own regression surfaced as data |
1776
+ | `dsn_bounce` *(reserved)* | External DSN; shape fixed, **never produced** in v1 |
1777
+
1778
+ **Each reason names one actor and one action** — that is the whole point of the closed set, and the
1779
+ criterion used to decide what belongs in it:
1780
+
1781
+ | Reason family | Who acts | Action |
1782
+ |---|---|---|
1783
+ | `unresolved_address`, `no_active_target` | operator / org admin | fix the binding |
1784
+ | `payload_invalid` | sender / ingest site | fix the payload |
1785
+ | `duplicate_message_id` | sender | none (idempotency worked) |
1786
+ | `lease_expired` | platform | observe (self-heals) |
1787
+ | `processing_error` | platform | fix the code; a rising rate is a regression signal |
1788
+ | `stale_signal` | **nobody** | it is a *decision*, not a failure |
1789
+
1790
+ `processing_error` exists because without it "the platform broke" had no name and kept being
1791
+ recorded as `stale_signal` — which asserts that someone decided the signal was not worth handling.
1792
+ Recording "we failed" as "this was worthless" is the same lie as the C5 defect, one layer down.
1793
+ `stale_signal` is therefore narrowed to exactly one meaning: a human or agent deliberately decided
1794
+ not to handle this signal. Both directions are pinned by tests — the failure family may not write
1795
+ `stale_signal`, the decision family may not write `processing_error`.
1796
+
1797
+ `payload_invalid` exists because the first real-instance probe exposed a lying reason:
1798
+ a chat request missing `payload.content` was recorded as `stale_signal` under the event
1799
+ name `duplicate_delivery_dropped`. A reason that lies is worse than no reason — the
1800
+ overview aggregating by reason conflated "expired" with "malformed". The observability
1801
+ event is `mailbox.signal_bounced`.
1802
+
1803
+ **The classification predicate is a fact, not an exception class.** A second
1804
+ real-instance probe (2026-11-13) caught the first fix still lying on one path: the same
1805
+ missing-`content` request this time threw a plain `TypeError` (`… reading 'trim'`) from a
1806
+ line *earlier* than the validation layer, so an `instanceof SignalPayloadInvalidError`
1807
+ check returned `undefined` and `drop()` fell back to its `stale_signal` default. In other
1808
+ words "what reason gets recorded" depended on **which line threw first** — coincidence,
1809
+ not a criterion. The projection is now
1810
+ `bounceReasonOfFailure(err, item)`: any failure on an item whose payload cannot be read
1811
+ as a turn (`isPayloadUnreadable()`, the *same* predicate `turnContentOf()` validates
1812
+ with) is `payload_invalid`. The reverse edge stays closed: an unknown exception on a
1813
+ **readable** payload is not projected, so `payload_invalid` cannot become the next
1814
+ catch-all bucket, and no exception at all yields no failure-family reason (deliberate
1815
+ drops stay `stale_signal`).
1816
+
1817
+ `bounceSignal()` performs two real transitions through the single execution point
1818
+ (`AgentMailbox.updateSignalStatus()`): `X → bounced` (the fact that delivery failed) and
1819
+ `bounced → catch_all` (the fact that it is now nobody's to collect yet). Collapsing them into
1820
+ one state would make "recorded but not yet collected" inexpressible.
1821
+
1822
+ ### 28.6 Invariants (guarded by behavioural tests)
1823
+
1824
+ | # | Invariant | Test |
1825
+ |---|---|---|
1826
+ | I1 | At most one active target per address | Concurrent binds ⇒ exactly one success; the partial unique index is the backstop |
1827
+ | I2 | `resolve()` never reads payload | Mutating `payload.extra` leaves the resolution unchanged |
1828
+ | I3 | No silent discard | A recipient-less signal yields a `bounced` row with a non-empty reason, visible in the catch-all overview; `dropped` delta = 0 |
1829
+ | I4 | All three links carry an envelope | Triggering chat / task / a2a yields `envelope IS NOT NULL` on each row |
1830
+ | I5 | Binding someone else's address is refused | Binding as another identity ⇒ rejection with an actionable hint |
1831
+ | — | Envelope uniqueness is index-adjudicated | `uq_mailbox_agent_message ON (agent_id, message_id) WHERE message_id IS NOT NULL AND status <> 'bounced'` (bounce rows record a *failed* delivery, not a second copy) |
1832
+
1833
+ ### 28.7 Tool surface
1834
+
1835
+ | Tool | Semantics |
1836
+ |---|---|
1837
+ | `bind_address` | Claim / rebind an address; omitting `targetRef` means self. Binding another agent's address is refused; the org segment must be your org's declared `org_slug` (C10-A anti-squatting) |
1838
+ | `address_list` | Read own (optionally org-wide) active bindings |
1839
+ | `address_revoke` | Stamp `revoked_at` on one's own binding |
1840
+ | `message_route` | Read one signal's resolution, `drop_reason` and catch-all bucket — the取证 path for I3 |
1841
+ | `catch_all` | Read/claim the catch-all overview |
1842
+
1843
+ Failure returns are written from the caller's point of view: a resolution failure returns
1844
+ `{ status: 'bounced', reason, catchAll }` rather than only logging — the agent cannot see
1845
+ logs, it can only model from the return value.
1846
+
1847
+ ### 28.8 Migration and rollback
1848
+
1849
+ Idempotent `ALTER TABLE … ADD COLUMN` for every new column (`mailbox_items.envelope`,
1850
+ `work_unit_ref`, `signal_class`, `intent`, `message_id`, `drop_reason`, `bounce_target`;
1851
+ `channel_bindings.address`, `revoked_at`; C10-A: `organizations.org_slug`,
1852
+ `agents.agent_alias`). The `address_bindings` view is recreated on every init so
1853
+ upgraded DBs expose `kind` (zero rows — non-destructive). **No backfill except one
1854
+ explicit write**: when the upgrade adds `org_slug`, existing orgs receive `org_<id>`
1855
+ via the single derivation point (never from `name`), once; all other historical rows
1856
+ keep `NULL` and the read path warns and falls back to
1857
+ `agent_id`. Old rows without `intent` / `round` are decoded once at the persistence →
1858
+ memory boundary (`rehydrateStructuredFields()`); that shim's removal condition is
1859
+ "`envelope IS NULL` rows = 0". Rollback is `git revert` per card; the resolver has an
1860
+ off-switch that restores the legacy `explicitAgentId → channel → instance` chain.
1861
+
1862
+ ### 28.9 Explicit boundaries (what v1 does not do)
1863
+
1864
+ No mail send/receive, no DNS/MX/SPF/DKIM/DMARC, no cross-org delivery, no alias
1865
+ self-service. C10-A built the `org_slug` / `agent_alias` columns (nullable + unique
1866
+ constraints, slug ownership enforced at bind); `role_slug` stays a reserved name with
1867
+ no table. `agent_alias` has **no writer yet** — the issuance/revocation lifecycle
1868
+ arrives with a later card; the envelope `auth` slot stays `null` until an adapter
1869
+ actually verifies (C10-D). `work_unit_ref` is a column with a **write count of zero** — the only writer
1870
+ arrives with WorkUnits, and creating a reference before the entity would be a dangling
1871
+ reference by construction.
1872
+
1873
+ ## 29. External Source Adapters (Webhook / RSS)
1874
+
1875
+ C10-B adds the first external-source ingestion path: events that originate outside the
1876
+ platform enter the mailbox as `external_signal` items under the same identity discipline
1877
+ as internal chains. Two consumers ship first — webhook and RSS — chosen because they need
1878
+ no DNS change and no auth chain: everything arrives `verified=false`, so the observe
1879
+ ceiling is exercised from day one.
1880
+
1881
+ ### 29.1 Adapter contract (translate, never route)
1882
+
1883
+ `ExternalSourceAdapter` (comms `external-source.ts`) translates a raw external event into
1884
+ a delivery envelope and nothing else. It does not resolve recipients, does not dedupe,
1885
+ does not write storage. The envelope shape:
1886
+ - `from: AddressRef{kind:'external', raw, verified:false}` — the external sender is never
1887
+ trusted; `verified` stays false until an adapter actually verifies (C10-D).
1888
+ - `to`: the resolved internal address (the bound agent).
1889
+ - `messageId`: the idempotency key supplied by the source.
1890
+ - `external_thread_ref`: opaque, read-only; it never routes and never dedupes.
1891
+ - `auth: null` — the envelope auth slot is untouched (single-writer rule, C10-A).
1892
+
1893
+ ### 29.2 Identity: one constructor, ensured before enqueue
1894
+
1895
+ External signals get their `work_unit_ref` from the single `WORK_UNIT_REF.external`
1896
+ constructor in shared `work-unit.ts` — shape `external:<sourceId>:<messageId>`, idempotent
1897
+ per `messageId`. The ref is ensured **before** enqueue at the single ingest point;
1898
+ `identity-single-constructor.guard.test.ts` bites on any second construction point. The
1899
+ fail-closed assembly guard rejects a ref-less external enqueue. No adapter gets a private
1900
+ write path and no adapter may resurrect a "link later" token.
1901
+
1902
+ ### 29.3 Single ingest point + ceiling
1903
+
1904
+ `ExternalSourceService` (org-manager) is the only ingest point: it constructs the ref,
1905
+ applies the signal-level ceiling, and enqueues. The ceiling is a single predicate: a
1906
+ `verified=false` external signal cannot create a task or send a message (behavior test
1907
+ bites: flip the ceiling → red). Adapters translate; the service decides.
1908
+
1909
+ ### 29.4 Kill switch (durable, read fresh)
1910
+
1911
+ Each source has its own `enabled` column in the `external_sources` table (storage). The
1912
+ ingest path reads `enabled` fresh from the DB on every event — not an in-memory flag — so
1913
+ toggling a source off stops ingestion immediately and the disabled state survives a
1914
+ process restart (post-#474 durable-store pattern). Going offline never drops already-queued
1915
+ items.
1916
+
1917
+ ### 29.5 Idempotency + overview
1918
+
1919
+ A duplicate `messageId` is bounced (`duplicate_message_id`) and produces exactly one
1920
+ mailbox item and one `work_units` row. External work units are identity anchors
1921
+ (`status=idle`), visible via `GET /api/agents/:id/work-units?status=idle`; they are not
1922
+ `running` turns. The L5 tool face (`external_source_register` / `list` / `toggle`, mirroring
1923
+ address-tools) plus `bind_address` lets an agent self-bind and register a source; full
1924
+ autonomous next-step observation is the post-B L5 gate.
1925
+
1926
+ ### 29.6 Worklog entity: the envelope is the declaration
1927
+
1928
+ Owner-visible defect (2026-11-26): every C10 signal landed in the overview's "history"
1929
+ bucket instead of a conversation. Root cause was **not** the frontend and **not** a missing
1930
+ field at ingest — the delivery address was *already* written by the single ingest point into
1931
+ `mailbox_items.envelope` (`to.address`). The resolver (`org-manager/worklog-entity.ts`,
1932
+ branch ⑥) only read `payload.extra.channelKey`, which is the **IM gateway's** declaration;
1933
+ C10 never writes that key, so resolution returned `null` → frontend "history".
1934
+
1935
+ Contract: **one fact, one writer, one reader.** Two entrances declare the conversation key
1936
+ in their own shape, and the resolver reads whichever is present:
1937
+
1938
+ | Entrance | Declaration | Stable across messages |
1939
+ | --- | --- | --- |
1940
+ | IM gateway (Feishu/Telegram/…) | `payload.extra.channelKey` (`im:<bot>:<scope>:<chat>`) | yes |
1941
+ | C10 external source (webhook/RSS) | `envelope.to.address` (`kind='markus'`) | yes — one address = one conversation |
1942
+
1943
+ Do **not** "fix" this by also writing `channelKey` at the C10 ingest point: that would be a
1944
+ second writer for a fact the envelope already carries, and the two would drift.
1945
+ `workUnitRef` is a **per-message** idempotency key and can never be reverse-parsed into a
1946
+ conversation — reading a declaration is the only correct path.
1947
+
1948
+ Two semantics that look like defects but are contracts (both cost a wrong defect report):
1949
+
1950
+ 1. **`catch_all` rows carry NULL `work_unit_ref` / `message_id` projections.** The envelope
1951
+ retains both. Evidence queries must therefore go by `envelope` (or by the returned
1952
+ `itemId`) — a `work_unit_ref LIKE …` probe reports a false zero.
1953
+ 2. **Bounced rows do not occupy the `messageId` unique key** (predicate `status <> 'bounced'`,
1954
+ pinned by `storage/test/mailbox-envelope.test.ts`). Replaying one `messageId` against an
1955
+ unbound address legitimately appends another bounce row: once the address is later bound,
1956
+ the same `messageId` must still be deliverable. A bounce row holding the key would block
1957
+ that redelivery forever.
1958
+
1959
+ Real-instance readings (2026-11-26, live DB, agent `agt_b56cd…`): 30 `external_signal` rows →
1960
+ **0 unresolved**, grouped into 2 address conversations (23 + 7). Unbound-address path: 20
1961
+ webhook posts → 20 `bounced/no_active_target` rows collected under
1962
+ `bounce_target=catchall:agt_b56cd…`, each retaining its own `messageId` in the envelope.
1963
+ Note the HTTP status is only an ACK — `200` with `{"status":"bounced"}` in the body is a
1964
+ bounce, not an ingest; discarding the body (`curl -o /dev/null`) reads it as success.
1965
+
1966
+ **L5 end-to-end gate: all five conditions PASS** (verified 2026-11-26 on the live
1967
+ instance). The gate needs: self-bind without UI, first real signal received, a
1968
+ **proposed next step**, a `work_units` row, and a `facts` row. Conditions 1/2/4 were
1969
+ confirmed in the first round; conditions 3 and 5 were confirmed in a second round
1970
+ with a signal that actually demanded a next step. The agent did not restate the
1971
+ input — it **rejected it on evidence**: the incoming item claimed "15s single take,
1972
+ cost −40%", the vendor's own pages say "30s single take, up to 50 omni-modal
1973
+ references, region-level editing" with no official 40% figure, and the release date
1974
+ conflicts (official 2026-07-31 vs the Seed Chinese homepage 2026.11.16). It named
1975
+ the next step ("verify first-party sources before the item enters the topic
1976
+ pipeline") and wrote `fact_d1c34d0a461491a2981fb36c`, whose `work_unit_ref` is
1977
+ exactly the signal's ref. Turn telemetry: ≈70 s, 340 `execution_stream_logs` rows.
1978
+ Signals also group into one address conversation instead of "history", whose newest
1979
+ row remains 2026-11-14.
1980
+
1981
+ Caveat, recorded rather than glossed: the receiving agent was `Secretary`, not a
1982
+ "content agent" as the gate's wording asks — the content agents are stopped and the
1983
+ platform refuses to wake them. The structural conditions are agent-agnostic and were
1984
+ genuinely exercised; the content-agent qualifier is not satisfied by this run.
1985
+ Readings: `docs/records/c10-l5-gate-verification-2026-11-26.md`.
1986
+
1987
+ ### 29.7 Boundaries
1988
+
1989
+ No mail send/receive, no DNS/MX/SPF/DKIM/DMARC (C10-D). `verified=false` is observe-only;
1990
+ the envelope `auth` slot stays `null` until an adapter verifies. Real-instance probe
1991
+ readings (second instance, HOME redirect, port 18731) are recorded in the C10-B delivery
1992
+ report; the traffic gate (≥1 real event → envelope row → resolving work_unit_ref →
1993
+ overview visible) is satisfied for both webhook and RSS.
1994
+
1995
+ ### 29.8 Organization ingress policy (three states, one reader)
1996
+
1997
+ `organizations.external_ingress ∈ {off, observe, accept}`, default **`off`**.
1998
+
1999
+ | state | inbound | owes a turn | intent floor |
2000
+ |---|---|---|---|
2001
+ | `off` | refused (`403`, nothing stored) | no | — |
2002
+ | `observe` | accepted, recorded | no | `deliver` |
2003
+ | `accept` | accepted, recorded | yes | `action_required` |
2004
+
2005
+ Why three states and not a boolean: "may outside systems reach us" and "may a received
2006
+ signal drive an agent" are different questions. A boolean forces an admin who wants a
2007
+ quiet inbox to also cut the wire, which loses the record they wanted.
2008
+
2009
+ Why the default is `off`: for an open-source product the default **is** the configuration
2010
+ most installs run, so the safe state must be the one you get without asking. The `ALTER
2011
+ TABLE … DEFAULT 'off'` backfills existing rows at migration time — no data rewrite, and an
2012
+ upgrading install lands on the safe side (Owner ruling 2026-11-19: no data migration, no
2013
+ DROP).
2014
+
2015
+ **One reader.** The only place the policy is consulted is the single ingest point
2016
+ (`ExternalSourceService.ingest`). The public webhook entry, RSS polling and the
2017
+ operator-delivery path all funnel through it, so no adapter can hold its own copy of the
2018
+ decision and no second gate can disagree with the first. Two consequences worth stating:
2019
+
2020
+ - Per-source `enabled` is **ANDed** with the policy, never a substitute. A source switched
2021
+ on under `off` is not delivering, and the settings UI reports it as `blocked_by_switch`
2022
+ rather than `delivering` — an "on" badge under a closed door is exactly the misreading the
2023
+ screen exists to prevent.
2024
+ - Operator delivery is gated too. It is a member-authenticated path, but its whole purpose
2025
+ is to exercise the external-signal pipeline; letting it bypass the org switch would mean
2026
+ the org's answer to "do we take outside input" has an exception nobody can see from the UI.
2027
+
2028
+ **One writer.** `OrganizationService.setExternalIngress(orgId, policy, actorUserId)`:
2029
+ the actor must resolve to a `users` row (agents have none — so an agent id or ghost id is
2030
+ refused), and every successful change writes exactly one `audit_logs` row
2031
+ (`external_ingress_changed`, with `from`/`to`). Downgrades are audited too: "when did we
2032
+ close this" must be answerable from the audit log alone. The storage repo method
2033
+ (`setExternalIngress`) is this method's instrument, not a public elevation path.
2034
+
2035
+ **Agents may register, humans open the door** (Owner ruling A, 2026-11-26). An agent keeps
2036
+ `external_source_register` / `_toggle` (RSS subscription is its job), and its receipts now
2037
+ carry the current policy plus an `ingressNote` when it is not `accept` — a silent success
2038
+ would let an agent believe it wired up something that can never fire. Changing the org
2039
+ policy is not on the tool surface at all.
2040
+
2041
+ **Secret rotation.** `ExternalSourceService.rotateSecret` replaces `config.token` through
2042
+ the repo's single `setConfig` writer. The previous secret stops working immediately and the
2043
+ new one is returned once; the list receipt only ever exposes `hasSecret` + the last four
2044
+ characters. Rotation deliberately does not re-run the registration gate: ownership is
2045
+ decided once, not re-litigated because a secret changed.
2046
+
2047
+ **Settings surface.** Settings → Connections → External signals: the policy selector and the
2048
+ per-agent source list (address, inbound URL, secret status, last event, last error) come from
2049
+ one response (`GET /api/external-sources` returns `{policy, sources}`) so the screen cannot
2050
+ render sources under a policy that has already changed. The URL is joined against the
2051
+ tunnel's `publicUrl`; with no tunnel it is shown as a local-only path with a warning, because
2052
+ a copyable `localhost` URL is indistinguishable from a working one until the first delivery
2053
+ fails.