@markus-global/cli 0.12.4 → 0.12.5-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 (159) hide show
  1. package/dist/background-maintenance.d.ts +25 -0
  2. package/dist/background-maintenance.d.ts.map +1 -1
  3. package/dist/background-maintenance.js +61 -0
  4. package/dist/background-maintenance.js.map +1 -1
  5. package/dist/commands/im-inbound-origin.d.ts +38 -0
  6. package/dist/commands/im-inbound-origin.d.ts.map +1 -0
  7. package/dist/commands/im-inbound-origin.js +48 -0
  8. package/dist/commands/im-inbound-origin.js.map +1 -0
  9. package/dist/commands/start.d.ts.map +1 -1
  10. package/dist/commands/start.js +211 -46
  11. package/dist/commands/start.js.map +1 -1
  12. package/dist/markus.mjs +18520 -9886
  13. package/dist/web-ui/assets/{AsyncState-BTLUPIr1.js → AsyncState-ByYn1wrM.js} +1 -1
  14. package/dist/web-ui/assets/ChatComponents-Bwh8SlUV.js +14 -0
  15. package/dist/web-ui/assets/{ContentRenderer-BZXRiKE3.js → ContentRenderer-GLgoGp2a.js} +6 -6
  16. package/dist/web-ui/assets/DeliverableShareModal-CRfnRuR3.js +1 -0
  17. package/dist/web-ui/assets/{Deliverables-3Y3zjT_1.js → Deliverables-EFsnf6kU.js} +2 -2
  18. package/dist/web-ui/assets/MarkdownMessage-CaLBeMto.js +4 -0
  19. package/dist/web-ui/assets/{Search-BI3hk-5j.js → Search-COiaXUNr.js} +1 -1
  20. package/dist/web-ui/assets/{SendToChat-D_5zHO-k.js → SendToChat-DleryIlc.js} +1 -1
  21. package/dist/web-ui/assets/Settings-CzY8z2Yh.js +8 -0
  22. package/dist/web-ui/assets/{Store-B8ksRjHF.js → Store-C4VpQCM_.js} +1 -1
  23. package/dist/web-ui/assets/Switch-ByogYoGH.js +1 -0
  24. package/dist/web-ui/assets/Team-Cutq2J24.js +93 -0
  25. package/dist/web-ui/assets/Work-BO-mz-na.js +142 -0
  26. package/dist/web-ui/assets/{arc-VmvI7TpW.js → arc-mYv67jdD.js} +1 -1
  27. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-CTUtPasm.js → architectureDiagram-3BPJPVTR-Bzpz_1r6.js} +1 -1
  28. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-xeYAqtZJ.js → blockDiagram-GPEHLZMM-BBrLiivl.js} +1 -1
  29. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BiFgoGY5.js → c4Diagram-AAUBKEIU-BwDUoXA_.js} +1 -1
  30. package/dist/web-ui/assets/channel-Bx09lbhA.js +1 -0
  31. package/dist/web-ui/assets/{chunk-2J33WTMH-DueHBqOn.js → chunk-2J33WTMH-DCSfJ-S9.js} +1 -1
  32. package/dist/web-ui/assets/{chunk-4BX2VUAB-B8zgDfSV.js → chunk-4BX2VUAB-CI0n1b2H.js} +1 -1
  33. package/dist/web-ui/assets/{chunk-55IACEB6-DieD55CP.js → chunk-55IACEB6-DqlSWLrm.js} +1 -1
  34. package/dist/web-ui/assets/{chunk-727SXJPM-Do4Z9LQ0.js → chunk-727SXJPM-BtmAfGYV.js} +1 -1
  35. package/dist/web-ui/assets/{chunk-AQP2D5EJ-qrYsW5ml.js → chunk-AQP2D5EJ-BgkA4lpQ.js} +1 -1
  36. package/dist/web-ui/assets/{chunk-FMBD7UC4-BSz3QT1q.js → chunk-FMBD7UC4-DCSr1JH4.js} +1 -1
  37. package/dist/web-ui/assets/{chunk-ND2GUHAM-utDWSydt.js → chunk-ND2GUHAM-CETYBRRm.js} +1 -1
  38. package/dist/web-ui/assets/{chunk-QZHKN3VN-Cd86CYHV.js → chunk-QZHKN3VN-C58yD7lH.js} +1 -1
  39. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-DGZqU3iA.js +1 -0
  40. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-DGZqU3iA.js +1 -0
  41. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-Dc6cP9WW.js → cose-bilkent-S5V4N54A-BpvdK03m.js} +1 -1
  42. package/dist/web-ui/assets/{dagre-BM42HDAG-4b0Wf_6D.js → dagre-BM42HDAG-CZ1K-KD5.js} +1 -1
  43. package/dist/web-ui/assets/{diagram-2AECGRRQ-zS_j1Kf4.js → diagram-2AECGRRQ-D136Ok1V.js} +1 -1
  44. package/dist/web-ui/assets/{diagram-5GNKFQAL-CPo-_Ime.js → diagram-5GNKFQAL-Ji6qPYYV.js} +1 -1
  45. package/dist/web-ui/assets/{diagram-KO2AKTUF-CjHOA4_j.js → diagram-KO2AKTUF-B-s2RC-f.js} +1 -1
  46. package/dist/web-ui/assets/{diagram-LMA3HP47-CalZRF6K.js → diagram-LMA3HP47-COWaps70.js} +1 -1
  47. package/dist/web-ui/assets/{diagram-OG6HWLK6-DnLAhsLX.js → diagram-OG6HWLK6-bh6MvwWn.js} +1 -1
  48. package/dist/web-ui/assets/{docx-preview-uRVPnxwM.js → docx-preview-BRynUqJd.js} +1 -1
  49. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-L0nzlMSn.js → erDiagram-TEJ5UH35-DOPh2LlL.js} +1 -1
  50. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-Bdc3UwtW.js → flowDiagram-I6XJVG4X-B_kxDHIp.js} +1 -1
  51. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-CFRmj_qc.js → ganttDiagram-6RSMTGT7-DYBKHOkK.js} +1 -1
  52. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-B5hZwcoJ.js → gitGraphDiagram-PVQCEYII-D8_0BxLC.js} +1 -1
  53. package/dist/web-ui/assets/index-9SXWNIl0.css +1 -0
  54. package/dist/web-ui/assets/index-TAHyKznL.js +867 -0
  55. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-DVT4RgPd.js → infoDiagram-5YYISTIA-DayJP7Ws.js} +1 -1
  56. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-Bf7pvUY_.js → ishikawaDiagram-YF4QCWOH-vzxCYVSq.js} +1 -1
  57. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-NVRjJlnd.js → journeyDiagram-JHISSGLW-B-Fud82o.js} +1 -1
  58. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-Co7BKMut.js → kanban-definition-UN3LZRKU-DzuKdB65.js} +1 -1
  59. package/dist/web-ui/assets/{mermaid.core-CCf28Hq6.js → mermaid.core-D4ql87kI.js} +5 -5
  60. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-DepMhVEb.js → mindmap-definition-RKZ34NQL-DosvXt2g.js} +1 -1
  61. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-Cq9ANaI0.js → pieDiagram-4H26LBE5-DhXtMWhr.js} +1 -1
  62. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CUY0BWhQ.js → quadrantDiagram-W4KKPZXB-D33pLLOq.js} +1 -1
  63. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-D9fU5rCm.js → requirementDiagram-4Y6WPE33-B-iIz-XM.js} +1 -1
  64. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-CMHhuSQF.js → sankeyDiagram-5OEKKPKP-BMd9AFEW.js} +1 -1
  65. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-Bjx53SID.js → sequenceDiagram-3UESZ5HK-CI1MIdwo.js} +1 -1
  66. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DVvatKnO.js → stateDiagram-AJRCARHV-Bq6FKPW2.js} +1 -1
  67. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-8nMhmWY5.js +1 -0
  68. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-9I80LG9m.js → timeline-definition-PNZ67QCA-BDdmmSRo.js} +1 -1
  69. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-B82Deutq.js → vennDiagram-CIIHVFJN-DP2q5vY2.js} +1 -1
  70. package/dist/web-ui/assets/{wardley-L42UT6IY-BKXtp57W.js → wardley-L42UT6IY-Bw3fjszD.js} +1 -1
  71. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-DzqTzfYa.js → wardleyDiagram-YWT4CUSO-37bQUocJ.js} +1 -1
  72. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-TowyDWYu.js → xychartDiagram-2RQKCTM6-DnLDZyNC.js} +1 -1
  73. package/dist/web-ui/index.html +2 -2
  74. package/docs/README.md +50 -16
  75. package/docs/api/guides/websocket.md +43 -0
  76. package/docs/api/reference.md +657 -0
  77. package/docs/architecture/a2a-communication.md +303 -0
  78. package/docs/architecture/agent-runtime.md +145 -28
  79. package/docs/architecture/architecture.md +30 -11
  80. package/docs/architecture/cognitive-architecture.md +189 -15
  81. package/docs/architecture/concurrent-processing.md +190 -31
  82. package/docs/architecture/context-assembly.md +264 -0
  83. package/docs/architecture/derived-views.md +463 -0
  84. package/docs/architecture/desktop-auto-update.md +185 -0
  85. package/docs/architecture/facts.md +406 -0
  86. package/docs/architecture/learning-loop.md +11 -0
  87. package/docs/architecture/limits.md +79 -0
  88. package/docs/architecture/mailbox-system.md +786 -668
  89. package/docs/architecture/memory-system.md +1 -1
  90. package/docs/architecture/messaging-gateway.md +7 -0
  91. package/docs/architecture/notification-delivery.md +221 -0
  92. package/docs/architecture/notification-sounds.md +177 -0
  93. package/docs/architecture/prompt-engineering.md +171 -700
  94. package/docs/{design/remote-access-contract.md → architecture/remote-access.md} +4 -0
  95. package/docs/architecture/state-machines.md +288 -5
  96. package/docs/architecture/tool-loop-harness.md +362 -0
  97. package/docs/architecture/tool-system.md +40 -16
  98. package/docs/design/background-callback-in-turn-delivery-2026-11-22.md +95 -0
  99. package/docs/design/c10-0b-pick-identity-leak-2026-11-22.md +233 -0
  100. package/docs/design/c10-a-identity-columns-2026-11-22.md +182 -0
  101. package/docs/design/c10-c-trust-boundary-2026-11-23.md +222 -0
  102. package/docs/design/c10-external-adapters-plan-2026-11-19.md +448 -0
  103. package/docs/design/c8-residual-mechanisms-2026-11-15.md +984 -0
  104. package/docs/design/external-signal-decision-loop-2026-11-25.md +579 -0
  105. package/docs/guides/development.md +1 -1
  106. package/docs/{architecture → guides}/mailbox-audit-checklist.md +7 -0
  107. package/docs/guides/remote-access.md +1 -1
  108. package/docs/{design/agent-stop-intent-audit.md → records/agent-stop-intent-audit-2026-11-08.md} +4 -0
  109. package/docs/records/c10-l5-gate-verification-2026-11-26.md +72 -0
  110. package/docs/records/c10-l5-live-verification-2026-11-25.md +117 -0
  111. package/docs/records/cut6-c4-verification-2026-11-12.md +268 -0
  112. package/docs/records/cut6-mailbox-address-envelope-design-2026-11-12.md +871 -0
  113. package/docs/records/cut7-c7a-red-green-evidence-2026-11-13.md +105 -0
  114. package/docs/records/cut7-c7a-workunit-implementation-2026-11-13.md +116 -0
  115. package/docs/records/cut7-c7b-verification-2026-11-14.md +90 -0
  116. package/docs/records/cut7-live-verification-2026-11-14.md +33 -0
  117. package/docs/records/cut7-wiring-negative-cache-2026-11-14.md +64 -0
  118. package/docs/records/cut7-workunit-execution-plan-2026-11-13.md +206 -0
  119. package/docs/records/cut8-a-entity-keys-design-2026-11-14.md +377 -0
  120. package/docs/records/cut8-b-turn-delta-injection-2026-11-14.md +362 -0
  121. package/docs/records/cut8-c-single-clock-2026-11-14.md +119 -0
  122. package/docs/records/cut8-c-single-clock-design-2026-11-14.md +150 -0
  123. package/docs/records/cut8-d-2026-11-14.md +231 -0
  124. package/docs/records/cut8-live-verification-2026-11-14.md +1018 -0
  125. package/docs/records/cut9-adjacent-identity-paths-2026-11-15.md +200 -0
  126. package/docs/records/cut9-identity-declaration-2026-11-15.md +163 -0
  127. package/docs/records/cut9-inbox-dual-run-diff-2026-11-15.md +117 -0
  128. package/docs/records/cut9-live-verification-2026-11-15.md +222 -0
  129. package/docs/records/cut9-runtime-probe-2026-11-19.md +520 -0
  130. package/docs/{design/deliverable-sharing.md → records/deliverable-sharing-2026-08-12.md} +10 -3
  131. package/docs/records/identity-backlog-disposition-2026-11-22.md +143 -0
  132. package/docs/records/marketplace-orphan-freeze-2026-11-22.md +239 -0
  133. package/docs/{architecture/notify-user-context-truth.md → records/notify-user-context-truth-2026-10-28.md} +6 -0
  134. package/docs/{handoff → records}/remote-access-handoff.md +1 -1
  135. package/package.json +1 -1
  136. package/templates/roles/HANDBOOK.md +1 -1
  137. package/templates/skills/agent-building/SKILL.md +1 -1
  138. package/dist/web-ui/assets/ChatComponents-DTB3H_n2.js +0 -12
  139. package/dist/web-ui/assets/DeliverableShareModal-BwZP39nd.js +0 -1
  140. package/dist/web-ui/assets/MarkdownMessage-DVfFMzM9.js +0 -4
  141. package/dist/web-ui/assets/Settings-DTUjLhJY.js +0 -8
  142. package/dist/web-ui/assets/Switch-RmZHA47D.js +0 -1
  143. package/dist/web-ui/assets/Team-BRgI1zM9.js +0 -85
  144. package/dist/web-ui/assets/Work-nah0UYFz.js +0 -142
  145. package/dist/web-ui/assets/channel-s7K3KXLr.js +0 -1
  146. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-B2mHhFY8.js +0 -1
  147. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-B2mHhFY8.js +0 -1
  148. package/dist/web-ui/assets/index-CzHSs0Vd.css +0 -1
  149. package/dist/web-ui/assets/index-TPf50ZeO.js +0 -867
  150. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-92MmE2MZ.js +0 -1
  151. package/docs/api/api.md +0 -353
  152. package/docs/architecture/llm-provider-timeouts.md +0 -60
  153. package/docs/architecture/state-ownership.md +0 -83
  154. /package/docs/architecture/{frontend/team-chat.md → team-chat.md} +0 -0
  155. /package/docs/{analysis → records}/2026-10-29-a2a-cache-hit-rate.md +0 -0
  156. /package/docs/{fixes → records}/2026-11-12-session-expiry-and-mention-thinking.md +0 -0
  157. /package/docs/{handoff → records}/approval-tri-state-handoff.md +0 -0
  158. /package/docs/{design → records}/overview-attention-redesign.md +0 -0
  159. /package/docs/{remote-access/fast-path-plan.md → records/remote-access-fast-path-plan-2026-10-17.md} +0 -0
@@ -0,0 +1,362 @@
1
+ # Cut 8 · C8-B — In-turn delta injection: a contradicting fact lands inside the turn that is already running
2
+
3
+ > Branch `task/c8-b-turn-delta-injection` → PR into `feat/refactor-plan`.
4
+ > Stacked on C8-A (`9908feec`), because C8-A is the card that decides *where* a
5
+ > same-entity fact goes; C8-B decides *what that fact looks like* once it goes
6
+ > in-turn. PR notes the stack explicitly.
7
+ > Design + test plan written before the first red run; §7 records what the
8
+ > implementation corrected.
9
+
10
+ ---
11
+
12
+ ## 1. Symptom
13
+
14
+ A turn is a long computation. While it runs, the outside world changes: a task
15
+ is cancelled, a requirement is rejected, a reviewer reverts a decision, a
16
+ colleague corrects a fact the turn is currently acting on. Today the turn does
17
+ not see any of it until it ends — the mailbox item is queued behind the running
18
+ turn.
19
+
20
+ The damage is not "late information". It is **irreversible work done on a
21
+ premise that was already false**: files written, commits pushed, messages sent,
22
+ reviews submitted — all after the cancel arrived.
23
+
24
+ The other direction is equally wrong: pouring the whole mailbox into the next
25
+ LLM call on every tool round breaks prompt caching, floods the context, and
26
+ makes the turn unreproducible.
27
+
28
+ ## 2. Root cause
29
+
30
+ Two facts were conflated into one queue:
31
+
32
+ | fact | correct treatment |
33
+ |---|---|
34
+ | "something new happened **about this same piece of work**" | belongs to the running turn — it changes what the turn should do |
35
+ | "something new happened **elsewhere**" | belongs to the queue — it must not interrupt |
36
+
37
+ The queue answered both with "wait". Queueing is a *scheduling* statement
38
+ ("you will get your turn"), and it silently became a *correctness* statement
39
+ ("your premise is still true"). One mechanism, two meanings — R2.
40
+
41
+ The root-cause test: could this recur under a different name? Yes — any new
42
+ signal type (a new IM gateway, a webhook, a new review event) would queue behind
43
+ a running turn and be seen too late. So the fix cannot be a per-type special
44
+ case. It has to be a statement about the **entity** (same `work_unit_ref`) and
45
+ about **when** the turn looks (immediately before the next LLM call).
46
+
47
+ ## 3. Contract (the five criteria, each one falsifiable)
48
+
49
+ 1. **Effective in the current turn.** A contradicting fact produces a new
50
+ `agent_decisions` row with `decision_type='cancel'` *before the turn's next
51
+ LLM call*, not after the turn ends. No new table: `agent_decisions` already
52
+ exists (`id, agent_id, decision_type, mailbox_item_id, context, reasoning,
53
+ outcome, created_at`).
54
+ 2. **Ordering.** Injection happens *before* the LLM call it is meant to inform.
55
+ Proven with a recorder: a decision recorded during injection must appear
56
+ before the next `chat`/`chatStream` call in one ordered trace.
57
+ 3. **Empty injection must not break the cache — byte level, never `hitRate`.** Two
58
+ requests whose *logical* delta input is "nothing" must share a byte-identical
59
+ messages prefix (`sha256`), whatever produced that "nothing". The segment is
60
+ **tail-appended**: earlier messages are never rewritten, so the prefix cannot
61
+ move.
62
+ 4. **Tail-variable, never head-variable.** Every variable value lives at the end
63
+ of a stable template; the segment is emitted even when empty (`count: 0` +
64
+ `none`). Omitting a段 when the count is 0 changes the template's byte shape
65
+ and is forbidden.
66
+ 5. **Single writer.** No second store of "pending facts for this turn" is
67
+ introduced: the delta is a *read* over the one mailbox queue; the only write
68
+ is the appended session message and the one decision row.
69
+
70
+ ## 4. Design (as implemented)
71
+
72
+ ### 4.1 One pure module: `packages/core/src/turn-delta.ts`
73
+
74
+ ```
75
+ classifyTurnDelta(row) -> 'contradiction' | 'authoritative' | 'decision' | null
76
+ buildTurnDeltaSegment({ snapshotSeq, rows }) -> { text, items, omitted, decision }
77
+ ```
78
+
79
+ * **Entity filter is upstream** (the query), so this module cannot decide "is it
80
+ about the same thing" — it only classifies rows it is given.
81
+ * Classification is **structural**, in this order:
82
+ 1. `contradiction` — the envelope carries `invalidatesPremise` or a non-empty
83
+ `supersedes` (a cancel / reject / revert / correction has to say so in a
84
+ field, not in prose).
85
+ 2. `authoritative` — `isAuthoritativeIntent(envelope.intent)`
86
+ (`trigger_execution` / `action_required`), the platform's existing single
87
+ authority predicate.
88
+ 3. `decision` — `routeMailboxItem(row).strictState`: the formal state-machine
89
+ item types (task/requirement/review/workflow status), i.e. a new decision
90
+ about the same entity.
91
+ 4. everything else → `null` (queue only; never in-turn). This is where
92
+ `heartbeat`, `daily_report`, `memory_consolidation`, `system_event` and
93
+ unrelated notifications fall out, by data, not by a name list.
94
+ * `supersedes` / `invalidatesPremise` are **new optional envelope fields**
95
+ (`DeliveryEnvelope`). They are additive: an envelope without them behaves
96
+ exactly as today. A structured correction chain is the only way to satisfy
97
+ "every entry carries `supersedes`" without parsing prose (R3).
98
+ * Rendering is a stable template with the variable part at the end:
99
+
100
+ ```
101
+ [LIVE UPDATE @<seq=N>]
102
+ count: <n>
103
+ - <class>/<sourceType>: <label> (item <id>)[ supersedes: a,b]
104
+ ...
105
+ ```
106
+
107
+ Empty: `count: 0` newline `none`. The header is emitted by a constant
108
+ (`TURN_DELTA_HEADER_PREFIX`) so callers/tests cannot drift from the shape.
109
+ At most **3** item lines and **600** characters total; anything beyond is
110
+ summarised in one line `- (+N more — call check_mailbox)` and counted in
111
+ `omitted`, so "10 facts" is provably not "10 lines".
112
+ * `decision` is `'cancel'` iff a contradiction is present, else `'continue'`.
113
+ `defer` is deliberately **not** produced here: "belongs to something else" is
114
+ already answered upstream by the entity filter (C8-A's destination
115
+ decision). Two places answering "is this mine" would be the R1 this cut is
116
+ removing.
117
+
118
+ ### 4.2 `seq`: an insertion ordinal, never a clock
119
+
120
+ The delta query is `work_unit_ref = <this turn> AND seq > <snapshot taken at turn
121
+ start>`. `seq` is a monotonic **insertion ordinal** owned by `AgentMailbox`
122
+ (`itemSeq: Map<id, seq>` assigned at `insertSorted`, bumped when an item is
123
+ merged so a fact can never be lost by merging into an older row).
124
+
125
+ It is deliberately *not* `Date.now()` and *not* `queued_at`: same-second inserts
126
+ would tie, and a clock in a rendered header is exactly the "two byte sequences
127
+ for one logical input" defect criterion 3 forbids. The rendered `@seq=` value is
128
+ the **snapshot** of the turn, constant for the whole turn, so repeated renders
129
+ are byte-identical.
130
+
131
+ ### 4.3 Where it runs
132
+
133
+ `Agent.injectTurnDelta(sessionId)` is called at the one place that is both
134
+ "after tool results" and "before the next LLM call" — the yield point each tool
135
+ loop already has (`handleMessage`, `chatStream`, `executeTask`, `respondInSession`).
136
+ It:
137
+
138
+ 1. reads `this.currentTurnWorkUnitRef` (in-memory, set by `onFocusChanged` — a
139
+ *notification*, never a DB lookup: C7-B's ruled constraint);
140
+ 2. returns `'continue'` immediately when the turn has no WorkUnit — **no entity,
141
+ no claim of relevance**. It does not fall back to "the agent's latest item",
142
+ which would be structure inferred from time;
143
+ 3. queries the mailbox queue for same-`workUnitRef` rows above the snapshot;
144
+ 4. appends one segment message to the session (tail append) — always, empty or
145
+ not;
146
+ 5. on `cancel`: records the decision through `AttentionController`
147
+ (`recordTurnDeltaDecision` → the existing `recordDecision`), carrying the
148
+ delta item's id and the side effects already performed in the turn, then
149
+ tells the caller to abort.
150
+
151
+ `agent_decisions` therefore keeps **one writer** (`AttentionController`).
152
+
153
+ ### 4.4 The switch
154
+
155
+ `turnDeltaInjection` is on by default and can be turned off at construction
156
+ (`new Agent({ …, turnDeltaInjection: false })` — **constructor-only today**: no
157
+ settings surface reads it yet, so turning it off requires a code change. Wiring
158
+ it to system settings would follow the `maxToolIterations` precedent, where
159
+ `agent-manager.ts` passes `maxToolIterations: this._maxToolIterations` into
160
+ `agentOpts` from configuration).
161
+ Off = the injection step is skipped entirely: no message appended, no decision
162
+ recorded, and the semantics are exactly C8-A's queue semantics. It is one flag
163
+ read at one point — not a second code path.
164
+
165
+ ## 5. Test plan — every assertion observed red before implementation
166
+
167
+ `packages/core/test/turn-delta.test.ts` (pure module)
168
+ 1. Empty input and "rows exist but none qualify" render byte-identically and both
169
+ contain `count: 0` + `none` (criterion 3 and 4, both directions).
170
+ 2. Rendering the same input twice is byte-identical (no clock, no counter).
171
+ 3. The rendered segment is a **suffix**: for a base message array, the serialized
172
+ prefix is byte-identical with and without injection (criterion 4).
173
+ 4. Ten qualifying facts → 3 item lines + `+7 more`; `omitted === 7`
174
+ (criterion 5).
175
+ 5. An unrelated notification (`heartbeat`, `daily_report`,
176
+ `memory_consolidation`) never appears and never raises the count
177
+ (criterion 4 of the card / scope).
178
+ 6. `supersedes` reaches the rendered line; `invalidatesPremise` yields
179
+ `decision === 'cancel'`; an `action_required` item alone yields `'continue'`.
180
+ 7. Total rendered length never exceeds 600 chars.
181
+
182
+ `packages/core/test/turn-delta-injection.test.ts` (real agent loop, fake LLM)
183
+ 8. A tool enqueues an authoritative fact during the turn → the recorder trace is
184
+ `tool → decision/inject → llm#2`, and `llm#2`'s messages contain
185
+ `[LIVE UPDATE @` (criterion 2).
186
+ 9. A tool enqueues a contradiction → exactly one `agent_decisions` row with
187
+ `decision_type='cancel'`, its `mailbox_item_id` is the delta item, and the
188
+ turn's next LLM call never happens (criterion 1).
189
+ 10. Same as 9 but with the switch off → no decision row and the turn continues
190
+ to `llm#2` (the off path is real, not dead code).
191
+ 11. A fact about a *different* WorkUnit does not appear in the injected segment
192
+ and does not record a decision.
193
+ 12. **One fact is reported once per turn.** A two-tool-round turn in which the
194
+ fact arrives in round 1: the fact label appears exactly once in the third
195
+ call's messages, while the second segment is still emitted as `count: 0`
196
+ (criterion 4) — i.e. the watermark advances, the template does not change
197
+ shape. Proven red by disabling the advance (`expected 2 to be 1`, §7.6).
198
+
199
+ ## 6. Verification
200
+
201
+ ### 6.1 Gates (same order as CI, final source state)
202
+
203
+ | gate | result |
204
+ |---|---|
205
+ | `tsc -b` | clean |
206
+ | `tsc --noEmit -p packages/web-ui` | clean |
207
+ | `eslint` on the touched files | 0 errors (7 pre-existing warnings) |
208
+ | `node scripts/architecture-guard.mjs` | 34 hits, all whitelisted; contracts 18/18 |
209
+ | `node scripts/security-guard.mjs` | ok |
210
+ | `vitest run` (whole repo, serial) | **8554 passed / 1 failed / 13 skipped** |
211
+ | `vitest run --project web-ui` | 1476 passed / 3 skipped / 0 failed |
212
+
213
+ The single failure is the known pre-existing CLI one
214
+ (`packages/cli/test/commands-start-integration.test.ts > auto-runs quickInit when
215
+ config is missing`, 60 s timeout) — it also fails on the C8-A base `9908feec`
216
+ and this card touches neither the CLI nor `quickInit`. Test count went from
217
+ 8536 (C8-A) to 8554: exactly the 18 new assertions of this card.
218
+
219
+ ### 6.2 Red at base, green at head (behavioural, not module-resolution)
220
+
221
+ The test file was copied into a detached worktree at base `9908feec`
222
+ (installed + `tsc -b`), with the one constant inlined (otherwise the red would be
223
+ "module not found", which proves nothing about behaviour):
224
+
225
+ | assertion | base `9908feec` | head |
226
+ |---|---|---|
227
+ | authoritative fact is injected **before** `llm#2` (ordering recorder) | ✗ `expected '…' to contain '[LIVE UPDATE @seq='` | ✓ |
228
+ | contradicting fact → `agent_decisions(decision_type='cancel')` in the same turn | ✗ `expected [decision:pick, llm#1, …] to include 'decision:cancel'` | ✓ |
229
+ | a fact about a **different** WorkUnit injects nothing (control) | ✓ | ✓ |
230
+ | switch off ⇒ no segment, no decision row (control) | ✓ | ✓ |
231
+
232
+ The two controls stay green on both sides: "the same entity cancels" cannot be
233
+ explained by "every fact cancels", and the off switch is not dead code.
234
+
235
+ ### 6.3 The four pieces of evidence the card asks for
236
+
237
+ All four produced by the shipped code (`packages/core/dist/*`), 2026-11-14
238
+ 17:54 (+08:00).
239
+
240
+ **① The cancel ledger row, read back with SQL.** The decision was written by the
241
+ production writer (`AttentionController.recordDecision` →
242
+ `SqliteDecisionRepo.save`) into a real SQLite table created from the live
243
+ schema `agent_decisions`:
244
+
245
+ ```json
246
+ {"id":"dec_cfea0892d6c2087b4a9fe9a6","agent_id":"probe-agent","decision_type":"cancel",
247
+ "mailbox_item_id":"mbx_f5c2c89f596d602a44c947cb",
248
+ "context":"{\"currentFocusType\":\"human_chat\",\"currentFocusLabel\":\"Please do it.\",\"currentFocusItemId\":\"mbx_2e8daf6d951e7003df4f12ce\",\"mailboxDepth\":1,\"queuedItemTypes\":[\"task_status_update\"]}",
249
+ "reasoning":"[turn-delta] contradiction/task_status_update (mbx_f5c2c89f596d602a44c947cb) supersedes the premise this turn was executing",
250
+ "outcome":"turn_aborted_before_next_llm_call","created_at":"2026-11-14T09:54:45.513Z"}
251
+ ```
252
+
253
+ Live table for reference (read-only `~/.markus/data.db`, 17:54): 226 963 rows,
254
+ 4 of them `cancel` — the table and its enum already existed; this card added no
255
+ schema.
256
+
257
+ **② No delta vs empty delta — prefix `sha256`, with byte lengths.**
258
+
259
+ ```
260
+ no-delta segment bytes: 35 | empty-delta segment bytes: 35
261
+ no-delta segment sha256: 3d4c91e108a56c63678dff76f4bf57964a93e46315f53687e6dda90267b71817
262
+ empty-delta segment sha256: 3d4c91e108a56c63678dff76f4bf57964a93e46315f53687e6dda90267b71817
263
+ messages prefix (4 messages): 269 bytes
264
+ prefix sha256 without injection : ad53864a9a3358cdf0cb8ff302425dfde0e3f7890e58c88a3821882dd27536ad
265
+ prefix sha256 after empty-delta inject: ad53864a9a3358cdf0cb8ff302425dfde0e3f7890e58c88a3821882dd27536ad
266
+ prefix sha256 after no-delta inject : ad53864a9a3358cdf0cb8ff302425dfde0e3f7890e58c88a3821882dd27536ad
267
+ ```
268
+
269
+ "Empty delta" here means *rows arrived but none qualified* (a heartbeat, a daily
270
+ report, a dream run); "no delta" means nothing arrived. Same bytes, `count: 0`,
271
+ `none` — and the 269-byte prefix never moves, because injection only appends.
272
+
273
+ **③ Ten facts truncated to three + "+7 more".**
274
+
275
+ ```
276
+ [LIVE UPDATE @seq=30]
277
+ count: 10
278
+ - decision/task_comment: fact 0 (item mbx_0)
279
+ - decision/task_comment: fact 1 (item mbx_1)
280
+ - decision/task_comment: fact 2 (item mbx_2)
281
+ - (+7 more — call check_mailbox to list them)
282
+ ```
283
+ 212 characters, `omitted = 7`.
284
+
285
+ **④ `inject()` before `llm.complete()` — recorder trace.**
286
+
287
+ ```
288
+ authoritative case: ["decision:pick","llm.complete#1","tool.result","decision:continue","llm.complete#2"]
289
+ tool.result index 2 < llm.complete#2 index 4
290
+ llm.complete#2 messages contain the segment: true
291
+ contradiction case: ["decision:pick","llm.complete#1","tool.result","decision:continue","decision:cancel"]
292
+ no llm.complete#2 at all — the turn was aborted, not finished
293
+ ```
294
+
295
+ The injected segment as the model actually received it:
296
+
297
+ ```
298
+ [LIVE UPDATE @seq=1]
299
+ count: 1
300
+ - authoritative/requirement_update: Scope changed — take action (item mbx_b72b0c937a819da9cf59240c)
301
+ ```
302
+
303
+ ## 7. Where the implementation corrected the plan
304
+
305
+ 1. **`count` is the number of facts that arrived, not the number rendered.** My
306
+ first test expectation was `count: 7` after truncation (i.e. the rendered
307
+ count). That reads as "you are missing nothing" while hiding seven facts, so
308
+ the implementation reports `count: 10` and the omitted count separately in
309
+ `- (+7 more …)`; the expectation was corrected (recorded here rather than
310
+ silently edited).
311
+ 2. **`decisive` must be computed from all qualifying facts, not from the rendered
312
+ three.** A cancel sitting at position 5 is still a cancel; deriving the
313
+ decision from the rendered slice would have made "the 5th fact cancels the
314
+ turn" depend on the character budget. Found while writing the renderer.
315
+ 3. **`outcome` has to be passed *into* the single writer.** The first version
316
+ assigned `decision.outcome` after `recordDecision()` — which had already
317
+ persisted the row, so every cancel row read back `outcome: null`. The probe's
318
+ SQL read-back is what exposed it (§6.3 ①); the fix routes `outcome` through
319
+ `recordDecision(type, item, reasoning, outcome?)` so there is still exactly
320
+ one write.
321
+ 4. **Structural contradiction had to be a field, not a heuristic.** `task_status_update`
322
+ payloads carry only `summary` / `content` / `taskId` — the status itself lives
323
+ in prose. Inferring "was cancelled" from text is R3, so `DeliveryEnvelope`
324
+ gained two optional fields (`supersedes`, `invalidatesPremise`), additive and
325
+ defaulted: an envelope that does not set them behaves exactly as before.
326
+ `payload.extra` was rejected for this: the registry already documents that
327
+ routing must not read it, and a second "structure lives in extra" convention
328
+ is how the previous cutter's R1s started.
329
+ 5. **`defer` is not a delta decision.** The card's table lists it; at this layer
330
+ it is unreachable by construction — "belongs to something else" is answered by
331
+ the entity filter before the module runs. Producing a `defer` here would be a
332
+ second place answering "is this mine".
333
+ 6. **The watermark is turn state, not a per-call constant** (self-review, second
334
+ round). The first version took `mailbox.currentSeq()` once per tool loop and
335
+ passed it into `injectTurnDelta()` — a snapshot nothing ever advanced. A fact
336
+ that arrived mid-turn was therefore re-injected at *every* later yield point in
337
+ the same turn: two `[LIVE UPDATE]` segments carrying the same item, context
338
+ growing with zero new information. The red test is behavioural (a two-tool-round
339
+ turn with one fact; the fact label must appear exactly once) and it was proven
340
+ red by temporarily disabling the advance (`expected 2 to be 1`). The fix puts
341
+ the cursor next to the turn identity it belongs to (`turnDeltaCursor`, reset in
342
+ `onFocusChanged` where `currentTurnWorkUnitRef` is set, advanced only inside
343
+ `injectTurnDelta`), and the four call sites lose their private snapshots. This
344
+ is the same R2 the card is about: a cursor that four call sites each own is a
345
+ fact with four writers.
346
+ 7. **Counting the header is not counting the fact.** The first version of the new
347
+ test counted `[LIVE UPDATE @seq=` occurrences — but the *empty* segment carries
348
+ the same header (`count: 0` + `none`, criterion 4), so the assertion was red
349
+ against correct code. Counting the fact label instead makes the assertion mean
350
+ what it says, and the empty segment is then asserted separately (`count: 0`).
351
+
352
+
353
+ ## 8. Boundaries
354
+
355
+ - No new table, no migration: `agent_decisions` already exists.
356
+ - C8-A's territory (`TRIAGE_STALE_DROP_TYPES`, `resolveEntityKeys`,
357
+ `a2a_message.affinity`) untouched.
358
+ - `mailbox_items.work_unit_ref` keeps its one writer (`linkMailboxItem`).
359
+ - The injected message is a plain session `user` message at the tail: nothing in
360
+ the system prompt, nothing in existing message bytes.
361
+ - Envelope additions (`supersedes`, `invalidatesPremise`) are optional and
362
+ additive; a producer that does not set them behaves exactly as before.
@@ -0,0 +1,119 @@
1
+ # Cut 8-C — readings and evidence (2026-11-14)
2
+
3
+ > **Historical record (2026-11-14).** The mechanisms measured here (dual-clock heartbeat scheduling,
4
+ > `HEARTBEAT_CLOCK_SOURCE`, per-tick dream trigger) were changed or deleted by the Forever Loop
5
+ > refactor (M1–M7). Current mechanism: `docs/architecture/architecture.md`. Symbol names below are
6
+ > historical and have 0 hits in `packages/*/src`.
7
+
8
+ Companion to `docs/records/cut8-c-single-clock-design-2026-11-14.md`.
9
+ Branch `task/c8-c-single-clock` → PR to `feat/refactor-plan`.
10
+
11
+ ## 1. Criterion: no second periodic business clock in the agent
12
+
13
+ `grep -rn "setInterval" packages/core/src --include=*.ts` after the change, with the
14
+ disposition of every hit. The acceptance wording matters: **C8-C removes the second
15
+ *periodic business* clock — not "every `setInterval`"**. Provider/transport/terminal/UI
16
+ timers are per-operation lifecycles and stay.
17
+
18
+ | Location | Kind | Disposition |
19
+ |---|---|---|
20
+ | `packages/core/src/clock.ts:68` `AgentClock.tick` | the single periodic driver for time-driven transitions | **kept — this is the one** (design R-10.1) |
21
+ | `packages/core/src/heartbeat.ts:181` | the former second business clock | **removed from the default path**: the private `setInterval` now exists only inside the `legacy` branch, reachable solely via `MARKUS_HEARTBEAT_CLOCK=legacy`. Default (`clock`) arms **zero** timers — asserted by `vi.getTimerCount() === 0`. |
22
+ | `packages/core/src/attention.ts:498` watchdog / `:967` leaseRenew / `:997` backstop | per-item lifecycle timers (created when an item starts, cleared when it ends) | kept — not a cluster-periodic clock |
23
+ | `packages/core/src/agent.ts:6482`, `:7098`, `:10042` cancelPollTimer / wait loops | cancellation-poll / wait loops for one operation | kept — bounded by the operation |
24
+ | `packages/core/src/concurrent/task-executor.ts:199` | wait-for-completion poll | kept |
25
+ | `packages/core/src/tools/shell-session.ts:290` | command output poll | kept |
26
+ | `packages/core/src/llm/model-catalog.ts:97` | model catalogue cache refresh | kept |
27
+ | `packages/core/src/llm/oauth-manager.ts:491` | OAuth device-code poll | kept |
28
+
29
+ Readings:
30
+
31
+ * `heartbeat.ts` owns a timer **only** in `legacy` mode; `getMode()` reports which.
32
+ * In `clock` mode the heartbeat cadence is a `ClockSource` named `heartbeat`
33
+ (`HEARTBEAT_CLOCK_SOURCE`), asserted by `heartbeat-single-clock.test.ts`
34
+ (6 tests, incl. `vi.getTimerCount() === 0` after `start()`).
35
+ * `updateInterval()` re-registers the source instead of restarting a timer — asserted.
36
+ * `stop()` unregisters the source — asserted.
37
+
38
+ ## 2. Criterion: heartbeat produces zero mailbox rows
39
+
40
+ `heartbeat-no-mailbox-row.test.ts` (3 tests):
41
+
42
+ | Mode | 3 triggers | Patrols | `heartbeat` rows |
43
+ |---|---|---|---|
44
+ | `clock` (default) | 3 | 3 | **0** |
45
+ | `legacy` (`MARKUS_HEARTBEAT_CLOCK=legacy`) | 1 | — | **1** (rollback channel intact) |
46
+
47
+ The old re-entrancy protection ("heartbeat folding" inside `Mailbox.enqueue`) was needed
48
+ only because the row path could start a second patrol right after the first finished
49
+ (7–12 s apart in production). With no row there is nothing to fold, so re-entrancy is
50
+ guarded at the single place that starts a patrol — `runHeartbeatPatrol` / `heartbeatInFlight`.
51
+ Asserted: a second trigger while a patrol is in flight is skipped, and a trigger after it
52
+ settles runs normally.
53
+
54
+ ## 3. Criterion: dream triggers exactly once per schedule
55
+
56
+ `dream-single-trigger.test.ts` (4 tests):
57
+
58
+ | Tick | `dream:trigger` | `ran` | Dream LLM runs |
59
+ |---|---|---|---|
60
+ | due, window open | 1 | `true` | 1 |
61
+ | due again, same window | 1 | `false` | 0 |
62
+ | `memory_consolidation` row, `clock` mode | 0 | — | 0 (row acknowledged, no LLM turn) |
63
+ | `memory_consolidation` row, `dual` mode | 0 | — | 0 dream + 1 LLM turn (pre-C8-C behaviour) |
64
+
65
+ `ran: false` is a deliberate skip, not a miss — the event count stays 1:1 with the schedule.
66
+ The decision still has exactly one implementation (`shouldRunDreamCycle`, called only from
67
+ `consolidateMemory`), which now returns `{ ran, windowKey }` so the event reports the
68
+ decision instead of re-deriving it.
69
+
70
+ **Boundary (C8-A owns this line):** removing `memory_consolidation` from
71
+ `TRIAGE_STALE_DROP_TYPES` is *not* in this cut. That "type → disposition" table has one
72
+ writer, and the CTO assigned the removal to C8-A while it re-works the same layer. C8-C
73
+ ships the producer side only — no third opinion, no side channel that pretends the list
74
+ was changed.
75
+
76
+ ## 4. Criterion: `rest(wakeOn)` wakes on the event, without polling
77
+
78
+ `trigger-subscription.test.ts` (12 tests):
79
+
80
+ * `matchesWakeCondition` — pure predicate; `mailbox-type` matches only its type,
81
+ `mailbox-any` matches any mailbox item, non-mailbox events never match.
82
+ * `TriggerRegistry.dispatch` — synchronous match; one-shot by default; `once: false` keeps
83
+ the subscription; another agent's events never fire it.
84
+ * **No timer per wait**: 25 live subscriptions ⇒ `vi.getTimerCount() === 0`.
85
+ * Expiry is swept, not swallowed: `sweepExpired()` returns what it dropped, and an expired
86
+ wait can no longer match. On a live agent the sweep runs on the clock source
87
+ `trigger-expiry` (60 s), so the process still has one periodic driver.
88
+ * Tool surface: `rest` registers exactly one subscription and answers
89
+ `{ status: 'resting', subscriptionId, wakeOn, expiresAt, note }`; an unusable condition
90
+ answers `{ status: 'error' }` and registers nothing; `list_waits` / `cancel_wait` are
91
+ read/cancel paths.
92
+ * Waking: enqueueing a matching mailbox item emits `trigger:matched` exactly once; a
93
+ non-matching item emits nothing. The listener is registered at **construction**, so a
94
+ declared wait is never inert just because the attention loop has not started yet.
95
+
96
+ ## 5. Test evidence (red → green)
97
+
98
+ Red was captured before the implementation on this branch:
99
+
100
+ * `heartbeat-single-clock.test.ts` — 5 of 6 red at the starting commit (`start()` armed a
101
+ timer, `HEARTBEAT_CLOCK_SOURCE` did not exist).
102
+ * `heartbeat-no-mailbox-row.test.ts` — 3 of 4 red (each tick enqueued a row).
103
+ * `dream-single-trigger.test.ts` — no `dream:trigger` event existed; the row replayed.
104
+ * `trigger-subscription.test.ts` — module and tool did not exist.
105
+
106
+ Green now, together: 25/25. Related families re-run unchanged:
107
+ `heartbeat.test.ts` (14), `heartbeat-liveness.test.ts` (9),
108
+ `heartbeat-dedup-and-session-rollover.test.ts` (16), `dream-guard-durable.test.ts` (10),
109
+ `agent-clock.test.ts` (6) — 55/55.
110
+
111
+ ## 6. Rollback (independent, per channel)
112
+
113
+ | Channel | Switch | Effect |
114
+ |---|---|---|
115
+ | Heartbeat clock | `MARKUS_HEARTBEAT_CLOCK=legacy` | private `setInterval` returns, heartbeat returns to the mailbox-row path |
116
+ | Dream trigger | `MARKUS_DREAM_PATH=dual` | `memory_consolidation` rows replay the dream again |
117
+
118
+ Both are read at construction/decision time and are independent: flipping one never changes
119
+ the other's behaviour, so either can be reverted alone.
@@ -0,0 +1,150 @@
1
+ # Cut 8-C — Single clock: heartbeat as a liveness tick, one dream trigger, minimal Trigger/Subscription
2
+
3
+ > **Historical record.** The durable contract from this cut now lives in
4
+ > [`agent-runtime.md §6`](../architecture/agent-runtime.md) — one clock, a tick is not a message,
5
+ > one dream trigger. This file keeps the observed-before/after evidence and the cut narrative.
6
+
7
+ Status: implementation note (Living for this cut). Branch `task/c8-c-single-clock`, target `feat/refactor-plan`.
8
+
9
+ ## 1. Observed behaviour (before this cut)
10
+
11
+ | # | Symptom | Reading |
12
+ |---|---|---|
13
+ | 1 | An agent runs **two periodic timers**: `HeartbeatScheduler` owns its own `setInterval`, `AgentClock` owns another | `packages/core/src/heartbeat.ts:133` (`setInterval`), `packages/core/src/clock.ts:68` |
14
+ | 2 | Heartbeat is a **queue producer**: every tick becomes a `heartbeat` mailbox row, which is then processed, completed and retained | `packages/core/src/agent.ts:1135` `mailbox.enqueue('heartbeat', …)`; `heartbeat` rows dominate the completed population (~70% of `mailbox_items`, ≥165k rows) |
15
+ | 3 | Time-driven and signal-driven work share one queue, so "queueing = ageing" and queue noise are structural | same |
16
+ | 4 | The dream has **two entry links** — a clock source (`memory-consolidation`) and a mailbox item type (`memory_consolidation`) — and the mailbox type is in the age-based drop list, so the cleaning task can be silently discarded | `packages/core/src/agent.ts:1393`, `:2916`; `packages/shared/src/limits.ts:556` |
17
+ | 5 | Waiting for an external event has no primitive: an agent either polls (heartbeat) or blocks on the queue with no declared condition | no `rest(wakeOn)`, no subscription registry |
18
+
19
+ ## 2. Root cause
20
+
21
+ **R2 — one invariant, two execution points.** "How much time has passed and what is due" is one
22
+ invariant. It currently has two executors (`HeartbeatScheduler.timer` and `AgentClock.timer`),
23
+ each with its own cadence arithmetic, jitter and stop semantics. Anything that wants "run every
24
+ N minutes" has to pick one of them, and picking the wrong one silently changes when the agent
25
+ wakes.
26
+
27
+ **R1 — one fact, two writers.** "Should the dream run now?" is decided in `shouldRunDreamCycle`
28
+ (one decision function, good) but *reached* through two links: the clock source and the
29
+ `memory_consolidation` mailbox row. The row link is additionally subject to age-based dropping,
30
+ so the same fact can be (a) decided twice or (b) dropped because the queue was busy.
31
+
32
+ The heartbeat row is R2 as well: a **tick** (a liveness beat, no content) is expressed as a
33
+ **message** (content plus a lifecycle row). That is a modelling error — ticks are not messages,
34
+ and giving them a row gives them retention, triage and drop semantics they never needed.
35
+
36
+ ## 3. Design
37
+
38
+ ### 3.1 One clock (heartbeat channel)
39
+
40
+ `AgentClock` stays the only owner of `setInterval` for time-driven transitions.
41
+ `HeartbeatScheduler` keeps its *policy* (interval, active hours, deep-sleep interval growth,
42
+ status reporting) and loses its *timer*: it becomes a clock source named `heartbeat` registered
43
+ by `Agent.start()`.
44
+
45
+ ```
46
+ Agent.start()
47
+ └─ clock.register({ name: 'heartbeat', everyMs: interval, initialDelayMs: jitter, fn: () => heartbeat.tick() })
48
+ └─ clock.register({ name: 'memory-consolidation', … }) // dream (single trigger)
49
+ └─ clock.register({ name: 'mailbox-maintenance', … })
50
+ └─ clock.register({ name: 'wakeup-sweep', … })
51
+ └─ clock.register({ name: 'trigger-expiry', … }) // subscriptions, lazy-free
52
+ ```
53
+
54
+ `HeartbeatScheduler.tick()` emits one observable event and nothing else:
55
+
56
+ ```
57
+ heartbeat:trigger { agentId, triggeredAt, mode: 'clock'|'legacy', producedMailboxItem: boolean }
58
+ ```
59
+
60
+ Deep-sleep (`updateInterval`) re-registers the source instead of restarting a private timer, so
61
+ cadence changes still take effect immediately and still keep one timer in the process.
62
+
63
+ ### 3.2 Heartbeat produces no mailbox rows
64
+
65
+ In `clock` mode the `heartbeat:trigger` listener runs the patrol **directly**
66
+ (`handleHeartbeat`) instead of `mailbox.enqueue('heartbeat')`:
67
+
68
+ * no row ⇒ no `mailbox_items` growth, no triage, no retention, no drop list membership;
69
+ * the patrol function is unchanged, so `shouldDeferHeartbeatForHumanChat`, the state
70
+ fingerprint skip, deep-sleep and `recordHeartbeatSkip` (the liveness timestamp writer)
71
+ keep their current semantics;
72
+ * re-entrancy is guarded by a single in-flight flag — this replaces the previous
73
+ "heartbeat folding" in `Mailbox.enqueue`, whose only job was to stop back-to-back patrols
74
+ that the row path could create. One guard, not two mechanisms;
75
+ * failures are contained by `AgentClock` (a throwing source is logged, never wedges the clock).
76
+
77
+ ### 3.3 One dream trigger
78
+
79
+ * The named clock source `memory-consolidation` is the **only** producer of a dream. It emits
80
+ `dream:trigger { agentId, windowKey, ran: boolean }` exactly once per due tick, so the
81
+ event count is 1:1 with the schedule (and `ran` distinguishes "due but deduped").
82
+ * `memory_consolidation` being **removed from `TRIAGE_STALE_DROP_TYPES`** is owned by
83
+ **C8-A**, not this cut: that "type → disposition" table has exactly one writer, and two
84
+ people editing it would be the very `R2` this cut is fixing. C8-A implements the removal
85
+ while it re-works the same layer (recorded on the C8-A card by the CTO). This cut
86
+ therefore ships **only the producer side** and does not touch the list, nor adds a
87
+ side-channel that pretends it was done.
88
+ * The `memory_consolidation` mailbox case is kept as a **drain** for rows already persisted
89
+ before this cut, but in `clock` mode it no longer replays a dream; it acknowledges the row
90
+ with a typed result. In `dual` mode it behaves exactly as today.
91
+
92
+ ### 3.4 `Trigger / Subscription / rest(wakeOn)`
93
+
94
+ Minimal, event-driven, zero polling (`packages/core/src/trigger.ts`):
95
+
96
+ ```ts
97
+ type WakeCondition =
98
+ | { kind: 'mailbox-type'; sourceType: MailboxItemType }
99
+ | { kind: 'mailbox-any' };
100
+
101
+ interface TriggerEvent { type: 'mailbox:new-item'; agentId: string; sourceType: MailboxItemType; itemId: string; }
102
+
103
+ matchesWakeCondition(cond, event): boolean // pure
104
+ class TriggerRegistry {
105
+ subscribe({ agentId, wakeOn, note, timeoutMs, once }): Subscription
106
+ dispatch(event: TriggerEvent): Subscription[] // pure match, no timers
107
+ list(agentId): Subscription[]
108
+ consume(id) / clearAgent(agentId)
109
+ sweepExpired(now) // called by the clock source, not a timer
110
+ }
111
+ ```
112
+
113
+ The `rest(wakeOn)` tool registers one subscription and returns immediately; the agent ends its
114
+ turn. When a matching event arrives (`mailbox:new-item` on the agent's own bus), the registry
115
+ fires the subscription, logs `trigger:matched`, and the agent is woken through the normal
116
+ attention path. No polling loop, no timer per subscription: expiry is swept by the existing
117
+ clock source `trigger-expiry`, so the number of timers stays one.
118
+
119
+ ## 4. Per-channel switches (independent rollback)
120
+
121
+ | Channel | Flag | Default | Rollback effect |
122
+ |---|---|---|---|
123
+ | Heartbeat clock | `MARKUS_HEARTBEAT_CLOCK=legacy` | `clock` | `HeartbeatScheduler` uses its old private `setInterval` and heartbeat returns to the mailbox-row path |
124
+ | Dream trigger | `MARKUS_DREAM_PATH=dual` | `clock` | `memory_consolidation` mailbox rows replay the dream again (old double link) |
125
+
126
+ The two flags are read independently; flipping one never changes the other's behaviour, so a
127
+ single channel can be reverted alone.
128
+
129
+ ## 5. Test plan (red first)
130
+
131
+ | Test file | Assertion | Must be red before the change |
132
+ |---|---|---|
133
+ | `packages/core/test/heartbeat-single-clock.test.ts` | clock mode: `HeartbeatScheduler.start()` creates **no** timer (`vi.getTimerCount() === 0`), advancing fake time fires nothing, `AgentClock.tick()` fires exactly one trigger; legacy mode still arms its own timer | yes — today `start()` arms a `setInterval` |
134
+ | `packages/core/test/heartbeat-no-mailbox-row.test.ts` | N heartbeat ticks ⇒ **0** `heartbeat` mailbox enqueues, N patrols; legacy mode ⇒ N rows | yes — today each tick enqueues a row |
135
+ | `packages/core/test/dream-single-trigger.test.ts` | one due clock tick ⇒ one `dream:trigger`; a second tick in the same window ⇒ `ran: false`; a `memory_consolidation` row in clock mode does not run a second dream, and in `dual` mode it still does | yes — today there is no event and the row replays |
136
+ | `packages/core/test/trigger-subscription.test.ts` | subscription matches only its condition; dispatch fires the callback synchronously; no timer is created per subscription (timer count unchanged); expiry swept by the clock source; `rest` tool registers exactly one subscription and returns a machine-readable acknowledgement | yes — there is no such module/tool today |
137
+
138
+ Gate re-runs: every `heartbeat-*`, `dream-*`, `scheduled-*` file in the repo, plus the full
139
+ suite.
140
+
141
+ ## 6. Readings to capture (evidence, §4 of the card)
142
+
143
+ 1. `mailbox_items` new `heartbeat` rows in a 10-minute window after restart = **0**.
144
+ 2. `grep -rn setInterval packages/*/src` whitelist — the only per-agent periodic driver is
145
+ `packages/core/src/clock.ts`; every other hit is provider/transport/terminal/UI-scoped and
146
+ must justify itself in the record.
147
+ 3. `dream:trigger` event count vs. schedule count = 1:1.
148
+ 4. `rest(wakeOn)` wake without polling — subscription callback hit, log line quoted.
149
+
150
+ Readings are recorded in `docs/records/cut8-c-single-clock-2026-11-14.md`.