@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,312 @@
1
+ # Team Chat Page — Feature Model, State Machine & Interaction Contracts
2
+
3
+ > Branch: `refactor/team-chat-state-machine` (based on main #308, 19 commits ahead)
4
+ > Goal: map out feature requirements → refactor state management → eliminate fragile assignments → fix all state conflicts/data issues
5
+ > Status: design document v1 (under review)
6
+
7
+ ---
8
+
9
+ ## 1. Current-state Health Check (one-sentence verdict)
10
+
11
+ The core page of Team chat, `pages/Team.tsx`, is a **5918-line monolithic component**: roughly **78 useStates, 82 destructured states, 106 useRef/useCallback sites**, the same "abort/cleanup" sequence copy-pasted 4+ times, and the same state (messages/sending/activities) duplicated in 4 places and kept in sync by hand — a direct expression of "an unreasonable state machine with fragile assignments everywhere".
12
+
13
+ A previous round already built the skeleton of a state machine (a plain class `ConversationBufferManager` + the hook `useConversationBuffers`), **but it was only partially adopted**: old and new state coexist in Team.tsx, synchronized by convention.
14
+
15
+ ---
16
+
17
+ ## 2. Feature Requirements Breakdown (what the Team chat page actually does)
18
+
19
+ ### 2.1 Conversation model (four conversation shapes)
20
+
21
+ | Shape | convKey rule | Description |
22
+ |---|---|---|
23
+ | direct (1v1 agent) | agentId | Default shape, streaming replies |
24
+ | channel (group chat/channel) | `ch:<channel>` | Standalone channel, synced via REST |
25
+ | dm (direct message with a human member) | `dm:<userId>` | Same semantics as channel |
26
+ | session tabs | multiple sessions per agent | history pagination, title editing, model override |
27
+
28
+ ### 2.2 User-visible feature list
29
+
30
+ **Conversation side**
31
+ - Switch conversations (direct agent / channel / dm / session tab)
32
+ - Paginated loading of conversation history (older messages), `hasMore` cursor
33
+ - Conversation title editing (session_rename)
34
+ - session-switch **loading state** (history exists but is not fully loaded → show loading instead of a blank new conversation)
35
+ - Multi-conversation stream isolation (switching to B while A is streaming: A's stream continues, B renders independently)
36
+
37
+ **Send/reply side**
38
+ - Sending text + images + @mentions
39
+ - Reply (replyTo) quoting
40
+ - Sending state (sending), input debounce/duplicate-submit prevention
41
+ - Conversation model override, agent-bound model
42
+
43
+ **Streaming side**
44
+ - SSE chunked rendering (text + thinking segments + tool timeline)
45
+ - Tool call in-progress/completed collapsing
46
+ - Abort (stop) / retry / resume
47
+ - Exponential-backoff polling recovery after an SSE disconnect
48
+ - Soft disconnect → reattach continuation
49
+
50
+ **State/awareness side**
51
+ - Sidebar agent "working" red dot/busy state (from the same source as the Chat top badge)
52
+ - Unread counts, new-message bubble, scroll following
53
+ - Thinking-agents hint bar
54
+
55
+ **Other**
56
+ - Notification cards / user-input approval dialogs
57
+ - Task linkage (linkedTaskId), global search
58
+ - Mobile responsiveness (L2 floating panel, back stack)
59
+
60
+ ### 2.3 Backend interactions
61
+
62
+ - `api.agents.sendMessage` (REST + SSE stream)
63
+ - `api.sessions.*` (history pagination / getMessages / streamStatus / rename)
64
+ - `api.channels.sendMessage` (channel/dm go through REST with full responses)
65
+ - WS broadcast (agent:update / task:update / mailbox, etc.)
66
+
67
+ ---
68
+
69
+ ## 3. State-machine Health Check: Where the Fragile Assignments Are (list of defects)
70
+
71
+ ### A. Copy-pasted abort/cleanup sequences (most severe)
72
+ The same teardown is repeated in at least 4 places:
73
+
74
+ ```ts
75
+ resetSending(key);
76
+ actBuffers.delete(sessionId ?? key);
77
+ endStream(key);
78
+ if (sessionId) clearStreamSession(key, sessionId);
79
+ setSending(false);
80
+ setActivities([]);
81
+ ```
82
+
83
+ It appears in: the stop handler (2652-2659), send duplicate-submit retry (2701-2717), send resend after abort in the same conversation (2722-2751), channel abort (2762-2765). **Omitting one step = a state leak**, and the subtle ordering differences between the sites make safe reuse impossible.
84
+
85
+ ### B. Multiple state sources (4 copies of the same data)
86
+ `messages / sending / activities` exist simultaneously in:
87
+ 1. The internal Map of `ConversationBufferManager`
88
+ 2. The `setMessages/setSending/setActivities` of the `useConversationBuffers` hook
89
+ 3. Team.tsx's own `useState` (e.g. `sending`, `activities`, `loadingChat`, `streamingVisual`)
90
+ 4. `chatStore` (the global store in useChatStore.ts)
91
+
92
+ Manual synchronization across four places → **the direct source of state conflicts**.
93
+
94
+ ### C. A mutable session id captured by a closure
95
+ ```ts
96
+ let streamSessionId: string | null = ...; // rewritten at runtime by SSE events
97
+ ```
98
+ During streaming, session ownership can change at any moment, and every `updateConvMsgs(..., streamSessionId)` depends on this mutable variable — once the stream is switched away/merged, the write target is wrong.
99
+
100
+ ### D. Manual message-flag transformation
101
+ `isStopped / isError / isStreaming` and the tool segment's `running → stopped` are manually mapped in a dozen-plus places, with no unified "end-state convergence" function.
102
+
103
+ ### E. Timers/visual state
104
+ `thinkingAgents` (120s timeout), `streamingVisual` (STREAMING_MIN_DISPLAY_MS), `streamingTimerRef` — all "temporary visual state" separated from the real stream state, and prone to going out of sync.
105
+
106
+ ---
107
+
108
+ ## 4. Target State Machine Design
109
+
110
+ ### 4.1 Single source of truth
111
+ - **One state per convKey**, all converged into `ConversationBufferManager` (a plain class, unit-testable).
112
+ - The hook layer (`useConversationBuffers`) only acts as the "React bridge for the manager" — turning Map changes into render snapshots and **no longer holding an independent copy**.
113
+ - Team.tsx no longer creates its own `messages/sending/activities` useStates; it always reads the render state exposed by the hook.
114
+ - `chatStore` keeps only "cross-conversation" things (the streaming agent set, unread); per-conversation data does not enter the store.
115
+
116
+ ### 4.2 Conversation lifecycle state machine (per conversation)
117
+ ```
118
+ ┌────────┐ select/load ┌─────────┐
119
+ │ idle │─────────────▶│ loading │
120
+ └────────┘ └─────────┘
121
+ ▲ │ applyLoad / completeLoad
122
+ │ ▼
123
+ reset ┌───────┐ send ┌───────────┐
124
+ ◀─────────────────────────│ ready │──────────▶│ streaming │
125
+ │ └───────┘ └───────────┘
126
+ │ ▲ done / stop / abort / reconnect recovery
127
+ └─────────────────────────────┴──────────────┘
128
+ ```
129
+ - Invariant: **while in the streaming state, DB load results only write to the cache and never overwrite the display buffer** (already implemented).
130
+ - New invariant: **any path leaving streaming must, and may only, pass through the single convergence point `completeStream(key, { stopped | done | error | detached })`**, which uniformly handles: endStream, clearStreamSession, resetSending, tool running→stopped, and message isStopped/isError marking.
131
+
132
+ ### 4.3 Single entry point for abort/cleanup
133
+ Converge the group-A repeated sequence into a single method:
134
+
135
+ ```ts
136
+ manager.abortStream(key, opts: { markStopped?: boolean; sessionId?: string })
137
+ ```
138
+
139
+ Internally it guarantees idempotency: when already ready/idle it is a no-op; each sub-step checks its preconditions. All call sites (stop / duplicate-submit retry / same-conversation abort / channel abort / component unmount) call only this one method.
140
+
141
+ ### 4.4 Streaming session ownership
142
+ `streamSessionId` is no longer a "mutable closure variable"; instead it becomes the **active streaming session** tracked per `convKey` inside the manager (`activeStreamSession.get(key)`); SSE `session_start` updates it through the single write point `manager.setStreamSession`, and all reads go through `manager.getActiveStreamSession(key)`. This inherently avoids defect C.
143
+
144
+ ### 4.5 End-state convergence (D)
145
+ Provide `manager.finalizeAgentMessage(msg, outcome)` to uniformly handle isStopped/isError + tool segment convergence, replacing 12+ manual maps.
146
+
147
+ ---
148
+
149
+ ## 5. Migration Order and Acceptance Criteria
150
+
151
+ > Principle: **one rollback-safe commit per step; move to the next step only after typecheck + the relevant unit tests pass**; no "one-shot big-bang rewrite".
152
+
153
+ | Step | Content | Acceptance |
154
+ |---|---|---|
155
+ | S1 | Document + state-machine defect list | This file, typecheck passes |
156
+ | S2 | Land the single `abortStream` convergence entry point, replacing the 4 copy-pasted teardowns | ✅ `b0dd2c93`: stop/abort/resend/switch-conversation behavior unchanged, 5 idempotency unit tests |
157
+ | S3 | Converge streaming session ownership (defect C) | ✅ `682d0df7`: the duplicated formulas for `streamSessionId` and `effectiveSessionId` are merged; ownership remains the locally correct state of send() (needed to route to the right cache), and multi-conversation stream isolation behavior is unchanged |
158
+ | S4 | End-state convergence `finalizeAgentMessage` (defect D) | ✅ `9ecd655e`: 12+ manual isStopped/isError/tool transformations converged into 4 helper functions + 8 unit tests. **Follow-up completion** (after `d63f3c75`): the original done/error finishing paths did not pass through finalize, so `finalizeStreamEnd`/`finalizeLastStreamingBubble` fill in isStreaming convergence for direct-stream done/error/soft-disconnect + reattach abort (5 new unit tests) |
159
+ | S5 | Eliminate hidden dual sources (defects B/E), single responsibility for chatStore | ✅ `682d0df7`: chatStore deletes 8 dead state fields that were never read or written (226→110 lines), keeping only the streaming agent set + a version number; `messages/sending/activities` were already converged in the manager, and Team has no duplicate useStates |
160
+ | S6 | Converge visual state (defect E) | ✅ `50065608`: the `chatStreamActive` tail scan is extracted into the pure function `hasStreamingTail` (3 unit tests); the thinkingAgents lifecycle is self-consistent (WS event + 120s fallback) and needs no rework |
161
+ | S7 | Split the tab panel (conversation/stream rendering/approval/search) | ⬜ Not done: message rendering is already cohesive in ChatComponents/ExecutionTimeline, and Team.tsx is the orchestration layer; the split's benefit < its risk, so it is left for a later standalone PR |
162
+ | S8 | Migrate stream orchestration into the `useChatStream` hook | ✅ This round: `send` (~780 lines) / `stopSending` / `tryReattachActiveStream` (~390 lines) / `loadSessionMessages` are all moved out of Team.tsx; the logic passes typecheck + 239 unit tests + vite build all green |
163
+ | S9 | Fix concurrent cross-talk between multiple session tabs | ✅ `614f419f`: atomic reset of `resetConv(key, repinTo?)` + activeSession re-pin, eliminating the ordering bug "reset without re-pin → the old session's stream bleeds into the new buffer" (handleRememberConfirm pinned first and reset second — reversed order; a new tab conversation missed the pin). 2 regression unit tests added, 246 unit tests + build all green |
164
+
165
+ ### S8 notes: the `useChatStream` migration
166
+ - **Ownership model**: Team.tsx still holds all application state; the hook only borrows it through `ctx` (a stable handle) + `ctx.stateRef.current` (mutable read-only state, refreshed on every render). The hook privately holds stream-specific refs (`abortControllerRef`/`reattachAbortRef`/`reattachCooldownRef`/`userStoppedSessionsRef`/`lastSendGuardRef`/`lastSseEventTimeRef`), because every write point for them is inside the functions being moved in.
167
+ - **Wiring**: `loadSessions` is moved up to avoid the TDZ; Team destructures `hookSend / stopSending / tryReattachActiveStream / loadSessionMessages` from the hook and wires them to `sendRef` and 5 UI event sites.
168
+ - **State issues converged** (resolved together this round): the streaming session id no longer depends on a mutable closure variable (a hook-local `streamSessionId`); end states uniformly go through `finalizeStreamEnd`/`finalizeAgentMessage`; the sidebar busy state goes through the chatStore idempotent Set (see S5); shared refs such as `thinkingTimeoutRef`/`sessionSwitchSeqRef`/`oldestMsgId` that span non-stream code stay in Team and are injected into ctx.
169
+
170
+ > **Known leftover (platform tool limitation)**: the file-edit tool's `old_string` cannot match text containing `<thinking>`/`</thinking>` tags (cleaned by the render layer), so the original `send`/`tryReattachActiveStream`/`stopSending` in Team.tsx were renamed to `*Legacy` and kept (not wired up, exempted via `void` references), so the diff stays reviewable and any anomaly stays rollback-safe. The hook is the only effective implementation. Cleaning up the legacy copies requires manual deletion in the IDE or a tool that can match the tags verbatim.
171
+
172
+ **UI/UX improvements (landed together with the refactor)**: while loading, show the conversation name as a subtitle (switching to a session with history no longer looks like an empty new one); the send key → stop key during streaming generation; an empty-state greeting; a back-to-latest button + new-message count; an IME composition guard; mention/slash dropdowns; multi-conversation streams that do not contaminate each other.
173
+
174
+ **Regression scope**: direct-streaming, channel/dm, session-tab switching, history pagination, stop/retry/resume, reconnect recovery, sidebar busy state, unread counts, mobile.
175
+
176
+ ---
177
+
178
+ ## 6. Relationship to Existing Commits
179
+
180
+ The branch already has 19 commits; on the web-ui side these have already resolved: a streaming refcount leak, sidebar "working" residue (single source of truth), conversation history pagination, the session-switch loading state, and multi-conversation stream isolation. S2-S7 of this design document are a **deep refactor** on top of that; they do not overturn the existing results, only converge the remaining old/new coexistence and copy-paste.
181
+
182
+ ---
183
+
184
+ ## 7. Interaction Reliability Contracts (`feat/ui-optimize-1008`, 2026-10)
185
+
186
+ Three user-reported failures in the Team Chat page — a **stalled tool approval**, a **notification that
187
+ landed nowhere**, and an **unreliable "jump to search result"** — turned out to be the same two
188
+ structural faults in different clothes:
189
+
190
+ - **R1 — one fact, several writers.** Two independent async writers could publish the same fact, and
191
+ whichever finished last won. (Which session tab is active; where the viewport is; how much history a
192
+ window still has.)
193
+ - **R2 — one invariant, several measures.** The same invariant was computed in more than one place, so
194
+ the places could disagree — and one of them was cached past the point of being true. (`hasMore` read
195
+ from a React render-time projection; "the target session finished loading" inferred from
196
+ `!loadingChat`.)
197
+
198
+ Both are cured the same way: **delete the second writer / the second measure**, or move the fact into the
199
+ scope that actually owns it. The contracts below are the durable outcome; the round-by-round chase is
200
+ recorded in the commit message, and the invariants are pinned by unit tests in
201
+ `packages/web-ui/src/lib/*.test.ts` + `packages/web-ui/test/*.test.ts`.
202
+
203
+ ### 7.1 The message scroll container has exactly two write paths
204
+
205
+ `pages/Team.tsx` drives a single scroll container, and it may only be written by:
206
+
207
+ 1. **bottom-follow** while a stream is appending, and
208
+ 2. **one pending scroll intent** for the view (`pendingRestoreRef`, keyed by the scroll-memory key).
209
+
210
+ There is deliberately **no third path**. In particular the virtualizer's `scrollToIndex` / `measure()`
211
+ are forbidden: `scrollToIndex` arms an uncancellable internal rAF reconcile loop (≤ 5 s) that re-pushes
212
+ the viewport every time the measured offset of that index changes — which is exactly while lazy row
213
+ measurement is still settling — and `measure()` resets every cached row height to an estimate, causing
214
+ overlap and drift.
215
+
216
+ **Intent priority** (`ScrollIntentPriority`; the single arbiter is `shouldAcceptRestoreIntent`):
217
+
218
+ | priority | intent | meaning |
219
+ |---|---|---|
220
+ | 3 | `jump` | the user explicitly asked to see this message |
221
+ | 2 | `prepend` | pagination layout compensation (scrolled to top → older page inserted above) |
222
+ | 1 | `restore` | "bring me back to where I was" |
223
+
224
+ A later intent replaces an in-flight one **only if its priority is ≥** (equal ⇒ later wins) and only for
225
+ the same view. Consequence: an unsatisfied `jump` is never overridden by a `prepend` / `restore`.
226
+
227
+ **Viewport ownership** (`mayChangeViewportOwner`): only `jump` / `restore` may change who owns the
228
+ viewport. `prepend` moves pixels and nothing else — a pure layout compensation must not hand control
229
+ back to bottom-follow. `decideScrollFollow` takes `intentPending` so a pending intent also blocks
230
+ hand-back while the jump is still travelling.
231
+
232
+ **Release condition** (`anchorStability` + `planIntentPass`): an intent is released by **stability, not
233
+ by a timer**. "Rendered in the DOM" is not "at rest" — with estimated row heights, the first measurement
234
+ pass pushes the target away. `planIntentPass` therefore returns `refine` (correct now, keep retrying)
235
+ until the anchor is measured at its target position in **two consecutive passes**. While unsettled,
236
+ `RESTORE_INTENT_TTL_MS` (10 s) is not a release reason, and a `jump` / `prepend` is never downgraded to
237
+ "scroll to bottom". `GOTO_ROW_INSET` (12 px) parks the hit just below the viewport top so its trailing
238
+ context stays visible.
239
+
240
+ ### 7.2 Window bounds are per-buffer, owned by the buffer manager
241
+
242
+ `{ hasMore, oldestCursor }` used to live in **two globals** on `Team.tsx` while message content lived in
243
+ `ConversationBufferManager`, keyed per `bufferId`. Any session's load then overwrote the current view's
244
+ bounds → the loader read another session's `hasMore=false` / `oldestCursor=null`, spanned zero pages, and
245
+ a `jump` concluded "target not found → go to bottom". This is why it worked the first time (empty
246
+ buffer → the guarded path) and broke from the second visit onward.
247
+
248
+ Contract: bounds live **next to the messages they describe** — `windowBounds: bufferId → { hasMore,
249
+ oldestCursor }` inside the manager, same key, same storage, same lifetime (reset on eviction). The single
250
+ writer is the loader for **that** buffer. `loadMore()`'s return value is the only progress signal, and
251
+ `hasMore` is never re-derived from a render-time value.
252
+
253
+ ### 7.3 "Jump to message" is self-fetching and never shares the pagination channel
254
+
255
+ `loadMore()` returns `0` for three unrelated reasons — end of history, page dropped because the view
256
+ changed mid-flight, or "I joined someone else's in-flight request". A caller cannot tell them apart, so
257
+ `jumpToMessage` does **not** use that channel:
258
+
259
+ - `collectJumpWindow` — if the target is already in the buffer, **no fetch at all** (the fast path; this
260
+ is why same-session jumps always worked). Otherwise it pages from newest backwards until the target is
261
+ found, the target's own timestamp (`targetCreatedAt`) is passed, or the page cap (40) is hit.
262
+ - The collected ascending window plus its bounds are installed **in one write**; the scroll intent then
263
+ positions the view.
264
+ - `trimJumpWindow` — when the display cap trims, the target must survive (the cap keeps the newest, and
265
+ deep-history targets sit at the oldest end).
266
+ - Anchor resolution is **by row identity, not index** (`resolveRowAnchor`): the rendered list is a
267
+ projection of the buffer (activity-log rows and acknowledged notifications are filtered out), so a
268
+ buffer index does not address a rendered row.
269
+
270
+ ### 7.4 Session selection has one owner while a navigation is in flight
271
+
272
+ `navigationOwnsSessionChoice` — while a navigation intent is pending, the agent-switch effect must **not**
273
+ pick a session tab and must **not** schedule its own scroll restore. Otherwise two async writers race for
274
+ "which tab is active" (the late one wins → "it flashes the right message, then moves"), and a spurious
275
+ background load for the previously-viewed session can write bounds that the jump then reads.
276
+ `await switchSession()` resolves *after* messages are loaded, so callers must never infer "loaded" from
277
+ `!loadingChat`.
278
+
279
+ ### 7.5 Blocking approvals and notifications get a near-field entry point
280
+
281
+ Focus arbitration: **tool approval (it blocks the agent turn) > user input > notification.** One arbiter,
282
+ one modal at a time.
283
+
284
+ - **Tool approvals** (`hitlService.requestApprovalAndWait` suspends the whole agent turn) now get the same
285
+ treatment as `request_user_input`: an **amber banner above the composer** plus an auto-opened
286
+ `ToolApprovalModal`. Selection uses `details.toolName` — the marker unique to tool approvals — which
287
+ naturally excludes task/requirement structured approvals from the chat surface. The banner is scoped to
288
+ `activeSessionId` via `details.sessionId`, falling back to `agentId` for rows written before that field
289
+ existed. Auto-open happens once per approval, and only while the Team page is active on the chat tab.
290
+ - **Notifications**: clicking an agent in the roster (L1) opens **one review queue modal** — progress
291
+ `1 / N`, button "Next" → "Done" on the last — rather than N stacked modals. Closing it still performs
292
+ the landing. Only unread notifications auto-pop, and only on an explicit roster click (live arrivals
293
+ still go to the banner). Landing (`resolveReviewLanding`) prefers the session the notifications came
294
+ from and locates the earliest one, falling back to the main session only when they span sessions. The
295
+ notification's own time is shown via the single `lib/timeAgo.ts` implementation shared with the bell.
296
+
297
+ ### 7.6 Diagnostics
298
+
299
+ `lib/scrollDebug.ts` is an **opt-in, zero-overhead-when-off** trace for the intent path. Enable it once
300
+ in DevTools with `localStorage.setItem('markus.scrollDebug', '1')` (remove the key to disable). It prints
301
+ about ten decisions per jump (`jump:collected` / `jump:located` / `intent:apply` / `intent:refine` /
302
+ `intent:release-*`). This link is only truly observable in a live Electron window; the switch exists so
303
+ the next report can be diagnosed from evidence instead of inference.
304
+
305
+ ### 7.7 Known residuals
306
+
307
+ - Cross-agent jumps where the target session is not on the first page of that agent's session list still
308
+ switch by id; the left-hand tab title renders empty until refresh.
309
+ - Very deep targets need several sequential page fetches, so there is a brief wait between click and
310
+ landing (the viewport is pinned meanwhile — it does not bounce).
311
+ - A target that genuinely does not exist (deleted, or beyond the page cap) falls back to bottom with a
312
+ `console.warn` — an honest fallback, not a silent wrong jump.
@@ -0,0 +1,340 @@
1
+ # Learning Loop
2
+
3
+ > Normative Spec for Markus self-evolution. SSOT overview: [agent-runtime.md](./agent-runtime.md) §1.3–§1.4 / §7.
4
+ > Inspired by Hermes: execute ≠ learn; write-approval gate; progressive disclosure prerequisite.
5
+
6
+ ---
7
+
8
+ ## §0 Architecture map (one SOP, five triggers)
9
+
10
+ **Learning Habits** (§8) is the single encode SOP. Triggers must not steal each other's jobs:
11
+
12
+ | Mechanism | Trigger | Scenario | Habits injected? | Job |
13
+ |-----------|---------|----------|------------------|-----|
14
+ | Learning Habits | Always (non-dream) | N/A (L0 text) | — | Look back / me-vs-others / encode / verify |
15
+ | Remember | User button (DM) | `chat` child session | Yes | Human-driven chat replay (§9) |
16
+ | Distillation | Task **completed** (predicates) | **`distillation`** | **Yes** | Trajectory → Learning Habits encode (§2) |
17
+ | Dream | obs buffer ≥70% of budget (or ≥50 entries), ~1×/day | `memory_consolidation` | **No** | Hygiene: dedupe/merge/promote/TTL (§5) |
18
+ | Memory Flush | Context high-water | `memory_flush` / sys | No essay | Preserve before compaction |
19
+ | Heartbeat | Timer | `heartbeat` | Yes (short) | Patrol only; ≤1-line `memory_save` (§7) |
20
+
21
+ MUST NOT: Run post-task reflection under `memory_consolidation` (that scenario is Dream-only).
22
+ MUST NOT: Use Dream to encode a fresh task trajectory (Distillation owns that).
23
+
24
+ ---
25
+
26
+ ## §1 Goals
27
+
28
+ Turn **completed** task trajectories (especially those with reviewer/user feedback via revision)
29
+ into durable assets (memory → skills) without bloating the Context Surface.
30
+ Skill library growth MUST only increase L0 catalog size.
31
+
32
+ ---
33
+
34
+ ## §2 Distillation Hook
35
+
36
+ ### §2.1 Trigger
37
+
38
+ MUST: After a task reaches **`completed`** (including rejection→revision→later-approval),
39
+ evaluate distillation predicates asynchronously (MUST NOT block the status transition).
40
+
41
+ MUST NOT: Run distillation on `failed` / cancelled / still-open tasks — there is no accepted
42
+ outcome yet; wait until completion (or human Remember §9).
43
+
44
+ MUST fire when status is `completed` and **any** of:
45
+
46
+ 1. Tool-call count on the execution trajectory ≥ 5 (**known** count)
47
+ 2. Task experienced at least one review rejection / `executionRound > 1` (feedback exists)
48
+ 3. ≥ 2 similar tasks completed in a recent window (same project + overlapping title tokens)
49
+
50
+ MUST NOT fire when none of the above hold (trivial first-pass short tasks).
51
+ When tool-call count is unknown/missing, runtime MAY still distill on `completed` (transitional
52
+ until telemetry lands) — MUST NOT treat a **known** low count as “unknown”.
53
+
54
+ Test IDs: `B-hook-skip-trivial`, `B-hook-fire-complex`, `B-hook-skip-failed`.
55
+
56
+ ### §2.2 Execution
57
+
58
+ MUST: Run with `scenario: distillation` (capability pack `reflex` + distillation allowlist).
59
+ MUST NOT: Use `scenario: memory_consolidation` for post-task reflection.
60
+
61
+ MUST: Inject `## Learning Habits` (§8) into the system prompt for `distillation`
62
+ (`B-distill-habits-injected`). Dream MUST omit Habits (`B-dream-no-habits`).
63
+
64
+ MUST: Tool allowlist = reflex core ∪
65
+ `memory_update`, `memory_update_longterm`, `file_write`, `file_edit`,
66
+ `package_list`, `package_install`.
67
+ MUST NOT: Include `hub_install` / agent|team auto-deploy on the distillation turn
68
+ (`B-distill-no-hub-install`). Skill install MUST follow §8.3 impact/HITL
69
+ (`B-distill-package-install-allowed`): high/omitted → `request_user_input` then install;
70
+ low → may install directly.
71
+
72
+ MUST NOT: Require a structured JSON outcome enum. The agent follows Learning Habits —
73
+ encode with tools when there is a durable lesson; if nothing noteworthy, stop quietly.
74
+
75
+ Test IDs: `B-distill-uses-distillation-scenario`, `B-distill-habits-injected`,
76
+ `B-distill-package-install-allowed`.
77
+
78
+ ---
79
+
80
+ ## §3 Staged skills + approval (optional helper)
81
+
82
+ Primary agent path is §8.3: create under `builder-artifacts/skills/` then `package_install`
83
+ with impact/HITL. This section is an optional staging helper when the agent prefers a draft
84
+ before install.
85
+
86
+ MUST: `.pending/` drafts MUST NOT become live until human approve (or the agent installs via §8.3).
87
+
88
+ Storage options (either is compliant):
89
+
90
+ 1. `builder-artifacts/skills/.pending/<name>/SKILL.md` (+ skill.json), or
91
+ 2. Requirement type `skill-distillation` whose body is the SKILL.md content
92
+
93
+ MUST: On approve → install under `builder-artifacts/skills/<name>/` (or equivalent package path)
94
+ and expose via L0 catalog / `discover_tools`.
95
+
96
+ MUST: On reject → persist reason as negative feedback; SHOULD suppress near-identical re-proposals.
97
+
98
+ Test IDs: `B-stage-not-live`, `B-approve-install`, `B-reject-feedback`.
99
+
100
+ MUST NOT: Auto-write team skills from inside `task_execution`.
101
+
102
+ ---
103
+
104
+ ## §4 Skill stats
105
+
106
+ MUST: Persist per-skill stats (sidecar `stats.json` or `skill.json.stats`):
107
+
108
+ ```json
109
+ {
110
+ "usage_count": 0,
111
+ "success_count": 0,
112
+ "last_used": null,
113
+ "avg_token_cost": null,
114
+ "feedback": []
115
+ }
116
+ ```
117
+
118
+ MUST: `discover_tools` activation of a skill increments `usage_count` and updates `last_used`.
119
+ MUST: When a task that activated the skill reaches `completed`, increment `success_count`.
120
+ MUST: On task `rejected` (review), append a feedback line if the skill was active.
121
+ MUST NOT: Modify trust score based on these stats.
122
+
123
+ Test IDs: `B-stats-activate`, `B-stats-success`, `B-stats-reject-feedback`.
124
+
125
+ ---
126
+
127
+ ## §5 Dream Librarian
128
+
129
+ MUST: Dream runs only as `scenario: memory_consolidation` (hygiene). MUST NOT inject Learning Habits.
130
+ MUST NOT: Use Dream for post-task trajectory reflection (§2 owns that).
131
+
132
+ MUST: Periodic dream/consolidation SHOULD also:
133
+
134
+ 1. Suggest archive for skills with `usage_count = 0` and age > 30 days
135
+ 2. Suggest revise when `success_count / usage_count < 0.5` (usage ≥ 3)
136
+ 3. Suggest merge when duplicate skill names/tags collide
137
+ 4. Expire notebook entries per tier TTL (`NOTEBOOK_TTL_MS_*`) — the `state.md` TTL prune was removed with that store (2026-09-16)
138
+ 5. Promote recurring observations (3+) into `knowledge.md`
139
+ 6. When negative feedback ≥ 3 on a skill, open/suggest a revision task
140
+ 7. When ≥ 3 agents independently record the same insight theme, suggest a team skill
141
+
142
+ Test IDs: `C-dream-archive-suggest`, `C-dream-state-ttl`, `C-dream-promote-insight`,
143
+ `B-dream-no-habits`.
144
+
145
+ ---
146
+
147
+ ## §6 Fanout + metrics API
148
+
149
+ MUST: On new live skill or major version, enqueue at most **one** skill-update mailbox item per
150
+ agent per calendar day (merge multiples). Recipients MUST match skill tags ↔ agent ROLE/skills.
151
+
152
+ MUST: Evolution metrics API exposes:
153
+
154
+ - skill reuse rate = tasks that activated ≥1 skill / tasks completed
155
+ - first-pass rate = tasks approved without prior rejection / tasks reviewed
156
+ - distill rate = tasks that ran post-task distillation / tasks completed
157
+
158
+ Healthy distill rate band: 10–30% (informational).
159
+
160
+ Test IDs: `C-fanout-cap`, `C-fanout-tag-match`, `C-metrics-api`.
161
+
162
+ ---
163
+
164
+ ## §7 Heartbeat
165
+
166
+ MUST NOT: Inject long self-evolution essays into reflex heartbeat prompts.
167
+ Distillation (§2), Dream (§5), and Prompt Habits (§8) cover learning; heartbeat MAY at most
168
+ `memory_save` a one-line insight.
169
+
170
+ Test ID: `B-hb-no-evolution-essay`.
171
+
172
+ ---
173
+
174
+ ## §8 Prompt Habits (Look back / Encode where / Skill impact)
175
+
176
+ MUST: Platform Tier-1 L0 injects a short `## Learning Habits` section into
177
+ `ContextEngine.buildSystemPrompt()` for all scenarios **except** `memory_consolidation`
178
+ (Dream). MUST include `distillation`, `chat`, `group_chat`, `task_execution`, `review`,
179
+ `heartbeat`.
180
+
181
+ MUST: Section length ≤ **1600 characters**.
182
+
183
+ MUST NOT: Rely on the retired alwaysOn `self-evolution` skill for this SOP — habits are
184
+ platform-native. The `self-evolution` skill package MUST NOT ship in `templates/skills/`.
185
+
186
+ ### §8.1 Look back
187
+
188
+ SHOULD before non-trivial work:
189
+
190
+ 1. Read injected `## Your Knowledge`
191
+ 2. `memory_search` and/or `recall_activity` for similar past work
192
+ 3. If L0 skill catalog matches → `discover_tools` activate before reinventing
193
+
194
+ MUST NOT require look-back for greetings / one-shot factual lookups / pure acks.
195
+
196
+ **Recall when memory is incomplete** (you misremember, key context/decisions are
197
+ hazy, or you must reconstruct what you did before) — reconstruct reliably, never
198
+ guess or fabricate:
199
+
200
+ 1. **Cheapest first**: skim `## Your Knowledge`; `memory_search` for past lessons/decisions.
201
+ 2. **What you actually did**: `recall_activity` (your tool/task history); `git log` when code is involved.
202
+ 3. **Across sessions**: `session` tool → list your sessions → `session get <id>`,
203
+ paging until `hasMore=false` and/or filtering by `since`/`until`, to rebuild the
204
+ full time-ordered timeline. MUST NOT conclude from a single page or from what is
205
+ merely visible in the current context window.
206
+ 4. Reconstruct (what / when / why) before reporting; if still unclear, say so honestly.
207
+
208
+ **Avoid over-recall**: stop digging once the needed context is in hand — preserve
209
+ working memory and momentum. Never let past detail drown current work; recall to
210
+ act, not to ruminate.
211
+
212
+ ### §8.2 Encode where
213
+
214
+ After complex, corrected, failed-then-fixed, or reusable work, SHOULD encode using the
215
+ **lightest store that changes future behavior**.
216
+
217
+ **Me vs others (first cut):**
218
+
219
+ | Audience | Store |
220
+ |---|---|
221
+ | Only helps *this* agent / *this* user (prefs, one-off lessons, personal workflows) | Memory (`memory_save` / `memory_update` → `knowledge.md`) or ROLE / HEARTBEAT |
222
+ | Helps *other agents* as an executable playbook / MCP / shared workflow | Skill under `builder-artifacts/skills/` then §8.3 install |
223
+
224
+ Skill MUST be steps/tools/boundaries — MUST NOT be a diary dump of transcripts.
225
+ Same theme recurring 3+ times AND shareable → SHOULD promote memory → skill.
226
+
227
+ | Learned what | Where |
228
+ |---|---|
229
+ | One-off lesson / gotcha | `memory_save` |
230
+ | Personal multi-step procedure | `memory_update` / `memory_update_longterm` → `knowledge.md` curated section |
231
+ | Always-on behavioral rule (this agent) | append ROLE.md via `file_edit`; identity/scope rewrite → ask human first |
232
+ | Recurring patrol check | edit HEARTBEAT.md (keep lean) |
233
+ | Team-reusable / MCP / shared workflow | create under `builder-artifacts/skills/` then §8.3 install |
234
+
235
+ SHOULD prefer concrete `[INSIGHT]` one-liners; SHOULD prune stale `knowledge.md` / HEARTBEAT entries;
236
+ MUST NOT dump raw transcripts into memory. Tool results SHOULD report `store: "knowledge.md"`
237
+ (legacy `MEMORY.md` is not the write target).
238
+
239
+ ### §8.3 Skill install impact
240
+
241
+ After creating/updating a skill artifact:
242
+
243
+ - **Low impact** (narrow tip, no MCP/network/secrets, unlikely to reshape other agents’
244
+ workflows): `package_install({ type: "skill", name, impact: "low" })` — MUST skip HITL.
245
+ - **High impact** (broad procedures, MCP/permissions, overlaps existing skills, org process):
246
+ MUST ask via `request_user_input` (or equivalent), then
247
+ `package_install({ type: "skill", name, impact: "high" })` — MUST require HITL.
248
+ - If `impact` omitted for `type: "skill"`, MUST treat as **high**.
249
+ - `type: "agent" | "team"`: MUST always HITL; MUST NOT auto-hire/deploy without explicit human ask.
250
+
251
+ Note: §3 `.pending` staging remains a distillation-helper path; **agent-facing instructions
252
+ MUST use builder-artifacts + `package_install` impact**, not `.pending` promote UI (not productized).
253
+
254
+ ### §8.4 Soften “No auto-install”
255
+
256
+ MUST: L0 platform rules distinguish skills (follow §8.3) from agents/teams (hard gate).
257
+
258
+ Test IDs: `B-prompt-learning-habits-present`, `B-prompt-learning-habits-absent-dream`,
259
+ `B-prompt-learning-habits-budget`, `B-skill-install-low-skips-hitl`,
260
+ `B-skill-install-high-requires-hitl`, `B-agent-install-always-hitl`,
261
+ `B-self-evolution-skill-retired`.
262
+
263
+ User-initiated Remember UX: §9.
264
+
265
+ ---
266
+
267
+ ## §9 Remember-from-message (user↔agent DM)
268
+
269
+ ### §9.1 UX
270
+
271
+ MUST: On agent bubbles in **user↔agent personal DM chat only**, offer a **Remember** action.
272
+
273
+ MUST NOT: Show Remember in Team/group chat or agent↔agent (A2A) threads.
274
+
275
+ SHOULD: Modal with optional user note (“what to remember”) + Confirm/Cancel.
276
+
277
+ MUST: On confirm, open a **new personal evolution child session** with that agent — process
278
+ visible to the user. MUST NOT inject evolution tool chatter into the parent DM transcript
279
+ beyond lineage metadata on the child.
280
+
281
+ ### §9.2 API
282
+
283
+ MUST: `POST /api/agents/:agentId/evolve-from-message` (same auth as chat).
284
+
285
+ Body:
286
+
287
+ | Field | Rule |
288
+ |---|---|
289
+ | `parentSessionId` | Required; MUST be a personal DM `chat_sessions` row for this user↔agent |
290
+ | `sourceMessageId` | Optional focus bubble id |
291
+ | `sourceText` | Optional client excerpt fallback |
292
+ | `userNote` | Optional highest-priority intent |
293
+
294
+ MUST reject non-DM / foreign parents (`B-evolve-api-rejects-non-dm-parent`).
295
+
296
+ MUST: Create child session; set `chat_sessions.metadata`:
297
+
298
+ ```json
299
+ {
300
+ "kind": "evolution",
301
+ "parentSessionId": "...",
302
+ "sourceMessageId": "...",
303
+ "sourceAgentId": "...",
304
+ "sourceExcerpt": "...",
305
+ "createdFrom": "remember_button"
306
+ }
307
+ ```
308
+
309
+ MUST: Seed a user message that includes:
310
+
311
+ 1. Capped parent transcript (last **40** messages or **~24k chars**; mark truncation)
312
+ 2. Tool summaries on assistant turns when present
313
+ 3. Focus message marker when available
314
+ 4. Explicit `parentSessionId`, `evolutionSessionId`, optional `sourceMessageId`
315
+ 5. Instruction to follow Learning Habits (§8) and, if truncated, fetch more via
316
+ `recall_context({ scope: "chat_session", session_id: parentSessionId, before, limit })`
317
+ 6. Prefer lessons from user corrections/outcomes; summarize encodings at end
318
+
319
+ MUST: Start the agent turn on the **child** session only (`scenario: chat`, tools on —
320
+ MUST NOT use dream `memory_consolidation`).
321
+
322
+ Test IDs: `B-evolve-api-creates-child-session`, `B-evolve-api-metadata-lineage`,
323
+ `B-evolve-seed-includes-parent-session-id`, `B-evolve-seed-includes-parent-transcript`,
324
+ `B-evolve-seed-includes-tool-summaries-when-present`, `B-evolve-seed-marks-focus-message`,
325
+ `B-evolve-api-seed-contains-habits-instructions`, `B-evolve-only-writes-child-session`,
326
+ `B-ui-remember-action-on-dm-agent-bubble`, `B-ui-remember-hidden-in-group-and-a2a`.
327
+
328
+ ### §9.3 `recall_context` scope `chat_session`
329
+
330
+ MUST: Extend `recall_context` with `scope: "chat_session"` + required `session_id`,
331
+ `limit` (default 40, max 100), `before` (ISO pagination).
332
+
333
+ MUST: Only allow sessions owned by the calling agent; reject foreign sessions.
334
+
335
+ Test IDs: `B-recall-chat-session-paginates`, `B-recall-chat-session-rejects-foreign`.
336
+
337
+ ### §9.4 Non-goals
338
+
339
+ MUST NOT: Session tree/forest explorer; auto-fork every assistant message; silent background
340
+ evolution without user confirm; Remember on group/A2A.