@markus-global/cli 0.12.3 → 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 +18523 -9866
  13. package/dist/web-ui/assets/{AsyncState-_UC7xcxJ.js → AsyncState-fJJNUOXK.js} +1 -1
  14. package/dist/web-ui/assets/ChatComponents-S7d2CAAU.js +14 -0
  15. package/dist/web-ui/assets/{ContentRenderer-C-V5k_3K.js → ContentRenderer-DWqhC0uq.js} +6 -6
  16. package/dist/web-ui/assets/DeliverableShareModal-B7DwzEnt.js +1 -0
  17. package/dist/web-ui/assets/{Deliverables-CQnWqbTb.js → Deliverables-CueBYYpx.js} +2 -2
  18. package/dist/web-ui/assets/MarkdownMessage-D8BsJzvD.js +4 -0
  19. package/dist/web-ui/assets/{Search-CVYQIy_D.js → Search-CaYXz3u-.js} +1 -1
  20. package/dist/web-ui/assets/{SendToChat-IOAvuta-.js → SendToChat-_9sm7UBY.js} +1 -1
  21. package/dist/web-ui/assets/Settings-DTL14pY8.js +8 -0
  22. package/dist/web-ui/assets/{Store-BEsLd_RN.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-DP1Vf7Sx.js → arc-JtkmqkSR.js} +1 -1
  27. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-Buq8JYN8.js → architectureDiagram-3BPJPVTR-B8zM5fky.js} +1 -1
  28. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-BCa2p2_X.js → blockDiagram-GPEHLZMM-BQgjaOcE.js} +1 -1
  29. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BxsgggQY.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-BJZZ60c9.js → chunk-2J33WTMH-KONx1qvt.js} +1 -1
  32. package/dist/web-ui/assets/{chunk-4BX2VUAB-C5hc4E6J.js → chunk-4BX2VUAB-BqkxAkWs.js} +1 -1
  33. package/dist/web-ui/assets/{chunk-55IACEB6-CbyvZ6Mk.js → chunk-55IACEB6-DxLiTj85.js} +1 -1
  34. package/dist/web-ui/assets/{chunk-727SXJPM-JmNt9TVA.js → chunk-727SXJPM-Dhj-9NIs.js} +1 -1
  35. package/dist/web-ui/assets/{chunk-AQP2D5EJ-BTk0v5ba.js → chunk-AQP2D5EJ-M1vQ4YYc.js} +1 -1
  36. package/dist/web-ui/assets/{chunk-FMBD7UC4-BO-dhB1U.js → chunk-FMBD7UC4-DaXv58SH.js} +1 -1
  37. package/dist/web-ui/assets/{chunk-ND2GUHAM-BdjCcLdb.js → chunk-ND2GUHAM-Brkz9FCu.js} +1 -1
  38. package/dist/web-ui/assets/{chunk-QZHKN3VN-BAzRC82n.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-CVffmErT.js → cose-bilkent-S5V4N54A-CSjC_YL5.js} +1 -1
  42. package/dist/web-ui/assets/{dagre-BM42HDAG-Dd9pB2fX.js → dagre-BM42HDAG-BevSxaQN.js} +1 -1
  43. package/dist/web-ui/assets/{diagram-2AECGRRQ-BG_AUqzM.js → diagram-2AECGRRQ-CT3Hj8jy.js} +1 -1
  44. package/dist/web-ui/assets/{diagram-5GNKFQAL-D5qFMRFf.js → diagram-5GNKFQAL-CAebHy6q.js} +1 -1
  45. package/dist/web-ui/assets/{diagram-KO2AKTUF-B3qTxSWl.js → diagram-KO2AKTUF-BvRWS7BX.js} +1 -1
  46. package/dist/web-ui/assets/{diagram-LMA3HP47-BrxC1636.js → diagram-LMA3HP47-gR9HBKc4.js} +1 -1
  47. package/dist/web-ui/assets/{diagram-OG6HWLK6-BvXyEQ9-.js → diagram-OG6HWLK6-B5HGsfNo.js} +1 -1
  48. package/dist/web-ui/assets/{docx-preview-DBAZFeEb.js → docx-preview-pRjmDg6F.js} +1 -1
  49. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-CMap9oy_.js → erDiagram-TEJ5UH35-mrPW01aQ.js} +1 -1
  50. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-BZerJtvk.js → flowDiagram-I6XJVG4X-BrZ1G-Tt.js} +1 -1
  51. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-CagPMHMO.js → ganttDiagram-6RSMTGT7-Dq_5mate.js} +1 -1
  52. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-DZ5dDKRu.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-CHLdsDUZ.js → infoDiagram-5YYISTIA-CcnNlnvs.js} +1 -1
  56. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-SdeinQaS.js → ishikawaDiagram-YF4QCWOH-BqHTPtO1.js} +1 -1
  57. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-BtlL2fi0.js → journeyDiagram-JHISSGLW-DKBB9B-C.js} +1 -1
  58. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-BKPQYXkB.js → kanban-definition-UN3LZRKU-BVO5tbNl.js} +1 -1
  59. package/dist/web-ui/assets/{mermaid.core-MkJR6w4B.js → mermaid.core-bMoKRCj4.js} +5 -5
  60. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-CbOmHX_u.js → mindmap-definition-RKZ34NQL-Bk0lFKmi.js} +1 -1
  61. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-CypGjJP1.js → pieDiagram-4H26LBE5-BRPnBLeL.js} +1 -1
  62. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CGtemfUz.js → quadrantDiagram-W4KKPZXB-CAqdqT5W.js} +1 -1
  63. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-N7YfpCvE.js → requirementDiagram-4Y6WPE33-Vv5YNzCu.js} +1 -1
  64. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-CYnSrei-.js → sankeyDiagram-5OEKKPKP-Ciq1EgmQ.js} +1 -1
  65. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-CsB7dCPF.js → sequenceDiagram-3UESZ5HK-DVRqp161.js} +1 -1
  66. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DTDFUXFP.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-C_bWAN9B.js → timeline-definition-PNZ67QCA-D0hr0d1U.js} +1 -1
  69. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-CX_qAuUT.js → vennDiagram-CIIHVFJN-CtuZLcPo.js} +1 -1
  70. package/dist/web-ui/assets/{wardley-L42UT6IY-q53jQ293.js → wardley-L42UT6IY-nP2-eCDJ.js} +1 -1
  71. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-D34dKCJU.js → wardleyDiagram-YWT4CUSO-Dxc7OveP.js} +1 -1
  72. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-BFAngp66.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-Ca9tWI9W.js +0 -12
  139. package/dist/web-ui/assets/DeliverableShareModal-BvpyowYJ.js +0 -1
  140. package/dist/web-ui/assets/MarkdownMessage-DedA8Zob.js +0 -4
  141. package/dist/web-ui/assets/Settings-BQDqf4q5.js +0 -8
  142. package/dist/web-ui/assets/Switch-C6InTNUi.js +0 -1
  143. package/dist/web-ui/assets/Team-nfNyWj-s.js +0 -85
  144. package/dist/web-ui/assets/Work-BQvgkynj.js +0 -142
  145. package/dist/web-ui/assets/channel-BTSrOo6c.js +0 -1
  146. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BSYlcnF9.js +0 -1
  147. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BSYlcnF9.js +0 -1
  148. package/dist/web-ui/assets/index-CKPQYzzR.js +0 -867
  149. package/dist/web-ui/assets/index-CzHSs0Vd.css +0 -1
  150. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-AVnDjlzF.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
@@ -0,0 +1,303 @@
1
+ # Agent-to-Agent Communication (A2A)
2
+
3
+ > Extracted **2026-11-15** from [`mailbox-system.md`](./mailbox-system.md) §11. The chapter was
4
+ > moved verbatim — no invariant, table, spec or code path was dropped — and its section numbers
5
+ > (§11.1 … §11.5) are kept unchanged so existing cross-references stay unambiguous.
6
+
7
+ **Scope of this file** — how one agent reaches another: DM/group channels, the
8
+ one-message-one-delivery-fact invariant, the reply sink, the entry-point inventory, tools &
9
+ transport, async-only correlation, and the two mechanisms that historically lived inside this
10
+ chapter (`PendingCallbackRegistry` §11.3, heartbeat integration §11.4). The **queue** that
11
+ carries these items — `enqueue` / `dequeueAsync`, priorities, enqueue-time dedup, attention
12
+ controller, leasing/retry, persistence, addresses/envelopes — stays in
13
+ [`mailbox-system.md`](./mailbox-system.md). A2A is a *producer* of `a2a_message` mailbox items;
14
+ the mailbox is the **only** delivery mechanism (§11.1.1 point 1).
15
+
16
+ Related: [mailbox-system.md](./mailbox-system.md) (queue, priority, attention, dedup) ·
17
+ [notification-delivery.md](./notification-delivery.md) (user & IM notification delivery) ·
18
+ [concurrent-processing.md](./concurrent-processing.md) (worker-pool / per-entity locking) ·
19
+ [state-machines.md](./state-machines.md) (delegation FSM).
20
+
21
+ ---
22
+
23
+ ## 11. Agent-to-Agent Communication (A2A via Mailbox)
24
+
25
+ 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.
26
+
27
+ ### 11.1 A2A DM Channels
28
+
29
+ A2A messages now route through **deterministic DM channels** that reuse the group-chat infrastructure for persistence, WebSocket delivery, and mailbox enqueue:
30
+
31
+ ```
32
+ Channel key: dm:a2a:{sorted_id_1}:{sorted_id_2}
33
+ (agent IDs sorted lexicographically — one channel per pair)
34
+ ```
35
+
36
+ ```
37
+ Agent A Agent B
38
+ ──────── ────────
39
+ tool: agent_send_message ──► AgentManager.sendMessage()
40
+ │
41
+ ▼
42
+ ensureDmChannel(dm:a2a:...)
43
+ │
44
+ ▼
45
+ sendGroupMessage(channelKey, ...)
46
+ ├─ persist to channel_messages
47
+ ├─ WebSocket broadcast
48
+ └─ enqueueToMailbox('a2a_message', { extra: { channelKey } })
49
+ │
50
+ ▼
51
+ AttentionController picks it up
52
+ (stable session: channel_{channelKey}_{agentId})
53
+ ```
54
+
55
+ Benefits over ephemeral session IDs:
56
+
57
+ - **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.
58
+ - **Stable sessions** — all messages in a pair share one session ID derived from the channel key
59
+ - **Enqueue-time dedup** — messages from the same `channelKey` coalesce ([`mailbox-system.md`](./mailbox-system.md) §14)
60
+ - **Group chat parity** — DM channels use the same `groupChatRepo`, member resolution, and API paths as custom group chats
61
+
62
+ 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`.
63
+
64
+ ### 11.1.1 Delivery invariant — one message, one delivery fact
65
+
66
+ > **Normative.** This section is the contract; the code must not have a second way
67
+ > to reach another agent. It replaces the previous, unwritten arrangement in which
68
+ > some paths persisted + woke the peer directly and others enqueued (see [`mailbox-system.md`](./mailbox-system.md) §14.5).
69
+
70
+ 1. **Exactly one delivery mechanism.** Every inter-agent message — DM
71
+ (`dm:a2a:*`), group/team channel, `@mention`, review/comment notification — MUST
72
+ reach the recipient as a mailbox item:
73
+ `enqueueToMailbox('a2a_message', { extra: { channelKey } })`.
74
+ `channel_messages` is a **projection** (UI history + the context slice the
75
+ recipient reads when it processes the item). It is **not** a delivery channel:
76
+ persisting a row has never delivered anything and must never be reported as if
77
+ it had.
78
+
79
+ 2. **No half-state.** Either a pending mailbox item exists for the recipient
80
+ (possibly merged with siblings, [`mailbox-system.md`](./mailbox-system.md) §14) or the message was never sent. The state
81
+ `delivered-but-not-awake` is forbidden — it is invisible to the sender and to
82
+ the UI, and it was the direct cause of the 2026-10-25 repeat-notification
83
+ incident.
84
+
85
+ 3. **Reply generation is not delivery.** `processGroupChatReply` exists to produce
86
+ a reply for an item the peer is **already** processing. It MUST NOT be used to
87
+ hand a new message to a peer; that is the mailbox's job.
88
+
89
+ 4. **Storm control is causal, never temporal.**
90
+ - *Chain*: `chainId` propagates trace-style. When an item is processed its
91
+ `extra.chainId` becomes the turn's current chain (per-worker
92
+ `SessionWorkspace.chainId`, so concurrent workers never share one); anything
93
+ the turn sends inherits it, and `sendGroupMessage` hands the parent to
94
+ `deliver()` with `depth + 1`. A fresh id is minted only when a delivery truly
95
+ starts a conversation. The context is cleared in the processing `finally` so
96
+ it cannot leak into the next turn.
97
+
98
+ > **Failure mode worth remembering**: this shipped once and did nothing,
99
+ > because the send logic existed **twice** in `AgentManager` — two
100
+ > near-identical `sendMessage` closures in different tool-context factories —
101
+ > and only one forwarded the chain. The A2A tools received the other one, so
102
+ > every delivery still minted a fresh id while the code read correctly. Both
103
+ > copies are now deleted in favour of one private `deliverA2AMessage()`.
104
+ > Reading either copy alone could not have revealed it: only the pair did.
105
+ - *Coalescing*: messages on the same `channelKey` merge into **one** mailbox
106
+ item at enqueue time ([`mailbox-system.md`](./mailbox-system.md) §14), with the full text preserved in the channel.
107
+ - Wall-clock throttles MUST NOT drop a wake. `a2aCooldowns` (per-channel 30 s)
108
+ and `wakeBudget` (global per-agent quota) were removed for exactly this
109
+ reason — both could answer "sent" for a message the peer never received.
110
+
111
+ 5. **The sender is told the truth.** `agent_send_message` returns
112
+ `{ deliveryState: 'queued' | 'coalesced', deliveryId, peerPendingItems,
113
+ coalescedCount }`. `coalesced` means "your message is part of the item the peer
114
+ will process next" — it is a delivery outcome, not a silent drop.
115
+
116
+ 6. **One place decides.** `AgentDelivery.deliver()` is the only caller of the
117
+ mailbox enqueue for inter-agent traffic. Any new feature that wants to reach
118
+ another agent calls it; it must not re-implement "persist + wake".
119
+
120
+ ### 11.1.2 Reply sink — one writer for "an agent said something in a channel"
121
+
122
+ A2A has two facts, and each needs exactly one writer:
123
+
124
+ | Fact | Writer | Never |
125
+ |---|---|---|
126
+ | "A message is addressed to agent X" | `AgentDelivery.deliver()` → `mailbox.enqueue('a2a_message')` | never a direct `getAgent(...).handleMessage(...)` |
127
+ | "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 |
128
+
129
+ `processGroupChatReply` used to be **both** — it woke the peer *and* wrote the
130
+ reply — which is why an A2A message had two possible lifecycles depending on which
131
+ branch produced it. Under this contract it has no role: the mailbox item wakes the
132
+ agent (with its own lease/retry/merge semantics), and the reply returns through
133
+ `responsePromise` to the single sink.
134
+
135
+ **No automatic reply chain.** A reply never triggers the peer. If the other side
136
+ has something to add it must call `agent_send_message` — a deliberate act. This
137
+ removes the class of incident in which two agents re-replied for 43 turns /
138
+ 35 minutes after a single proactive message.
139
+
140
+ ### 11.1.3 Replies are a decision, never a chain
141
+
142
+ The platform does not decide that an agent should answer. It delivers the message
143
+ and the agent decides:
144
+
145
+ * **Perception is automatic, response is optional.** A delivered message wakes the
146
+ agent (mailbox semantics); whether it says anything back is its own call. Ending
147
+ a turn without replying (`end_turn`) is a legitimate, expected outcome — for
148
+ human messages too.
149
+ * **No automatic reply chain.** A reply never triggers the peer. If the
150
+ conversation should continue, the replying agent calls `agent_send_message`
151
+ itself — a deliberate act with its own cost. There is therefore no "reflection"
152
+ to bound: without a chain, `DM_MAX_DEPTH`, per-round `respondedAgents`,
153
+ `shouldChainDmReply`'s regex, the 30 s `a2aCooldowns` and `wakeBudget` have **no
154
+ subject matter left**. They existed only to bound a chain the platform itself
155
+ was creating.
156
+ * **`chainId` is correlation, not a guard.** It is inherited from the inbound item
157
+ (§11.1.1 point 4), so a request and the answer it provokes share one id; it is
158
+ never used to throttle or to drop.
159
+ * **Nothing is lost when someone stays silent.** The message is in the channel and
160
+ in the recipient's mailbox history; silence is observable, not a delivery failure.
161
+
162
+ Rationale (learned the hard way, 2026-10): every storm guard we ever added was a
163
+ consequence of the platform auto-replying on the agent's behalf. Removing the
164
+ auto-reply removes the storm; keeping it forced us to invent judges (wall clock,
165
+ quota, regex) that had to guess "does this reply need an answer?" — and when they
166
+ guessed wrong they discarded the wake while still reporting success.
167
+
168
+ ### 11.1.4 Entry-point inventory (nothing may bypass the delivery service)
169
+
170
+ | Entry | Path | Notes |
171
+ |---|---|---|
172
+ | `agent_send_message` (DM) | `AgentDelivery.deliver` | one item per `channelKey`, mergeable |
173
+ | group chat, no @mention | `AgentDelivery.deliver` (`throttled` when a chain is hot) | awareness, not a reply request |
174
+ | group chat, @mention | `AgentDelivery.deliver` with `mentions` + `chainId` | the chain decision happens **after** delivery |
175
+ | `agent_delegate_task` | delegation manager → `deliver` | protocol on top of the same transport |
176
+ | review / comment / requirement notifications | `task-service` mailbox items | their own item types, not A2A; they must not invent a second wake path |
177
+
178
+ **Addressedness** (who is this message for): a message aimed at a specific agent —
179
+ a DM, or a group message where the agent was `@mentioned` — is delivered with a
180
+ one-line `[MENTIONED] This message is addressed to you …` prefix so the recipient
181
+ knows it is the target. Open/broadcast messages carry no marker. Single writer:
182
+ `DeliveryRequest.addressedTargetIds` (a list of the target ids that are actually
183
+ addressed) in `AgentDelivery.deliver()`; callers must not construct the marker
184
+ themselves.
185
+
186
+ The prefix also carries the **count**: `… Others also addressed: N.` Knowing that
187
+ nobody else was addressed ("this is yours to handle") is a different action from
188
+ knowing two others were ("whoever picks it up first"). The count is emitted
189
+ always, including `0`, for two reasons:
190
+
191
+ - **One template, one stable prefix.** The marker line is a prompt prefix shared by
192
+ every a2a message. Two shapes (with/without the clause) would fork that prefix and
193
+ degrade prompt-cache hits; a fixed template with only the trailing number varying
194
+ keeps the common prefix intact. Put variable content at the **end** of a stable
195
+ template, never by making the template conditional.
196
+ - **It is the decision-relevant part, and only that.** Names are deliberately not
197
+ included: the list would grow the line without bound and would expose unrelated
198
+ agents' identities to a third party. A count answers "must I act" without leaking.
199
+
200
+ It is an id list, deliberately, not a boolean. One group message can address two
201
+ of ten members: with a boolean a caller can only mark the whole batch (bystanders
202
+ think they were singled out) or none of it (the mentioned agent never learns it
203
+ was the target). With a list the ambiguous state is not expressible — which is
204
+ the point.
205
+
206
+ **Origin** (who sent it): `DeliveryRequest.origin` — `[FROM HUMAN] <name> … humans can
207
+ see this channel` versus `[FROM AGENT] … no human is waiting on this`. Produced
208
+ only in `deliver()`, like the addressedness marker. It is load-bearing: a human
209
+ group message delivered as a bare `a2a_message` would be read under the a2a prompt
210
+ section ("humans do NOT see this conversation"), so the agent misjudges the context
211
+ and answers the wrong audience.
212
+
213
+ **Machine-checkable**: `enqueueToMailbox('a2a_message'` may appear only inside
214
+ `agent-delivery.ts`; a direct `handleMessage`/`processGroupChatReply` used to hand a
215
+ message to another agent is a regression.
216
+
217
+ ### 11.2 Tools & Transport
218
+
219
+ - **`agent_send_message`**: Always asynchronous — returns immediately with `conversation_id` and `channel_key`. Messages are tagged `[conversation:...]` for multi-turn correlation.
220
+ - **`agent_delegate_task`**: Uses `DelegationManager` for protocol orchestration; transport goes through the DM channel path above.
221
+ - **`agent_broadcast_status`**: Lightweight path — writes to target agent's daily log without an LLM call. Does not use DM channels.
222
+ - **`agent_send_group_message`**: Team/custom group channels (`group:<teamId>`, `group:custom:<id>`). @mentions control which peer agents receive `a2a_message` mailbox items.
223
+
224
+ The `@markus/a2a` package retains `DelegationManager` and protocol types. `A2ABus` is exported with a `@deprecated` annotation for backward compatibility only.
225
+
226
+ ### 11.3 PendingCallbackRegistry
227
+
228
+ `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.
229
+
230
+ ```typescript
231
+ type CallbackType = 'background_exec' | 'wakeup' | 'a2a_reply';
232
+ type CallbackDelivery = 'in_session' | 'mailbox';
233
+
234
+ interface PendingCallback {
235
+ id: string; // Unique callback ID (e.g., background session ID, a2a_<conversation_id>)
236
+ agentId: string; // Originating agent
237
+ originSessionId: string; // Session to resume on completion (in_session mode)
238
+ type: CallbackType; // Operation type
239
+ deliveryMode?: CallbackDelivery; // in_session (default) → callback_result; mailbox → system_event
240
+ command?: string; // Optional context (shell command, etc.)
241
+ note?: string; // Free-text label (wakeup reason, delegation goal)
242
+ correlationId?: string; // Correlates an external event (conversation_id)
243
+ wakeAt?: number; // Scheduled wakeups: epoch ms when due
244
+ recurringMs?: number; // Recurring wakeups: re-arm interval
245
+ registeredAt: number; // Epoch ms
246
+ timeoutMs: number; // 10 min for background_exec; 30 min for a2a_reply; effectively ∞ for wakeup
247
+ }
248
+ ```
249
+
250
+ **Lifecycle:**
251
+
252
+ 1. **Register** — An async operation is registered as a `PendingCallback` and persisted via `SqlitePendingCallbackRepo`:
253
+ - `background_exec` → `registerBackgroundSession()` (called from `Agent.executeTool` on the tool result).
254
+ - `agent_send_message` with `reply_in_session` (alias `await_in_session`) → an `a2a_reply` callback keyed by `conversation_id`.
255
+ - `schedule_wakeup` → a `wakeup` callback with `wakeAt` (+ optional `recurringMs`).
256
+ 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.
257
+ 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.)
258
+
259
+ **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.
260
+
261
+ **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`.
262
+
263
+ The registry is a process singleton (`pendingCallbackRegistry`), restored from SQLite on startup so callbacks survive server restarts.
264
+
265
+ ### 11.4 Heartbeat Integration
266
+
267
+ Periodic heartbeat items (`priority: 3 — low`) drive proactive agent patrol. Beyond the standard checklist, heartbeat now integrates:
268
+
269
+ **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:
270
+
271
+ 1. Check linked tasks for progress
272
+ 2. Create follow-up tasks if needed
273
+ 3. Mark requirements complete when criteria are met
274
+ 4. Escalate or adjust approach if stuck
275
+
276
+ **Callback timeout handling** — Before building the heartbeat prompt, `handleHeartbeat()` calls `pendingCallbackRegistry.getTimedOut()`. For each expired callback:
277
+
278
+ 1. `expireTimedOut(id)` removes it from the registry (and persistence)
279
+ 2. Details are injected into the heartbeat prompt under **Timed-Out Async Operations** (background exec or an awaited A2A delegation whose reply never arrived)
280
+ 3. The agent investigates and takes corrective action during the heartbeat LLM session
281
+
282
+ This ensures orphaned async operations are surfaced even when the completion handler never fires (process crash, hung command, etc.).
283
+
284
+ 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.
285
+
286
+ ### 11.5 Async-Only A2A (Deadlock Prevention)
287
+
288
+ 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.
289
+
290
+ **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.
291
+
292
+ ---
293
+
294
+ ## Where the mailbox side lives
295
+
296
+ | Question | Document |
297
+ |---|---|
298
+ | Which item types exist, and their default priorities | [`mailbox-system.md`](./mailbox-system.md) §3 |
299
+ | How items are claimed, leased, yielded and retried | [`mailbox-system.md`](./mailbox-system.md) §4, §17, §18 |
300
+ | Enqueue API, merge/dedup at enqueue time (referenced by §11.1.1) | [`mailbox-system.md`](./mailbox-system.md) §5, §14 |
301
+ | Persistence (`mailbox_items`, `channel_messages`) | [`mailbox-system.md`](./mailbox-system.md) §6 |
302
+ | Addresses, envelopes and bounces (`refOrigin`, delivery facts) | [`mailbox-system.md`](./mailbox-system.md) §28 |
303
+ | User / IM notification delivery | [`notification-delivery.md`](./notification-delivery.md) |
@@ -5,6 +5,8 @@
5
5
  > Related: [prompt-engineering.md](./prompt-engineering.md), [tool-system.md](./tool-system.md),
6
6
  > [memory-system.md](./memory-system.md), [learning-loop.md](./learning-loop.md),
7
7
  > [state-machines.md](./state-machines.md).
8
+ > **State ownership contract**: see **Appendix A** of this file (merged from `state-ownership.md` on
9
+ > 2026-11-15 — 状态归属就是执行模型的一部分,分开维护会出现两处各自漂移).
8
10
 
9
11
  **Formula**: `Agent = LLM + Harness + Learning Loop`.
10
12
  **Hard constraint**: the Context Surface keeps cold-start fixed prefix cheap while skills/experience grow unbounded.
@@ -37,7 +39,7 @@ MUST: Skill full bodies and deferred tool schemas MUST enter context only via `d
37
39
 
38
40
  MUST NOT: Inject full SKILL.md bodies at spawn into the system prompt.
39
41
 
40
- Test IDs: `A-skill-l0-only`, `A-tooldef-budget`.
42
+ Test IDs: `A-skill-l0-only`.
41
43
 
42
44
  ### §1.3 Execute ≠ learn
43
45
 
@@ -65,12 +67,10 @@ Test IDs: `B-approve-install`, `B-reject-feedback`, `B-stats-reject-feedback`.
65
67
 
66
68
  ### §2.1 Pack definitions
67
69
 
68
- | Pack | Scenarios | ToolDef budget (tokens) | Prompt profile |
69
- |------|-----------|-------------------------|----------------|
70
- | `reflex` | `memory_consolidation` (Dream), `memory_flush`, `distillation` | 3_000 | `reflex` |
71
- | `converse` | `heartbeat`, `chat`, `a2a`, `group_chat`, `comment_response`, `requirement_action`, `workflow_action` | 8_000 | `converse` |
72
- | `execute` | `task_execution` | 10_000 | `execute` |
73
- | `govern` | `review`, `deliberation` | 8_000 | `govern` |
70
+ The pack table is defined once, in [`tool-system.md §1.0`](./tool-system.md). It is not repeated
71
+ here: on 2026-11-15 the two copies had already drifted (this file and `tool-system.md` disagreed
72
+ about whether `heartbeat` belongs to `reflex` or `converse`). Budgets and the scenario list live
73
+ in that one table; this section only states the runtime obligation.
74
74
 
75
75
  MUST: `selectTools` / allowlists MUST resolve through the pack for the active scenario.
76
76
 
@@ -106,9 +106,9 @@ MUST: Default `converse` MUST NOT include `spawn_subagents` or `deliverable_crea
106
106
 
107
107
  MUST: `execute` MUST include code/shell/coding groups (or equivalent) needed for task work.
108
108
 
109
- MUST: Keyword matching and `recentToolNames` MAY accelerate loading but MUST NOT exceed the pack `toolDefTokens` budget.
109
+ MUST: Keyword matching and `recentToolNames` MAY accelerate loading; selection only ever adds to the face — no budget eviction exists (§5).
110
110
 
111
- Test IDs: `A-pack-converse-no-spawn`, `A-pack-execute-has-code`, `A-tooldef-sticky-capped`.
111
+ Test IDs: `A-pack-converse-no-spawn`, `A-pack-execute-has-code`.
112
112
 
113
113
  ---
114
114
 
@@ -116,10 +116,6 @@ Test IDs: `A-pack-converse-no-spawn`, `A-pack-execute-has-code`, `A-tooldef-stic
116
116
 
117
117
  | Constant | Value | Purpose |
118
118
  |----------|-------|---------|
119
- | `TOOL_DEF_BUDGET_REFLEX` | 3_000 | Max tool schema tokens |
120
- | `TOOL_DEF_BUDGET_CONVERSE` | 8_000 | Max tool schema tokens |
121
- | `TOOL_DEF_BUDGET_EXECUTE` | 10_000 | Max tool schema tokens |
122
- | `TOOL_DEF_BUDGET_GOVERN` | 8_000 | Max tool schema tokens |
123
119
  | `ROLE_PROMPT_MAX_TOKENS` | 6_000 | ROLE soft size metric (warn only; never truncate) |
124
120
  | `KNOWLEDGE_PROMPT_MAX_TOKENS` | 1_500 | knowledge.md injection (`execute`/`govern`) |
125
121
  | `KNOWLEDGE_PROMPT_MAX_TOKENS_CONVERSE` | 1_200 | knowledge.md injection (`converse`) |
@@ -135,7 +131,6 @@ Test IDs: `A-pack-converse-no-spawn`, `A-pack-execute-has-code`, `A-tooldef-stic
135
131
  | `SYSTEM_NORMS_CHARS` | 2_000 | Team norms body cap (execute/govern) |
136
132
  | `SYSTEM_WORKFLOWS_MAX_CONVERSE` | 3 | Available-workflow lines in converse |
137
133
  | `SYSTEM_DYNAMIC_CONTEXT_CHARS_CONVERSE` | 800 | Caller `dynamicContext` blob cap (converse) |
138
- | `DEFERRED_CATALOG_MAX_CHARS` | 1_500 | Tier-3 rediscovery catalog hard cap |
139
134
  | `DEEP_SLEEP_IDLE_HEARTBEATS` | 3 | Consecutive idle before skip LLM |
140
135
  | `SUBTASK_SOFT_CAP` | 8 | Warn at/above this count |
141
136
 
@@ -210,29 +205,22 @@ MUST: Skill/MCP tool schemas (`feishu_*`, `*__*`, `chrome-devtools*`) MUST NOT e
210
205
  the LIVE tool list except via explicit `discover_tools` activation.
211
206
  MUST: Markus core tools (`TOOL_DEF_CORE_KEEP`: shell/file/task/memory/…) +
212
207
  `discover_tools` + HITL MUST stay LIVE for converse/execute/govern.
213
- MUST: When estimated tool-definition tokens still exceed the pack budget, evict
214
- optional extras / activated skill-MCP (LRU) only — never CORE_KEEP or HITL/discover.
215
- Prefer catalog (Tier 3 / inactive namespace list) over schema dump.
208
+ MUST NOT: Shrink the tool face to fit a token budget — no eviction mechanism exists
209
+ (Owner 2026-11-20, PR #471). External skill/MCP schemas enter only via `discover_tools`
210
+ activation (progressive disclosure); activation is sticky for the session. Context
211
+ pressure compresses history, never the face.
216
212
 
217
- Test IDs: `S-tool-mcp-progressive`, `S-tooldef-evict-mcp-before-core`, `S-activated-mcp-lru`.
218
-
219
- MUST (§Afford.S2): Evicted tool rediscovery catalog MUST be injected into the volatile
220
- `[Live context]` tail (never a system segment — byte-stable prefix must be preserved), as a
221
- short name-only (or name + ≤40 chars) list, total ≤ `DEFERRED_CATALOG_MAX_CHARS`.
222
-
223
- MUST NOT: Append the eviction catalog to `discover_tools.description` (that re-inflates
224
- `toolDefTokens` and defeats the budget).
213
+ Test IDs: `S-tool-mcp-progressive`, `S-discover-activated-protected`.
225
214
 
226
215
  MUST: After `discover_tools` activates tool names, the runtime MUST rebuild the LLM
227
216
  `tools` schema list before the next provider call (stream / chat / task / session
228
- continuations). Core + HITL stay immune; skill/MCP activations may later LRU-defer.
217
+ continuations). Activations are sticky for the session; nothing is evicted.
229
218
  MUST NOT: Reuse a stale pre-discover `llmTools` array across tool-loop iterations —
230
219
  that makes activation a no-op and causes discover_tools death spirals.
231
220
  MUST: Consecutive `discover_tools` calls (any args) ≥ 5 MUST be treated as a
232
221
  critical loop and break the tool loop.
233
222
 
234
- Test IDs: `A-tooldef-budget`, `A-tooldef-sticky-capped`, `S-catalog-not-in-tooldef`,
235
- `S-discover-activated-protected`, `S-discover-tools-spin`.
223
+ Test IDs: `S-discover-activated-protected`, `S-discover-tools-spin`.
236
224
 
237
225
  ### §5.1 max_tokens reservation clamp (§Afford.S4)
238
226
 
@@ -339,3 +327,132 @@ Live (operator):
339
327
  4. Complex task complete → distillation (Habits encode; skill install via §8.3 HITL)
340
328
  5. Deliverable update returns `version` bump
341
329
  6. `acceptTask(..., notes)` stores `approved_with_notes`
330
+
331
+ ## §12 Clock and heartbeat
332
+
333
+ `AgentClock` is the single periodic driver, and a heartbeat is no longer a **message**. The earlier
334
+ design had two timers (a heartbeat scheduler and `AgentClock` both owning a `setInterval`) and
335
+ modelled every tick as a `mailbox_items` queue row, which carried retention, triage and drop
336
+ semantics a tick never needed — `heartbeat` rows dominated the completed population (~70% of
337
+ `mailbox_items`). Both are gone (Forever Loop M6).
338
+
339
+ | Invariant | How it is enforced |
340
+ |---|---|
341
+ | **One clock, two sources** | `AgentClock` is the only periodic driver **of the agent runtime**: one timer per agent, coarse tick (`tickMs`, 1000 ms), each source keeping its own cadence and failure-isolated from the others. (The invariant is about the *agent cadence*, not about every `setInterval` in the process — unrelated subsystems keep their own: shell-session output polling, model-catalog refresh, OAuth device polling.) Exactly two sources are registered — `mailbox-maintenance` (defer release / lease reclaim / stale-row cleanup) and `trigger-expiry` (`rest(wakeOn)` expiry sweep + scheduled-wakeup sweep). **No heartbeat source exists on it**: a patrol is not time-driven at all — it runs only when the liveness fallback asks for one (`agent.triggerHeartbeat()` → `runHeartbeatPatrol()`), so the patrol interval is no longer a timer question, and a cadence change can never leave a second timer in the process. |
342
+ | **A tick is not a message** | The `heartbeat:trigger` listener runs the patrol directly. No `mailbox_items` row is produced, so the patrol has no retention, triage or age-based drop semantics. Re-entrancy is guarded by a single in-flight flag, which replaces the previous "heartbeat folding" inside `Mailbox.enqueue` — one guard, not two mechanisms. The `mailbox.enqueue('heartbeat')` row path is **gone**: cut 9 made `rest` the only sleep entry, so there is no rollback channel back to queue rows. |
343
+ | **One dream trigger** | The dream has no clock source: it is a **pre-sleep** act — `restOn()` runs `runDreamTick()` → `shouldRunDreamCycle` before parking, so the only producer is the decision to sleep. The `memory_consolidation` mailbox type is not a second entry link (and must not be subject to age-based dropping, otherwise the only cleaning task can be silently discarded when the queue is busy); in `clock` dream-path mode such a row is acknowledged, never replayed as a second trigger. |
344
+ | **One decision function** | `shouldRunDreamCycle` remains the only place that answers "should the dream run now". |
345
+
346
+ ---
347
+
348
+ ## Appendix A. State ownership contract
349
+
350
+ > **Status: living contract.** This describes how the code must behave today — update it in the same
351
+ > change that moves an owner.
352
+
353
+ > Why this document exists: pushing state down from "agent-level singleton" to "per-worker workspace"
354
+ > is the right direction, but it **legitimately changes** an implicit premise found all over the repo
355
+ > ("reading `currentSessionId` gives you this request's session").
356
+ > Changes of this kind don't throw errors, they compile, and all the old tests stay green — they only
357
+ > show up in production as "the agent has amnesia".
358
+ > So "who owns which state, who may read it, and in which context it may be read" has to be written down
359
+ > as a contract and enforced by machine.
360
+
361
+ **Applies to**: any change that touches session identity / history / concurrency / workspace state.
362
+
363
+ ---
364
+
365
+ ### A.1 The three execution contexts (first, figure out where you are)
366
+
367
+ | Context | When it occurs | `sessionWorkspaceStore.getStore()` | Default workspace |
368
+ |---|---|---|---|
369
+ | **HTTP thread** | `api-server` handling a request, SSE callbacks, route validation | `undefined` | `rootWorkspace` |
370
+ | **worker workspace** | an attention worker pool processing a mailbox item | that worker's workspace | that worker's workspace |
371
+ | **background timers / bare callbacks** | backstop timeouts, `setTimeout`, external events | `undefined` | `rootWorkspace` |
372
+
373
+ > The test: `private workspace() { return sessionWorkspaceStore.getStore() ?? this.rootWorkspace; }`
374
+ > Under concurrent mode (3 workers by default), **the HTTP thread and a worker do not see the same thing**.
375
+
376
+ ---
377
+
378
+ ### A.2 State ownership matrix (writer / reader / context)
379
+
380
+ | State | Ownership | Who writes | Who reads | Implicit reads allowed? |
381
+ |---|---|---|---|---|
382
+ | `currentSessionId` (in-memory session `sess_*`) | **per-worker** | the worker handling that item (restore / startNewSession / handle*) | the turn logic inside that same worker | ❌ **forbidden** to read across threads |
383
+ | `dbSessionMap` (`cs_*` → `sess_*` binding) | agent-level (shared across workers) | **written only in the worker handling that message** | anyone (looked up by DB id) | ✅ allowed (this is the only cross-thread-safe session bridge) |
384
+ | `MemoryStore.sessions` (the history itself) | agent-level singleton | `appendMessage` (inside a worker) | `getRecentMessages` / `getSession` | ✅ allowed (but an unknown id must warn — never silently return empty) |
385
+ | `chatSessionRepo` (`cs_*` persistence layer) | storage (out of process) | api-server (persist) | api-server / restore | ✅ allowed |
386
+ | `activeScenario` / `currentTaskId` / `turnModelOverride` / `currentInteractingUserId` | **per-worker** | same worker | same worker | ❌ forbidden to read across threads |
387
+ | `workerWorkspaces` / `workerStates` / `inFlightProcessing` | attention controller | attention itself | attention / targeted cancellation (**must carry workerId explicitly**) | ⚠️ only for targeted APIs that take a workerId |
388
+ | `session.summary` / fragments / slots | MemoryStore (singleton) | compactor | context assembly | ✅ allowed |
389
+
390
+ **In one sentence**: **per-worker things can never be obtained by "reading a global pointer"; they must be passed explicitly.**
391
+ The only session bridge that may be shared across threads is `dbSessionMap` (`cs_*` ↔ `sess_*`).
392
+
393
+ ---
394
+
395
+ ### A.3 Hard rules
396
+
397
+ 1. **DB ids and in-memory ids are never mixed**. `cs_*` is the request identity, `sess_*` is the internal cache key;
398
+ never use a `cs_*` directly as a `MemoryStore` key (that causes split-brain: one conversation splits into two stores).
399
+ 2. **Passing session identity across threads must be explicit**. For the HTTP thread to hand a session to a worker,
400
+ it may only go through the mailbox item's `extra.sessionHint` (normalized from the legacy `extra.sessionId` /
401
+ `extra.sessionRestore`), never through any shared pointer.
402
+ 3. **Session context is applied only in the workspace that handles that item**. "Eager restore" in the HTTP thread
403
+ is forbidden (it only writes `rootWorkspace`, which the worker never sees).
404
+ 4. **Failures must be visible**. Distinguish `found | missing | notLoaded`: the latter two must at minimum `log.warn`
405
+ with `dbSessionId / memorySessionId / agentId`. "Not found → return empty / create new / swallow the exception" is forbidden.
406
+ 5. **The binding may be written in exactly one place**: in the workspace that actually handles that message.
407
+ 6. **Targeted operations must carry a workerId** (cancellation, status queries, hot updates); inferring it from ALS is not allowed.
408
+
409
+ ---
410
+
411
+ ### A.4 Enforcement mechanisms already in place
412
+
413
+ | Mechanism | Location | What it protects |
414
+ |---|---|---|
415
+ | Streaming path carries the DB session id explicitly | `agent.ts` `sendMessageStream` → `extra.sessionHint` | rule R2 |
416
+ | Session resolution order "DB-bound in-memory session > workspace pointer > create new" | `resolveTurnSession` (single resolution point, called from `processMailboxItemCore`) | rule R1 |
417
+ | restore / binding executed in the workspace handling that item | `processMailboxItemCore` | rules R3/R5 |
418
+ | Lazy loading for history reads + warning on unknown id | `memory/store.ts` `getRecentMessages` | rule R4 |
419
+ | Invariant test suite | `packages/core/test/conversation-session-invariants.test.ts` | all of the above |
420
+ | Architecture gate | `scripts/architecture-guard.mjs` (must pass in CI) | bans `console.*`, bans empty `catch` |
421
+
422
+ ---
423
+
424
+ ### A.5 Checklist for adding/changing state
425
+
426
+ 1. Does this state belong to **agent level** or is it **per-worker**? (per-worker ⇒ it must be passed explicitly)
427
+ 2. Who writes it, who reads it, in which context? (fill it into the matrix in section 2 — **a blank cell is a risk**)
428
+ 3. What happens when it can't be read? Does it silently degrade? (it must be observable)
429
+ 4. Add an **invariant test** (not an assertion over an implementation snapshot), and do mutation validation (revert the fix → the case must go red).
430
+ 5. Does it affect the `worker=1` serial-equivalence contract? (equivalence must hold)
431
+
432
+ ---
433
+
434
+ ## Appendix B. Stop semantics — start and stop, nothing else
435
+
436
+ Owner rule (2026-11-08): **after an agent is stopped it must not start again on its own.** Only a
437
+ human can start it again, or the agent's own pending approval/question being answered. There are
438
+ **two verbs at two scopes** and no third:
439
+
440
+ | Scope | Actions | Meaning |
441
+ |-------|---------|---------|
442
+ | One agent | `start` / `stop` | Stop is sticky: only a human start revives it. |
443
+ | Whole team | `start` / `stop` | Start = start every member; stop = stop every member. |
444
+
445
+ There is **no pause / freeze / resume**, and no global "pause all": those were removed end to end
446
+ (HTTP routes, client methods, sidebar entry, WebSocket events, `isGlobalStopped()`/`globalPaused`,
447
+ i18n keys) because a third pair of verbs describing a temporary system-wide freeze is not something
448
+ a user can see or reason about.
449
+
450
+ MUST: **one writer** for "stopped by the human" — `agents.disabled` (persisted, written only when a
451
+ human presses stop). Runtime `status === 'offline'` must never be read as that intent: it also covers
452
+ crashed and never-started. MUST: one gate enforces the rule, not twelve call sites. A human action
453
+ may overturn the human's own earlier decision ("start team" starts members that had been stopped
454
+ individually); only **agent-initiated** paths are blocked by a stop.
455
+
456
+ The incident that produced this rule — twelve start paths, eleven of them keyed off "is it offline",
457
+ three of them reachable by an agent — is recorded in
458
+ [`records/agent-stop-intent-audit-2026-11-08.md`](../records/agent-stop-intent-audit-2026-11-08.md).