@markus-global/cli 0.11.2 → 0.11.3-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/commands/start.js +5 -2
  2. package/dist/commands/start.js.map +1 -1
  3. package/dist/markus.mjs +1254 -1121
  4. package/dist/web-ui/assets/{CommentInput-Cgu8208h.js → CommentInput-C-niUbUY.js} +1 -1
  5. package/dist/web-ui/assets/{ContentRenderer-rzRUDj8T.js → ContentRenderer-DxsnJJRX.js} +2 -2
  6. package/dist/web-ui/assets/{DeliverableShareModal-BvfmqTNG.js → DeliverableShareModal-DV3TiZx0.js} +1 -1
  7. package/dist/web-ui/assets/{Deliverables-DKTLnaF8.js → Deliverables-tlLsJnxZ.js} +1 -1
  8. package/dist/web-ui/assets/{Notifications-CWaO9onn.js → Notifications-4KXYRdkr.js} +1 -1
  9. package/dist/web-ui/assets/{Search-D_C5Eyed.js → Search-CPFwZv1U.js} +1 -1
  10. package/dist/web-ui/assets/{Settings-B5Ib6SFf.js → Settings-DIa-_qre.js} +6 -6
  11. package/dist/web-ui/assets/{Store-D__pfqoc.js → Store-JWjwXfTU.js} +1 -1
  12. package/dist/web-ui/assets/Team-COBxn96h.js +84 -0
  13. package/dist/web-ui/assets/{Work-BJ7kXixx.js → Work-BScJUqWL.js} +1 -1
  14. package/dist/web-ui/assets/{arc-BN0GMYN6.js → arc-DPZmpo1U.js} +1 -1
  15. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-BP5Nnl2Y.js → architectureDiagram-3BPJPVTR-DlOs02JO.js} +1 -1
  16. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-nKHUCU_z.js → blockDiagram-GPEHLZMM-C7qsXNUe.js} +1 -1
  17. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-DoS0wcHh.js → c4Diagram-AAUBKEIU-Drwp-rtM.js} +1 -1
  18. package/dist/web-ui/assets/channel-DCChB-1T.js +1 -0
  19. package/dist/web-ui/assets/{chunk-2J33WTMH-CP54_XNl.js → chunk-2J33WTMH-VgR09Mqk.js} +1 -1
  20. package/dist/web-ui/assets/{chunk-4BX2VUAB-DMvJaJb7.js → chunk-4BX2VUAB-CuwDpBRL.js} +1 -1
  21. package/dist/web-ui/assets/{chunk-55IACEB6-DQnZgoOO.js → chunk-55IACEB6-nC7YWJ_i.js} +1 -1
  22. package/dist/web-ui/assets/{chunk-727SXJPM-B5_3LI53.js → chunk-727SXJPM-Dw6mBsRE.js} +1 -1
  23. package/dist/web-ui/assets/{chunk-AQP2D5EJ-B5Mh5bI_.js → chunk-AQP2D5EJ-CPhNJbHl.js} +1 -1
  24. package/dist/web-ui/assets/{chunk-FMBD7UC4-mjYTpuBm.js → chunk-FMBD7UC4-AyhQakG8.js} +1 -1
  25. package/dist/web-ui/assets/{chunk-ND2GUHAM-BxTrseJg.js → chunk-ND2GUHAM-DgYemv8I.js} +1 -1
  26. package/dist/web-ui/assets/{chunk-QZHKN3VN-C1do5brE.js → chunk-QZHKN3VN-CLdqxrFB.js} +1 -1
  27. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-CrNiYfSI.js +1 -0
  28. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-CrNiYfSI.js +1 -0
  29. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-DMn7aSDK.js → cose-bilkent-S5V4N54A-DrOgwDIH.js} +1 -1
  30. package/dist/web-ui/assets/{dagre-BM42HDAG-CE-tTagY.js → dagre-BM42HDAG-DhoJiA83.js} +1 -1
  31. package/dist/web-ui/assets/{diagram-2AECGRRQ-BwyvxbJa.js → diagram-2AECGRRQ-BDILSgqK.js} +1 -1
  32. package/dist/web-ui/assets/{diagram-5GNKFQAL-Nopndxl0.js → diagram-5GNKFQAL-CeXywd1i.js} +1 -1
  33. package/dist/web-ui/assets/{diagram-KO2AKTUF-CGTjHHnD.js → diagram-KO2AKTUF-Bi4RlMT0.js} +1 -1
  34. package/dist/web-ui/assets/{diagram-LMA3HP47-DhC3AqLA.js → diagram-LMA3HP47-Cw1yxk8b.js} +1 -1
  35. package/dist/web-ui/assets/{diagram-OG6HWLK6-BIuzyWJO.js → diagram-OG6HWLK6-Bl857da2.js} +1 -1
  36. package/dist/web-ui/assets/{docx-preview-ClO_djcO.js → docx-preview-CjoUhrMq.js} +1 -1
  37. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-Nmfi9Wv0.js → erDiagram-TEJ5UH35-DEiaMhuV.js} +1 -1
  38. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-BVAM5QzO.js → flowDiagram-I6XJVG4X-BgKZhO0h.js} +1 -1
  39. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-BGdTbY0A.js → ganttDiagram-6RSMTGT7-Dkx-EaS8.js} +1 -1
  40. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-BMfug5mp.js → gitGraphDiagram-PVQCEYII-DXaQwA0y.js} +1 -1
  41. package/dist/web-ui/assets/{index-1X1Ykov8.js → index-C_QhfMcC.js} +72 -72
  42. package/dist/web-ui/assets/index-DEN_qReg.css +1 -0
  43. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-DAqSLNMU.js → infoDiagram-5YYISTIA-Dpx9IOkx.js} +1 -1
  44. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-Bro4RrlG.js → ishikawaDiagram-YF4QCWOH-BWqWgitQ.js} +1 -1
  45. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-CdRHOaID.js → journeyDiagram-JHISSGLW-BBwIZ4k9.js} +1 -1
  46. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-9iLNl-rB.js → kanban-definition-UN3LZRKU-C_MRWV8R.js} +1 -1
  47. package/dist/web-ui/assets/{mermaid.core-BRHCbDDt.js → mermaid.core-BMAh3nnq.js} +5 -5
  48. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-BLm-XQ6W.js → mindmap-definition-RKZ34NQL-B6vJQcat.js} +1 -1
  49. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-ith90T5A.js → pieDiagram-4H26LBE5-BxdEttqt.js} +1 -1
  50. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-Cb08oHG7.js → quadrantDiagram-W4KKPZXB-gsNs2VfP.js} +1 -1
  51. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-DzMKi4w8.js → requirementDiagram-4Y6WPE33-BSC9KvC2.js} +1 -1
  52. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-C0Wv4A7m.js → sankeyDiagram-5OEKKPKP-DktAZfe_.js} +1 -1
  53. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-C_HL9WB0.js → sequenceDiagram-3UESZ5HK-BIPt8kGU.js} +1 -1
  54. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-BFfTVEYQ.js → stateDiagram-AJRCARHV-DiXmJWB0.js} +1 -1
  55. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-COOgTXIX.js +1 -0
  56. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-cyPnAADn.js → timeline-definition-PNZ67QCA-LRi7H35g.js} +1 -1
  57. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-Cb82-9OZ.js → vennDiagram-CIIHVFJN-DWQ1I022.js} +1 -1
  58. package/dist/web-ui/assets/{wardley-L42UT6IY-BTW1NXXR.js → wardley-L42UT6IY-BUb6dYqN.js} +1 -1
  59. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-C_F_dT6n.js → wardleyDiagram-YWT4CUSO-BYE1B3xT.js} +1 -1
  60. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-clcfplhG.js → xychartDiagram-2RQKCTM6-D-pS2-Sa.js} +1 -1
  61. package/dist/web-ui/index.html +2 -2
  62. package/docs/README.md +93 -0
  63. package/docs/api/api.md +353 -0
  64. package/docs/architecture/agent-runtime.md +341 -0
  65. package/docs/architecture/architecture-fragility.md +184 -0
  66. package/docs/architecture/architecture.md +938 -0
  67. package/docs/architecture/cognitive-architecture.md +322 -0
  68. package/docs/architecture/concurrent-processing.md +550 -0
  69. package/docs/architecture/frontend/team-chat.md +312 -0
  70. package/docs/architecture/learning-loop.md +340 -0
  71. package/docs/architecture/llm-provider-timeouts.md +60 -0
  72. package/docs/architecture/mailbox-system.md +1635 -0
  73. package/docs/architecture/memory-system.md +533 -0
  74. package/docs/architecture/prompt-engineering.md +1377 -0
  75. package/docs/architecture/state-machines.md +665 -0
  76. package/docs/architecture/state-ownership.md +83 -0
  77. package/docs/architecture/streaming-and-reattach.md +193 -0
  78. package/docs/architecture/tool-system.md +266 -0
  79. package/docs/design/deliverable-sharing.md +238 -0
  80. package/docs/guides/coding-tools.md +765 -0
  81. package/docs/guides/community.md +104 -0
  82. package/docs/guides/development.md +179 -0
  83. package/docs/guides/guide.md +362 -0
  84. package/docs/guides/release-and-distribution.md +165 -0
  85. package/docs/guides/remote-access.md +286 -0
  86. package/docs/guides/skill-ecosystem.md +129 -0
  87. package/docs/records/agent-platform-friction-2026-10.md +98 -0
  88. package/docs/records/animation-budget-focus-vs-visibility-2026-10-08.md +110 -0
  89. package/docs/records/audit-fixes-2026-09.md +173 -0
  90. package/docs/records/branch-consolidation.md +597 -0
  91. package/docs/records/file-edit-literal-replacement-fix.md +132 -0
  92. package/docs/records/message-stop-cancel-fix-plan.md +209 -0
  93. package/docs/records/platform-hardening-2026-10.md +1365 -0
  94. package/docs/records/session-identity-plan.md +130 -0
  95. package/docs/records/settings-model-routing-first-visit-fix.md +101 -0
  96. package/docs/records/team-chat-stream-transport-vs-turn-2026-10-08.md +152 -0
  97. package/package.json +2 -1
  98. package/templates/roles/HANDBOOK.md +12 -7
  99. package/dist/web-ui/assets/Team-FFbGLcXj.js +0 -84
  100. package/dist/web-ui/assets/channel-C_kHFvaW.js +0 -1
  101. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-UF2PuXCi.js +0 -1
  102. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-UF2PuXCi.js +0 -1
  103. package/dist/web-ui/assets/index-3PQIqBtv.css +0 -1
  104. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-DuO1A2q2.js +0 -1
@@ -0,0 +1,550 @@
1
+ # Concurrent Processing
2
+
3
+ > Status: **implemented** · Last updated: 2026-09-11
4
+ > Scope: how a single agent processes **multiple mailbox items / sessions at once**
5
+ > through a pool of isolated workers, while preserving factual consistency.
6
+ > Design origin: the original design memo (rationale, alternatives, phase plan) — superseded by this
7
+ > document and retired; recoverable from git history.
8
+
9
+ Related docs: [mailbox-system.md](./mailbox-system.md) (queue, priority, attention),
10
+ [architecture.md](./architecture.md) (runtime overview),
11
+ [streaming-and-reattach.md](./streaming-and-reattach.md) (streaming, stop / reattach),
12
+ [cognitive-architecture.md](./cognitive-architecture.md) (attention & cognition),
13
+ [state-machines.md](./state-machines.md) (task/requirement FSM).
14
+
15
+ ---
16
+
17
+ ## 1. Overview
18
+
19
+ By default Markus models an agent as a **single-threaded cognitive entity**: every
20
+ stimulus flows through one mailbox and the attention controller focuses on one item at a
21
+ time. That serialisation is deliberate — it is what keeps the agent's beliefs about the
22
+ world consistent.
23
+
24
+ **Concurrent processing** relaxes *where* the serialisation happens, not *whether* it
25
+ happens. When enabled, an agent runs a **pool of N worker loops**, each a full but
26
+ independent consumer of the same mailbox:
27
+
28
+ - Workers run in **parallel across different entities** (different task, requirement,
29
+ conversation, or user).
30
+ - Within any single entity, processing is still **strictly serial** — enforced by an
31
+ *entity-affinity lock* in the mailbox.
32
+ - Workers do not share mutable session state: each mounts its own
33
+ [`SessionWorkspace`](../../packages/core/src/session-workspace.ts) via `AsyncLocalStorage`.
34
+ - Worker activity is made visible to every other worker through a persistent
35
+ **concurrent handoff log**, injected into the system prompt.
36
+
37
+ The invariant is simple to state:
38
+
39
+ > **Concurrency only ever happens *between* entities. A single entity is never
40
+ > processed by two workers at the same time.**
41
+
42
+ `maxWorkers = 1` reproduces the pre-concurrency behaviour exactly — that is the
43
+ compatibility floor and the regression contract.
44
+
45
+ ---
46
+
47
+ ## 2. Configuration
48
+
49
+ Stored under the `agent` section of `~/.markus/markus.json` and surfaced in
50
+ **Settings → Concurrent Processing** (see `packages/web-ui/src/pages/Settings.tsx`).
51
+
52
+ ```jsonc
53
+ {
54
+ "agent": {
55
+ "concurrent": {
56
+ "enabled": true, // master switch — DEFAULT ON (maxWorkers=3)
57
+ "maxWorkers": 3, // 1 = serial (identical to legacy); 1–10
58
+ "conflictPolicy": "auto" // auto = requeue & retry; report = emit conflict event
59
+ }
60
+ }
61
+ }
62
+ ```
63
+
64
+ | Field | Type | Default | Meaning |
65
+ |-------|------|---------|---------|
66
+ | `enabled` | boolean | **`true`** | Master switch. `false` forces serial mode (worker count 1). |
67
+ | `maxWorkers` | number | **`3`** | Worker count, clamped to `[1, 10]`. `1` = serial. |
68
+ | `conflictPolicy` | `'auto' \| 'report'` | `'auto'` | Behaviour when a worker meets a locked entity. |
69
+
70
+ ### Unified concurrency gate (one knob, two limits)
71
+
72
+ `maxWorkers` is the **single source of truth** for how much concurrency an agent has.
73
+ It drives *both* limits, which used to be two independent and mutually contradicting
74
+ knobs (`maxWorkers` vs `profile.maxConcurrentTasks`, defaulting to 1):
75
+
76
+ | Limit | Derived value | Where |
77
+ |---|---|---|
78
+ | Attention worker count | `enabled ? clamp(maxWorkers, 1, 10) : 1` | `AttentionController.setWorkerCount` |
79
+ | Task-execution concurrency | `min(worker count, profile.maxConcurrentTasks ?? worker count)` | `TaskExecutor → TaskQueue` |
80
+
81
+ Consequences:
82
+
83
+ - **No more drift.** `Agent.applyConcurrency()` is the one entry point (constructor and
84
+ the live `AgentManager.concurrentConfig` hot-update both call it), so the worker pool
85
+ and the task queue can never disagree.
86
+ - **`min`, never `max`.** Task concurrency can never exceed worker concurrency, so
87
+ `maxWorkers = 1` still implies fully serial task execution (the equivalence contract
88
+ holds without a special case).
89
+ - **`profile.maxConcurrentTasks` is now a ceiling, not the gate.** It can only make task
90
+ concurrency *tighter*. Leaving it unset means task concurrency follows `maxWorkers`
91
+ (previously it silently stayed at 1, so three workers would pick up three task items
92
+ while the queue admitted one — the other two workers blocked, and task throughput was
93
+ pinned at 1).
94
+ - **Turning concurrency off really turns it off.** Previously the live-update path only
95
+ applied `enabled: true`, so unchecking the switch left running agents at their old
96
+ worker count until a restart.
97
+
98
+ **Default-value note.** The runtime default is *enabled with 3 workers*. The type
99
+ declaration (`packages/shared/src/types/agent.ts` → `AgentConcurrentConfig`), the
100
+ settings API (`packages/org-manager/src/api-server.ts`), and the Settings UI all agree on
101
+ this. To run serially, explicitly set `"enabled": false` (or `maxWorkers: 1`).
102
+
103
+ Changing the setting at runtime calls `AttentionController.setWorkerCount(n)`, which
104
+ restarts the worker pool to apply the new count — no agent restart required.
105
+
106
+ ---
107
+
108
+ ## 3. Architecture
109
+
110
+ ```
111
+ ┌────────────────────────────────────────────┐
112
+ AgentMailbox ──────►│ AttentionWorkerPool (N workers) │
113
+ (priority queue, │ │
114
+ entity locks) │ worker 1 ── dequeueAsync() ──► item A │
115
+ │ worker 2 ── dequeueAsync() ──► item B │
116
+ │ worker 3 ── dequeueAsync() ──► item C │
117
+ └───────────────┬────────────────────────────┘
118
+ │ each worker runs an isolated
119
+ │ SessionWorkspace (AsyncLocalStorage)
120
+ ▼
121
+ processFocusedItem(item) — unchanged state machine
122
+ │
123
+ ┌───────────────────────┼────────────────────────┐
124
+ entity lock handoff log tool write lock
125
+ (mailbox, per entity) (JSONL, per agent) (agent-level FIFO)
126
+ ```
127
+
128
+ ### 3.1 Worker pool — `packages/core/src/attention.ts`
129
+
130
+ Serial mode launches one `runLoop` (`workerCount === 1`). Concurrent mode launches
131
+ `launchWorkerPool()`, spawning one `concurrentWorkerLoop(workerId, gen)` per worker.
132
+
133
+ Each `concurrentWorkerLoop` is a **pure consumer**:
134
+
135
+ ```
136
+ while (running) {
137
+ item = await mailbox.dequeueAsync(); // one item, never repeats
138
+ keys = mailbox.entityKeysOf(item); // ≥1 key; falls back to system:{agentId}
139
+ if (!mailbox.lockEntities(keys, item.id)) { // multi-key, all-or-nothing
140
+ mailbox.putBack(item); // busy → back off & retry
141
+ await sleep(250 + min(retryCount,8)*250);
142
+ continue;
143
+ }
144
+ const ws = delegate.getWorkerWorkspace(workerId);
145
+ await sessionWorkspaceStore.run(ws, () => processFocusedItem(item));
146
+ mailbox.unlockEntities(keys, item.id);
147
+ }
148
+ ```
149
+
150
+ <!-- verified-against-code: 2026-09-11, packages/core/src/attention.ts:798-806, packages/core/src/mailbox.ts:437-489 -->
151
+
152
+ Design choice — **"concurrency without interruption" (Scheme A)**: the worker loop
153
+ deliberately does **not** run triage, LLM deliberation, or interrupt/preempt logic.
154
+ Those remain the serial `runLoop`'s job. This keeps the concurrent path small and
155
+ predictable: a worker only ever dequeues, locks, processes, unlocks, and loops.
156
+
157
+ - `workerCount === 1` → the original `runLoop` is used verbatim (no behavioural drift).
158
+ - Worker state (current focus, processing start time, in-flight user cancel) is held
159
+ per worker in `workerStates: Map<number, AttentionWorkerState>`.
160
+ - `gen` (loop generation) guards against stale loops: bumping the generation makes the
161
+ old pool drain and exit before a new pool starts.
162
+ - Aggregate status: any worker non-idle ⇒ agent not idle (`activeWorkerCount()`,
163
+ `getStatus()`).
164
+
165
+ ### 3.2 Session state isolation — `packages/core/src/session-workspace.ts`
166
+
167
+ Every mutable field that used to be a **single value on the Agent instance** is moved
168
+ into a per-worker `SessionWorkspace`:
169
+
170
+ | Workspace field | Replaces (agent-level single value) |
171
+ |---|---|
172
+ | `workerId` | — (new; worker identity) |
173
+ | `currentSessionId` | `Agent.currentSessionId` |
174
+ | `currentTaskId` | `Agent.currentTaskId` |
175
+ | `currentInteractingUserId` | `Agent.currentInteractingUserId` |
176
+ | `activeScenario` | `Agent.activeScenario` |
177
+ | `pendingInjections` | `Agent.pendingInjections` |
178
+ | `activeStreamToken` | `Agent.activeStreamToken` |
179
+ | `currentActivity` | `AgentState.currentActivity` |
180
+ | `processingMailboxItemId` | `Agent.processingMailboxItemId` |
181
+ | `lastInjectedActivityType` | dedup hint for injected activities |
182
+ | `turnModelOverride` | per-turn model pick |
183
+ | `volatileState` / `pendingDeliberationResult` | per-turn transient state |
184
+ | `toolSticky` | `Agent.toolSticky` (recent/activated tool schema names) |
185
+ | `activatedSkills` | `Agent.activatedSkillInstructions` (skill instruction bodies) |
186
+
187
+ The last two rows were found the hard way (2026-09-16). Both were **keyed by session but
188
+ stored on the Agent instance** — an incoherent combination: with N workers handling N
189
+ sessions, all workers share one object, so every session switch reset it. Consequences:
190
+ the emitted `tools` schema drifted call-to-call (a cache-prefix break, since tool schemas
191
+ serialise ahead of the system prompt), and a `discover_tools` activation could vanish
192
+ mid-session — the documented `discover_tools → think → discover_tools` spiral. The skill
193
+ map additionally leaked in **serial** mode, since it was neither keyed nor reset: a skill
194
+ body activated in session A stayed in every later session's system prompt.
195
+
196
+ **Rule:** assembly state that is keyed by session must also be stored per worker. The
197
+ session key is retained (not dropped) so that, in serial mode with one root workspace,
198
+ switching sessions still drops the previous session's state instead of leaking it.
199
+
200
+ Guard test: `agent-worker-scoped-state.test.ts` — two workspaces on different sessions must
201
+ not clobber each other's sticky tools in either order, and a skill activated in session A
202
+ must be absent from session B in both serial and concurrent modes.
203
+
204
+ The workspace is bound to the async call chain via a process-level
205
+ `AsyncLocalStorage` (`sessionWorkspaceStore`). Code that previously read
206
+ `this.currentSessionId` now reads `this.workspace.currentSessionId`, so awaited
207
+ continuations inside a worker always see *their own* state.
208
+
209
+ - **Serial mode**: all processing shares `rootWorkspace` — semantically identical to the
210
+ old instance-level fields.
211
+ - **Concurrent mode**: each worker mounts a distinct workspace; `currentActivity` no
212
+ longer overwrites across workers, and live activities are aggregated by
213
+ `Agent.getLiveActivities()`.
214
+
215
+ ### 3.3 Mailbox changes — `packages/core/src/mailbox.ts`
216
+
217
+ Two additions make the queue safe for multiple consumers:
218
+
219
+ 1. **Broadcast wake-up.** `dequeueAsync()` parks waiters in `idleWaiters: Set<() => void>`
220
+ instead of a single resolver; `wakeIdleLoop()` wakes *all* of them. Each woken worker
221
+ re-runs `dequeue()`, and the `shift()`-style splice gives mutual exclusion — exactly
222
+ one worker wins each item. The arm-before-recheck pattern prevents lost wakeups.
223
+
224
+ 2. **Entity-affinity locks.** `entityKeysOf(item)` → `lockEntities(keys, holder)` /
225
+ `unlockEntities(keys, holder)`. The worker locks **every** entity dimension of an item
226
+ at once (all-or-nothing), and `dequeue()` skips any item that shares a locked key, so
227
+ two workers can never hold the same entity:
228
+
229
+ ```
230
+ entityKeysOf(item): // ≥1 key, never empty
231
+ task:{taskId} ← payload.taskId / metadata.taskId
232
+ req:{requirementId} ← payload.requirementId
233
+ conv:{dbSessionId|sessionId} ← metadata.dbSessionId / metadata.sessionId
234
+ user:{senderId} ← metadata.senderId
235
+ channel:{channelKey} ← payload.extra.channelKey (a2a_message)
236
+ system:{agentId} ← fallback when no concrete entity resolves
237
+ ```
238
+
239
+ The per-type scope list is **declarative** — `MAILBOX_TYPE_REGISTRY[type].entityScopes`
240
+ in `@markus/shared`, resolved by `resolveEntityKeys` — so no item type is left unkeyed:
241
+ `a2a_message` locks its channel, and `heartbeat` / group chats fall back to
242
+ `system:{agentId}` (serial within one agent). The key convention matches the
243
+ pre-existing `consolidateByEntity` merge logic. (`entityKeyOf()` / `lockEntity()` /
244
+ `unlockEntity()` survive as single-key conveniences for logging / handoff, but locking
245
+ always goes through the multi-key API.)
246
+
247
+ <!-- verified-against-code: 2026-09-11, packages/core/src/mailbox.ts:437-489, packages/shared/src/types/mailbox.ts:102-118 -->
248
+
249
+ ## 4. Consistency model
250
+
251
+ Concurrency is safe only if every worker can reason about what the others are doing.
252
+ Three mechanisms provide that.
253
+
254
+ ### 4.1 Concurrent handoff log — `packages/core/src/concurrent-handoff.ts`
255
+
256
+ A lightweight, ordered, append-only log. Each worker writes one line at key lifecycle
257
+ points:
258
+
259
+ | `kind` | When | Purpose |
260
+ |---|---|---|
261
+ | `declared` | worker starts an item | declares intent → prevents duplicate work |
262
+ | `fact` | worker establishes a global fact | makes side effects visible |
263
+ | `done` | worker finishes / fails | summary of result + leftovers |
264
+ | `conflict` | worker meets a locked entity | surfaces contention |
265
+
266
+ - Storage: in-memory ring buffer (last `HANDOFF_MAX_KEEP = 64`) **plus** JSONL
267
+ persistence under the agent's data dir. `O_APPEND` single writes make concurrent
268
+ appends atomic — no interleaving, and history survives restart.
269
+ - `inFlight()` reconstructs "who is doing what right now" from `declared`/`fact`
270
+ records that have no matching `done`/`conflict`, paired by **(worker, entity)** — a
271
+ worker serving several entities keeps *all* of them visible (keying by `workerId`
272
+ alone silently dropped all but the last).
273
+ - The JSONL file **compacts** once `HANDOFF_COMPACT_THRESHOLD = 512` lines accumulate:
274
+ the in-memory ring buffer is rewritten wholesale, so the file is bounded by
275
+ `HANDOFF_MAX_KEEP + threshold` instead of growing without limit for the process
276
+ lifetime. Records `id`s combine `Date.now()` + an instance token + a process-monotonic
277
+ counter, so ids stay unique across instances *and* within a single millisecond.
278
+ - `clear()` **truncates** the file (`writeFileSync(path, '')`). The previous
279
+ `appendFileSync(path, '')` wrote zero bytes without truncating, so `load()` after a
280
+ restart resurrected records that had been "cleared".
281
+ - The log's lifetime is synced to the worker count: `applyConcurrency()` calls
282
+ `syncHandoffLog()` (create + `load()` when crossing into worker > 1, drop when falling
283
+ back to serial). Previously a hot-update from serial → concurrent never created the
284
+ log, so `getConcurrentContext()` silently returned nothing.
285
+
286
+ ### 4.2 Prompt injection — `packages/core/src/context-engine.ts`
287
+
288
+ `buildSystemPrompt` appends a **`## Concurrency Context(并发上下文)`** block when
289
+ concurrency is active and more than one worker is running. It contains:
290
+
291
+ - the current worker id and total worker count;
292
+ - other workers' in-flight intents;
293
+ - the most recent handoff records (`HANDOFF_CONTEXT_LIMIT = 8`, own records filtered);
294
+ - three consistency rules — *do not assume exclusive cognition*, *never process an
295
+ entity another worker holds*, *report conflicts instead of overwriting*.
296
+
297
+ The block is injected into the **volatile** segment only, so the stable prompt prefix
298
+ (and its cache) is untouched. This is precisely the owner's requirement: a worker knows
299
+ it is one of several, knows what others finished, and can avoid contradictory or
300
+ duplicate actions.
301
+
302
+ ### 4.3 Tool write lock — `packages/core/src/agent.ts` + `packages/core/src/resource-locks.ts`
303
+
304
+ > **History:** this section previously described `withToolWriteLock(fn)` as an
305
+ > "agent-level FIFO promise chain". That was replaced by **resource-domain locks**;
306
+ > the text below is the current truth.
307
+
308
+ `Agent.executeTool` gates every write-semantic tool through
309
+ `ResourceLockRegistry.withLocks()` (`resourceLocks.ts`). Read-only tools do not take a
310
+ lock. The lock is released on the throw path too (no leak).
311
+
312
+ **Domain table** — `Agent.WRITE_TOOL_DOMAINS` is the single source of truth
313
+ (`agent.ts`). Each entry maps a tool to a mutual-exclusion domain, optionally keyed by an
314
+ argument so that *different* resources run in parallel:
315
+
316
+ > **Grain: resources, not tool names (2026-09-16).** A domain keyed by tool name lets one
317
+ > resource have two non-conflicting write paths. Two real cases fixed:
318
+ > ① `update_notebook` was registered under domain `notebook` while its alias
319
+ > `update_working_memory` lived under `working-memory` — both write the **same** Map
320
+ > (`Agent.writeNotebookEntry`), yet they were judged non-conflicting, so the lock did
321
+ > nothing. (The alias has since been **removed** and the tool renamed `notebook_upsert`;
322
+ > the resource-key fix below is what makes any such duplication impossible.)
323
+ > ② `file_write knowledge.md` took `fs:<path>` while `memory_update` took
324
+ > `memory` — the same file, two mutually non-exclusive paths, so a hand edit could be
325
+ > **silently overwritten** by the next in-memory whole-file rewrite.
326
+ > Both are fixed by resolving tools to a **resource key** via
327
+ > `packages/core/src/lock-resources.ts` (`AGENT_MEMORY_RESOURCE_DOMAIN = 'agent-memory'`,
328
+ > `memoryResourceForPath()`, `memoryResourceLock()`). Table entries for memory tools now
329
+ > carry `{ domain: 'agent-memory', resource: 'knowledge' | 'notebook' }`, and
330
+ > `Agent.resourceLocksFor(toolCall, dataDir)` rewrites an `fs`-domain lock into the memory
331
+ > resource lock when the path names an agent memory file (`knowledge.md`, `NOTEBOOK.md`,
332
+ > `state.md`, `role/ROLE.md`, `role/HEARTBEAT.md`).
333
+ > Invariant pinned by `packages/core/test/lock-resource-keys.test.ts`: **same resource ⇒ same lock key**
334
+ > (incl. aliases and the `file_write` route), while distinct
335
+ > resources still run in parallel.
336
+
337
+ | Domain | Keyed by | Examples |
338
+ |---|---|---|
339
+ | `'*'` | — (global exclusive) | `shell_execute`, `apply_patch`, `package_install`, `hub_install`, `background_exec`, `process` |
340
+ | `fs` | normalized path | `file_write`, `file_edit`, `generate_image`, `office_generate` |
341
+ | `task` / `requirement` / `workflow` / `project` / `deliverable` | entity id | `task_update`, `requirement_update_status`, `workflow_run`, `deliverable_update` |
342
+ | `terminal` / `browser` | terminal id / page id | `exec_terminal`, `click`, `navigate_page` |
343
+ | `a2a-out` | target agent / channel | `agent_send_message`, `feishu_send_message` |
344
+ | `agent-memory` | **resource key** (`knowledge` / `notebook` / `identity` / `state`) | `memory_save`, `memory_update`, `memory_update_longterm`, `memory_delete`, `notebook_upsert` / `notebook_clear`, `file_write` / `file_edit` on an agent memory file |
345
+ | `session`, `session-tools`, `schedule`, `llm-config`, `org`, `ui`, `deliberation`, `mailbox-admin`, `notify` | single resource or item id | `session`, `discover_tools`, `team_update` |
346
+
347
+ **Classification is closed and test-enforced.** `Agent.isWriteTool` is *default-deny*:
348
+
349
+ 1. name ∈ `WRITE_TOOL_DOMAINS` → write (fine-grained domain);
350
+ 2. name ∈ `TOOL_LOCK_FREE` → **never locked** (pure readers; see below);
351
+ 3. otherwise → write with domain `tool:<name>`.
352
+
353
+ Two important subtleties:
354
+
355
+ - **`TOOL_LOCK_FREE` must stay exempt.** `request_user_input` / `request_user_approval`
356
+ **block on a human**, and `spawn_subagent(s)` run for minutes. If they took `'*'`, the
357
+ entire agent's writes would freeze for the whole wait. This is asserted by a test.
358
+ - **Unknown tools get `tool:<name>`, not `'*'`.** MCP/skill/dynamically-registered tools
359
+ are capability-unknown, but serialising *all* of them against *all* writes would break
360
+ the platform's "multiple tool calls in one turn run in parallel" contract and stall the
361
+ 20 MCP tool families we ship. Per-name mutual exclusion keeps two concurrent calls to
362
+ the *same* tool serialised (the common intra-tool race) while different tools stay
363
+ parallel. The residual (an unknown tool writing the *same file* as a concurrent
364
+ `file_write` is not mutually excluded) is listed in §7.
365
+ - **Nesting is fail-fast, not deadlock.** `LockNestingConflictError` is thrown when a
366
+ call chain requests a lock conflicting with one it already holds (`resource-locks.ts`).
367
+ The old `pump()` counted the chain's *own* locks as conflicts and would **hang
368
+ forever**; granting instead would silently weaken `'*'` exclusivity (another chain's
369
+ locks are not rolled back). A loud error is the only safe of the three.
370
+
371
+ **Session persistence under concurrency.** `MemoryStore.saveDebounce` is keyed by
372
+ `session.id` (`memory/store.ts`). A single instance-level timer meant worker B's save
373
+ cancelled worker A's pending write, silently dropping A's session from disk until the
374
+ next save. Session files, by contrast, are per-session (`sessions/<id>.json`), so
375
+ cross-session writes do not race.
376
+
377
+ **`knowledge.md` is NOT safe by "synchronous read-modify-write".** Each individual
378
+ `readFileSync`/`writeFileSync` is synchronous, but a *logical* update is
379
+ read → transform → write, and synchronous code still yields between those steps
380
+ whenever the read-modify-write spans an `await` — which it does on the dream-cycle
381
+ path. Concretely (see §4.9 defect registry):
382
+
383
+ - Tool-path writes (`memory_save` / `memory_update` / `notebook_upsert`) take the
384
+ `agent-memory:<resource>` lock (`knowledge` / `notebook`), so they mutually exclude.
385
+ - The dream cycle (`consolidateMemory` → `dreamConsolidateMemory(entries)`, whose result
386
+ lands through the store's write APIs) runs from a timer, **outside any tool
387
+ call**, and therefore **outside any lock**. A concurrent `memory_update` could land
388
+ between the dream's read and write and lose one of the two updates. (The old
389
+ `pruneMemoryMd()` → `compressLongTermMemory()` tail of this pipeline was removed —
390
+ `consolidateMemory()` now runs only the dream cycle.)
391
+
392
+ Fixed by wrapping the whole dream-critical section in
393
+ `resourceLocks.withLock(memoryResourceLock('knowledge'), …)`, so the dream cycle and
394
+ tool-path writes now share one exclusion key.
395
+
396
+ **The notebook has a second, subtler concurrency hazard: normalization writes.**
397
+ Once the notebook gained TTL + entry caps, "apply the invariants" became a
398
+ **mutating** step (it evicts). Doing that at injection time — the obvious place,
399
+ because that is where the entries are rendered — means *reading the prompt mutated
400
+ agent state*, so two concurrent workers rendering their prompts could both evict and
401
+ both persist, and the loser's write would resurrect entries the winner deleted.
402
+ It is therefore applied only at two race-safe points: **after load** (before any
403
+ worker starts) and **after every write** (already inside the writer, so serialized by
404
+ construction). Injection is then a pure read of already-legal state.
405
+
406
+ **Residual risk (backlog).** There is no *cross-process* mutex. Desktop and CLI
407
+ running the same agent concurrently can still interleave on `NOTEBOOK.md` /
408
+ `knowledge.md`. Fixing this needs a new process-coordination mechanism (file lock or
409
+ single-instance IPC) and is listed in §7.
410
+
411
+ ### 4.9 Shared mutable state — inventory, defects, and their guards
412
+
413
+ A single agent instance serves several workers. Entity locks keep *different entities* apart,
414
+ but everything an agent holds **outside** an entity is shared. This inventory is the check-list
415
+ to consult before adding a writer.
416
+
417
+ | Shared state | Scope | Owner / write path | Protection |
418
+ |---|---|---|---|
419
+ | Notebook map + `NOTEBOOK.md` | per-agent | `Agent.writeNotebookEntry` (single write path), persist debounce w/ 10 s maxWait | `agent-memory:notebook` lock; normalize-on-load + on-write (never at render time) |
420
+ | `knowledge.md` (curated + observations) | per-agent | `MemoryStore` (`addLongTermMemory`, `enforceMemoryBudgets`, `removeLongTermSection`) | `agent-memory:knowledge` lock; atomic write |
421
+ | Handoff log | per-agent | `ConcurrentHandoffLog` | debounced flush; bounded ring (64) |
422
+ | Entity locks | per-agent | `mailbox.entityKeyOf` | in-process map — **not** cross-process |
423
+ | `ResourceLockRegistry` | per-agent | `withLocks` | in-process map — **not** cross-process |
424
+ | Activated skills | **per session/worker** | `SessionWorkspace.activatedSkills` | correct by construction — the model example to copy |
425
+
426
+ Defect registry (found 2026-09-16; each row is a *fixed* bug kept as a regression anchor):
427
+
428
+ | ID | Defect | Root cause | Fix | Guard |
429
+ |---|---|---|---|---|
430
+ | **P0-1** | two paths to the same notebook Map (formal name + alias) never excluded each other | lock granularity was the **tool name**, and the alias was registered under a different domain (`working-memory`) | both resolve to `agent-memory:notebook` via `WRITE_TOOL_DOMAINS.resource` (the alias was later removed and the tool renamed `notebook_upsert`) | `lock-resource-keys.test.ts` — resource key equality + live serialisation |
431
+ | **P0-2** | a hand edit to `knowledge.md` / `NOTEBOOK.md` could be **silently overwritten** by the next in-memory whole-file rewrite | `file_write` took `fs:<path>` while `memory_update` took `memory` — same file, two non-exclusive paths | `Agent.resourceLocksFor(tc, dataDir)` rewrites an fs lock into the memory resource lock when the path names an agent memory file | same file — `file_write`/`file_edit` key equality |
432
+ | **P0-3** | two OS processes (desktop + CLI) on the same agent have **no** mutual exclusion | `ResourceLockRegistry` and entity locks are in-process maps | **not fixed** — needs a process-level arbiter (file lock / single-instance election) | listed in §7 |
433
+
434
+ Invariant to preserve when touching this area: **same resource ⇒ same lock key** — same resource ⇒ same
435
+ lock key, *including aliases and the generic-file-tool route* — while distinct resources must
436
+ stay parallel (a test asserts notebook∥knowledge concurrency is 2, not 1).
437
+
438
+ ## 5. Cancellation & streaming (Scheme B — directed cancel)
439
+
440
+ In serial mode, stopping a stream could target "the agent". Under concurrency that is
441
+ ambiguous — the wrong worker could be cancelled. The fix is a **directed cancel**:
442
+
443
+ - `cancelActiveStream(target?)` where `target = { itemId?, sessionId? }`.
444
+ - The caller (HTTP thread, which has **no** AsyncLocalStorage context of its own)
445
+ resolves the owning worker via
446
+ `AttentionController.findWorkerByItemId()` / `findWorkerBySessionId()`.
447
+ - Cancellation then runs *inside that worker's own workspace context* via
448
+ `sessionWorkspaceStore.run(ws, () => cancelActiveStreamCore())`, so only the intended
449
+ worker's stream is aborted.
450
+ - Frontend **stop** and **retry** paths pass a stable `sessionId` target so a stop in one
451
+ session tab never touches another tab's in-flight stream.
452
+
453
+ See [streaming-and-reattach.md](./streaming-and-reattach.md) for the stream lifecycle.
454
+
455
+ ## 6. Serial-mode equivalence (the regression contract)
456
+
457
+ `maxWorkers = 1` must be byte-for-byte equivalent to the pre-concurrency runtime:
458
+
459
+ | Concern | Serial (worker = 1) | Concurrent (worker > 1) |
460
+ |---|---|---|
461
+ | Loop | original `runLoop` | `concurrentWorkerLoop` × N |
462
+ | Workspace | shared `rootWorkspace` | one per worker |
463
+ | Attention/triage/deliberation | full pipeline | not run in worker loops |
464
+ | Entity lock | no-op (no contention) | enforced |
465
+ | Handoff log | written on lifecycle (harmless) | injected into prompts |
466
+ | Status | instance-level | aggregated across workers |
467
+
468
+ This equivalence is the reason the refactor could land incrementally (state isolation
469
+ first, workers second) and is asserted by the existing serial test suites.
470
+
471
+ ## 7. Known limitations
472
+
473
+ These are deliberate trade-offs, documented rather than hidden:
474
+
475
+ 1. **Entity-key coverage is per-entity, not global.** `entityKeysOf` covers `task:` /
476
+ `req:` / `conv:` / `user:` / `channel:` and always returns ≥1 key — unresolved items
477
+ (`heartbeat`, group chats without a channel) fall back to `system:{agentId}` — so
478
+ `a2a_message`, `heartbeat`, and group chats **are** entity-locked. The remaining gap is
479
+ the *shared* surface: two workers on **different** entities can still run multi-step
480
+ read-modify-write flows across the same *shared* files or global memory concurrently,
481
+ guarded only by the *soft* signal in the handoff log, not a hard lock. Extending
482
+ coverage to a global write arbiter is an architecture-level follow-up.
483
+
484
+ <!-- verified-against-code: 2026-09-11, packages/core/src/mailbox.ts:437-451, packages/shared/src/types/mailbox.ts:83-118 -->
485
+
486
+ 2. **Tool write lock granularity.** `withToolWriteLock` serialises a *single tool call*,
487
+ not an entire task/flow. It narrows but does not eliminate cross-tool interleaving.
488
+ Two further residuals are explicit:
489
+ - **Dynamic tools are capability-unknown.** A tool outside the builtin registry gets
490
+ domain `tool:<name>` (§4.3), so it is not mutually excluded from `file_write` /
491
+ `shell_execute` even if it mutates the same resources. Builtins are safe because a
492
+ test asserts every one of them is classified.
493
+ - **`background_exec` / `process` are protected at *dispatch*, not for the job's
494
+ lifetime.** The lock covers registering the job in the process table; the spawned
495
+ process then runs outside the lock and may write files concurrently with other
496
+ workers. Treat long background jobs as a handoff-log *fact*, not as lock-covered.
497
+
498
+ 3. **Write-lock nesting is fail-fast.** A call chain that requests a lock conflicting
499
+ with one it already holds raises `LockNestingConflictError` (§4.3) instead of
500
+ deadlocking. Channel that error into the model's tool result; do not retry the
501
+ identical call.
502
+
503
+ 4. **Backstop timeout cancellation is best-effort.** When `processFocusedItem`'s backstop
504
+ timeout fires, it cancels the in-flight stream and requeues the item. If the underlying
505
+ transport has already detached, an orphaned turn could still complete side effects
506
+ before the requeued item runs — a small double-side-effect window. (Noted in the code
507
+ comment in `attention.ts`.)
508
+
509
+ 5. **Conflict back-off.** Under `conflictPolicy: 'auto'`, a worker that loses the entity
510
+ lock backs off for `250ms × (1 + min(retryCount, 8))` before retrying, instead of
511
+ busy-waiting. `report` additionally emits an `agent:entity-conflict` event.
512
+
513
+ 6. **Cost.** N workers can mean up to N concurrent LLM calls. `maxWorkers` (default 3)
514
+ is the cost ceiling; low-value items can still be aggregated/merged by the mailbox.
515
+
516
+ 7. **Locking is in-process only (P0-3).** `ResourceLockRegistry` and the entity-lock map are
517
+ per-process structures. Two OS processes serving the same agent (desktop app + CLI) can
518
+ therefore both take the "same" lock and interleave writes to `knowledge.md` /
519
+ `NOTEBOOK.md` / the handoff log. Atomic file writes bound the damage (a torn file is never
520
+ parsed back) but do not prevent a lost update. Closing this needs an architecture-level
521
+ mechanism — file-based advisory locks or single-instance election — and is tracked as its
522
+ own piece of work; see [memory-system.md](./memory-system.md) §10.3.
523
+
524
+ ## 8. Testing
525
+
526
+ Concurrency-specific suites under `packages/core/test/`:
527
+
528
+ | File | Covers |
529
+ |---|---|
530
+ | `attention-concurrent.test.ts` | worker pool start/stop, directed cancel, conflict policy |
531
+ | `mailbox-concurrent.test.ts` | broadcast wake-up, entity lock/unlock, key derivation |
532
+ | `agent-concurrent-activity.test.ts` | per-worker `currentActivity` isolation |
533
+ | `agent-write-lock.test.ts` | domain-lock serialisation, per-path/per-entity parallelism, no-leak on throw, **write-tool classification totality**, lock-free HITL tools, unknown-tool per-name domain |
534
+ | `resource-locks.test.ts` | domain conflict matrix, FIFO fairness, reentrancy |
535
+ | `resource-locks-chain.test.ts` | **nested conflicting acquisition fails fast (no self-deadlock)**, cross-chain exclusion not weakened, parallel siblings still serialised |
536
+ | `concurrent-handoff.test.ts` | **`clear()` truncates disk**, `inFlight()` pairs by (worker, entity), **file compaction bound**, id uniqueness across instances, corrupt-line tolerance |
537
+ | `memory-session-debounce.test.ts` | **per-session debounce isolation** (two workers' sessions both persist) |
538
+ | `attention-directed-cancel.test.ts` | `cancelActiveStream(target)` routing |
539
+
540
+ `worker = 1` equivalence is covered by the pre-existing attention/mailbox suites, which
541
+ continue to pass unchanged.
542
+
543
+ **Gap:** there is no end-to-end mock test that drives *two workers through two complete
544
+ session message chains in parallel*, nor a full regression for "two items of the same
545
+ entity arriving concurrently". Adding one is the recommended next hardening step.
546
+
547
+ ---
548
+
549
+ > This document describes the system **as built**. For the original rationale,
550
+ > alternatives considered, and phase plan, see the design memo.