@markus-global/cli 0.11.2-rc.0 → 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 +1260 -1125
  4. package/dist/web-ui/assets/{CommentInput-Cqi5Hldw.js → CommentInput-C-niUbUY.js} +1 -1
  5. package/dist/web-ui/assets/{ContentRenderer-BAB3il9e.js → ContentRenderer-DxsnJJRX.js} +2 -2
  6. package/dist/web-ui/assets/{DeliverableShareModal-DJXkM66x.js → DeliverableShareModal-DV3TiZx0.js} +1 -1
  7. package/dist/web-ui/assets/{Deliverables-zKPxgZAN.js → Deliverables-tlLsJnxZ.js} +1 -1
  8. package/dist/web-ui/assets/{Notifications-HAycgg2x.js → Notifications-4KXYRdkr.js} +1 -1
  9. package/dist/web-ui/assets/{Search-SZuDcxy0.js → Search-CPFwZv1U.js} +1 -1
  10. package/dist/web-ui/assets/{Settings-CZgNsYSC.js → Settings-DIa-_qre.js} +6 -6
  11. package/dist/web-ui/assets/{Store-BS7VNrsr.js → Store-JWjwXfTU.js} +1 -1
  12. package/dist/web-ui/assets/Team-COBxn96h.js +84 -0
  13. package/dist/web-ui/assets/{Work-BN-LsW3k.js → Work-BScJUqWL.js} +1 -1
  14. package/dist/web-ui/assets/{arc-CsnWE2QW.js → arc-DPZmpo1U.js} +1 -1
  15. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-CLek8I2z.js → architectureDiagram-3BPJPVTR-DlOs02JO.js} +1 -1
  16. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-jSgWEHN7.js → blockDiagram-GPEHLZMM-C7qsXNUe.js} +1 -1
  17. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BaC188UT.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-CdtP4-T4.js → chunk-2J33WTMH-VgR09Mqk.js} +1 -1
  20. package/dist/web-ui/assets/{chunk-4BX2VUAB-BSgBKyC9.js → chunk-4BX2VUAB-CuwDpBRL.js} +1 -1
  21. package/dist/web-ui/assets/{chunk-55IACEB6-XB_ZMqfw.js → chunk-55IACEB6-nC7YWJ_i.js} +1 -1
  22. package/dist/web-ui/assets/{chunk-727SXJPM-YFPBFW4M.js → chunk-727SXJPM-Dw6mBsRE.js} +1 -1
  23. package/dist/web-ui/assets/{chunk-AQP2D5EJ-CDbFN1Un.js → chunk-AQP2D5EJ-CPhNJbHl.js} +1 -1
  24. package/dist/web-ui/assets/{chunk-FMBD7UC4-BGKt8xP8.js → chunk-FMBD7UC4-AyhQakG8.js} +1 -1
  25. package/dist/web-ui/assets/{chunk-ND2GUHAM-DKicpX2b.js → chunk-ND2GUHAM-DgYemv8I.js} +1 -1
  26. package/dist/web-ui/assets/{chunk-QZHKN3VN-BD4tv8RZ.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-BjOoIarG.js → cose-bilkent-S5V4N54A-DrOgwDIH.js} +1 -1
  30. package/dist/web-ui/assets/{dagre-BM42HDAG-BWal5GOH.js → dagre-BM42HDAG-DhoJiA83.js} +1 -1
  31. package/dist/web-ui/assets/{diagram-2AECGRRQ-CJj-CzRg.js → diagram-2AECGRRQ-BDILSgqK.js} +1 -1
  32. package/dist/web-ui/assets/{diagram-5GNKFQAL-4IMjuEPm.js → diagram-5GNKFQAL-CeXywd1i.js} +1 -1
  33. package/dist/web-ui/assets/{diagram-KO2AKTUF-DQiRAfss.js → diagram-KO2AKTUF-Bi4RlMT0.js} +1 -1
  34. package/dist/web-ui/assets/{diagram-LMA3HP47-BMPvbEbY.js → diagram-LMA3HP47-Cw1yxk8b.js} +1 -1
  35. package/dist/web-ui/assets/{diagram-OG6HWLK6-D5_vmdXl.js → diagram-OG6HWLK6-Bl857da2.js} +1 -1
  36. package/dist/web-ui/assets/{docx-preview-Cdouj_6e.js → docx-preview-CjoUhrMq.js} +1 -1
  37. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-DOnDuvXd.js → erDiagram-TEJ5UH35-DEiaMhuV.js} +1 -1
  38. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-DL6G76eC.js → flowDiagram-I6XJVG4X-BgKZhO0h.js} +1 -1
  39. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-CwHnuRR8.js → ganttDiagram-6RSMTGT7-Dkx-EaS8.js} +1 -1
  40. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-BFUnsmW_.js → gitGraphDiagram-PVQCEYII-DXaQwA0y.js} +1 -1
  41. package/dist/web-ui/assets/{index-BSktaJwx.js → index-C_QhfMcC.js} +74 -74
  42. package/dist/web-ui/assets/index-DEN_qReg.css +1 -0
  43. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-DhU1bQNw.js → infoDiagram-5YYISTIA-Dpx9IOkx.js} +1 -1
  44. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-o6ujfUJF.js → ishikawaDiagram-YF4QCWOH-BWqWgitQ.js} +1 -1
  45. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-Dx_SZ8zv.js → journeyDiagram-JHISSGLW-BBwIZ4k9.js} +1 -1
  46. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-D4BWXcIn.js → kanban-definition-UN3LZRKU-C_MRWV8R.js} +1 -1
  47. package/dist/web-ui/assets/{mermaid.core-BHDulYyB.js → mermaid.core-BMAh3nnq.js} +5 -5
  48. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-BVy6py_h.js → mindmap-definition-RKZ34NQL-B6vJQcat.js} +1 -1
  49. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-CUr5__J1.js → pieDiagram-4H26LBE5-BxdEttqt.js} +1 -1
  50. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-C5Owt_r4.js → quadrantDiagram-W4KKPZXB-gsNs2VfP.js} +1 -1
  51. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-Bb933lBb.js → requirementDiagram-4Y6WPE33-BSC9KvC2.js} +1 -1
  52. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-CJq-boMJ.js → sankeyDiagram-5OEKKPKP-DktAZfe_.js} +1 -1
  53. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-BP8L47v3.js → sequenceDiagram-3UESZ5HK-BIPt8kGU.js} +1 -1
  54. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-Byk9-Yrm.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-2z8RR-l_.js → timeline-definition-PNZ67QCA-LRi7H35g.js} +1 -1
  57. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-CSwDDhHv.js → vennDiagram-CIIHVFJN-DWQ1I022.js} +1 -1
  58. package/dist/web-ui/assets/{wardley-L42UT6IY-DW30MdHd.js → wardley-L42UT6IY-BUb6dYqN.js} +1 -1
  59. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-DUb2r21l.js → wardleyDiagram-YWT4CUSO-BYE1B3xT.js} +1 -1
  60. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-4DTcVUL8.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-B6vw2Oj5.js +0 -84
  100. package/dist/web-ui/assets/channel-CqbBz9iL.js +0 -1
  101. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-DDQJP38f.js +0 -1
  102. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-DDQJP38f.js +0 -1
  103. package/dist/web-ui/assets/index-3PQIqBtv.css +0 -1
  104. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-CWa-Q2Gf.js +0 -1
@@ -0,0 +1,1377 @@
1
+ # Prompt Engineering & Context Assembly
2
+
3
+ This document specifies how Markus constructs prompts, manages context, and orchestrates LLM interactions across all scenarios. It complements [state-machines.md](./state-machines.md) (task lifecycle), [memory-system.md](./memory-system.md) (storage layers), and [cognitive-architecture.md](./cognitive-architecture.md) (deterministic context assembly).
4
+
5
+ ---
6
+
7
+ ## 1. LLM Call Taxonomy
8
+
9
+ ### 1.1 Two-Tier Call Model
10
+
11
+ LLM calls are organized in two tiers:
12
+
13
+ **Tier 1 -- (retired)**: the former Cognitive Preparation calls (Appraisal / Reflection / Evaluation) were **removed** — they were extra LLM calls before the main call. Context preparation is now **deterministic (no LLM)**: a small bounded block (recent activity + working-memory keys) plus the ContextEngine's own relevant-memory retrieval. Deeper recall is agent-driven via `memory_search` / `kb_search`.
14
+
15
+ | # | Phase | Status |
16
+ |---|-------|--------|
17
+ | P1 | **Appraisal** | **removed** — replaced by deterministic assembly |
18
+ | P3 | **Reflection** | **removed** |
19
+ | P5 | **Evaluation** (D3) | **removed** |
20
+
21
+ P2 (Directed Retrieval) and P4 (Assembly) are code-only phases with no LLM call.
22
+
23
+ **Tier 2 -- Main Processing Calls**: The primary LLM calls that produce agent actions and responses. These use the full model and have access to tools.
24
+
25
+ | # | Scenario | Entry Point | Method | Streaming | Tools | Network Retry | Loop Limit |
26
+ |---|----------|-------------|--------|-----------|-------|---------------|------------|
27
+ | 1 | **Human Chat** (non-stream) | API `/api/agents/:id/chat` | `handleMessage()` | No | Yes | Yes | 200 (safety net) |
28
+ | 2 | **Human Chat** (stream/SSE) | API `/api/agents/:id/chat?stream=1` | `handleMessageStream()` | Yes | Yes | Yes | 200 (safety net) |
29
+ | 3 | **Task Execution** | `TaskService.runTask()` → `_executeTaskInternal()` | `llmRouter.chatStream()` | Yes | Yes | Yes | **None** |
30
+ | 4 | **Respond-in-Session** | API `/api/agents/:id/sessions/:sid/messages` | `respondInSession()` | Yes | Yes | Yes | 200 (safety net) |
31
+ | 5 | **Heartbeat** | `HeartbeatScheduler` → `handleHeartbeat()` | `handleMessage(scenario:'heartbeat')` | No | Subset | Yes (via handleMessage) | 200 + 3 retries |
32
+ | 6 | **A2A Chat** | API `/api/agents/:id/a2a` / channel routing | `handleMessage(scenario:'a2a')` | No | Yes | Yes (via handleMessage) | 200 |
33
+ | 7 | **Comment Response** | Mailbox `task_comment` / `requirement_update` | `handleMessage(scenario:'comment_response')` | No | Yes | Yes (via handleMessage) | 200 |
34
+ | 8 | **Internal (Lightweight)** | Various | `handleMessage(scenario:'heartbeat')` | No | Varies | Yes (via handleMessage) | 200 |
35
+
36
+ **Cognitive depth (retired)** — the former D0–D3 ladder (`selectCognitiveDepth`) decided how many
37
+ Tier 1 calls preceded each Tier 2 call. It belonged to CPP and is **gone**: **every** Tier 2 call
38
+ now runs with **zero** preceding Tier 1 LLM calls; context is assembled deterministically instead.
39
+
40
+ ### 1.2 Lightweight Internal Calls (Scenario 8)
41
+
42
+ These are `handleMessage()` calls with `scenario: 'heartbeat'` and typed session IDs (e.g. `sys_<agentId>_<ts>`). Each call creates a persisted session for full traceability.
43
+
44
+ | Sub-scenario | Trigger | Session ID Pattern | Purpose |
45
+ |-------------|---------|-------------------|---------|
46
+ | **Daily Report** | `consolidateMemory()` (once/day) | `sys_<agentId>_<ts>` | Generate brief status report → `daily-logs/` |
47
+ | **Memory Flush** | turn-level preflight when context usage is high (see §5.7) | `sys_<agentId>_<ts>` | Prompt agent to `memory_save` important info before the context window fills |
48
+ | **LLM Summarizer** | `contextEngine.smartSummarizeAndTruncate()` | N/A (internal) | Compress older conversation messages into a summary (no tools) |
49
+ | **Dream Consolidation** | `consolidateMemory()` (once/day, ≥50 entries) | `sys_<agentId>_<ts>` | LLM reviews memory entries, outputs prune/merge plan (no tools) |
50
+
51
+ ---
52
+
53
+ ### 2.0 Cache-Scope Layout Principle (design philosophy)
54
+
55
+ **The rule.** Prefix caches are *byte prefixes*: the first byte that differs discards
56
+ everything after it (Anthropic, OpenAI, DeepSeek, AWS, vLLM, SGLang all cache by leading
57
+ token sequence; DeepSeek's unit is 64 tokens and it is automatic). Therefore the request
58
+ must be ordered by **sharing scope, widest first** — content shared by more concurrent
59
+ requests must physically precede content shared by fewer.
60
+
61
+ Ordering by *stability alone* is not enough. Two agents can each be perfectly stable and
62
+ still share **nothing**, because their divergence point sits at byte 0. Stability decides
63
+ *when* a byte changes; scope decides *how many requests pay for it*.
64
+
65
+ The request is laid out in five scopes:
66
+
67
+ | Scope | Shared by | Content | Change cadence |
68
+ |---|---|---|---|
69
+ | **U** Universal | every agent in the installation | platform L0: Tool Usage, Search & Exploration, Learning Habits, Autonomy, Model Routing, Tool Error Recovery, Security, Referencing, User Language, Collaboration Rules, Task Workflow, Prompt Composition, Handbook | per release |
70
+ | **O** Org | every agent in the org | org context (`CONTEXT.md`), `## About the Owner` (`USER.md`) | days–weeks |
71
+ | **A** Agent | one agent | ROLE.md persona, policies, identity, workspace paths | per config |
72
+ | **S** Session | one session | trust level, environment probe, scenario instructions | per session |
73
+ | **V** Volatile | one LLM call | task board, knowledge, notebook, skills, team status, mailbox | per call (history tail) |
74
+
75
+ **Corollary 1 — the divergence point is the design target.** The system `text` is emitted
76
+ as two breakpoint segments. Segment 1 is **scope U only**; segment 2 carries A/S (and the
77
+ org/team blocks). For N agents, segment 1 is then *one* shared cache entry plus N short
78
+ agent-specific suffixes, instead of N fully independent entries.
79
+
80
+ **Corollary 2 — tools are prefix too.** Tool schemas serialise ahead of the messages on
81
+ OpenAI-compatible providers, so the `tools` array must also be *common-core-first* and
82
+ byte-stable per session (§2.1.1 inv. 6, §7).
83
+
84
+ **Corollary 3 — scope is decided by *who shares it*, not by subject matter.** `## About the
85
+ Owner` reads like agent context but is org-scoped. `## Your Environment` is session-scoped
86
+ even though most of it is machine-constant, because one field (free disk) churns.
87
+
88
+ **Corollary 4 — a scope's churn must not exceed its tier.** Any byte that changes faster
89
+ than its tier's cadence demotes the rest of that tier *and every later tier* to a cache
90
+ miss. Two live leaks of this kind were measured on 2026-09-16 across 30 agents / 901 calls:
91
+
92
+ | Leak | Effect |
93
+ |---|---|
94
+ | `ROLE.md` (agent-private) emitted as the **first bytes** of the system prompt, ahead of the ~19.7k-char universal L0 block | **cross-agent prefix overlap = 2–3 chars / 30k+ ≈ 0.0 %** |
95
+ | `## Your Environment` carrying a live `diskFreeMB` figure, and `docker --version` probes that intermittently timed out | only **4 of 150** consecutive same-agent call pairs were byte-identical |
96
+
97
+ **Corollary 5 — measure, or the invariant rots.** The only reason these survived four
98
+ audit rounds is that no cache-hit telemetry existed to falsify the "cache-friendly"
99
+ comments in the code. Every rule in §2.1.1 therefore ships with a guard test, and cache
100
+ hit rate is recorded per session (§3.9, RC4).
101
+
102
+ ---
103
+
104
+ ## 2. System Prompt Architecture
105
+
106
+ The system prompt is built by `ContextEngine.buildSystemPrompt()`. Under **Scheme A**, the
107
+ system prompt (`text`) is split into **two tiers**, both **byte-stable**; and all per-call
108
+ dynamic content is moved **out of the system prompt entirely** into a volatile tail message.
109
+
110
+ ```
111
+ ╔══════════════════════════════════════════════════════════╗
112
+ ║ SYSTEM `text` — BYTE-STABLE (every segment = breakpoint)║
113
+ ║ Identical byte-for-byte across turns for the same agent.║
114
+ ║ This byte-stability IS the implicit prefix-cache key. ║
115
+ ║ ║
116
+ ║ TIER 1 — STABLE · SCOPE U (UNIVERSAL) ║
117
+ ║ Byte-identical for EVERY agent (shared cache entry). ║
118
+ ║ Tool Usage / Search & Exploration / Learning / ║
119
+ ║ Autonomy / Model Routing / Tool Error Recovery / ║
120
+ ║ Security / Referencing / User Language / ║
121
+ ║ Collaboration Rules / Task Workflow / Prompt ║
122
+ ║ Composition / Platform Handbook. ║
123
+ ║ ⟂ No agent-varying branch may appear here (§2.0 cor. 3)║
124
+ ║ ║
125
+ ║ TIER 2 — SEMI-STABLE (cache_control: ephemeral ✓) ║
126
+ ║ SCOPE A (agent) FIRST: Role.md persona · Policies · ║
127
+ ║ Identity · Workspace · Trust ║
128
+ ║ then SCOPE O/T: Org (CONTEXT.md) · Team Announcements ║
129
+ ║ & Norms · User Profiles · Env · Scenario (LAST) · ║
130
+ ║ Team Data Directory · Activated-skills body ║
131
+ ║ (agent-written memory — knowledge.md — ║
132
+ ║ is NOT here: it rides the volatile tail, see §2.1.1) ║
133
+ ╚══════════════════════════════════════════════════════════╝
134
+ ╔══════════════════════════════════════════════════════════╗
135
+ ║ VOLATILE TAIL — `[SYSTEM] [Live context]` (NOT system) ║
136
+ ║ one `role: user` message appended as the LAST message, ║
137
+ ║ AFTER all history. Only this tail changes per call ║
138
+ ║ → cache across system+history persists. ║
139
+ ║ contextHint ([CONTEXT x% used …]) · Relevant Memories ║
140
+ ║ Channel History (recent msgs) · Date/locale · Mailbox ║
141
+ ║ & attention · Team Status · Working Memory · ║
142
+ ║ Cognitive/Notebook context · task board · deliverables ║
143
+ ║ · deferred-tool catalog (Afford.S2) ║
144
+ ║ · Your Knowledge (knowledge.md) · Working State ║
145
+ ║ (notebook) ← agent-written, see §2.1.1 inv. 5 ║
146
+ ╚══════════════════════════════════════════════════════════╝
147
+ ```
148
+
149
+ ### 2.1 KV-Cache Optimization Strategy
150
+
151
+ `buildSystemPrompt()` returns `{ text, segments, volatile }` under **Scheme A**: `text` is a byte-stable, two-tier system (Tier 1 STABLE + Tier 2 SEMI-STABLE); all per-call dynamic content lives in `volatile`, assembled by `prepareMessages()` into a single `[SYSTEM] [Live context]` message (role `user`) appended as the **last message of the request** (after all history). Details:
152
+
153
+ 1. **Tier 1 (Stable)**: Role, policies, tool usage rules, communication rules, collaboration rules. Scenario-free — stay cached across ALL mode switches (chat ↔ heartbeat ↔ a2a ↔ deliberation). A cache breakpoint after this tier caches this prefix across all calls.
154
+
155
+ 2. **Tier 2 (Semi-stable)**: Identity, org context, workspace paths, scenario instructions last. Change on org/config events (days–weeks), but stay stable within a session. Scenario placed last keeps the identity/org prefix stable across mode switches (OpenAI benefit). A breakpoint here caches the combined Tier 1+2 prefix. These two tiers together form the byte-stable system `text`. **Agent-written memory (knowledge.md, NOTEBOOK.md) is deliberately NOT in this tier** — see §2.1.1 invariant 5.
156
+
157
+ 3. **Volatile tail (Scheme A)** — replaces the old Tier 3: Project/task board, system announcements, feedback, available skills (query-filtered), `## Notebook` (cognitive), relevant memories, team status, channel history, mailbox state, working memory, timestamps, deferred-tool catalog. These change per call and live **outside the system**: `prepareMessages()` assembles them (plus `contextHint`) into one `[SYSTEM] [Live context]` message appended as the **LAST message of the request**. Values are quantized where possible (timestamps to 5-min buckets, mailbox elapsed time to coarse labels, notebook ages to buckets) to reduce churn. Sitting in the **history tail** rather than in the system message means changing it never invalidates the byte-stable system + history prefix (implicit prefix-cache on OpenAI-compatible providers).
158
+
159
+ > **Placement is load-bearing — it must be the LAST message.** Do NOT "insert it just before the current query": inside an agent tool loop the last user message is the ORIGINAL task instruction (index 1) — every later turn is assistant/tool — so that insertion point is actually the *front* of the history. Rewriting `messages[1]` every turn broke the byte-identical prefix right after `system` and re-billed the entire replayed history on every LLM call (measured on real logs: 46% prefix reuse instead of 79%, ~90k tokens re-sent per call).
160
+
161
+ **Message-level cache breakpoints**: In addition to system caching, a `cacheBreakpoint` is placed on
162
+ the last message before the current turn in the conversation history, letting providers (e.g.
163
+ Anthropic) cache the stable conversation prefix independently of new messages.
164
+
165
+ **Channel session reuse**: A2A and group chat messages sharing a channel reuse a stable session ID
166
+ (`channel_{channelKey}_{agentId}`); history accumulates and only the delta is added on later turns.
167
+ Channel history is injected as part of the volatile `[Live context]` tail, not prepended into
168
+ history — preserving conversation-prefix cache stability.
169
+
170
+ **Tool definition caching (Anthropic)**: The last tool in the `tools` array is marked with
171
+ `cache_control: { type: 'ephemeral' }`, caching the (deterministically registry-ordered) tool
172
+ definitions prefix.
173
+
174
+ **Dynamic value quantization**: Several dynamic fields use coarse labels to reduce churn: notebook
175
+ entry ages (`just now`, `recent`, `~Nh ago`), mailbox elapsed labels (`just started`, `a few minutes`,
176
+ `~Nmin`), timestamps drop seconds (minute-level). Coarser timestamp buckets were rejected — the tail
177
+ has many other per-call fields, so the marginal benefit did not justify inaccurate time perception.
178
+
179
+ ### 2.1.1 Prefix-cache invariants (regression-tested)
180
+
181
+ The implicit prefix cache is **byte-prefix based**: the first byte that differs throws away
182
+ everything after it. That makes four things invariants rather than preferences. Each has a
183
+ guard test; break one and long sessions silently re-bill their whole history on every call.
184
+
185
+ | # | Invariant | Where | Guard test |
186
+ |---|-----------|-------|-----------|
187
+ | 1 | The volatile `[Live context]` block is the **last message** — never inserted at `messages[1]` | `context-engine.prepareMessages` | `context-engine.test.ts` → `C-cache-volatile-tail`, `C-cache-volatile-stable-head` |
188
+ | 2 | The request-history window **slides in blocks**, not per message | `history-window.ts` (`requestHistoryStart`), used by every `Agent.requestHistory()` call | `history-window.test.ts` |
189
+ | 3 | The deferred-tool catalog (Afford.S2) rides the **volatile tail**, never the system prompt | `Agent.consumeDeferredToolCatalog()` + `mergeVolatile()` | `agent-deep.test.ts` → `deferred-tool catalog placement` |
190
+ | 4 | ContextOS `[SLOTS]` + `[CONTEXT SUMMARY]` are **derived in the engine**, so every prepare path carries them | `context-engine.prepareMessages` defaults from `(memory, sessionId)` | `context-engine.test.ts` → `ContextOS slots + summary ride EVERY prepare path` |
191
+ | 5 | Agent-written knowledge / state (`## Your Knowledge`, `## Notebook`) ride the **volatile tail**, never Tier 2 | write-frequency tier boundary, below | `cache-optimization.test.ts` → `C-cache-knowledge-body`, `C-cache-knowledge-write` |
192
+ | 6 | The `tools` array is **byte-stable per session** — no per-turn counts, dynamic lists, or selection-derived content in any tool `description` / `inputSchema` | `tool-selector.ts` `buildDiscoverTool` (registry-derived, sorted) | `tool-selector.test.ts` → `CACHE: discover_tools description is byte-stable …` |
193
+ | 7 | When volatile state **changes**, it is also persisted as a replayable `[SYSTEM] [State checkpoint]` (append-only ⇒ cache-extending) | `context-engine.prepareMessages` | `context-volatile-gating.test.ts` → checkpoint describe |
194
+ | 8 | The system prompt is emitted in **scope order, widest first**: the universal (scope-U) block comes FIRST and is **byte-identical for every agent**; agent-private persona/policies are emitted *after* it | `context-engine.buildSystemPrompt` (`stable` vs `agentPersona` → head of `semiStable`) | `context-cache-scope.test.ts` → *two different agents produce a byte-identical scope-U segment* |
195
+ | 9 | **No agent-varying branch may appear inside the universal block.** A condition on agent state (skills, team, config) is a divergence point for the whole install | `context-engine.buildSystemPrompt` (the old `hasBrowserSkill` branch was the counter-example) | `context-cache-scope.test.ts` → *a browser-skill difference does NOT fork the universal block* |
196
+ | 10 | Session-scoped sticky tool state (`recent`/`activated`) is **monotonic within a session** (grows, never evicts) and **reset on session switch** — the emitted `tools` schema warms up and then stays byte-stable | `Agent.stickyTools()` (`toolSticky`, keyed by session) | `tool-selector.test.ts` (schema stability) + agent tool-loop tests |
197
+ | 11 | Byte-stable tiers may only contain **quantized** values — anything that churns faster than its tier (free disk, precise timestamps, live counts) must be quantized, moved to the volatile tail, or removed | `buildEnvironmentSection` (disk → 10 GB bands), `environment-profile.ts` (probe retry) | `context-cache-scope.test.ts`; env drift measured at offset 30228 on 2026-09-16 |
198
+ | 12 | Assembly state that is **keyed by session** must also be **stored per worker** (`SessionWorkspace`), never on the `Agent` instance | `Agent.stickyTools()`, `Agent.activatedSkills()` → `SessionWorkspace.toolSticky` / `.activatedSkills` | `agent-worker-scoped-state.test.ts` |
199
+ | 13 | A scenario emitted by the caller is **authoritative**; the engine may *normalize* it (channel-derived) but must never clobber it. Every scenario block declares (a) output visibility, (b) the tool that reaches a human, (c) the silence rule | `context-engine.buildScenarioSection` + `prepareMessages` normalize; `agent.ts` `a2a_message` default | `context-scenario-matrix.test.ts` |
200
+
201
+ **Invariant 6 — why tools dominate the risk.** Measured on a live agent tail:
202
+ `fixed 19660 (system 8618 + tools 11042)` — the **tool schemas cost more than the
203
+ entire system prompt**, and they serialise *ahead* of it, so one byte of drift
204
+ there invalidates system + all replayed history. `discover_tools.description` used
205
+ to embed the *unloaded* remainder (`allTools − alreadySelected`), so its sample
206
+ names and its `… +N` tail tracked the per-turn keyword selection and changed on
207
+ nearly every call — under a comment that claimed it was cache-friendly. It is now
208
+ derived from the tool **registry** (minus `TOOL_DEF_CORE_KEEP`) and sorted, so it
209
+ changes only when a tool or skill is genuinely installed or removed. This is also
210
+ what `tool-system.md` §1.0.1 already required (`MUST NOT` append a catalog to
211
+ `discover_tools.description`); the code had been violating its own spec.
212
+
213
+ **Invariant 7 — why a checkpoint and not just "re-send less".** See §2.1.2: the
214
+ tail is ephemeral and is not replayed, so gating alone *lost* information. The
215
+ checkpoint restores completeness while keeping the token saving, because an
216
+ append-only message extends the cached prefix instead of being re-billed per call.
217
+
218
+ **Invariant 2 — request-history window.** A raw `getRecentMessages(id, N)` returns the *last N*
219
+ messages, so once a session is longer than N the window head moves by 1–2 messages **every turn**
220
+ and the whole replayed history misses the cache. The fix is quantization, not a bigger N: keep at
221
+ least `SESSION_REQUEST_HISTORY_MIN` (400) messages and advance the window start only in
222
+ `SESSION_REQUEST_HISTORY_BLOCK` (100) steps, so the head — and therefore the whole replayed prefix —
223
+ stays byte-identical for ~50 turns. Per-call token packing still bounds the prompt (the budget path
224
+ compresses/trims independently), and storage-level compaction
225
+ (`SESSION_STORAGE_COMPACT_TRIGGER` 2000 / `KEEP` 1000) remains the deliberate, rare anchor shift
226
+ every ~1000 messages.
227
+
228
+ **Invariant 4 — why it matters.** Only the non-stream chat path used to pass `slotsSegment` /
229
+ `summarySegment` explicitly. The streaming path, every tool-loop continuation, and the
230
+ task/review/session scenarios silently dropped `session_pin` anchors **and** the
231
+ `[CONTEXT SUMMARY]` compaction anchor. Deriving them inside `prepareMessages` makes it impossible
232
+ for a new call site to forget them.
233
+
234
+ **Invariant 5 — agent-written memory/knowledge belongs to the volatile tail.** `## Your Knowledge`
235
+ (knowledge.md) and `## Notebook` (NOTEBOOK.md) are **agent-written** and change far more
236
+ often than "semi-stable" implies: `memory_save` appends to `## _observations` on *every* call, and
237
+ `memory_update` rewrites curated sections. While they sat in the byte-stable Tier 2, every one of
238
+ those writes invalidated the cached prefix for the **entire replayed history** — a high-frequency
239
+ cache buster hiding inside the tier whose whole justification is "changes only occasionally".
240
+ Measured on this org's 91 agents: 498 accumulated `_observations` lines (36 agents), i.e. 498
241
+ full-prefix invalidations since the last prune, plus every `memory_update`.
242
+
243
+ The tier boundary is therefore **write frequency, not subject matter**:
244
+
245
+ | Block | Written by | Frequency | Tier |
246
+ |-------|-----------|-----------|------|
247
+ | `## Your Knowledge` (knowledge.md) | the agent (`memory_save`/`memory_update`) | many× per task | **volatile** |
248
+ | `## Notebook` (NOTEBOOK.md) | the agent | per task | **volatile** |
249
+ | Relevant memories, notebook, mailbox, task board, team status | platform | per turn | volatile |
250
+ | `## About the Owner` (USER.md), org/team context, workspace paths, team announcements/norms, `## Your Trust Level` | humans / org config | days–weeks | Tier 2 (cached) |
251
+ | Role, policies, tool-usage rules, Learning Habits | repo/build | only on release | Tier 1 (cached) |
252
+
253
+ **The trade-off, stated honestly:** volatile tokens are never prefix-cached, so the move is not
254
+ free — it costs up to `KNOWLEDGE_PROMPT_MAX_TOKENS` (1 500; 1 200 converse; 0 reflex) extra
255
+ full-price tokens **per call**. It is worth it because the alternative was a full-history re-bill
256
+ (~30k–90k tokens, depending on window) **per memory write**: the crossover is roughly one write per
257
+ 50 calls, and active agents write memory several times per task. Keeping knowledge cached only wins
258
+ for an agent that never learns anything.
259
+
260
+ Guard tests: `cache-optimization.test.ts` → `C-cache-knowledge-body`, `C-cache-knowledge-write`
261
+ (the latter asserts that a `memory_save` leaves `result.text` byte-identical while still reaching the
262
+ model through `result.volatile`). Both were verified to FAIL against the old Tier-2 placement.
263
+
264
+ ### 2.1.2 ContextOS v2 — change-gated volatile delivery (2026-09-16)
265
+
266
+ **Problem.** The volatile tail used to be re-sent **in full on every LLM call**.
267
+ Inside a single user turn a tool loop can issue 60+ calls, so the blob
268
+ (~7 800 chars) was re-delivered verbatim each time. Measured on
269
+ `sess_1789536167018_dxnmco` (66 calls, one user turn, `inputTokens` 24 481 → 269 168):
270
+
271
+ - consecutive-call similarity of the compiled tail: **0.9989**
272
+ - one persistent fact (`worker 2 is working on the same topic`) was re-delivered **66×**
273
+ - the assistant went on to re-narrate that same fact in **3 separate iterations**
274
+ and re-emitted identical progress-recap lines **×4 / ×3 / ×2**
275
+
276
+ Root cause: a tail message is read as the *newest user input immediately before
277
+ generating*. Re-stating unchanged background therefore reads as the user
278
+ repeating themselves — and the model answers by repeating itself.
279
+
280
+ **Policy.** Placement is unchanged (still the last message, so the system +
281
+ history prefix keeps hitting the prefix cache); only *what the tail carries*
282
+ changed:
283
+
284
+ | Situation | Tail content |
285
+ |---|---|
286
+ | First call of a user turn | water-level hint + **all** volatile sections (full) |
287
+ | A section's content hash changed | hint + that section in full; the rest digested |
288
+ | Nothing changed | hint + one-line digest naming the omitted sections |
289
+ | ≥ `CONTEXT_VOLATILE_REARM_CALLS` (8) calls since the last full refresh | hint + **all** sections (forced re-arm) |
290
+
291
+ Branch key: `isFirstCallOfTurn = !messages.slice(turnStart + 1).some(m => m.role === 'assistant')`.
292
+ Section identity: `sha1(body).slice(0,8)`, held in the engine's bounded
293
+ per-session map (`VOLATILE_SNAPSHOT_MAX_SESSIONS = 64`).
294
+
295
+ **Completeness invariant (v3, 2026-09-16 — supersedes the v2 wording).**
296
+ `isFirstCallOfTurn` is kept *deliberately*: a turn boundary is a fresh decision
297
+ point, and the tail is ephemeral (see below), so a full refresh there is a real
298
+ guarantee rather than redundancy.
299
+
300
+ The v2 note claimed "content is never *permanently* hidden: … every new user turn
301
+ starts from a full snapshot". That reasoning was **wrong**, and the mechanism
302
+ below is what makes the claim true now.
303
+
304
+ > **The volatile tail is ephemeral and is never replayed.**
305
+ > `[SYSTEM] [Live context]` is produced only in `context-engine.ts` and appended to
306
+ > the *outgoing* request; it is **never written back to the session store**
307
+ > (verified: `agent.ts` persists only real user text, assistant replies, tool
308
+ > results and continuation prompts). It therefore **does not appear in the next
309
+ > call's replayed history.** An LLM has no memory across calls beyond what is
310
+ > replayed, so under pure change-gating an omitted section was genuinely *gone*
311
+ > from the model's context until the next re-arm. Gating on its own was a
312
+ > completeness **regression** against the original re-send-everything design.
313
+
314
+ **Fix — durable state checkpoints.** Whenever the state actually changes (or on
315
+ the first call of a session, when no snapshot exists yet), `prepareMessages`
316
+ appends a `[SYSTEM] [State checkpoint]` message carrying the **full** current
317
+ state to durable session history, in addition to putting the fresh sections in
318
+ this call's tail:
319
+
320
+ - **Complete** — the newest checkpoint is replayed on every later call, so
321
+ omitting an unchanged section from the tail no longer removes it from context.
322
+ - **Cheap** — the checkpoint is *append-only*, so it extends the cacheable prefix
323
+ instead of being re-billed on every call. Older checkpoints are superseded
324
+ (last-write-wins) and are folded away by the normal compaction path.
325
+ - **Single choke point** — written inside `prepareMessages`, not at the ~8 call
326
+ sites, so a new call site cannot forget it (same rationale as the
327
+ slots/summary derivation in §3.7).
328
+ - **Best-effort** — a persistence failure logs a warning; that call's tail still
329
+ carries the state verbatim, so the agent is never blind.
330
+ - Recognised by `isSyntheticMessage()`, so a checkpoint never counts as a user turn.
331
+
332
+ **The digest must state where the content lives.** The v2 wording was "Act only on
333
+ the sections shown above" — false whenever nothing changed, because the tail then
334
+ carries *only* the digest and there is nothing shown above. The v3 text names the
335
+ `[SYSTEM] [State checkpoint]` history message explicitly and labels the block as
336
+ reference material that must not be re-announced.
337
+
338
+ **Relative-time labels must not break the gate.** `hashSection()` hashes a
339
+ *normalised* body: `(7h ago)`, `(23m ago)`, `(just started)`, `(2 days ago)` all
340
+ collapse to `(age)`. `## Notebook` renders entry ages, so hashing the raw body
341
+ made the gate fire — re-sending ~12 KB and persisting a redundant checkpoint —
342
+ every time an age label rolled over its hour bucket.
343
+
344
+ **Regression guards**: `context-volatile-gating.test.ts` (gating, checkpoint
345
+ persistence, label normalisation), `context-engine-cache-v3.test.ts`
346
+ (knowledge selection).
347
+
348
+ **Transient harness prompts are deduped** (`dedupeTransientPrompts`).
349
+ `[Continue from where you left off …]` and `[SYSTEM] Loop detected: …` are
350
+ appended to *durable* memory by the agent loop, so they stack up (observed: 4
351
+ copies of the continuation prompt plus a loop warning in one session). They are
352
+ negative instructions ("do not repeat") — the pattern LLMs handle worst — and
353
+ each copy counts as a `user` turn, corrupting `findCurrentTurnStart` and
354
+ cache-breakpoint placement. `prepareMessages` now collapses each family to its
355
+ latest copy. The transform is pure and deterministic, so the byte-identical
356
+ prefix is unaffected.
357
+
358
+ **Regression guard**: `packages/core/test/context-volatile-gating.test.ts`.
359
+
360
+ **Resolved in v2.1** — see §3.8. A single turn issuing 60+ LLM calls is now
361
+ folded in place: when the absolute history ceiling trips, the fold boundary is
362
+ the END of history instead of the current turn start, so the same block-wise fold
363
+ reaches inside the current turn. No separate intra-turn code path was needed.
364
+
365
+ **Sample-size caveat.** The similarity/repeat figures come from one 66-call
366
+ session. Treat them as an existence proof of the failure mode, not as a
367
+ population statistic.
368
+
369
+ **References**
370
+ - DeepSeek KV-cache guide — prefix must match from token 0; a mid-context rewrite
371
+ invalidates the suffix. <https://api-docs.deepseek.com/guides/kv_cache/>
372
+ - Manus context engineering — keep the prefix stable, append-only, and do not
373
+ give the agent "a few-shot of itself". <https://manus.im/blog/Context-Engineering-for-AI-Agents-Lessons-from-Building-Manus>
374
+ - Negation is the weakest instruction form in LLMs. <https://aclanthology.org/2023.starsem-1.10/>
375
+
376
+ ### 2.2 Spec: injection-point ownership audit (C3)
377
+
378
+ The tiering above is the intended design; this spec makes it an enforced invariant so a new
379
+ injection point cannot silently land in a stable tier and bust the cache prefix.
380
+
381
+ - **Behavior**: every prompt injection point has an explicit owner. Identity, policies,
382
+ tool-usage rules → **Tier 1 (stable)**. Org/workspace/scenario/announcements/norms/
383
+ activated-skills/user-profile/trust → **Tier 2 (semi-stable; written on org/config events)**.
384
+ Agent-written memory (`## Your Knowledge`, `## Notebook`) → **volatile** (§2.1.1
385
+ invariant 5). All per-call situational meta (the deterministic `## Cognitive Context` block,
386
+ triage decision, mailbox state, task board, timestamps, relevant memories, team
387
+ status, query-filtered skills, working memory, contextHint) → **volatile tail (the `[Live
388
+ context]` message), never in any system segment**.
389
+ - **Invariants**:
390
+ - The system `text` (all segments) contains **no** per-call varying content (cognitive-context/triage/notebook/
391
+ mailbox/task/date/skills markers appear only in the `volatile` tail).
392
+ - Every system segment carries a `cacheBreakpoint`; the deterministic `## Cognitive Context`
393
+ block and `## Relevant Memories` ride the `volatile`/dynamic tail, never a stable
394
+ system-prompt section (see [cognitive-architecture.md](./cognitive-architecture.md) §3).
395
+ - **Note — CPP retired; the deterministic block is always injected**: the deterministic situational
396
+ block (recent activity + working-memory keys) is now **always** injected as the `## Cognitive
397
+ Context` section — there is no CPP toggle and no pre-call LLM (see §1.1). It is **complementary
398
+ to, not mutually exclusive with**, the ContextEngine's relevant-memory retrieval: in the same turn
399
+ both `## Cognitive Context` and `## Relevant Memories` are injected when available.
400
+ - **Design rationale**: dynamic content in the byte-stable system prefix invalidates every downstream
401
+ cache hit; Scheme A keeps it in the volatile **history tail**, preserving prefix reuse across mode
402
+ switches (Anthropic explicit + OpenAI/DeepSeek implicit).
403
+ - **Testing** (`packages/core/test/cache-optimization.test.ts` — the "C3:" cases): with a
404
+ prompt carrying a deterministic `## Cognitive Context` block, mailbox/attention meta, channel history, sender identity and a
405
+ timestamp, assert (a) **every system segment is a cache breakpoint and carries no dynamic marker**,
406
+ (b) those markers appear only in `volatile`, (c) identity / tool-usage rules stay in the stable
407
+ prefix while the **agent-written knowledge body stays OUT of it** (`C-cache-knowledge-body`) and a
408
+ `memory_save` leaves the system text byte-identical (`C-cache-knowledge-write`), and (d) the
409
+ deterministic `## Cognitive Context` block rides the volatile tail rather than being injected as a stable system-prompt section,
410
+ and (e) two turns with different per-turn context yield byte-identical `text` but different
411
+ `volatile`. The cache-hit-rate metric is tracked separately (see
412
+ [architecture.md §11.1](./architecture.md) observability).
413
+ - **Status**: implemented (Scheme A — volatile tail; adds the enforcing guard tests, the
414
+ byte-stability regression, and the `usage.compressed`-driven cache/compression metrics).
415
+
416
+ ### 2.2 Section Details
417
+
418
+ #### Role System Prompt (§1)
419
+ Source: `role.systemPrompt` parsed from the agent's `ROLE.md`.
420
+ Contains the core behavioral instructions, personality, and domain expertise.
421
+
422
+ #### Your Knowledge (§14)
423
+ Source: `memory.getLongTermMemory()` — curated sections from `knowledge.md` (legacy `MEMORY.md` is migrated once and not written afterward).
424
+ The `## _observations` buffer is **excluded** from the prompt; observations are surfaced via `memory_search`, the ContextEngine's deterministic relevant-memory retrieval, or mechanical relevance matching (written to Notebook as `relevant-context`). This section represents the agent's consolidated long-term knowledge — procedures, conventions, domain facts the agent maintains via `memory_update`.
425
+
426
+ #### Dynamic Context — Notebook (§21)
427
+ Source: `getDynamicContext()` — three sources:
428
+ 1. **Registered providers**: Callback functions set via `registerDynamicContextProvider()`.
429
+ 2. **Activated skill instructions**: When an agent calls `discover_tools` to activate a skill, its instructions are wrapped in `<skill name="...">...</skill>` tags and injected here.
430
+ 3. **Notebook**: Persistent cognitive workspace from `NOTEBOOK.md`, rendered as `## Notebook`. Each entry shows its key, age label, and managed type tag:
431
+
432
+ | Tag | Writer | Typical keys |
433
+ |-----|--------|--------------|
434
+ | `agent` | `notebook_upsert` / `notebook_clear` | Agent-chosen keys (priorities, blockers, decisions) |
435
+ | `system` | Runtime (triage, mechanical retrieval) | `triage-decision`, `relevant-context` |
436
+
437
+ **Bounding ([memory-system.md](./memory-system.md) §2).** The block is bounded on four independent axes, because each alone is insufficient:
438
+
439
+ | Axis | Limit | Failure it prevents |
440
+ |------|-------|---------------------|
441
+ | Entry count | 16 total, 4 `agent` | "26 entries against a nominal cap of 4" — three of four writers bypassed the cap and the load path trimmed nothing |
442
+ | Per-entry chars | 6000 (1500 for `relevant-context`, `NOTEBOOK_RELEVANT_CONTEXT_MAX_CHARS`) | one 9 475-char entry — more than the whole block budget — crowding every real note out |
443
+ | Total block chars | 6000 | the block reaching 41 % of the volatile tail |
444
+ | TTL | `agent` 96h / `system` 24h | month-old situational state (`triage-decision`) re-injected as current fact |
445
+
446
+ Overflow is handled by **inline truncation**, not omission: an entry too large for the remaining budget is sliced with a `_[truncated]_` marker rather than dropped whole, and any entry that still cannot be shown appears in a sorted index line. So the agent always sees that a note exists (and can `file_read` NOTEBOOK.md) instead of it vanishing silently.
447
+
448
+ **Ordering is deterministic**: `updatedAt` DESC with a `key` ASC tie-break. Ranking matters for staleness; determinism matters for caching — for the same logical state the block must serialize to the same bytes, or every assembly dirties the volatile tail and re-bills those tokens. (Map insertion order did neither: evict + re-insert permuted the block.)
449
+
450
+ The `notebookWriter` dual-destination was **removed**: relevance-matched memories are injected **only** for the current turn as `## Relevant Memories`, and a small deterministic `## Cognitive Context` block (recent activity + working-memory keys) may be injected — neither is written to Notebook. Notebook holds only deliberate working state. See [memory-system.md](./memory-system.md).
451
+
452
+ The legacy notebook aliases `update_working_memory` / `clear_working_memory` were **removed** — use `notebook_upsert` / `notebook_clear`.
453
+
454
+ #### Content layers (availability tiers: which content is always on vs on-demand)
455
+
456
+ | Layer | Content | When |
457
+ |-------|---------|------|
458
+ | **L0** | Role, tool rules, search, **Learning Habits** (≤1600 chars; look-back / encode-where / skill impact — [learning-loop.md](./learning-loop.md) §8), autonomy, security, resource refs, user language, shortest task workflow | Always (non-dream) |
459
+ | **L1** | Identity (capped roster), org/workspace, knowledge, active tasks | Identity always; tasks when present |
460
+ | **L2** | Skill catalog metadata (name + one-line description) | Always via identity / discover_tools |
461
+ | **L3+** | Skill full bodies, Error Recovery, Quality Gates, full Task Workflow, deliverable format | `discover_tools` activate, or scenarios: `task_execution` / `review` / `deliberation` / `comment_response` |
462
+
463
+ > **SSOT**: Budgets, packs, and afford fail-closed rules live in [agent-runtime.md](./agent-runtime.md). The sections below are normative Spec supplements.
464
+
465
+ ### 2.3 Spec: Prompt profiles (`promptProfile`)
466
+
467
+ MUST: `buildSystemPrompt()` MUST accept `promptProfile: 'reflex' | 'converse' | 'execute' | 'govern'` derived from the scenario pack ([agent-runtime.md](./agent-runtime.md) §2 / §4).
468
+
469
+ | Section | reflex | converse | execute/govern |
470
+ |---------|--------|----------|----------------|
471
+ | ROLE | full (soft warn metric) | full | full |
472
+ | Collaboration Rules (L0) | yes | yes | yes |
473
+ | knowledge.md as `## Your Knowledge` | omitted | capped (`KNOWLEDGE_PROMPT_MAX_TOKENS_CONVERSE`) | capped (`KNOWLEDGE_PROMPT_MAX_TOKENS`) |
474
+ | ~~state.md~~ | — | retired 2026-09-16 → notebook `system` tier | — |
475
+ | L3 quality/git/error-recovery | omitted | omitted (incl. comments) | included |
476
+ | Search Strategy | complete, concise | complete, concise | complete, concise |
477
+ | Team announcements / norms | capped | 400 chars | 2000 chars |
478
+ | Channel history / shared deliverables | omitted | optional short | as needed |
479
+ | Full roster | manager + ≤3 active | existing caps | existing caps |
480
+ | Date / locale / Interaction Mode | yes | always retained | yes |
481
+
482
+ MUST: ROLE.md is always injected in full (persona only). `ROLE_PROMPT_MAX_TOKENS` is warn-only.
483
+ MUST NOT: Append `HANDBOOK.md` into ROLE. Distill collaboration hard rules into L0
484
+ `## Markus Collaboration Rules`; HANDBOOK.md is a depth handbook via `file_read`.
485
+ Long-tail API/reference content belongs in skills, not ROLE/HANDBOOK always-on.
486
+ MUST: knowledge injection MUST exclude observations buffer; converse uses a short
487
+ digest cap (full text via `memory_search` / files). Knowledge body headings `##`
488
+ MUST be demoted to `###` under `## Your Knowledge` so they do not collide with
489
+ system sections; stale fault/transcript sections are deprioritized when truncating.
490
+ MUST NOT: Inject full history into reflex (the retired `state.md` block is gone — situational state rides `## Notebook`).
491
+ MUST: Converse size is controlled by progressive disclosure + afford guard, **not**
492
+ by post-assemble truncation of ROLE/L0/Collaboration Rules/mode/date.
493
+ MUST NOT: Emit `_[ROLE truncated]_` / `_[system trimmed]_` markers.
494
+
495
+ #### Conversation-first vs Task-when-needed (L0 + chat scenario)
496
+
497
+ MUST: Human chat defaults to **conversation-first** — agents MAY advance real work
498
+ (edit files, run commands, multi-step debugging) in the live conversation without
499
+ forcing `task_create`.
500
+ MUST: Task workflow is for async work, delegation, multi-agent parallel delivery,
501
+ formal review/audit trail, or when the human explicitly asks for a task.
502
+ MUST: **STOP** means only: after `task_create` for a piece of work, do not continue
503
+ **that task** in chat. Work never placed on a task may continue conversationally.
504
+ MUST: Requirements gate applies to **tasks** (`gate all tasks`), not to conversational chat work.
505
+ MUST: Conflict priority:
506
+ `Owner explicit instruction > conversation-first default > Protocol (once a task exists) > ROLE persona > Position (manager)`.
507
+ MUST: Managers are **player-coach** — Position does not forbid hands-on building when ROLE is a builder/founder.
508
+
509
+ MUST: L0 includes **How Your Prompt Is Composed** — ROLE.md is persona; L0 is always-on
510
+ platform rules; HANDBOOK/skills are on demand. ROLE line count ≠ full constraints.
511
+
512
+ MUST (`task_submit_review`): Auto-fill `task_id` from execution ALS/`activeTasks` when
513
+ present; otherwise `task_id` is required. MUST NOT guess from the TaskService board.
514
+ Work-context-bound tools MUST NOT sticky into free chat — but MUST remain available in
515
+ entity-bound sessions (task_execution, review, comment_response, requirement_action,
516
+ workflow_action) (`S-execute-only-no-sticky-converse`).
517
+
518
+ Test IDs: `A-profile-reflex-omits`, `A-profile-role-full`, `A-collab-rules-always-on`,
519
+ `A-conversation-first-chat`, `A-knowledge-heading-demote`, `A-role-no-shared-append`,
520
+ `A-knowledge-cap`, `A-profile-converse-no-l3`, `S-execute-only-no-sticky-converse`.
521
+
522
+ ### 2.4 Spec: Afford fail-closed packing
523
+
524
+ MUST: After assembling system + tools, compute `fixed = systemTokens + toolDefTokens`.
525
+ MUST: If `promptAffordTokens != null` and
526
+ `fixed + PROMPT_AFFORD_OUTPUT_RESERVE + safetyMargin > promptAffordTokens`:
527
+ 1. Downgrade once to `reflex` pack + profile and re-assemble.
528
+ 2. If still over, MUST NOT call the provider; return actionable error (`prompt_pack_rejected`).
529
+ MUST: Heartbeat paths that hit reject MUST end activity with `success: false`.
530
+ MUST NOT: Only shrink `messageBudget` while shipping an over-afford fixed prefix.
531
+
532
+ MUST (§Afford.S1): `handleMessageStream` MUST use the same `ensureAffordablePromptPack`
533
+ gate as `handleMessage` before any provider call.
534
+
535
+ MUST (§Afford.S3): `SYSTEM_PROMPT_BUDGET_CONVERSE` is a soft observe/warn metric for
536
+ converse system size. MUST NOT truncate ROLE/L0/mode/date to meet it. Hard limits
537
+ are enforced by the provider afford guard (downgrade/reject).
538
+
539
+ MUST (§Afford.S4): Provider MUST clamp `max_tokens` to remaining afford (proactive when
540
+ `lastPromptAffordTokens` known; reactive on reservation 402).
541
+
542
+ Test IDs: `A-afford-downgrade`, `A-afford-heartbeat-fail`, `S-stream-afford-reject`,
543
+ `S-stream-afford-downgrade`, `S-converse-system-budget`, `S-converse-keeps-date`,
544
+ `S-max-tokens-clamp-remaining`.
545
+
546
+ Cold-start acceptance: converse fixed ≤ 28_000; reflex fixed ≤ 8_000
547
+ (`A-budget-contract-converse`, `A-budget-contract-reflex`).
548
+
549
+ #### Identity Section (§7)
550
+ Source: `buildIdentitySection()`.
551
+ Contains:
552
+ - Agent name, role, position (manager vs worker)
553
+ - Assigned skills (names only — activate via `discover_tools` for full instructions)
554
+ - Organization name, Agent ID
555
+ - Manager info (for workers)
556
+ - Colleague list capped at `SYSTEM_COLLEAGUES_MAX` (10); remainder via `team_list` / `agent_list_colleagues`
557
+ - Other teams capped at `SYSTEM_OTHER_TEAMS_MAX`; humans at `SYSTEM_HUMANS_MAX`
558
+ - **Manager Responsibilities** (for managers): player-coach — own Owner pair-work when ROLE fits; delegate for specialty/parallel/async; Reporting; Cross-team (peer managers); Escalation; Hiring
559
+
560
+ #### Skills (Hermes L0–L1 progressive disclosure)
561
+ Skill **full bodies are not injected at spawn** (including former `alwaysOn` builtins and
562
+ assigned skills). The catalog lists name + description; agents call
563
+ `discover_tools({ name: [...] })` to load `<skill>` instructions into the volatile tail
564
+ context. MCP servers for assigned skills still connect at spawn (tools only).
565
+
566
+ #### Task Board (§23)
567
+ Source: `opts.assignedTasks`.
568
+ Displays the agent's active tasks and team tasks, **capped to prevent prompt bloat**:
569
+ - **My active tasks**: Top 15 by priority (critical → high → medium → low), each with title, ID, priority, and truncated description (150 chars).
570
+ - **Team tasks**: Top 10 by priority, with title, ID, assignee, and priority.
571
+ - Overflow is indicated with a count and a hint to use `task_list` for the full list.
572
+ - Completed/closed tasks are only shown as a count.
573
+
574
+ #### Mailbox & Attention Context (§26)
575
+ Source: `getMailboxContext()` → `buildMailboxSection()` in `ContextEngine`.
576
+ Every LLM call passes through the mailbox, so this section is always populated. It injects:
577
+ - **Current focus**: What the agent is currently working on (item type, summary, time elapsed).
578
+ - **Pending queue**: Count and top items in the mailbox, so the agent knows what's waiting.
579
+ - **Recent decisions**: Last 3-5 attention decisions (continue/preempt/cancel/merge/defer) with reasoning. The `preempt` decision means current work was **paused** (deferred for later resumption); the `cancel` decision means current work was **permanently stopped**.
580
+ - **Merged content**: If a `merge` decision injected additional context (e.g., a comment on the current task), it appears here.
581
+
582
+ In addition to the passive `## Your Attention State` section, agents can query
583
+ their mailbox on demand using `check_mailbox` in any scenario.
584
+
585
+ **Triage context budget** is generous — up to 20 recent messages × 2000 chars each, plus full item content (3000 chars per candidate) and the agent's active task list. Tens of thousands of tokens are acceptable for triage because accurate prioritization decisions save far more cost downstream. The triage LLM can also invoke a curated set of **read-only tools** (`task_list`, `task_get`, `requirement_list`, `requirement_get`, `list_projects`, `team_list`) to gather additional context before deciding. These are controlled by `TRIAGE_ALLOWED_TOOLS` and `TRIAGE_MAX_TOOL_ITERATIONS` in `limits.ts`.
586
+
587
+ **Task status notifications** are purely informational — the system's side-effect mechanism handles all actions (execution start/cancel, reviewer notification, dependency unblocking). Agents are instructed not to send redundant A2A messages for routine status changes.
588
+
589
+ All 12 mailbox item types (`human_chat`, `task_status_update`, `session_reply`, `daily_report`, `memory_consolidation`, `heartbeat`, etc.) route through this section. Internal agent processes like heartbeats, daily reports, and memory consolidation also enqueue to the mailbox, meaning the agent always has full situational awareness about its own cognitive state. See [mailbox-system.md](./mailbox-system.md) for the full design.
590
+
591
+ #### Concurrency Context (volatile tail)
592
+ Source: `buildSystemPrompt()` with `opts.concurrentContext` in `ContextEngine`.
593
+ Injected **only** when concurrent processing is enabled *and* `workerCount > 1` (see
594
+ [concurrent-processing.md](./concurrent-processing.md)). It is a **volatile-tail** segment,
595
+ never a system-prompt section, so its per-turn churn cannot invalidate the STABLE /
596
+ SEMI-STABLE prefix cache. It injects:
597
+ - **Worker identity**: "this session is one of N workers (worker W)".
598
+ - **In-flight siblings**: up to 4 recent `declared`/`fact` handoff records from *other* workers (own records filtered out).
599
+ - **Recent handoffs**: up to 4 `done`/`conflict` records from other workers, newest first.
600
+ - **Consistency rules**: (1) do not assume exclusive cognition — check shared knowledge + handoff log before any persistent decision; (2) an entity is processed by one worker at a time — do not force work whose entity is held; (3) on a detected conflict, report the divergence instead of silently overwriting.
601
+
602
+ The data comes from the agent's `ConcurrentHandoffLog`; the injectable subset is bounded
603
+ by `HANDOFF_CONTEXT_LIMIT` (8).
604
+
605
+ #### Scenario Section (§15)
606
+ Source: `buildScenarioSection()`.
607
+ Placed at the **end of Tier 2** so the identity/org prefix remains stable across mode switches (chat ↔ heartbeat ↔ a2a). Twelve distinct instruction sets depending on `scenario` parameter (see §5.9 for the full matrix). Each scenario is slim and references the global Task Workflow and Tool Usage Rules rather than re-explaining them. Each scenario includes a **Communication channel** paragraph that specifies output visibility and appropriate tools:
608
+
609
+ | Scenario | Key Instructions | Output Visibility | Communication Tools |
610
+ |----------|-----------------|-------------------|-------------------|
611
+ | `chat` | Inline immediate-answer work. Sustained implementation → `task_create`. | **Directly visible** to the chatting human (real-time stream) | Speak naturally; `agent_send_message` for agents |
612
+ | `task_execution` | Isolated session. Decompose → execute → `task_submit_review`. | Visible in **task execution logs** (Work page) | `notify_user` for critical updates; `agent_send_message` for agents |
613
+ | `heartbeat` | Brief check-in: review tasks, retry failures, active goals; at most one-line `memory_save` (no long evolution essays). Inline prompt includes `## Active Goals` when standing goals exist. | **Not visible** to anyone | `notify_user` (only way to reach humans); `agent_send_message` for agents |
614
+ | `chat` (evolution child) | User-initiated Remember session ([learning-loop.md](./learning-loop.md) §9): seeded with parent DM transcript + `parentSessionId`; agent follows Learning Habits and may page history via `recall_context(scope=chat_session)`. | Visible to the human in that personal session | Same as chat; high-impact skill/ROLE changes use `request_user_input` |
615
+ | `distillation` | Post-task Learning Loop ([learning-loop.md](./learning-loop.md) §2): on **completed** only; Habits encode (memory/skill); `package_install` with §8.3 impact/HITL. No JSON outcome ritual. | **Not visible**; system session | Memory / file encode + skill create/install (approval for high impact) |
616
+ | `a2a` | Coordination only. Concise, structured. Complex work → `task_create`. | Visible to **peer agent** only | Reply directly; `notify_user` to escalate to humans |
617
+ | `group_chat` | Team group chat channel. Silence by default, @mention routing, processing checklist, reply-in-group rules. | Visible to **all team members** | `agent_send_group_message` for replies; `notify_user` for private escalation |
618
+ | `comment_response` | Context-first protocol. Batch awareness (handle bundled comments as one). Use `reply_to_comment_id` for structural quoting. Convergence check before replying. | **Not directly visible** | `task_comment` / `requirement_comment` for thread (with `reply_to_comment_id`); `notify_user` if urgent |
619
+ | `deliberation` | Multiple mailbox items — assess before committing. Use `check_mailbox` for full queue inspection; `defer_mailbox_item` / `drop_mailbox_item` for queue management; `notebook_upsert` to record situational assessment; finish with `complete_deliberation`. Goal tools (`goal_create`, `goal_update`, `goal_status`) available. | **Not visible** | Inline handling via deliberation whitelist (`notify_user`, `task_comment`, `agent_send_message`, etc.) |
620
+ | `review` | Evaluate deliverable quality against acceptance criteria. | **Not directly visible** | `task_update` for verdict; `notify_user` optionally |
621
+ | `memory_consolidation` | Internal memory management. Purely private. | **Not visible**; internal only | No communication tools needed |
622
+
623
+ #### Referencing Markus Resources
624
+
625
+ Placed in **Tier 1 (Stable)** (`## Referencing Markus Resources`, near the Deliverable Output Format section). Teaches agents the link conventions the Web UI markdown renderer understands, so references become clickable in chat/comments/reports:
626
+
627
+ - **Bare ID** in prose (`tsk_…`, `req_…`, `proj_…`, `dlv_…`, `agt_…`, `team_…`) → inline clickable chip (auto-linked by `preprocessEntityIds` in `markdown-utils.ts`).
628
+ - **Titled link** `[Title](task:tsk_…)` (types: `task`, `requirement`, `project`, `deliverable`, `agent`, `team`) → chip showing the title.
629
+ - **Card**: a reference **alone on its own line/paragraph** renders as a rich block card (icon + title + status + summary) via `EntityCard`. Agents are told to reference a new `dlv_…` on its own line after `deliverable_create` so users get a clickable deliverable card.
630
+ - Agents must NOT paste raw `/api/…` paths or bare `http(s)://` internal URLs — those render as external links, not in-app navigation.
631
+
632
+ This closes the previous gap where the renderer silently auto-linked IDs but no prompt told agents to emit them.
633
+
634
+ #### Async Work, Callbacks & Timing
635
+
636
+ Placed in **Tier 1 (Stable)** (`## Async work, callbacks & timing`, after the agent-communication rules). Establishes the event-driven behavioral model that backs the callback/wakeup infrastructure (see [mailbox-system.md](./mailbox-system.md) §3.4/§11.3):
637
+
638
+ - **Await, don't poll**: after starting async work, register for the completion event and stop — do not busy-loop checking status. `background_exec` reports completion automatically; a tight `process poll` loop is discouraged.
639
+ - **`schedule_wakeup` / `cancel_wakeup`**: agents set precise time-based follow-ups (`in_seconds` or ISO `at`, optional `recurring_seconds`) instead of relying on the heartbeat, which is now a coarse safety-net (default `DEFAULT_HEARTBEAT_INTERVAL_MS`, 6h) rather than a frequent poll.
640
+ - **`set_heartbeat_interval`**: agents (or users, via the Heartbeat tab / config API) can adjust the coarse safety-net cadence itself (clamped 5min–24h, applied live). This is distinct from `schedule_wakeup` — the latter is for precise one-off/recurring follow-ups; the former only changes how often the fallback patrol fires.
641
+ - **`agent_send_message` `reply_in_session`** (alias: deprecated `await_in_session`): the peer's reply resumes the **current conversation** (an `a2a_reply` callback correlated by `conversation_id`), instead of landing in a disconnected a2a session. Non-blocking — the send returns immediately and the reply re-wakes the thread.
642
+ - **`agent_send_message` `wake_recipient`**: if the recipient is stopped, optionally wake (start) them before dispatch; the response always reports `recipient.status` so a stopped recipient is never a silent dead letter.
643
+ - **Two delivery forms**: `in_session` (result resumes the origin session — `background_exec`, `reply_in_session`) vs `mailbox` (fresh attention cycle — `schedule_wakeup`, autonomous follow-ups). Documented so agents pick the right one.
644
+ - Note: `task_create` is intentionally **not** wired for in-session return — tasks are an independent, tracked/reviewed workflow whose results flow through the board, review, and `notify_user`, not back into the creating conversation.
645
+
646
+ #### Behavioral Policies (coding-agent patterns)
647
+
648
+ Placed in **Tier 1 (Stable)** (`## Error Recovery` + `## Autonomy & Escalation`). Production-coding-agent patterns encoded as durable rules:
649
+
650
+ - **Bounded retry + escalate**: at most ~2 attempts at the same failing action without new evidence; then stop and escalate (`request_user_input` for a decision that has no built-in UI, `notify_user` for FYI, mark `blocked`). Never loop; never fail silently.
651
+ - **Autonomy calibration**: reversible/low-stakes → pick a sensible default and record the assumption; irreversible/destructive/scope-expanding → `request_user_input` first. When unsure about reversibility, treat as irreversible.
652
+ - **Requirement/task approval**: after `requirement_propose` / `task_create`, do **not** use `request_user_input` to ask the human to approve — the entity card already has Approve/Reject, and creation already notifies them. Skip extra `notify_user` reminders at creation time; at most one non-blocking nudge if something stays pending for a very long time.
653
+ - **Self-contained delegation contract**: delegations must carry goal, context, constraints, expected return format, and preserve `conversation_id` — recipients have no access to the sender's session.
654
+ - **Decision-ready return contract**: async results and delegation replies are summarized for immediate action, not raw stdout/log dumps.
655
+
656
+ ### 2.3 Skill Filtering
657
+
658
+ **removed (2026-09-16)** — `filterSkillsByRelevance()` (query-keyword scoring, "top 30") was deleted as dead code; it was never called. The every-turn skill catalog is ORG context (scope O) — byte-stable for the whole org — so ranking it per query would convert a shared cached block into a per-call one. See §3.9.1 O4.
659
+
660
+ ---
661
+
662
+ ## 3. Message Assembly & Context Compression
663
+
664
+ `ContextEngine.prepareMessages()` assembles the final message array sent to the LLM. It operates in four stages.
665
+
666
+ ### 3.1 Token Budget Calculation
667
+
668
+ ```
669
+ contextWindow = model's context window (e.g. 200K for Claude Sonnet 4)
670
+ maxOutput = min(model.maxOutputTokens, contextWindow × 40%)
671
+ safetyMargin = ceil(min(contextWindow × 8%, 16000))
672
+ messageBudget = contextWindow − systemTokens − toolDefTokens − maxOutput − safetyMargin
673
+ ```
674
+
675
+ **maxOutput reservation**: Uses the model's actual `maxOutputTokens` from the model catalog (e.g. 64K for Claude Sonnet 4, 128K for Claude Opus 4.6), capped at 40% of the context window. This ensures the budget reserves enough space for the model's full output capability without over-compressing messages.
676
+
677
+ Token estimates use tiktoken when available (model-specific encoding), falling back to `chars / 3.5` heuristic.
678
+
679
+ ### 3.2 Compression Pipeline
680
+
681
+ **Policy: budget-first (model window AND provider afford).** Markus packs against the
682
+ real model window, then further clamps by any OpenRouter prompt-afford hint (from a prior
683
+ `Prompt tokens limit exceeded: X > Y` 402). Compression runs when history exceeds
684
+ `CONTEXT_PROACTIVE_COMPACT_RATIO` (75% — the history-occupancy water level, i.e. the history's
685
+ share of `messageBudget`) — not only when the hard window overflows. Session restore also trims before the first LLM call
686
+ (`SESSION_RESTORE_MAX_MESSAGES` / `SESSION_RESTORE_MAX_MESSAGE_TOKENS`).
687
+
688
+ ```
689
+ Session Messages
690
+ │
691
+ ▼
692
+ Stage 0: Clamp messageBudget by promptAffordTokens − PROMPT_AFFORD_OUTPUT_RESERVE
693
+ │
694
+ ▼
695
+ Stage 1: Pathological single-message shrink ONLY
696
+ └─ shrinkOversizedMessages(cap: CONTEXT_ABSURD_MESSAGE_CHARS = 200k)
697
+ └─ sanitizeMessageSequence()
698
+ │
699
+ ▼
700
+ (runs if totalTokens > messageBudget OR > proactive 75% threshold)
701
+ │
702
+ ▼
703
+ Stage 2: Token-budget-driven compression (progressive)
704
+ ├─ 2a: shrinkOversizedMessages(cap: max(8000, budget/4)) + compactOldTurns()
705
+ ├─ 2b: smartSummarizeAndTruncate(keep: max(24, 55%))
706
+ └─ 2c: stronger summarize(keep: max(16, 40%)) + re-shrink
707
+ │
708
+ ▼
709
+ Stage 3: Last-resort trimming
710
+ └─ trimToFitBudget() — drop oldest, protect index 0 (task prompt)
711
+ │
712
+ ▼
713
+ Final: [system prompt, ...compressed messages]
714
+ Metrics: systemTokens / historyTokens / toolDefTokens / totalPromptTokens / compactStage
715
+ ```
716
+
717
+ - **Safety margin**: `min(contextWindow * 0.08, 16000)` — modest, to prefer packing
718
+ history over reserving unused slack.
719
+ - **Channel history**: `CHANNEL_CONTEXT_MESSAGES = 15` (load, inject, and prompt copy aligned).
720
+ - **Tool result offload**: `TOOL_RESULT_OFFLOAD_CHARS = 12_000` (preview kept in context).
721
+ - **Storage-side compaction** is a separate, high-volume safety net (not a per-call token
722
+ saver): on-disk sessions are compacted only at
723
+ `SESSION_STORAGE_COMPACT_TRIGGER = 2000` messages, keeping
724
+ `SESSION_STORAGE_COMPACT_KEEP = 1000`; oversized on-disk tool results are shrunk at
725
+ `SESSION_STORAGE_TOOL_SHRINK_CHARS = 100k`. See [memory-system.md](./memory-system.md).
726
+
727
+ **Design rationale (Hermes progressive disclosure + afford-aware packing)**: keep cold-start
728
+ system+tools lean (~10k target), activate skill bodies on demand, and never fill a 128k/1M
729
+ window when the provider key can only afford ~37k prompt tokens.
730
+
731
+ **Lightweight sessions**: All interactions (heartbeat, A2A, memory flush, comments) use the same `prepareMessages()` pipeline. Sessions are persisted to JSON files for full traceability. The `scenario` parameter controls what context is included in the system prompt — lightweight scenarios (`heartbeat`, `a2a`, `comment_response`) skip heavy context like assigned tasks, deliverables, and chat session lists.
732
+
733
+ ### 3.3 Task Prompt Protection
734
+
735
+ The first user message in a task session often contains the task description and the `task_submit_review` instruction. This message is **protected** throughout all compression stages:
736
+ - `smartSummarizeAndTruncate()` detects `TASK EXECUTION` or `task_submit_review` markers and preserves the first message verbatim.
737
+ - `compactOldTurns()` skips compaction of block 0 if it matches the task prompt pattern.
738
+ - `trimToFitBudget()` preserves index 0 and only compacts it as a last resort.
739
+
740
+ ### 3.4 Tool Block Compaction
741
+
742
+ `summarizeToolBlock()` compresses an `[assistant+toolCalls, tool, tool, ...]` block into a single assistant message:
743
+ - Preserves tool names and truncated arguments.
744
+ - **Error results** are preserved in full (up to 200 chars) — errors in context help the model self-correct.
745
+ - Research tool results (`web_search`, `file_read`, etc.) retain up to 500 chars of findings.
746
+ - **Serialization diversity**: Uses 4 rotating summary templates to prevent the model from mimicking uniform compaction patterns.
747
+
748
+ ### 3.5 LLM-Powered Summarization
749
+
750
+ When available, `smartSummarizeAndTruncate()` uses an LLM call to summarize older messages:
751
+ - The summarizer LLM call is cheap: truncates each message to 300 chars, total input capped at 8000 chars.
752
+ - No `maxTokens` cap — the router fills in the model's real output limit (the prompt itself bounds output to "under 1500 characters"). Temperature 0.2.
753
+ - Fallback: `buildHeuristicSummary()` extracts key sentences from assistant messages.
754
+ - The summary is **not** persisted to disk — `prepareMessages()` must stay pure (no `writeDailyLog`).
755
+ It is instead carried in-history as a `[SYSTEM] [Conversation history summary …]` message, and the
756
+ durable compaction summary lives in the fixed `[CONTEXT SUMMARY]` segment (the session's `summary` field).
757
+
758
+ ### 3.6 Message Sanitization
759
+
760
+ `sanitizeMessageSequence()` ensures structural correctness before LLM submission:
761
+ - Every `assistant(toolCalls)` must be followed by ALL corresponding `tool` result messages.
762
+ - Orphaned tool messages are dropped.
763
+ - Incomplete assistant+tool blocks are dropped entirely.
764
+ - Consecutive user messages are merged (unless either is a system injection like `[SYSTEM]` or `[Conversation history summary`).
765
+
766
+ ### 3.7 Fixed/Variable Split & Session Anchors (ContextOS)
767
+
768
+ A complement to the compression pipeline above: separate the prompt into a **fixed segment**
769
+ (system + tools + SLOT anchors) that is **never business-compacted**, and a **variable segment**
770
+ (history) that is the only thing compression/truncation touches. Motivation: long-session "loop"
771
+ bugs where compaction discarded the agent's work anchors, so the agent lost its "position" and
772
+ re-read the same files forever (diagnosed on 8/20; deliverable notes are archived in git history).
773
+ Scope: `packages/core/src/context-slot.ts` + `tools/session.ts` + the `prepareMessages` slot
774
+ plumbing.
775
+
776
+ **Fixed vs variable:**
777
+
778
+ - **Fixed (never compacted)**: system prompt, tool definitions, and the **SLOT segment**.
779
+ - **Variable**: conversation history — the only thing shaved/compressed/truncated.
780
+
781
+ **SLOT fixed segment (`[SLOTS]`)** — `context-slot.ts`:
782
+ - Slots are agent-managed named anchors (`goal` / `done` / `next`, or any agent-chosen key)
783
+ persisted on the session (`ConversationSession.slots`).
784
+ - At send time, `prepareMessages` accepts `slotsSegment` (= `serializeSlots(sessionId)`), subtracts
785
+ `slotsTokens` from the budget, and appends it to the system message (`[SLOTS] (agent-managed, not
786
+ compacted)\n· key: text…`). It is **excluded from the compaction/truncation chain** — so after any
787
+ compress or truncate, the agent still sees its current goal/done/next and can continue **without
788
+ re-reading files**.
789
+ - Runtime caps: `CONTEXT_SLOT_MAX_CHARS` (1200).
790
+
791
+ **Session tools (agent-driven compaction + anchors)** — `tools/session.ts` exposes 10 operations so
792
+ the agent can actively manage long sessions instead of relying only on passive auto-compaction:
793
+ `list | get | compact(keepLast, goal?, done?, next?) | pin | unpin | retrieve | include | purge | status | rename`.
794
+ - `compact` folds expired history into structured anchors (`compactWithAnchor`: pin goal/done/next
795
+ into SLOTs, then compress), keeping recent N; raw history is archived to `conversation_fragment`
796
+ (never deleted) and recoverable via `include`.
797
+ - `pin`/`unpin`: write/remove named slot anchors (survive compression + truncation).
798
+ - `include`: place archived fragment back into context precisely.
799
+ - All read/write ops are guarded by `checkOwnership(sessionId, agentId)` — an agent may only manage
800
+ its own session.
801
+
802
+ **Context watermark (`[CONTEXT X% used …]`)** — the agent can observe its own pressure (no more
803
+ silent truncation) and act:
804
+ - `usedPct = (fixedTokens + variableTokens) / effectiveBudget`.
805
+ - `[CONTEXT WARN]` at ≥80%: nudge to `session_compact` or `session_pin` an anchor.
806
+ - `[CONTEXT CRIT]` at ≥95%: warn that the system will hard-truncate oldest turns; instruct to
807
+ immediately `session_compact` + `session_pin`.
808
+ - Injected via the volatile `[SYSTEM] [Live context]` tail (see §2.1), never into the system prefix.
809
+
810
+ **Why this fixes the loop**: previously compaction dropped anchors → the agent lost position → it
811
+ re-read the same files to re-orient → that re-reading itself grew context → re-truncated → loop.
812
+ With SLOT anchors locked in the fixed segment, a compressed/truncated history still carries
813
+ goal/done/next every turn, so the agent resumes without re-reading — the trigger for the loop is gone.
814
+
815
+ ---
816
+
817
+ ### 3.8 Compaction defects fixed in v2.1 (2026-09-16)
818
+
819
+ Four defects were found by auditing the pipeline against the published designs
820
+ (Anthropic compaction, DeepSeek V3.2 context management, fast-agent).
821
+
822
+ **(a) Fold direction was inverted — `compactOldTurns()`.** It walked blocks
823
+ oldest→newest, kept each verbatim while the budget allowed, then summarised *or
824
+ dropped* the remainder. That preserves the **oldest** conversation and
825
+ summarises/discards the **most recent** past turns — the opposite of "keep the
826
+ recent window verbatim, summarise the distant past" — and it discarded exactly
827
+ the context the model still needed. Now the recency walk accumulates from the END
828
+ and keeps the newest blocks verbatim. Order is preserved, and folding is
829
+ block-wise via `parseIntoBlocks()`, so an assistant tool-call is never separated
830
+ from its tool results. Task prompts (`TASK EXECUTION` / `task_submit_review`) stay
831
+ protected verbatim even though they are the oldest block.
832
+
833
+ **(b) The watermarks could never fire on a large window.**
834
+ `CONTEXT_PROACTIVE_COMPACT_RATIO` / `CONTEXT_WARN_RATIO` are relative to the model
835
+ window, so on the 1311k window Markus runs, proactive compaction sits around
836
+ ~500k tokens. The observed session finished a single turn at 269k input tokens —
837
+ ~12 % of the window — with `compactStage === 'none'` throughout: **no maintenance
838
+ compression ever ran.** Added an absolute ceiling:
839
+
840
+ | Constant | Value | Meaning |
841
+ |---|---|---|
842
+ | `CONTEXT_ABS_HISTORY_TOKENS` | 120 000 | above this, maintenance compression fires regardless of window % |
843
+ | `CONTEXT_ABS_HISTORY_TARGET_TOKENS` | 72 000 | what a fold compresses down to (hysteresis: grow to 120k, fold to 72k) |
844
+
845
+ When the ceiling trips, `historyTarget` replaces the window-derived
846
+ `messageBudget` (which would otherwise authorise keeping everything — a silent
847
+ no-op) and the fold boundary becomes `messages.length`, which is what also covers
848
+ the single-gigantic-turn case.
849
+
850
+ **(c) `smartSummarizeAndTruncate()` reordered history.** Eligible messages were
851
+ sorted by **priority**, and `retained` was then built straight from that sorted
852
+ array — so the summariser received a priority-shuffled transcript and the kept
853
+ older messages were replayed in importance order instead of time order. Both
854
+ `older` and `promoted` are now re-sorted by original index. (Chronological input
855
+ also produces a better summary, and restores determinism, which the prefix cache
856
+ relies on.)
857
+
858
+ **(d) `findCurrentTurnStart()` counted synthetic messages as user turns.**
859
+ Engine-synthesised blocks — the compaction summary, the `[SYSTEM] [Live context]`
860
+ tail, `[Continue from where you left off …]` and `[SYSTEM] Loop detected: …` —
861
+ are `role: 'user'` but are not user turns. Since `findCurrentTurnStart()` decides
862
+ both the turn boundary and the prefix-cache breakpoint, they were placed against
863
+ the wrong boundary. `isSyntheticMessage()` now skips them.
864
+
865
+ > **Why the synthetic blocks cannot simply become `role: 'system'`:** the
866
+ > Anthropic adapter does `find(m => m.role === 'system')` and then
867
+ > `filter(m => m.role !== 'system')`, so any non-first system message is silently
868
+ > dropped there (the summary would vanish). Skipping them during accounting is the
869
+ > provider-safe fix. Revisit only if every adapter is switched to multi-system
870
+ > handling.
871
+
872
+ **Regression guard**: `packages/core/test/context-compaction-v21.test.ts`.
873
+
874
+ ### 3.9 Root cause analysis: why these defects keep returning (2026-09-16)
875
+
876
+ Three rounds of auditing found six defect classes. They are **not six independent
877
+ bugs** — they are six surfaces of four design gaps, which is why fixing one kept
878
+ exposing the next. This section records the gaps so the next fix is aimed at the
879
+ cause rather than the symptom.
880
+
881
+ | # | Root cause | Design or implementation debt | Surfaces it produced |
882
+ |---|---|---|---|
883
+ | RC1 | **The fixed/variable split has no third tier.** Context was modelled as *fixed* (system + tools + slots) vs *variable* (history + volatile tail). Stable-but-large session state — knowledge, notebook, skills catalog, deferred tools, task board — has neither a home nor a delivery contract, so it was dumped into the *per-call* tail. | **Design** | Tail re-sent 66× in one turn; every "make the tail smaller" fix then risked losing the state outright (§2.1.2) |
884
+ | RC2 | **No harness channel.** Providers accept only system/user/assistant/tool, so the engine synthesises `role:'user'` for state, `[Continue …]` and loop warnings. There is no explicit framing that marks a block as *telemetry, not instruction*. | **Design** | Turn accounting corrupted (`findCurrentTurnStart`); negative priming from stacked \"do not repeat\" prompts; state read as the newest user message and re-announced |
885
+ | RC3 | **No context budget owner.** Each feature pushes into the dynamic array with its own cap; nobody owns the total, the priority order, or eviction. | **Design** | Byte-constant noise lines survive forever (`_(66 completed/closed tasks)_`); knowledge truncated by *document order* mid-sentence; `## Notebook` reached 41 % of the tail |
886
+ | RC4 | **Cache-friendliness was a patch, not an invariant — and was unmeasurable.** Registration-order emission was fixed case-by-case; `discover_tools.description` still embedded per-turn counts *directly under a comment claiming cache-safety*; the documented MUST-NOT in `tool-system.md` was violated by the code. No cache-hit telemetry and a 0.7 heuristic polluting the denominator meant regressions were **invisible**. | **Design (missing guard) + implementation** | Tool prefix silently busted every turn; the same class of bug reappeared across rounds |
887
+ | RC5 | **The toolset is recomputed per turn, not accumulated per session.** `recentToolNames` is an instance-level LRU(10); `activatedExtraTools` is instance-level and never reset. Both drift within a turn **and leak across sessions**. | **Implementation** | Capability surface changes every turn (cache break); one session inherits tools activated in another |
888
+ | RC6 | **Estimated vs reported usage is a dual rail.** Budget and `[CONTEXT x%]` come from the local `TokenCounter`; server-reported `inputTokens` is used only for the audit log, only calibrates the estimator, and is wired on *one* code path (`agent.ts:4373`). | **Implementation** | The displayed water level is an estimate; the cache-hit denominator was back-filled with `totalTokens*0.7` |
889
+
890
+ #### What was fixed in this round
891
+
892
+ | Root cause | Fix | Where |
893
+ |---|---|---|
894
+ | RC1 + RC2 | Durable `[SYSTEM] [State checkpoint]` history message on change (complete + append-only + cache-extending); tail digest names where the content lives; relative-time labels normalised out of the hash | §2.1.2, `context-engine.ts` |
895
+ | RC3 | Closed-task counters deleted; **team active tasks kept in full** but ranked actionable-first; empty board skipped for converse; `prepareKnowledgeForPrompt(raw, maxChars, query?)` ranks by relevance, selects **whole** sections, and always emits a title index of what was omitted | §3.9.1, `context-engine.ts` |
896
+ | RC4 | `discover_tools.description` is now a pure function of the **registry** (minus `TOOL_DEF_CORE_KEEP`), deterministically sorted; byte-stability guard test added; per-session cache-hit window + `cacheHitRateWindow` / `cacheHitRateSamples` telemetry that returns `null` (not 0) when nothing was reported | `tool-selector.ts`, `agent-metrics.ts` |
897
+
898
+ > **A note on RC3's shape:** the first attempt at the task-board fix collapsed
899
+ > *all* non-actionable team tasks into a count bucket. That was rejected on review
900
+ > — it traded information away for tokens, hiding \"what is my team working on?\"
901
+ > from a manager. Only the genuinely constant counters were removed. **Deleting
902
+ > noise is a win; deleting signal is a regression**, and the two look identical in
903
+ > a token-diff.
904
+
905
+ #### 3.9.1 Open items — status after the cache-scope round (2026-09-16, v4)
906
+
907
+ | # | Item | Status |
908
+ |---|---|---|
909
+ | O1 | **Tool schema drift (RC5).** Session-level monotonic toolset. | **DONE.** `Agent.stickyTools()` keeps `recent`/`activated` in a session-keyed record (`toolSticky`), monotonic within a session (freezes at `STICKY_RECENT_TOOLS_MAX` instead of evicting) and reset on session switch, so the *cross-session leak* is closed as well as the per-turn drift. Remaining (deferred): the call-site inconsistency where the stream/task/risk paths do not pass `extraRecentToolNames`, and `Mask, Don't Remove` decode-time placeholders (not applicable to closed APIs). |
910
+ | O2 | **Reported usage as the single source of truth (RC6).** | **PARTIAL — calibration only.** `calibrateTokenCounter(response.usage.inputTokens)` is now wired on 8 paths, and `extractCacheReadTokens()` already parses DeepSeek's `prompt_cache_hit_tokens` **and** OpenAI/OpenRouter `prompt_tokens_details.cached_tokens`, feeding `cacheHitRateWindow` (reported-only denominator). Still open: using reported tokens to *drive* the budget/water level and marking it `src=reported\|estimated`. Deferred per Owner's call — do DeepSeek-first if pursued. |
911
+ | O3 | **`## Notebook` size (RC3).** Largest single tail section (mean 9 163 chars, 41 % of tail). | **DONE (size + lifecycle).** Added a TOTAL cap (`NOTEBOOK_PROMPT_MAX_CHARS = 6000`) on top of the per-entry cap, keeping the most recent entries and naming any omitted keys — so the block can no longer dominate the tail. Relevance ranking deliberately NOT applied: the notebook is the agent's own workspace, and dropping a note it wrote itself is a correctness risk, not a token win. Follow-up ([memory-system.md](./memory-system.md) §2): the cap alone was not enough — entry count/TTL/single-writer were missing, so a real notebook reached 26 entries / 33 KB and an 18-day-old triage decision was re-injected as current fact. Now: single write path (`Agent.writeNotebookEntry`), per-tier TTL, cross-tier entry cap, normalize-on-load, deterministic ordering, and inline truncation instead of whole-entry omission. |
912
+ | O4 | **`filterSkillsByRelevance` dead code.** | **DONE.** Deleted. It was never called, and the every-turn `## Available Skills` table is ORG context (scope O) — byte-stable for the whole org — so ranking it per query would convert a shared cached block into a per-call one. Rationale recorded in-code. |
913
+
914
+ **Evidence provenance.** All measured figures come from
915
+ `~/.markus/llm-logs/2026-09-16.jsonl` (66-call session; 377 tails) plus a
916
+ read-only audit of `packages/core/src`. The 322 tails taken *before* the gating
917
+ commit are a historical snapshot used to size the problem, **not** a description
918
+ of current `HEAD`.
919
+
920
+ ## 4. Tool Loop Harness
921
+
922
+ The "harness" is the while-loop that drives agentic tool use: LLM → tool calls → results → LLM → ... until the model stops calling tools.
923
+
924
+ ### 4.1 Harness Variants
925
+
926
+ | Harness | Location | Loop Condition | max_tokens Handling | Loop Detection | Network Retry | Iteration Limit |
927
+ |---------|----------|----------------|--------------------|--------------------|---------------|-----------------|
928
+ | `handleMessage` | Chat (non-stream) | `tool_use \|\| max_tokens` | ✅ Continuation prompt | ✅ `ToolLoopDetector` | ✅ `withNetworkRetry` | configurable (default 200) |
929
+ | `handleMessageStream` | Chat (stream) | `tool_use \|\| max_tokens` | ✅ Continuation prompt | ✅ `ToolLoopDetector` | ✅ `withNetworkRetry` | configurable (default 200) |
930
+ | `_executeTaskInternal` | Task execution | `tool_use \|\| max_tokens` | ✅ Continuation prompt | — (uses reminder instead) | ✅ `withNetworkRetry` | None |
931
+ | `respondInSession` | Session reply | `tool_use \|\| max_tokens` | ✅ Continuation prompt | — | ✅ `withNetworkRetry` | 200 |
932
+
933
+ **Design rationale for iteration limits**: Task execution has **no hard iteration limit**. Complex tasks (writing code, running tests, debugging) legitimately require 100+ tool calls. Natural limiters are sufficient: the context window triggers compression, cancel tokens allow external stop, and the model naturally finishes by calling `task_submit_review`. Chat and similar paths use a **configurable** safety cap via `AgentOptions.maxToolIterations` and the system settings API (range 1–10000, default 200) — not a hardcoded 200. Real loop protection still comes primarily from `ToolLoopDetector`, not from this cap.
934
+
935
+ ### 4.2 Common Harness Flow
936
+
937
+ ```
938
+ 0. Deterministic context assembly (no LLM): read recent activity + working-memory
939
+ keys; ContextEngine retrieves relevance-matched memories (bounded).
940
+ 1. Build system prompt (contextEngine.buildSystemPrompt)
941
+ → injects ## Relevant Memories (this turn only) + a deterministic ## Cognitive Context
942
+ 2. Build tool definitions (toolSelector.selectTools)
943
+ 3. Prepare messages (contextEngine.prepareMessages — compress to fit budget)
944
+ 4. LLM call (llmRouter.chat / chatStream, wrapped in withNetworkRetry)
945
+ 5. WHILE response requires continuation:
946
+ a. If tool_use: execute tools → append results → re-prepare messages → LLM call
947
+ b. If max_tokens: append continuation prompt → re-prepare messages → LLM call
948
+ 6. Output guardrail check
949
+ 7. Persist final reply to session
950
+ ```
951
+
952
+ Step 0 is **deterministic** — there is no Cognitive Preparation Pipeline and no pre-call LLM. The ContextEngine assembles a small, bounded situational block from recent activity and working-memory keys, and performs its own bounded relevant-memory retrieval. Deeper cross-domain recall is agent-driven via `memory_search` / `kb_search`.
953
+
954
+ ### 4.3 Tool Execution
955
+
956
+ All tool calls within a single LLM response are executed **in parallel** (`Promise.all`) in `handleMessage` and `handleMessageStream`. In `_executeTaskInternal` and `respondInSession`, they are executed **sequentially** (for-of loop) with per-tool status events.
957
+
958
+ **Write serialisation under concurrency.** When the agent runs a concurrent worker pool,
959
+ state-mutating tool calls are routed through an agent-level FIFO **write lock**
960
+ (`Agent.withToolWriteLock`, see [concurrent-processing.md](./concurrent-processing.md)) so
961
+ two workers cannot mutate shared state at the same instant. Read-only tools are not
962
+ blocked; the lock is released even when the wrapped call throws. Note this serialises a
963
+ *single tool call*, not an entire multi-step flow — see the known-limitations section of
964
+ that doc.
965
+
966
+ `spawn_subagent` and `spawn_subagents` let the model delegate focused subtasks to lightweight LLM subagents; `spawn_subagents` runs several in parallel. They are registered on the Agent like other built-in tools. All subagent limits (max parallel count, LLM retry policy, preview truncation lengths) are centralized in `packages/shared/src/limits.ts` — not hardcoded in the subagent module.
967
+
968
+ Large tool results (>50K chars) are offloaded to `{agentDataDir}/tool-outputs/` with a preview in context (Manus-inspired "restorable compression").
969
+
970
+ ### 4.4 Loop Detection
971
+
972
+ `ToolLoopDetector` is active in both `handleMessage` and `handleMessageStream`. It tracks recent tool calls and detects repetitive patterns. When a critical loop is detected, a `[SYSTEM]` warning is injected into the conversation to nudge the model toward a different approach.
973
+
974
+ ### 4.5 Task Completion Reminder
975
+
976
+ In `_executeTaskInternal`, every 10 tool iterations, a `[SYSTEM REMINDER]` message is injected reminding the agent to call `task_submit_review`. This combats the "lost in the middle" effect where long tool-use sequences push the original instructions out of the model's attention.
977
+
978
+ ### 4.6 Mid-Execution Reflection Nudge
979
+
980
+ Every 30 tool iterations during task execution, a `[REFLECTION CHECKPOINT]` message is injected prompting the agent to capture any insights discovered during the current task. This ensures lessons are saved while context is fresh, rather than relying solely on post-task reflection.
981
+
982
+ ### 4.7 Post-Task Reflection
983
+
984
+ When a task is accepted (`triggerPostTaskReflection` in `task-service.ts`), the system sends a reflection prompt to the assigned agent. The prompt includes:
985
+ - An **execution trace summary** (execution rounds, duration, result summary, recent notes)
986
+ - Differentiated guidance for **revision** cases (focus on what went wrong) vs **success** cases (focus on what worked)
987
+ - Guidance to create **skill packages** via skill-building for complex procedures (5+ steps)
988
+
989
+ ---
990
+
991
+ ## 5. Scenario-Specific Prompt Assembly
992
+
993
+ ### 5.1 Human Chat (`handleMessage` / `handleMessageStream`)
994
+
995
+ ```
996
+ ┌─ System Prompt (full: identity + memory + tasks + scenario=chat)
997
+ ├─ Session Messages (from memory store, compressed by prepareMessages)
998
+ └─ User Message (latest)
999
+ ```
1000
+
1001
+ Session management:
1002
+ - Uses `currentSessionId`. Creates session if none exists.
1003
+ - Messages persisted to session JSON files and replayed on next call.
1004
+ - Input/output guardrails applied.
1005
+
1006
+ ### 5.2 Task Execution (`_executeTaskInternal`)
1007
+
1008
+ ```
1009
+ ┌─ System Prompt (full: identity + memory + tasks + scenario=task_execution)
1010
+ │ + projectContext (project info, repositories, governance rules)
1011
+ ├─ Task Prompt (injected as first user message):
1012
+ │ [TASK EXECUTION — Task ID: xxx]
1013
+ │ {description}
1014
+ │ {resume/retry instructions if applicable}
1015
+ │ ## Completion Requirements — MANDATORY
1016
+ │ You MUST call task_submit_review ...
1017
+ └─ Session Messages (task session: task_{id}_r{round})
1018
+ ```
1019
+
1020
+ Key differences from chat:
1021
+ - **Deterministic session ID**: `task_{taskId}_r{round}`. Retries within the same round reuse session history (preserving tool call results). New rounds get fresh sessions.
1022
+ - **Project repo access**: Agents can read and write files freely; the only hard restriction is that writes to other agents' directories are blocked. The agent manages its own workspace setup (worktrees, branching) via `shell_execute`.
1023
+ - **Git command governance**: The shell tool enforces a three-tier model (Allow / Approval / Deny). Safe operations execute immediately, risky ones (checkout existing branch, merge, rebase, push to protected branches) pause for human approval via `HITLService.requestApprovalAndWait()`, and destructive operations (force push) are always denied. Approval responses include optional comments/reasons, which are returned to the agent as actionable feedback.
1024
+ - **Retry with history**: If the session has prior assistant work (from interrupted attempts), a `[SYSTEM: Your previous execution attempt was interrupted...]` message is appended instead of the full task prompt.
1025
+ - **AbortController**: Linked to `cancelToken` for external cancellation.
1026
+
1027
+ ### 5.3 Heartbeat (`handleHeartbeat`)
1028
+
1029
+ Heartbeat uses `handleMessage(prompt, undefined, undefined, { sessionId: 'hb_<agentId>_<ts>', allowedTools, scenario: 'heartbeat' })`.
1030
+
1031
+ The heartbeat user prompt is assembled inline; the system prompt still comes from `buildSystemPrompt(scenario:'heartbeat')` (identity, `## Your Knowledge`, and the cached `heartbeat` scenario section); mailbox context and `## Notebook` ride the volatile `[Live context]` tail rather than the system prefix. The inline prompt is deliberately **slim** — it carries only per-call dynamic content and defers durable rules to the cached system prompt. It includes:
1032
+ 1. `[HEARTBEAT CHECK-IN]` header + agent's custom checklist (from `role.heartbeatChecklist`)
1033
+ 2. Last heartbeat summary (from memory search)
1034
+ 3. Conditional dynamic sections, only when present: `## Background Processes Completed` (finished `background_exec` sessions), `## Timed-Out Async Operations`, **`## Active Goals`** (when `goalFetcher` is wired — each standing goal's title, status, `currentIteration`/`maxIterations`, and completion criteria), and the manager `## Daily Report Required` section (after 20:00)
1035
+ 4. Slim `## Failed Task Recovery` and `## Requirement Monitoring` (2-3 lines each)
1036
+ 5. `## Self-Evolution` — a compact Knowledge Lifecycle **decision matrix** that routes each learning to the right home (`memory_save` / `memory_update_longterm` / skill / ROLE.md / HEARTBEAT.md), with the revision-rate quality signal folded into a single line
1037
+ 6. `## Patrol Reminder` — lightweight-patrol do/don't rules; points to `schedule_wakeup` for precise follow-ups and `set_heartbeat_interval` to adjust cadence. It explicitly **defers** communication-channel and async-timing details to the cached scenario/Tier-1 sections rather than restating them
1038
+ 7. `## Finishing Up` — `memory_save` a `heartbeat:summary`, produce the daily report if required, else respond `HEARTBEAT_OK`
1039
+
1040
+ **Deduplication note**: earlier versions of the inline prompt restated `## Communication Channels`, `## Core Principle: Patrol, Don't Build`, `## Prefer Scheduled Wakeups`, `## What You CAN/MUST NOT Do`, and `## Conditional Actions`. These duplicated the cached `heartbeat` scenario section (§5.3 / `buildScenarioSection`) and Tier-1 rules, so they were removed from the (uncached) inline user prompt to cut per-heartbeat token cost. The `heartbeat` scenario section is now the single source of truth for comms/priorities.
1041
+
1042
+ **Notebook Guidelines** (in mailbox checklists / system prompt when queue context is present): use `notebook_upsert` to save priorities, context, decisions, and blockers; `notebook_clear` when context becomes irrelevant. Do not store raw message content — use `memory_save` for durable observations.
1043
+
1044
+ Tool whitelist = **reflex allowlist** (`REFLEX_CORE_TOOLS` + manager `team_status`):
1045
+ `task_list`, `task_get`, `memory_save`, `memory_search`, `notify_user`, `request_user_input`,
1046
+ `schedule_wakeup`, `cancel_wakeup`, `set_heartbeat_interval`, `discover_tools`, `check_mailbox`,
1047
+ `file_read`, `agent_send_message`, `notebook_upsert`. MUST NOT imply `task_create` /
1048
+ `requirement_propose` / `package_install` / `goal_*` in heartbeat (see Interaction Mode).
1049
+
1050
+ **Heartbeat cadence & configurability**: the periodic heartbeat is a coarse safety-net (`DEFAULT_HEARTBEAT_INTERVAL_MS`, 6h) behind the event-driven `schedule_wakeup` mechanism — it is NOT the primary timing mechanism. The interval is configurable at three levels: (a) the user via `PATCH /api/agents/:id/config` (`heartbeatIntervalMs`) or the Agent Profile → Heartbeat tab; (b) the agent itself via the `set_heartbeat_interval` tool (clamped to `MIN_HEARTBEAT_INTERVAL_MS`–`MAX_HEARTBEAT_INTERVAL_MS`, i.e. 5min–24h). Both apply **live** via `Agent.setHeartbeatInterval()` (restarts the scheduler) and persist (agent-driven changes flow through the `agent:heartbeat-interval-changed` event → `agentRepo.updateConfig`). A one-time SQLite migration (gated by `PRAGMA user_version`) bumps agents still on the legacy 30-min default to the 6h safety-net without clobbering any interval a user or agent set deliberately.
1051
+
1052
+ Agent communication guidance (heartbeat context):
1053
+
1054
+ **Reaching humans** — raw text output is NOT visible to humans in heartbeat mode:
1055
+ | Situation | Tool | Example |
1056
+ |-----------|------|---------|
1057
+ | Status report, finding, alert | `notify_user` (appears in chat timeline + bell) | "Daily report: completed 3 tasks today" |
1058
+ | Task completed notification | `notify_user` + `related_task_id` | "Task X is ready for review" (clicks to task) |
1059
+ | Need user to approve/reject | `request_user_approval` | "Approve deployment to production?" |
1060
+ | Need user to choose between options | `request_user_approval` with custom `options` | "Should I use approach A or B for the auth refactor?" |
1061
+ | Need user freeform input | `request_user_approval` with `allow_freeform: true` | "What credentials should I use?" |
1062
+ | Want to discuss interactively | Mention user via task/requirement comment | Use `task_comment` or `requirement_comment` |
1063
+ | Need to review past execution details | `recall_activity` | `recall_activity({ task_id: "tsk_abc" })` to find what happened |
1064
+ | Routine heartbeat, nothing notable | Neither | Agent responds with `HEARTBEAT_OK` |
1065
+
1066
+ **Reaching agents** — use `agent_send_message` to send to a peer agent's mailbox.
1067
+
1068
+ Retry: 3 retries with exponential backoff (3s base).
1069
+
1070
+ ### 5.4 A2A Chat
1071
+
1072
+ Uses `handleMessage(message, fromAgentId, senderInfo, { sessionId, scenario: 'a2a' })`.
1073
+
1074
+ **Session ID strategy**: When a `channelKey` is present (group chat context), the session ID is `channel_{channelKey}_{agentId}` — stable across all messages in the same channel. This enables conversation history accumulation and KV-cache reuse. For direct 1:1 A2A messages without a channel, a timestamp-based `a2a_{agentId}_{ts}` session is used (one-off).
1075
+
1076
+ The sender's identity is injected via `senderIdentity` in `buildSystemPrompt`. Channel-based A2A (via group chats) passes `channelContext` — recent channel messages are prepended to the session on the first turn; subsequent turns inject only delta messages (last 5).
1077
+
1078
+ ### 5.4.1 Group Chat
1079
+
1080
+ Group chat messages (to `group:<teamId>` channels) are broadcast to ALL team members simultaneously via `processGroupChatReply()` in `api-server.ts`. Each agent processes the message independently with `scenario: 'group_chat'` (for human messages) or `scenario: 'a2a'` (for agent chain replies).
1081
+
1082
+ **Static rules in system prompt**: The `group_chat` scenario section in `buildScenarioSection()` contains all static group chat rules (silence by default, @mention routing, processing checklist, reply-in-group). This content is part of the Tier 1 stable system prompt and benefits from KV-caching.
1083
+
1084
+ **Per-message prefix**: Only variable, per-message information remains in the user message prefix:
1085
+ - Channel header (team size, agent name, channel key)
1086
+ - Targeting info (who is @mentioned, reply target, whether this agent is the target)
1087
+ - Team member roster (for @mention format reference)
1088
+
1089
+ Empty or `[NO_RESPONSE]` replies are silently discarded (not persisted or broadcast).
1090
+
1091
+ ### 5.5 Respond-in-Session
1092
+
1093
+ `respondInSession()` is used for continuing a specific session (e.g., task execution follow-up messages via the API). It always uses `scenario: 'chat'` and streams output via `onLog` events.
1094
+
1095
+ ### 5.6 Daily Report
1096
+
1097
+ ```
1098
+ [DAILY REPORT REQUEST]
1099
+ Generate a brief daily status report. Include:
1100
+ 1. What you worked on today (if anything)
1101
+ 2. Current status and any blockers
1102
+ 3. What you plan to work on next
1103
+ ...
1104
+ Keep the report concise (3-5 sentences). Do NOT use any tools.
1105
+ ```
1106
+
1107
+ Called via `sendMessage(prompt, undefined, undefined, { sourceType: 'daily_report', sessionId: 'sys_<agentId>_<ts>', scenario: 'heartbeat' })`.
1108
+ Result written to `daily-logs/` via `memory.writeDailyLog()`.
1109
+
1110
+ ### 5.7 Memory Flush
1111
+
1112
+ ```
1113
+ [MEMORY FLUSH — System Request]
1114
+ The conversation context is approaching its limit...
1115
+ Use memory_save to persist:
1116
+ - Key decisions or conclusions reached
1117
+ - Important facts learned...
1118
+ ```
1119
+
1120
+ Called via `handleMessage(prompt, undefined, undefined, { sessionId: 'sys_<agentId>_<ts>', scenario: 'heartbeat' })`.
1121
+
1122
+ **Trigger (spec)**: a **turn-level preflight** — before a turn packs context, if the
1123
+ previous turn's context usage crossed a threshold (~75%) and this session has not flushed
1124
+ yet, run `memoryFlush` once (deduplicated per session; the flush itself uses an independent
1125
+ `sys_` session so it cannot recurse into another flush). See the memory-flush spec in
1126
+ [memory-system.md](./memory-system.md) for the authoritative behavior, invariants, and
1127
+ tests. Status: implemented — `maybeMemoryFlushPreflight()` is wired into the three main turn paths
1128
+ (`handleMessage`, `handleMessageStream`, and task execution in `agent.ts`), deduplicated per session.
1129
+
1130
+ ### 5.8 Dream Consolidation
1131
+
1132
+ Not a `handleMessage` call — uses `llmRouter.chat()` directly with a specialized prompt:
1133
+
1134
+ ```
1135
+ System: You are a memory consolidation assistant...
1136
+ User: ## Memory Entries\n{id|timestamp|type|tags|content for each entry}
1137
+ ## Instructions: Output JSON with remove, merge operations...
1138
+ ```
1139
+
1140
+ Capped at 500 most recent entries (`MAX_ENTRIES_FOR_LLM`). Output is parsed as JSON and applied programmatically (remove entries, merge duplicates). Vector index is synchronized post-consolidation.
1141
+
1142
+ ### 5.9 Scenario × Context Matrix (2026-09-16)
1143
+
1144
+ Every `AgentScenario` must render a `## Current Interaction Mode` block answering three
1145
+ questions the model **cannot infer from history**: (a) *is my text output visible to anyone?*,
1146
+ (b) *which tool actually reaches a human?*, (c) *when must I stay silent?* Losing any of the
1147
+ three is a **completeness** regression, not a token saving — a model that does not know its
1148
+ output is invisible will end the turn with prose and accomplish nothing.
1149
+
1150
+ | Scenario | Output visible? | Reaches a human via | Silence rule | Boundary guard |
1151
+ |---|---|---|---|---|
1152
+ | `chat` | yes (streamed) | direct text | — | stop when done, no check-in questions |
1153
+ | `task_execution` | no (logs only) | `notify_user` / `task_note` | — | `task_submit_review` mandatory |
1154
+ | `heartbeat` | **no** | `notify_user` (only path) | `HEARTBEAT_OK` | reflex pack only |
1155
+ | `a2a` (DM) | auto-sent to peer | — | `[NO_RESPONSE]` on ack/conclusion | DM dedup + loop guard |
1156
+ | `a2a` (group channel) | **normalized → `group_chat`** | — | `[NO_RESPONSE]` | see invariant below |
1157
+ | `group_chat` | auto-sent to channel | `notify_user` (private) | `[NO_RESPONSE]` (default) | @mention routing |
1158
+ | `comment_response` | no | `task_comment` / `requirement_comment` | `[NO_REPLY_NEEDED]` | context-first, no bare ack |
1159
+ | `requirement_action` | no | `requirement_comment` / `notify_user` | — | ≥1 action tool required |
1160
+ | `workflow_action` | no | `notify_user` | — | ≥1 action tool required |
1161
+ | `review` | no | `task_comment` / `notify_user` | — | reviewer ≠ assignee |
1162
+ | `deliberation` | no | `complete_deliberation` | — | strict-state items untouchable |
1163
+ | `distillation` | no | `notify_user` (rare) | stop with no tools if nothing durable | Learning Habits |
1164
+ | `memory_consolidation` | no | — (tools forbidden) | — | JSON-only output |
1165
+
1166
+ **Invariant 13a — a caller-supplied scenario is authoritative.** `agent.ts` used to force
1167
+ `opts.scenario = 'a2a'` for every `sourceType: 'a2a_message'`, clobbering an explicit scenario
1168
+ from the caller. `a2a_message` is a *transport* (it is what a channel message looks like when it
1169
+ comes from an agent rather than a human), not a scenario. The engine now defaults to `'a2a'` only
1170
+ when the caller stayed silent.
1171
+
1172
+ **Invariant 13b — channel-derived normalization.** `a2a` covered two physically different
1173
+ channels. A group-channel item rendered the 1:1 wording — *"Humans do NOT see this conversation …
1174
+ absorb silently"* — which is false in a group chat, where the reply is **auto-broadcast to
1175
+ humans**. `buildSystemPrompt` now normalizes `a2a` + `channelKey.startsWith('group:')` →
1176
+ `group_chat`, and `api-server.ts` stops downgrading a group channel to `'a2a'` for chained
1177
+ (agent-triggered) replies. The A2A-ness of such a message is carried by the caller's injected
1178
+ `[AGENT COLLABORATION]` prefix, not by switching the scenario.
1179
+
1180
+ Guard test: `context-scenario-matrix.test.ts` — asserts all 12 scenarios render a non-trivial
1181
+ block, that each declares visibility/reachability, that `a2a`+group renders the group block and
1182
+ never the DM/"humans do NOT see this" wording, and that `distillation` (which previously said only
1183
+ "free-text is not a chat reply") states visibility explicitly. Run against the old code, the
1184
+ group-channel and distillation cases fail.
1185
+
1186
+ ---
1187
+
1188
+ ### 5.10 Scenario × Tool Face — prompts must not name tools the model doesn't have (2026-09-16)
1189
+
1190
+ The matrix in §5.9 answers *what the model is told*. This section is its dual: *what the model can
1191
+ actually call*. A prompt that mandates a tool absent from the request's `tools` array is worse than
1192
+ a missing instruction — the model burns turns on `discover_tools` (or loops on validation errors)
1193
+ and the scenario silently fails.
1194
+
1195
+ **The selection path.** `ToolSelector.selectTools` builds the schema from
1196
+ `BASE_TOOL_NAMES` ∪ keyword-matched `ToolGroup`s ∪ `recentToolNames` ∪ `discover_tools`
1197
+ activations, with `TOOL_DEF_CORE_KEEP` protected from eviction. A tool name that appears in **no**
1198
+ group and is not in the keep-set can therefore never reach the model by default — even when it is
1199
+ fully registered and the scenario's prompt demands it.
1200
+
1201
+ **The authoritative-allow-list contract.** Scenarios whose prompt issues hard mandates carry an
1202
+ explicit `allowedTools` set. `agent.ts` applies it in two directions: it *filters* the selection
1203
+ **and** *unions in* any allowed tool that keyword selection missed (offering its live
1204
+ description/schema from the registry). The existing sets are
1205
+ `HEARTBEAT_ALLOWED_TOOLS`, `DELIBERATION_ALLOWED_TOOLS`, `DISTILLATION_EXTRA_TOOLS` and — added in
1206
+ this pass — `COMMENT_RESPONSE_ALLOWED_TOOLS`, `REQUIREMENT_ACTION_ALLOWED_TOOLS`,
1207
+ `WORKFLOW_ACTION_ALLOWED_TOOLS` (+ `TASK_EXECUTION_EXTRA_TOOLS` spliced into the `isTaskExecution`
1208
+ branch). `SCENARIO_ALLOWED_TOOLS` exposes the map.
1209
+
1210
+ Why each one is load-bearing:
1211
+
1212
+ | Scenario | Prompt mandate | Why default selection can't surface it |
1213
+ |---|---|---|
1214
+ | `requirement_action` | *"**MANDATORY**: before deciding, call `requirement_get`"*, *"`requirement_update_status`"* | neither is in `TOOL_DEF_CORE_KEEP`/`BASE_TOOL_NAMES`, and there is **no `requirement` or `workflow` tool group** |
1215
+ | `workflow_action` | *"use `workflow_status`"*, *"`workflow_cancel`"* | same — no group can ever select them |
1216
+ | `comment_response` | *"call `task_get`/`requirement_get` first"* | `requirement_get` is discover-only for `converse` |
1217
+ | `task_execution` | *"run builds and tests via `background_exec`"*, *"register key outputs via `deliverable_create`"* | the `shell` group carries only `shell_execute`; `background_exec` is in no group at all |
1218
+
1219
+ **Invariant 14 — prompt-declared tools ⊆ scenario tool face.** Guard test
1220
+ `scenario-tool-face.test.ts` builds each scenario's prompt, asserts the prompt text actually
1221
+ mentions the mandated names, asserts those names are in the scenario's `allowedTools`, and asserts
1222
+ they are genuinely *absent* from the always-on keep-set (proving the allowance is load-bearing
1223
+ rather than redundant). It also asserts the action scenarios do **not** carry `shell_execute`,
1224
+ `apply_patch`, `package_install` or `hub_install`.
1225
+
1226
+ **Invariant 14b — an allow-list may narrow, never widen, the capability boundary.** The union step
1227
+ in `agent.ts` only offers names the scenario's allow-list declares; it is not a bypass of
1228
+ `allowedTools` filtering.
1229
+
1230
+ ---
1231
+
1232
+ ### 5.11 Async callbacks must replay their originating scenario (2026-09-16)
1233
+
1234
+ `background_exec` is documented in the `task_execution` prompt as *"run builds and tests via
1235
+ `background_exec` — continue other subtasks while waiting"*. That contract is only meaningful if
1236
+ the **completion** turn can act. It could not.
1237
+
1238
+ Both callback dispatch branches (`callback_result`, and the callback-typed `system_event` emitted
1239
+ by `deliverCallback`'s mailbox path) hardcoded `scenario: 'heartbeat'`. `heartbeat` maps to the
1240
+ **reflex** pack, and `REFLEX_CORE_TOOLS` contains **no work tools** — no `file_write`,
1241
+ `file_edit`, `shell_execute`, `apply_patch`, `task_note`, `subtask_complete`,
1242
+ `deliverable_create`, `task_submit_review`. The heartbeat prompt additionally says *"your text
1243
+ output is NOT visible … end with `HEARTBEAT_OK`"*. So a build launched from a task session could,
1244
+ on completion, only **notify** — never fix the failure, never record progress, never submit.
1245
+
1246
+ **Mechanism.** The scenario is captured where it is still knowable and replayed where it is needed:
1247
+
1248
+ | Step | Where | What |
1249
+ |---|---|---|
1250
+ | capture | `registerBackgroundSession(...)` / `a2a_reply` / `schedule_wakeup` registration | `this.activeScenario` → `PendingCallback.originScenario` |
1251
+ | carry | `deliverCallback` | writes it into the mailbox item's `payload.extra.scenario` (both delivery modes) |
1252
+ | replay | `callback_result` / callback-typed `system_event` dispatch | `asAgentScenario(extra.scenario) ?? 'heartbeat'` |
1253
+
1254
+ Capture must happen at **registration**, not delivery: the completion fires later, outside any
1255
+ turn, when `activeScenario` no longer refers to the launching scenario. Both delivery modes carry
1256
+ it — `mailbox` surfaces a *new* attention cycle, but the work still needs work tools.
1257
+
1258
+ **Invariant 15 — an untrusted scenario string is never cast.** `buildHandleOpts` used to do
1259
+ `opts.scenario = ex.scenario as AgentScenario`. Because that override runs **after** each branch's
1260
+ explicit default, it silently won: any mailbox producer could set an arbitrary scenario, and
1261
+ unknown/legacy values became the turn's scenario. It now goes through `asAgentScenario()` and is
1262
+ ignored when unrecognized, so the branch default (`heartbeat`) survives. `AGENT_SCENARIOS` is the
1263
+ runtime mirror of the `AgentScenario` union and the single validation authority.
1264
+
1265
+ Guard test: `callback-scenario.test.ts` — asserts reflex has no work tools, that
1266
+ `registerBackgroundSession` records the launch scenario, that `deliverCallback` propagates it in
1267
+ both modes, that dispatch replays it, that a missing scenario falls back to `heartbeat`, and that
1268
+ invalid values (`'bogus-scenario'`) are rejected rather than passed through.
1269
+
1270
+
1271
+
1272
+ ## 6. Output Token Resolution
1273
+
1274
+ The `LLMRouter` resolves `maxTokens` (output token limit) for every LLM call:
1275
+
1276
+ 1. If the caller explicitly sets `request.maxTokens`, that value is used.
1277
+ 2. Otherwise, the router looks up the model in `BUILTIN_MODEL_CATALOG` and uses the model's `maxOutputTokens` (e.g. 64K for Claude Sonnet 4, 128K for Claude Opus 4.6).
1278
+ 3. As a final fallback (unknown models), the provider's configured default applies (typically 4096).
1279
+
1280
+ This ensures that modern models with large output windows are not artificially constrained, allowing full-length code generation, detailed analyses, and long-form writing without premature `max_tokens` truncation.
1281
+
1282
+ ---
1283
+
1284
+ ## 7. Tool Selection
1285
+
1286
+ ### 7.0 Memory & Notebook Tools
1287
+
1288
+ Five primary memory tools (down from seven); legacy aliases preserved:
1289
+
1290
+ | Tool | Purpose |
1291
+ |------|---------|
1292
+ | `notebook_upsert` | Upsert a keyed entry in `NOTEBOOK.md` (situational workspace) |
1293
+ | `notebook_clear` | Remove one entry or all agent-managed entries |
1294
+ | `memory_save` | Append one observation to `## _observations` in `knowledge.md` |
1295
+ | `memory_update` | Edit curated `knowledge.md` sections (always in `## Your Knowledge`) |
1296
+ | `memory_search` | Search observations and curated knowledge |
1297
+
1298
+ **Legacy memory aliases** (same handlers): `memory_list`, `memory_delete`, `memory_update_longterm`. (The notebook aliases `update_working_memory` / `clear_working_memory` were removed — use `notebook_upsert` / `notebook_clear`.)
1299
+
1300
+ Goal tools (`goal_create`, `goal_update`, `goal_status`) are available during **heartbeat** and **deliberation** for standing-goal management.
1301
+
1302
+ `ToolSelector.selectTools()` determines which tools appear in each LLM call:
1303
+
1304
+ 1. **Always-on tools**: Core set always included (e.g., `memory_save`, `memory_search`, `memory_update`, `notebook_upsert`, `notebook_clear`, `file_read`, `file_write`, `task_create`, `task_list`, `spawn_subagent`, `spawn_subagents`, `check_mailbox`, etc.)
1305
+ 2. **Manager-only tools**: Added when `isManager=true` (e.g., `task_assign`, `team_status`, `delegate_message`)
1306
+ 3. **Package tools**: Available to all agents, activated by keyword (e.g., `package_list`, `package_install`, `hub_search`, `hub_install`)
1307
+ 4. **Task-execution tools**: Added when `isTaskExecution=true` (e.g., `task_submit_review`, `subtask_create`)
1308
+ 5. **Recently used tools**: Tools used in recent calls are re-included to maintain continuity
1309
+ 6. **Mailbox management tools**: `defer_mailbox_item`, `drop_mailbox_item`,
1310
+ `prioritize_mailbox_item` — registered for all agents, available during
1311
+ deliberation and focused processing.
1312
+ 7. **Activated tools**: Tools the agent explicitly activated via `discover_tools`
1313
+ 8. **Skill-provided tools**: MCP tools from activated skills
1314
+ 9. **`discover_tools` meta-tool**: Always present, enabling agents to list/activate/install skills at runtime
1315
+
1316
+ ### 7.2 Agent/Team Creation & Deployment
1317
+
1318
+ Creation and deployment are **two separate phases** with an explicit user gate between them.
1319
+
1320
+ **Simple hire (no artifact design):** `package_install(type:"agent", name, agent_name, team_name?)` — optional `team_name` find-or-creates a team; or `team_id` from `list_teams`. There is **no** `team_create` tool.
1321
+
1322
+ **Custom package flow:**
1323
+ **Phase 1 — Create (design the artifact):**
1324
+ - Activate `agent-building`, `team-building`, or `skill-building` skill via `discover_tools`
1325
+ - Write manifest + content files with `file_write` to `~/.markus/builder-artifacts/{agents|teams|skills}/{name}/` (dirs are ensured at startup; chat JSON is **not** auto-saved)
1326
+ - This produces a package on disk. No live resources are created.
1327
+
1328
+ **Phase 2 — Deploy (ONLY on explicit user request):**
1329
+ | Method | When to use | Tools |
1330
+ |--------|-------------|-------|
1331
+ | Local / builtin package | Agents, teams, skills from package_list | `package_list` → `package_install` (`type:"team"` creates team+members together) |
1332
+ | Hub one-step | Community packages from Markus Hub | `hub_search` → `hub_install` |
1333
+
1334
+ **Post-deploy:** Onboard new agents via `agent_send_message` (project context) → `task_create` (initial work).
1335
+
1336
+ **Critical rules:**
1337
+ - Agents must NEVER auto-deploy. `package_install` and `hub_install` create live agents that consume LLM tokens and join the organization. Only execute when the user explicitly says "install", "deploy", "hire", or "start".
1338
+ - Never create org teams/agents via `shell_execute`, direct DB edits, or paths outside `builder-artifacts`.
1339
+
1340
+ ---
1341
+
1342
+ ## 8. Provider Routing & Resilience
1343
+
1344
+ ### 8.1 LLM Router
1345
+
1346
+ `LLMRouter` manages multiple provider instances (Anthropic, OpenAI, Google, Ollama) with:
1347
+ - **Complexity-based tiers**: Default provider covers all complexity levels; secondary providers handle specific tiers (e.g., Anthropic for complex, OpenAI-compatible for simple/moderate).
1348
+ - **Circuit breaker**: After 2 consecutive failures, a provider is marked degraded for 5 minutes (30 minutes for auth/billing errors).
1349
+ - **Fallback chain**: If the primary provider fails, the router tries the next provider in the tier list.
1350
+
1351
+ ### 8.2 Network Retry
1352
+
1353
+ `withNetworkRetry()` wraps **all** LLM calls (chat, stream, task execution, respond-in-session) with exponential backoff:
1354
+ - Max retries: configurable via `Agent.NETWORK_RETRY_MAX`
1355
+ - Only retries on network errors (connection refused, timeout, DNS failure).
1356
+ - Non-network errors (400, 401, 403) are thrown immediately.
1357
+
1358
+ ### 8.3 Compaction (Anthropic)
1359
+
1360
+ For Claude Opus 4.x and Sonnet 4.x models, Anthropic's server-side `compact_20260112` beta is enabled. This provides transparent context compression at the API level, complementing Markus's own context management.
1361
+
1362
+ ---
1363
+
1364
+ ## 9. Cross-Reference
1365
+
1366
+ | Document | Relationship |
1367
+ |----------|-------------|
1368
+ | [state-machines.md](./state-machines.md) | Task state transitions trigger different LLM call paths (§5.2 task execution, §5.3 heartbeat review) |
1369
+ | [memory-system.md](./memory-system.md) | Notebook + `knowledge.md` layers (`state.md` retired 2026-09-16); `## Your Knowledge` and `## Notebook` in prompts; consolidation (§5.6-5.8) |
1370
+ | [cognitive-architecture.md](./cognitive-architecture.md) | Deterministic context assembly (§3); CPP and its depth levels removed |
1371
+ | `packages/core/src/agent.ts` | Implementation of all 8 LLM call scenarios and 4 harness variants |
1372
+ | `packages/core/src/context-engine.ts` | `buildSystemPrompt()` and `prepareMessages()` implementation; SLOT fixed segment, volatile tail, watermark |
1373
+ | `packages/core/src/context-slot.ts` | SLOT segment model: `SlotEntry` / `SlotsStore` / `buildSlotSegment()` — the never-compacted anchors (§3.7) |
1374
+ | `packages/core/src/tools/session.ts` | Session 10-op tool family (compact/pin/include/retrieve…) + `checkOwnership` (§3.7) |
1375
+ | `packages/core/src/llm/router.ts` | Provider routing, circuit breaker, model catalog, output token resolution |
1376
+ | `packages/core/src/tool-selector.ts` | Tool selection logic |
1377
+ | ~~`context-os.md`~~ | **Merged into this document §3.7** (Fixed/Variable split, SLOT anchors, session tools, watermark). "ContextOS" is the name of that mechanism; deliverable notes (8/20 repro, regression ledger) are archived in git history. |