@markus-global/cli 0.11.2 → 0.11.3

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-DN3Cichs.js} +1 -1
  5. package/dist/web-ui/assets/{ContentRenderer-rzRUDj8T.js → ContentRenderer-CjHOyYgJ.js} +2 -2
  6. package/dist/web-ui/assets/{DeliverableShareModal-BvfmqTNG.js → DeliverableShareModal-CBSvxB-X.js} +1 -1
  7. package/dist/web-ui/assets/{Deliverables-DKTLnaF8.js → Deliverables-BaAF4-w0.js} +1 -1
  8. package/dist/web-ui/assets/{Notifications-CWaO9onn.js → Notifications-CCsdBfdg.js} +1 -1
  9. package/dist/web-ui/assets/{Search-D_C5Eyed.js → Search-BiBdevAU.js} +1 -1
  10. package/dist/web-ui/assets/{Settings-B5Ib6SFf.js → Settings-CawBnWuy.js} +6 -6
  11. package/dist/web-ui/assets/{Store-D__pfqoc.js → Store-BWi97VP9.js} +1 -1
  12. package/dist/web-ui/assets/Team-CfUDkdc3.js +84 -0
  13. package/dist/web-ui/assets/{Work-BJ7kXixx.js → Work-DrIXOW-P.js} +1 -1
  14. package/dist/web-ui/assets/{arc-BN0GMYN6.js → arc-Cg0-C295.js} +1 -1
  15. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-BP5Nnl2Y.js → architectureDiagram-3BPJPVTR-BctEHNLp.js} +1 -1
  16. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-nKHUCU_z.js → blockDiagram-GPEHLZMM-hxr2ZwOV.js} +1 -1
  17. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-DoS0wcHh.js → c4Diagram-AAUBKEIU-CfIRo1GE.js} +1 -1
  18. package/dist/web-ui/assets/channel-DAQ2Rbxq.js +1 -0
  19. package/dist/web-ui/assets/{chunk-2J33WTMH-CP54_XNl.js → chunk-2J33WTMH-T0bENsqX.js} +1 -1
  20. package/dist/web-ui/assets/{chunk-4BX2VUAB-DMvJaJb7.js → chunk-4BX2VUAB-ChLLkyYx.js} +1 -1
  21. package/dist/web-ui/assets/{chunk-55IACEB6-DQnZgoOO.js → chunk-55IACEB6-BD3ENYp9.js} +1 -1
  22. package/dist/web-ui/assets/{chunk-727SXJPM-B5_3LI53.js → chunk-727SXJPM-BAes4atE.js} +1 -1
  23. package/dist/web-ui/assets/{chunk-AQP2D5EJ-B5Mh5bI_.js → chunk-AQP2D5EJ-FymM7gfT.js} +1 -1
  24. package/dist/web-ui/assets/{chunk-FMBD7UC4-mjYTpuBm.js → chunk-FMBD7UC4-N5sRT0m9.js} +1 -1
  25. package/dist/web-ui/assets/{chunk-ND2GUHAM-BxTrseJg.js → chunk-ND2GUHAM-BSjS3JyS.js} +1 -1
  26. package/dist/web-ui/assets/{chunk-QZHKN3VN-C1do5brE.js → chunk-QZHKN3VN-Dkwitdbr.js} +1 -1
  27. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BZyCVtJb.js +1 -0
  28. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BZyCVtJb.js +1 -0
  29. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-DMn7aSDK.js → cose-bilkent-S5V4N54A-BLuYATCK.js} +1 -1
  30. package/dist/web-ui/assets/{dagre-BM42HDAG-CE-tTagY.js → dagre-BM42HDAG-DGLiqiH2.js} +1 -1
  31. package/dist/web-ui/assets/{diagram-2AECGRRQ-BwyvxbJa.js → diagram-2AECGRRQ-Cq_GnNKs.js} +1 -1
  32. package/dist/web-ui/assets/{diagram-5GNKFQAL-Nopndxl0.js → diagram-5GNKFQAL-CHNz-2dA.js} +1 -1
  33. package/dist/web-ui/assets/{diagram-KO2AKTUF-CGTjHHnD.js → diagram-KO2AKTUF-D8eKa7jh.js} +1 -1
  34. package/dist/web-ui/assets/{diagram-LMA3HP47-DhC3AqLA.js → diagram-LMA3HP47-RkDgQcLr.js} +1 -1
  35. package/dist/web-ui/assets/{diagram-OG6HWLK6-BIuzyWJO.js → diagram-OG6HWLK6-LqxQrIwa.js} +1 -1
  36. package/dist/web-ui/assets/{docx-preview-ClO_djcO.js → docx-preview-Be-Qo_ag.js} +1 -1
  37. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-Nmfi9Wv0.js → erDiagram-TEJ5UH35-BX0zZgYQ.js} +1 -1
  38. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-BVAM5QzO.js → flowDiagram-I6XJVG4X-DKnfIFA4.js} +1 -1
  39. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-BGdTbY0A.js → ganttDiagram-6RSMTGT7-DjBURmY-.js} +1 -1
  40. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-BMfug5mp.js → gitGraphDiagram-PVQCEYII-BvSi7SvS.js} +1 -1
  41. package/dist/web-ui/assets/{index-1X1Ykov8.js → index-D8vskks7.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-CwtIgim2.js} +1 -1
  44. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-Bro4RrlG.js → ishikawaDiagram-YF4QCWOH-CWhXJfSa.js} +1 -1
  45. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-CdRHOaID.js → journeyDiagram-JHISSGLW-DN9rorlL.js} +1 -1
  46. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-9iLNl-rB.js → kanban-definition-UN3LZRKU-Burf5FE8.js} +1 -1
  47. package/dist/web-ui/assets/{mermaid.core-BRHCbDDt.js → mermaid.core-Dx4rzlyC.js} +5 -5
  48. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-BLm-XQ6W.js → mindmap-definition-RKZ34NQL-DqZ21Siw.js} +1 -1
  49. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-ith90T5A.js → pieDiagram-4H26LBE5-C_4ksu-T.js} +1 -1
  50. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-Cb08oHG7.js → quadrantDiagram-W4KKPZXB-Dl6Rjg1X.js} +1 -1
  51. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-DzMKi4w8.js → requirementDiagram-4Y6WPE33-CzmWi02d.js} +1 -1
  52. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-C0Wv4A7m.js → sankeyDiagram-5OEKKPKP-D8K7e8we.js} +1 -1
  53. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-C_HL9WB0.js → sequenceDiagram-3UESZ5HK-1z9rqtVx.js} +1 -1
  54. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-BFfTVEYQ.js → stateDiagram-AJRCARHV-nneYkkHa.js} +1 -1
  55. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-C-hpzcms.js +1 -0
  56. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-cyPnAADn.js → timeline-definition-PNZ67QCA-D6GmLlRi.js} +1 -1
  57. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-Cb82-9OZ.js → vennDiagram-CIIHVFJN-TVefhiCa.js} +1 -1
  58. package/dist/web-ui/assets/{wardley-L42UT6IY-BTW1NXXR.js → wardley-L42UT6IY-BgUuAeiM.js} +1 -1
  59. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-C_F_dT6n.js → wardleyDiagram-YWT4CUSO-CyJ_l94o.js} +1 -1
  60. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-clcfplhG.js → xychartDiagram-2RQKCTM6-kajbbx7a.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,665 @@
1
+ # State Machines
2
+
3
+ This document defines the Finite State Machine (FSM) specifications for tasks, requirements, and related subsystems in Markus (goals, callbacks, mailbox items, A2A channels, notebook).
4
+
5
+ ## 1. Unified Status Vocabulary
6
+
7
+ Tasks and requirements share a **single status enum** (`ItemStatus`). Not every status applies to both types, but when the same concept exists, it uses the same name and behaves the same way.
8
+
9
+ | Status | Label | Tasks | Requirements | Description |
10
+ |--------|-------|:-----:|:------------:|-------------|
11
+ | `pending` | Pending | ✓ | ✓ | Created, awaiting human approval |
12
+ | `in_progress` | In Progress | ✓ | ✓ | Approved, work is active |
13
+ | `blocked` | Blocked | ✓ | ○ | On hold (dependencies, manual pause) |
14
+ | `review` | In Review | ✓ | ○ | Execution done, awaiting reviewer evaluation |
15
+ | `completed` | Completed | ✓ | ✓ | Successfully finished |
16
+ | `failed` | Failed | ✓ | ○ | Unrecoverable error after retry exhaustion |
17
+ | `rejected` | Rejected | ✓ | ✓ | Proposal not approved by human |
18
+ | `cancelled` | Cancelled | ✓ | ✓ | Deliberately stopped after work began |
19
+ | `archived` | Archived | ✓ | ○ | Historical record, no longer active |
20
+
21
+ ✓ = actively used, ○ = reserved for future use
22
+
23
+ **Key design decisions:**
24
+ - `rejected` ≠ `cancelled`. Rejection means "we don't want this" (proposal denied). Cancellation means "we chose to stop" (work was underway).
25
+ - There is no `approved` status. Approval transitions directly to `in_progress` (for both tasks and requirements). The intermediate state added no user decision point.
26
+ - There is no `draft` status. Items are created directly as `pending`. The distinction between "draft" and "submitted for review" added no practical value — agents create items programmatically and don't iterate on drafts.
27
+ - `pending` replaces the old `pending_approval` (tasks), `pending_review` (requirements), and `draft` (requirements).
28
+ - **All tasks start as `pending`** — both human-created and agent-created tasks begin in `pending` status. Human-created tasks require the user to explicitly click "Start Execution" to transition to `in_progress`. Agent-created tasks require human approval (HITL). This gives humans full control over when execution begins.
29
+
30
+ ---
31
+
32
+ ## 2. Task States
33
+
34
+ ### State Transition Diagram
35
+
36
+ ```
37
+ ┌─────── (retry fresh) ───────┐
38
+ │ │
39
+ ▼ │
40
+ pending ──────► in_progress ──► review ──► completed ──► archived
41
+ │ │ ▲ │
42
+ │ │ │ └── (revision) ──► in_progress
43
+ │ │ │
44
+ │ ▼ │
45
+ │ blocked ┘ (resume / deps satisfied)
46
+ │ │
47
+ ▼ ▼
48
+ rejected failed ──► archived
49
+ │
50
+ └── (retry fresh) ──► in_progress
51
+ ```
52
+
53
+ ### Transition Table
54
+
55
+ **All state transitions go through `updateTaskStatus()`**, which validates every transition against the declarative `TASK_TRANSITIONS` matrix defined in `@markus/shared`. Transitions not in the matrix are rejected with an error. No direct status mutation.
56
+
57
+ | From | To | Trigger | Method |
58
+ |------|----|---------|--------|
59
+ | `pending` | `in_progress` | Human approves or starts execution (no blockers) | `approveTask()` |
60
+ | `pending` | `blocked` | Human approves or starts execution (has unmet blockers) | `approveTask()` |
61
+ | `pending` | `rejected` | Human rejects | `rejectTask()` |
62
+ | `in_progress` | `review` | Agent execution finishes | Auto (log handler in `runTask`) |
63
+ | `in_progress` | `blocked` | User pauses task | API `POST /tasks/:id/pause` |
64
+ | `in_progress` | `failed` | Error + retries exhausted | Auto (retry logic) |
65
+ | `in_progress` | `cancelled` | User cancels | `cancelTask()` |
66
+ | `blocked` | `in_progress` | User resumes, or all blockers satisfied | `resumeTask` / `checkDependentTasks()` |
67
+ | `blocked` | `cancelled` | User cancels / cascade cancel | `cancelTask()` |
68
+ | `blocked` | `failed` | Blocker failed → cascade fail (dead dependency) | `autoFailBlockedDependent()` |
69
+ | `review` | `completed` | Reviewer approves | `acceptTask()` |
70
+ | `review` | `in_progress` | Reviewer requests revision (new round) | `requestRevision()` |
71
+ | `review` | `cancelled` | User cancels | `cancelTask()` |
72
+ | `failed` | `in_progress` | User clicks Retry (fresh start, new round) | `retryTaskFresh()` |
73
+ | `failed` | `archived` | Manual archival | `archiveTask()` |
74
+ | `completed` | `archived` | Manual archival | `archiveTask()` |
75
+ | `cancelled` | `in_progress` | Run Now (scheduled tasks) | `resetTaskForRerun()` |
76
+ | `cancelled` | `archived` | Manual archival | `archiveTask()` |
77
+ | `rejected` | `archived` | Manual archival | `archiveTask()` |
78
+
79
+ ### Side Effects in `updateTaskStatus()`
80
+
81
+ | Trigger | Side Effect |
82
+ |---------|-------------|
83
+ | → `in_progress` (from non-`in_progress`) | Auto-start: `runTask()` via `setImmediate` |
84
+ | `in_progress` → anything else | Cancel running execution (cancel token) |
85
+ | → `completed` / `failed` / `cancelled` / `rejected` / `archived` | Set `completedAt`; check dependent tasks for unblocking |
86
+ | → `review` | Notify reviewer (agent via mailbox, or human via approval request) |
87
+ | **Most status changes** | Enqueue `task_status_update` to assigned agent's mailbox (see [mailbox-system.md](./mailbox-system.md)). Skipped when: (a) auto-start triggers execution (the execution-mode item serves as both trigger and notification), or (b) `in_progress → review` (assignee self-initiated via `task_submit_review`) |
88
+
89
+ ### FSM Enforcement
90
+
91
+ The legal transition set is defined as a declarative matrix `TASK_TRANSITIONS` in `@markus/shared/types/task.ts`. `updateTaskStatus()` validates every transition against this matrix and rejects any transition not present. This is the single source of truth — when adding a new status or transition, update the matrix first, then update this document.
92
+
93
+ ### Key Rules
94
+
95
+ 1. **Single entry point**: All status changes go through `updateTaskStatus()`. Methods like `approveTask`, `acceptTask`, `requestRevision` prepare the task then delegate to `updateTaskStatus`.
96
+ 2. **Workers cannot self-complete**: Execution finish → `review`, not `completed`. A reviewer must approve.
97
+ 3. **Reviewer ≠ Worker**: Self-review is blocked. `reviewerId` is mandatory at task creation.
98
+ 4. **Retry = fresh start**: Retry increments `executionRound`, creates a new LLM session, discards previous execution context. Only the task description and notes carry over.
99
+ 5. **Pause = blocked**: Pausing a running task sets it to `blocked` and cancels execution. Resume calls `runTask` with full previous context.
100
+ 6. **Rejected ≠ Cancelled**: `rejectTask()` sets `rejected` (proposal denied before work). `cancelTask()` sets `cancelled` (work stopped after starting). `rejected` is a terminal state — the proposal was not approved.
101
+ 7. **Preemption ≠ blocked**: When the attention controller **preempts** (pauses) a task for a higher-priority item, the task stays `in_progress` (not `blocked`). The mailbox item is deferred and automatically resurfaced when the agent is idle. The same execution round and session context are preserved. **Cancellation** is different: when the controller **cancels** a task (because the incoming message explicitly revokes the work), the mailbox item is permanently dropped and will NOT be resumed.
102
+ 8. **Irreversible actions require confirmation**: The UI requires explicit user confirmation (via modal dialogs) for Reject, Cancel (always, regardless of dependents), and Archive operations. This prevents accidental data loss.
103
+ 9. **Scheduled task button restrictions**: Completed scheduled tasks do not show "Reopen" (the schedule handles re-runs). Failed scheduled tasks show only "Run Now" (no "Retry"/"Continue" since the scheduler manages retries). Cancelled scheduled tasks show "Run Now" and "Resume Schedule" to allow re-activation.
104
+ 10. **Human-created tasks**: Created as `pending` with no HITL approval request and no `task_created` notification (no self-notification). The UI shows "Start Execution" instead of "Approve" for human-created pending tasks. Agent-created tasks show "Approve" and trigger HITL approval flow.
105
+
106
+ ---
107
+
108
+ ## 3. Execution Rounds
109
+
110
+ Each task tracks an `executionRound` counter (starts at 1). It increments when:
111
+
112
+ - Reviewer requests revision (`requestRevision`)
113
+ - Scheduled task fires again (`resetTaskForRerun`)
114
+ - User clicks Retry (`retryTaskFresh`)
115
+
116
+ Within a single round, transient retries (network errors, timeouts) reuse the same LLM session — the agent picks up where it left off with full conversation history.
117
+
118
+ A new round always gets a fresh LLM session (`task_{taskId}_r{round}`).
119
+
120
+ ### Context by Round Type
121
+
122
+ | Scenario | Previous execution context | LLM session |
123
+ |----------|---------------------------|-------------|
124
+ | Transient retry (same round) | N/A — same session | Reused (full history) |
125
+ | Review revision (new round) | Included with `🔴 REVISION REQUIRED` header | Fresh |
126
+ | Scheduled rerun (new round) | Included (last N rounds) | Fresh |
127
+ | User Retry (new round) | **Not included** — clean start | Fresh |
128
+
129
+ ---
130
+
131
+ ## 4. Scheduled (Recurring) Tasks
132
+
133
+ Scheduled tasks follow the same state machine as standard tasks, with these differences:
134
+
135
+ ### Lifecycle
136
+
137
+ ```
138
+ pending → in_progress → review → completed
139
+ │
140
+ (scheduled rerun)
141
+ │
142
+ ▼
143
+ in_progress → review → completed → ...
144
+ ```
145
+
146
+ After `completed`, the `ScheduledTaskRunner` checks `nextRunAt`. When it's time, it calls `resetTaskForRerun()` which bumps `executionRound` and transitions back to `in_progress`.
147
+
148
+ ### Schedule Mechanism
149
+
150
+ 1. **`ScheduledTaskRunner`** polls every 60 seconds.
151
+ 2. Checks `nextRunAt` against current time.
152
+ 3. Fires only when task is in a "fireable" state (`completed`, `failed`) and not paused.
153
+ 4. Tasks in `in_progress`, `review`, `blocked`, `pending`, `cancelled`, `archived`, `rejected` are **skipped**.
154
+ 5. `config.paused = true` skips the task.
155
+ 6. `maxRuns` limit stops scheduling when `currentRuns >= maxRuns`.
156
+ 7. **Cancelling** a scheduled task automatically pauses its schedule (`config.paused = true`). The user can later resume the schedule or use "Run Now" to manually trigger execution.
157
+
158
+ ### Schedule Configuration Editing
159
+
160
+ The schedule configuration (`every`, `cron`, `maxRuns`, `timezone`) can be modified while a scheduled task exists:
161
+
162
+ - **Frontend**: "Edit" button appears on the schedule info banner (hidden when task is running or for one-shot `runAt` tasks). Opens an inline editor to switch between interval/cron mode and set max runs.
163
+ - **API**: `PUT /api/tasks/:id/schedule` with body `{ every?, cron?, maxRuns?, timezone? }`. Setting `every` clears `cron`/`runAt`; setting `cron` clears `every`/`runAt`. Recalculates `nextRunAt`.
164
+ - **Agent tool**: `task_update` accepts a `schedule` object `{ every?, cron?, max_runs?, timezone? }` for scheduled tasks.
165
+
166
+ ### Key Differences from Standard Tasks
167
+
168
+ | Aspect | Standard Task | Scheduled Task |
169
+ |--------|---------------|----------------|
170
+ | After `completed` | Terminal (can archive) | Waits for next scheduled run |
171
+ | Review acceptance | → `completed` (done) | → `completed` → next run at `nextRunAt` |
172
+ | Deliverables | Replaced each run | Accumulated (tagged with run number) |
173
+
174
+ ---
175
+
176
+ ## 5. Review Flow
177
+
178
+ ```
179
+ Agent (Worker) System Reviewer Agent
180
+ │ │ │
181
+ │── execution finishes ─►│ │
182
+ │ │── status → review ──────────►│
183
+ │ │── notify reviewer ──────────►│
184
+ │ │ (handleMessage with │
185
+ │ │ task context + prompt) │
186
+ │ │ │
187
+ │ │◄── acceptTask() ─────────────│
188
+ │ │ (→ completed) │
189
+ │ │ OR │
190
+ │ │◄── requestRevision(reason) ──│
191
+ │ │ (→ in_progress, new round) │
192
+ │ │ │
193
+ │◄── auto re-execute ───│ │
194
+ │ │ │
195
+ ```
196
+
197
+ ### Reviewer Notification
198
+
199
+ When a task enters `review` status (via `updateTaskStatus`), the system automatically:
200
+ 1. Looks up the `reviewerId` on the task
201
+ 2. Sends a structured review request to the reviewer — agent via mailbox, or human via HITL approval
202
+ 3. The message includes: task description, deliverables, subtask status, recent notes, and instructions
203
+
204
+ ### Reviewer Actions
205
+
206
+ - **Approve**: Calls `acceptTask(taskId)` → task moves to `completed`
207
+ - **Approve with notes** (`approved_with_notes`): Task moves to `completed` (or continues downstream);
208
+ notes are stored on the task (note / metadata) and SHOULD surface to the assignee via notebook/state
209
+ on the next related turn. Minor issues MUST NOT force a full revision round.
210
+ - **Request Revision**: Calls `requestRevision(taskId, reason)` → task moves to `in_progress` with incremented `executionRound`
211
+
212
+ ### Spec: `approved_with_notes`
213
+
214
+ MUST: Review verdict enum includes `approved` | `approved_with_notes` | `rejected`.
215
+ MUST: `approved_with_notes` completes the review gate without requiring another full execution round.
216
+ MUST: Notes are persisted and visible to the assignee.
217
+ Test ID: `C-review-notes`.
218
+
219
+ ### Spec: `task_context` on assign
220
+
221
+ MUST: When a task is assigned, the system attaches a read-only `task_context` package:
222
+ parent requirement summary, related deliverable refs (+ version), predecessor output summary,
223
+ project knowledge pointer. MUST inject into the assignee's first `execute` pack turn under a hard cap.
224
+ Test ID: `C-task-context-inject`.
225
+
226
+ ### Spec: Deliverable versioning
227
+
228
+ MUST: `deliverable_update` increments `version` and appends a `changelog` entry.
229
+ MUST: Reads return current `version`.
230
+ Test ID: `C-deliv-version`.
231
+
232
+ ### Spec: Subtask soft cap
233
+
234
+ MUST: When subtask count would exceed `SUBTASK_SOFT_CAP` (8), the tool MUST warn in the result
235
+ but MUST NOT block creation.
236
+ Test ID: `C-subtask-soft-cap`.
237
+
238
+ ### Spec: Deep sleep (heartbeat)
239
+
240
+ MUST: After `DEEP_SLEEP_IDLE_HEARTBEATS` consecutive idle/zero-change heartbeats with no active
241
+ tasks/pending reviews and no human/task mailbox pressure, heartbeat MUST skip the LLM call,
242
+ extend interval (≤ 24h), and wake on `human_chat` / new task / review events.
243
+ Test IDs: `A-deep-sleep-skip`, `A-deep-sleep-wake`.
244
+
245
+ ### Spec: Post-task distillation
246
+
247
+ MUST: On task `completed` (and gated predicates), enqueue Learning Loop distillation
248
+ ([learning-loop.md](./learning-loop.md)) without blocking the status transition.
249
+ MUST NOT: Distill on `failed` — wait for completion or human Remember.
250
+
251
+ ---
252
+
253
+ ## 6. Comment & Notification Rules
254
+
255
+ Comments on tasks and requirements trigger agent notifications via the agent's **mailbox**. Notifications are enqueued as `task_comment` or `requirement_comment` mailbox items. The system ensures **each agent receives at most one notification per comment**, regardless of how many rules match. See [mailbox-system.md](./mailbox-system.md) for details on the mailbox architecture.
256
+
257
+ **Structural reply-to**: Comment notifications include `replyToId` linking to a parent comment. The notification payload also includes an agent streak count (consecutive agent-only comments without human input) to help agents self-moderate reply frequency.
258
+
259
+ ### 6.1 Task Comment Notifications
260
+
261
+ When a comment is posted on a task, the following agents are notified (in priority order, deduplicated):
262
+
263
+ | # | Who | Condition | Mechanism | Reason |
264
+ |---|-----|-----------|-----------|--------|
265
+ | 1 | @mentioned agents | Always (except self and assignee on `in_progress` tasks) | `enqueueToMailbox('task_comment')` | Explicit intent to notify |
266
+ | 2 | Assigned agent (`assignedAgentId`) | Task is `in_progress` | Live inject into LLM session (`injectUserMessage`) | Agent sees comment immediately in current work context |
267
+ | 3 | Assigned agent (`assignedAgentId`) | Task is NOT `in_progress` | `enqueueToMailbox('task_comment')` | Agent is not actively working, needs separate notification |
268
+ | 4 | Creator (`createdBy`) | Task is NOT `in_progress` | `enqueueToMailbox('task_comment')` | Creator should know about discussion on their task |
269
+
270
+ **Key rules:**
271
+ - **Deduplication**: A `Set` tracks notified agent IDs. Each agent gets exactly one notification, even if they match multiple rules (e.g., creator = assignee, or creator is also @mentioned).
272
+ - **Self-skip**: The comment author never receives a notification about their own comment.
273
+ - **In-progress optimization**: When the task is `in_progress`, the assigned agent already receives every comment via live session injection. No separate mailbox notification is sent. The creator is also skipped — the assignee is responsible during execution.
274
+ - **@mention overrides**: Explicit @mentions always trigger notification, even for agents who would otherwise be skipped (except the assigned agent on `in_progress` tasks who already gets inject, and the comment author).
275
+
276
+ ### 6.2 Requirement Comment Notifications
277
+
278
+ | # | Who | Condition | Mechanism |
279
+ |---|-----|-----------|-----------|
280
+ | 1 | @mentioned agents | Always (except self) | `enqueueToMailbox('requirement_comment')` |
281
+ | 2 | Creator (`createdBy`) | Always (except self) | `enqueueToMailbox('requirement_comment')` |
282
+
283
+ Requirements have no running agent, so there is no live injection mechanism. All notifications are routed through the mailbox.
284
+
285
+ ### 6.3 Requirement Approval Notifications
286
+
287
+ When a human approves or rejects an agent-proposed requirement (`source: 'agent'`), the creator agent receives a `requirement_update` mailbox item with `actionRequired: true` and priority 1 (high). Both decisions trigger an LLM call with `scenario: 'requirement_action'`, prompting the agent to take immediate action:
288
+
289
+ | Decision | Notified | Agent Action |
290
+ |----------|----------|--------------|
291
+ | **Approved** | Creator agent | Create tasks via `task_create` to fulfill the requirement |
292
+ | **Rejected** | Creator agent | Review rejection reason; resubmit via `requirement_resubmit` with updates, or abandon |
293
+
294
+ Both decisions also create an HITL notification visible in the UI notification bell.
295
+
296
+ ### 6.4 Notification Paths
297
+
298
+ Comments flow through two code paths depending on the caller:
299
+
300
+ | Path | Caller | File |
301
+ |------|--------|------|
302
+ | HTTP API | Human via Web UI | `api-server.ts` POST `/api/tasks/:id/comments`, `/api/requirements/:id/comments` |
303
+ | Agent tool | Agent via `task_comment` / `requirement_comment` | `task-service.ts` `postTaskComment()`, `postRequirementComment()` |
304
+
305
+ Both paths apply identical notification logic (dedup, self-skip, stakeholder auto-notify).
306
+
307
+ ---
308
+
309
+ ## 7. Cancellation
310
+
311
+ ### Single Task Cancellation
312
+
313
+ When a task is cancelled:
314
+ 1. Running execution is stopped (cancel token)
315
+ 2. Status → `cancelled`
316
+ 3. If the task is a scheduled task, the schedule is automatically paused (`scheduleConfig.paused = true`)
317
+ 4. Dependent tasks are checked:
318
+ - If the cancelled task was a dependent's **only** remaining blocker, the dependent unblocks
319
+ - If the dependent has other incomplete blockers, it stays `blocked`
320
+
321
+ A cancelled scheduled task can be re-activated via "Run Now" (`cancelled → in_progress`) or by resuming the schedule after un-cancelling.
322
+
323
+ ### Cascade Cancellation
324
+
325
+ User can choose to cascade-cancel all dependent tasks:
326
+ 1. The task and all its `blocked` dependents are cancelled
327
+ 2. Their dependents are recursively checked
328
+
329
+ ### What Cannot Be Cancelled
330
+
331
+ - `pending` tasks → use Reject instead (sets `rejected`)
332
+ - Already terminal tasks (`completed`, `failed`, `cancelled`, `rejected`, `archived`)
333
+
334
+ ---
335
+
336
+ ## 8. Requirement FSM
337
+
338
+ Requirements represent high-level work items fulfilled by one or more tasks.
339
+
340
+ ### State Transition Diagram
341
+
342
+ ```
343
+ (agent) (human approves) (agent reviews &
344
+ │ │ marks complete)
345
+ ▼ ▼ ▼
346
+ pending ──────────► in_progress ──────────► completed
347
+ │ ▲ ▲
348
+ ▼ │ │
349
+ rejected ── resubmit ──┘ │
350
+ │
351
+ any ──► cancelled │
352
+ │
353
+ [all tasks done] ──notify agent──┘ (agent decides: complete or create more tasks)
354
+ ```
355
+
356
+ ### Transitions
357
+
358
+ | From | To | Trigger |
359
+ |------|----|---------|
360
+ | (new, agent) | `pending` | Agent proposes via `requirement_propose` |
361
+ | (new, human) | `in_progress` | User creates directly (auto-approved) |
362
+ | `pending` | `in_progress` | User approves |
363
+ | `pending` | `rejected` | User rejects |
364
+ | `rejected` | `pending` | Agent resubmits via `requirement_resubmit` (optionally with updates) |
365
+ | `in_progress` | `completed` | Agent evaluates all tasks done and marks complete |
366
+ | any | `cancelled` | Manual cancellation |
367
+
368
+ ### Key Rules
369
+
370
+ 1. **User-created requirements auto-approve** — start at `in_progress`
371
+ 2. **Agent proposals need user approval** — start at `pending`
372
+ 3. **Max 3 pending proposals per agent** — prevents spam
373
+ 4. **Completion is agent-driven** — when all linked tasks reach terminal state, the system notifies the creator agent (via `requirement_update` with `actionRequired: true`). The agent reviews the results and decides whether to mark the requirement as `completed` or create additional tasks. There is no automatic completion.
374
+ 5. **Approval triggers agent action** — when a requirement is approved (`pending → in_progress`), the creator agent receives a high-priority `requirement_update` with `actionRequired: true`, prompting immediate task creation.
375
+ 6. **No `approved` intermediate state** — approval goes directly to `in_progress`, same as tasks
376
+ 7. **No `draft` state** — items are created directly as `pending`; there is no separate drafting phase
377
+ 8. **Rejected requirements can be resubmitted** — agent calls `requirement_resubmit` to move back to `pending`, optionally updating title, description, priority, or tags. Rejection metadata is cleared on resubmit
378
+ 9. **Heartbeat checks requirements** — agents proactively check their created requirements during heartbeat: reviewing progress of `in_progress` requirements, reminding users about stale `pending` proposals, and handling `rejected` requirements
379
+ 10. **Optional goal loop overlay** — requirements may carry `GoalConfig` (`loopEnabled`, `completionCriteria`, `maxIterations`, etc.). When enabled, a parallel goal loop state runs on top of the requirement FSM (see §11)
380
+
381
+ ---
382
+
383
+ ## 9. Mailbox Notifications for State Changes
384
+
385
+ Every status transition in both task and requirement FSMs generates an automatic **mailbox notification** to the relevant agent. This ensures agents maintain full awareness of their work state.
386
+
387
+ ### Task Status Changes
388
+
389
+ `updateTaskStatus()` enqueues a `task_status_update` item to the assigned agent's mailbox for non-execution status transitions. When a transition triggers execution (→ `in_progress`), the notification is **skipped** because `runTask()` sends its own `task_status_update` with execution context via `sendTaskExecution()`:
390
+
391
+ ```
392
+ non-execution status change → agent.enqueueToMailbox('task_status_update', {
393
+ summary: "Task 'X' status: old → new",
394
+ content: transition details + action guidance,
395
+ taskId
396
+ })
397
+
398
+ execution trigger (→ in_progress) → runTask() → agent.sendTaskExecution() → enqueues task_status_update with extra.triggerExecution
399
+ ```
400
+
401
+ ### Requirement Status Changes
402
+
403
+ `updateRequirementStatus()` enqueues a `requirement_update` item to the creator agent:
404
+
405
+ ```
406
+ requirement status change → agent.enqueueToMailbox('requirement_update', {
407
+ summary: "Requirement 'X' status: old → new",
408
+ content: transition details,
409
+ requirementId, fromStatus, toStatus
410
+ })
411
+ ```
412
+
413
+ ### Design Rationale
414
+
415
+ - **Informational context only**: Task status notifications (`task_status_update`) are enqueued with `invokesLLM: false` — they do **not** trigger LLM processing. They exist as decision context for triage and as episodic memory, not as work items.
416
+ - **Side-effect system handles all actions**: The `updateTaskStatus()` method in `TaskService` automatically handles all real side effects triggered by status changes:
417
+ - **→ `in_progress`**: Auto-starts task execution via `runTask()`
418
+ - **Leaving `in_progress`**: Cancels any running execution
419
+ - **→ `review`**: Notifies the reviewer (agent or human)
420
+ - **Terminal states** (`completed`, `failed`, `cancelled`): Checks and unblocks dependent tasks
421
+ - **Agents should NOT duplicate these actions**: Do not send A2A messages to notify about task status changes — the system handles everything. A2A should only be used for substantive coordination that goes beyond a status change.
422
+ - **Episodic memory**: These notifications become part of the agent's mailbox timeline — the authoritative record of everything that happened. See [mailbox-system.md](./mailbox-system.md).
423
+ - **Event-driven**: Notifications are fire-and-forget (`enqueueToMailbox`). The agent's attention controller uses them as context during triage deliberation.
424
+
425
+ ---
426
+
427
+ ## 10. Migration from Legacy Statuses
428
+
429
+ On startup, the following data migrations run automatically:
430
+
431
+ | Table | Old Value | New Value | Reason |
432
+ |-------|-----------|-----------|--------|
433
+ | `tasks` | `pending_approval` | `pending` | Unified naming |
434
+ | `requirements` | `draft` | `pending` | `draft` state eliminated |
435
+ | `requirements` | `pending_review` | `pending` | Unified naming |
436
+ | `requirements` | `approved` | `in_progress` | `approved` state eliminated |
437
+
438
+ ---
439
+
440
+ ## 11. Goal Loop States
441
+
442
+ Requirements with an optional `GoalConfig` gain a **goal loop state** overlay when `loopEnabled` is true. The requirement FSM (§8) still governs approval and completion; goal loop states track heartbeat-driven iteration.
443
+
444
+ ### State Diagram
445
+
446
+ ```
447
+ requirement in_progress + loopEnabled
448
+ │
449
+ ▼
450
+ goal_active ◄─────────────────────────┐
451
+ │ │
452
+ │ heartbeat check │ next iteration
453
+ │ (incrementGoalIteration) │ (autoResume)
454
+ ▼ │
455
+ ┌─────────┼─────────┐ │
456
+ │ │ │ │
457
+ ▼ ▼ ▼ │
458
+ goal_completed goal_max_iterations goal_paused
459
+ (criteria met) (iteration limit) (loop disabled
460
+ │ │ or waiting)
461
+ ▼ │ │
462
+ requirement │ │
463
+ → completed └──── goal_update ─────┘
464
+ loopEnabled=false (re-enable / raise max)
465
+ ```
466
+
467
+ ### Transitions
468
+
469
+ | From | To | Trigger |
470
+ |------|----|---------|
471
+ | — | `goal_active` | `enableGoalLoop()` or `goal_create` on an `in_progress` requirement |
472
+ | `goal_active` | `goal_active` | Heartbeat patrol assesses progress; `currentIteration` increments |
473
+ | `goal_active` | `goal_completed` | Agent evaluates criteria met → requirement marked `completed`, `loopEnabled` → false |
474
+ | `goal_active` | `goal_max_iterations` | `currentIteration >= maxIterations` |
475
+ | `goal_active` | `goal_paused` | `disableGoalLoop()` or `goal_update(loop_enabled: false)` |
476
+ | `goal_paused` | `goal_active` | `enableGoalLoop()` / `goal_update(loop_enabled: true)` with `autoResume` |
477
+ | `goal_max_iterations` | `goal_active` | `goal_update` raises `max_iterations` or resets iteration count |
478
+
479
+ ### Key Rules
480
+
481
+ 1. **Heartbeat-driven** — active goals appear in the heartbeat **Active Goals** section via `goalFetcher`; the agent creates follow-up tasks and reassesses each iteration
482
+ 2. **Orthogonal to requirement status** — goal loop states apply only while the requirement is `in_progress`; terminal requirement statuses (`completed`, `cancelled`, `rejected`) end the loop
483
+ 3. **Safety cap** — `maxIterations` prevents unbounded heartbeat cycles; hitting the limit enters `goal_max_iterations`, not automatic completion
484
+ 4. **Tools** — `goal_create`, `goal_update`, `goal_status` manage the loop; see [mailbox-system.md](./mailbox-system.md) §11.4
485
+
486
+ ---
487
+
488
+ ## 12. Pending Callback States
489
+
490
+ `PendingCallbackRegistry` tracks async operations (e.g., `background_exec`) that must report results through the mailbox. See [mailbox-system.md](./mailbox-system.md) §11.3.
491
+
492
+ ### State Diagram
493
+
494
+ ```
495
+ registerBackgroundSession()
496
+ │
497
+ ▼
498
+ pending ────── resolve() ──────► resolved
499
+ │ (operation done) │
500
+ │ └── enqueue callback_result
501
+ │
502
+ ├── getTimedOut() ──► timed_out
503
+ │ │
504
+ │ └── expireTimedOut() ──► expired
505
+ │ (removed; surfaced in heartbeat)
506
+ └── (server restart) ──► pending (restored from SQLite)
507
+ ```
508
+
509
+ ### Transitions
510
+
511
+ | From | To | Trigger | Side Effect |
512
+ |------|----|---------|-------------|
513
+ | — | `pending` | `registerBackgroundSession()` / `PendingCallbackRegistry.register()` | Persisted via `SqlitePendingCallbackRepo` |
514
+ | `pending` | `resolved` | Operation completes; `resolve(id)` | Registry entry removed; `callback_result` mailbox item enqueued |
515
+ | `pending` | `timed_out` | Heartbeat calls `getTimedOut()` (`now - registeredAt > timeoutMs`) | Detected only — entry still in registry |
516
+ | `timed_out` | `expired` | Heartbeat calls `expireTimedOut(id)` | Registry entry removed; details injected into heartbeat prompt (no `callback_result`) |
517
+ | `pending` | `pending` | Server restart | `setPersistence()` restores all pending callbacks |
518
+
519
+ ### Key Rules
520
+
521
+ 1. **Resolved → mailbox** — only the `resolved` path produces a `callback_result` item; timeouts are surfaced for agent investigation, not auto-enqueued
522
+ 2. **Default timeout** — 10 minutes for `background_exec`
523
+ 3. **Origin session preserved** — `originSessionId` on the callback is copied into `callback_result.extra` for session resumption
524
+
525
+ ---
526
+
527
+ ## 13. Mailbox Item Lifecycle (`callback_result`)
528
+
529
+ All mailbox items, including `callback_result`, follow the standard attention pipeline. See [mailbox-system.md](./mailbox-system.md) §6.5.
530
+
531
+ ### Pipeline
532
+
533
+ ```
534
+ enqueue (queued)
535
+ │
536
+ ▼
537
+ dequeueAsync → (entity lock, concurrent mode) → processing
538
+ │
539
+ ▼
540
+ AttentionController triage → handleMessage(originSessionId)
541
+ │
542
+ ▼
543
+ complete (completed)
544
+ ```
545
+
546
+ > **Concurrent mode.** With a worker pool ([concurrent-processing.md](./concurrent-processing.md)),
547
+ > a worker takes an **entity-affinity lock** right after `dequeueAsync` and releases it in a
548
+ > `finally` after processing; items whose entity is already locked are skipped by
549
+ > `dequeue()` (put back and retried after a back-off). The worker loop **does not run
550
+ > triage / interrupt logic**, so the `deferred`, `dropped`, and `preempt` outcomes below are
551
+ > produced by the **serial** loop only. A worker's terminal outcomes are: *completed*,
552
+ > *requeued* (backstop timeout / non-user failure), or *completed-incomplete* for user items.
553
+
554
+ ### Terminal Outcomes (all mailbox items)
555
+
556
+ After `processFocusedItem` runs, exactly one terminal outcome is chosen (implemented in
557
+ [`attention.ts`](../../packages/core/src/attention.ts) `processFocusedItem`):
558
+
559
+ | Outcome | Trigger | Persistence effect | Resumable? |
560
+ |---------|---------|--------------------|-----------|
561
+ | **completed** | Normal finish (marker present, or accepted without-retry case) | `complete(id)` | No (done) |
562
+ | **dropped** | Explicit `cancel` decision / `[cancelled]` reply | `complete(id)` (permanent) | No |
563
+ | **deferred** | `preempt` decision / `[preempted]` reply | `deferDequeued(item)` | Yes — `resurfaceDue()` re-queues when idle |
564
+ | **requeued** | Backstop **timeout**, agent stopped mid-flight, or abnormal reply on a background type (< max retries) | `requeue(item)` | Yes — re-processed from queue |
565
+ | **completed (incomplete)** | Marker still missing after in-session continuation, or abnormal reply on a user-interaction item | `complete(id)` | No |
566
+
567
+ **Specs that refine these outcomes** (behavior/invariants/tests live in
568
+ [mailbox-system.md](./mailbox-system.md)):
569
+
570
+ - **Timeout → requeue must be single-flight**: on backstop timeout the in-flight processing
571
+ is cancelled and any late result is discarded, so a requeue cannot double side effects.
572
+ Status: planned.
573
+ - **completed (incomplete) must be visible**: the marker-missing terminal emits a structured
574
+ `incomplete` event / activity entry rather than resolving silently. Status: planned.
575
+
576
+ ### `callback_result` Specifics
577
+
578
+ | Stage | Behaviour |
579
+ |-------|-----------|
580
+ | **Enqueue** | Priority 1 (high); `invokesLLM: true`; payload includes `callbackId`, `originSessionId`, `callbackType` in `extra` |
581
+ | **Process** | Routed to originating session when known; falls back to system session |
582
+ | **Complete** | Activity recorded; item marked `completed` in persistence |
583
+
584
+ Unlike informational `task_status_update` items, `callback_result` always invokes an LLM call — the agent must act on async operation outcomes.
585
+
586
+ ---
587
+
588
+ ## 14. A2A DM Channel States
589
+
590
+ A2A messaging routes through **deterministic DM channels** (`dm:a2a:{sorted_id_1}:{sorted_id_2}`). Channels are created lazily on the first message and persist indefinitely — there is no explicit close state.
591
+
592
+ ### State Diagram
593
+
594
+ ```
595
+ (first agent_send_message between pair)
596
+ │
597
+ ▼
598
+ created ──► active ◄──────┐
599
+ │ │
600
+ │ messages │ new message
601
+ ▼ │
602
+ idle ─────────┘
603
+ (no recent traffic)
604
+ ```
605
+
606
+ ### Transitions
607
+
608
+ | From | To | Trigger |
609
+ |------|----|---------|
610
+ | — | `created` | First A2A message; `ensureDmChannel()` creates group-chat record with deterministic `channelKey` |
611
+ | `created` | `active` | Message sent/received; persisted to `channel_messages`, target agent mailbox enqueued (`a2a_message`) |
612
+ | `active` | `idle` | No messages for a period (implicit — channel remains open) |
613
+ | `idle` | `active` | New `agent_send_message` or inbound `a2a_message` |
614
+
615
+ ### Key Rules
616
+
617
+ 1. **One channel per agent pair** — IDs sorted lexicographically; same key regardless of sender
618
+ 2. **Stable sessions** — session ID derived from `channel_{channelKey}_{agentId}`; history recallable via `recall_context`
619
+ 3. **Fire-and-forget** — `agent_send_message` is always async; no `wait_for_reply`
620
+ 4. **No teardown** — channels survive agent restarts and idle periods; see [mailbox-system.md](./mailbox-system.md) §11.1
621
+
622
+ ---
623
+
624
+ ## 15. Notebook Lifecycle
625
+
626
+ `NOTEBOOK.md` is the agent's persistent cognitive workspace. Entry lifecycle is separate from task/requirement FSMs but follows the agent runtime.
627
+
628
+ ### State Diagram
629
+
630
+ ```
631
+ agent start
632
+ │
633
+ ▼
634
+ loadNotebook() ──► in-memory Map (keyed entries)
635
+ │
636
+ ├── session: updateWorkingMemory / triage
637
+ │ │
638
+ │ └── scheduleNotebookPersist (2s debounce)
639
+ │ │
640
+ │ ▼
641
+ │ saveNotebook() → NOTEBOOK.md on disk
642
+ │
643
+ agent stop
644
+ │
645
+ └── flush debounce → persistNotebookSync()
646
+ ```
647
+
648
+ ### Entry Managed Types
649
+
650
+ | Tag | Writer | Purpose |
651
+ |-----|--------|---------|
652
+ | `agent` | `notebook_upsert` / `notebook_clear` / `notebook_read` | Agent-chosen keys (priorities, blockers, decisions) |
653
+ | `system` | Triage, mechanical retrieval | `triage-decision`, `relevant-context` |
654
+
655
+ ### Transitions
656
+
657
+ | Event | Effect |
658
+ |-------|--------|
659
+ | Agent start | `loadNotebook(dataDir)` populates in-memory workspace; injected as `## Notebook` in every turn |
660
+ | Entry upsert | `updateWorkingMemory(key, content, managed?)` — agent-managed entries capped at 4 keys / 6000 chars each |
661
+ | Entry clear | `clearWorkingMemory(key?)` — single key or all entries |
662
+ | Debounced persist | 2s after last mutation → `saveNotebook()` |
663
+ | Agent stop | Cancel debounce timer; synchronous final `persistNotebookSync()` |
664
+
665
+ See [memory-system.md](./memory-system.md) and [cognitive-architecture.md](./cognitive-architecture.md) for storage format and deterministic context assembly.