@markus-global/cli 0.12.3 → 0.12.5-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/dist/background-maintenance.d.ts +25 -0
  2. package/dist/background-maintenance.d.ts.map +1 -1
  3. package/dist/background-maintenance.js +61 -0
  4. package/dist/background-maintenance.js.map +1 -1
  5. package/dist/commands/im-inbound-origin.d.ts +38 -0
  6. package/dist/commands/im-inbound-origin.d.ts.map +1 -0
  7. package/dist/commands/im-inbound-origin.js +48 -0
  8. package/dist/commands/im-inbound-origin.js.map +1 -0
  9. package/dist/commands/start.d.ts.map +1 -1
  10. package/dist/commands/start.js +211 -46
  11. package/dist/commands/start.js.map +1 -1
  12. package/dist/markus.mjs +18523 -9866
  13. package/dist/web-ui/assets/{AsyncState-_UC7xcxJ.js → AsyncState-ByYn1wrM.js} +1 -1
  14. package/dist/web-ui/assets/ChatComponents-Bwh8SlUV.js +14 -0
  15. package/dist/web-ui/assets/{ContentRenderer-C-V5k_3K.js → ContentRenderer-GLgoGp2a.js} +6 -6
  16. package/dist/web-ui/assets/DeliverableShareModal-CRfnRuR3.js +1 -0
  17. package/dist/web-ui/assets/{Deliverables-CQnWqbTb.js → Deliverables-EFsnf6kU.js} +2 -2
  18. package/dist/web-ui/assets/MarkdownMessage-CaLBeMto.js +4 -0
  19. package/dist/web-ui/assets/{Search-CVYQIy_D.js → Search-COiaXUNr.js} +1 -1
  20. package/dist/web-ui/assets/{SendToChat-IOAvuta-.js → SendToChat-DleryIlc.js} +1 -1
  21. package/dist/web-ui/assets/Settings-CzY8z2Yh.js +8 -0
  22. package/dist/web-ui/assets/{Store-BEsLd_RN.js → Store-C4VpQCM_.js} +1 -1
  23. package/dist/web-ui/assets/Switch-ByogYoGH.js +1 -0
  24. package/dist/web-ui/assets/Team-Cutq2J24.js +93 -0
  25. package/dist/web-ui/assets/Work-BO-mz-na.js +142 -0
  26. package/dist/web-ui/assets/{arc-DP1Vf7Sx.js → arc-mYv67jdD.js} +1 -1
  27. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-Buq8JYN8.js → architectureDiagram-3BPJPVTR-Bzpz_1r6.js} +1 -1
  28. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-BCa2p2_X.js → blockDiagram-GPEHLZMM-BBrLiivl.js} +1 -1
  29. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BxsgggQY.js → c4Diagram-AAUBKEIU-BwDUoXA_.js} +1 -1
  30. package/dist/web-ui/assets/channel-Bx09lbhA.js +1 -0
  31. package/dist/web-ui/assets/{chunk-2J33WTMH-BJZZ60c9.js → chunk-2J33WTMH-DCSfJ-S9.js} +1 -1
  32. package/dist/web-ui/assets/{chunk-4BX2VUAB-C5hc4E6J.js → chunk-4BX2VUAB-CI0n1b2H.js} +1 -1
  33. package/dist/web-ui/assets/{chunk-55IACEB6-CbyvZ6Mk.js → chunk-55IACEB6-DqlSWLrm.js} +1 -1
  34. package/dist/web-ui/assets/{chunk-727SXJPM-JmNt9TVA.js → chunk-727SXJPM-BtmAfGYV.js} +1 -1
  35. package/dist/web-ui/assets/{chunk-AQP2D5EJ-BTk0v5ba.js → chunk-AQP2D5EJ-BgkA4lpQ.js} +1 -1
  36. package/dist/web-ui/assets/{chunk-FMBD7UC4-BO-dhB1U.js → chunk-FMBD7UC4-DCSr1JH4.js} +1 -1
  37. package/dist/web-ui/assets/{chunk-ND2GUHAM-BdjCcLdb.js → chunk-ND2GUHAM-CETYBRRm.js} +1 -1
  38. package/dist/web-ui/assets/{chunk-QZHKN3VN-BAzRC82n.js → chunk-QZHKN3VN-C58yD7lH.js} +1 -1
  39. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-DGZqU3iA.js +1 -0
  40. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-DGZqU3iA.js +1 -0
  41. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-CVffmErT.js → cose-bilkent-S5V4N54A-BpvdK03m.js} +1 -1
  42. package/dist/web-ui/assets/{dagre-BM42HDAG-Dd9pB2fX.js → dagre-BM42HDAG-CZ1K-KD5.js} +1 -1
  43. package/dist/web-ui/assets/{diagram-2AECGRRQ-BG_AUqzM.js → diagram-2AECGRRQ-D136Ok1V.js} +1 -1
  44. package/dist/web-ui/assets/{diagram-5GNKFQAL-D5qFMRFf.js → diagram-5GNKFQAL-Ji6qPYYV.js} +1 -1
  45. package/dist/web-ui/assets/{diagram-KO2AKTUF-B3qTxSWl.js → diagram-KO2AKTUF-B-s2RC-f.js} +1 -1
  46. package/dist/web-ui/assets/{diagram-LMA3HP47-BrxC1636.js → diagram-LMA3HP47-COWaps70.js} +1 -1
  47. package/dist/web-ui/assets/{diagram-OG6HWLK6-BvXyEQ9-.js → diagram-OG6HWLK6-bh6MvwWn.js} +1 -1
  48. package/dist/web-ui/assets/{docx-preview-DBAZFeEb.js → docx-preview-BRynUqJd.js} +1 -1
  49. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-CMap9oy_.js → erDiagram-TEJ5UH35-DOPh2LlL.js} +1 -1
  50. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-BZerJtvk.js → flowDiagram-I6XJVG4X-B_kxDHIp.js} +1 -1
  51. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-CagPMHMO.js → ganttDiagram-6RSMTGT7-DYBKHOkK.js} +1 -1
  52. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-DZ5dDKRu.js → gitGraphDiagram-PVQCEYII-D8_0BxLC.js} +1 -1
  53. package/dist/web-ui/assets/index-9SXWNIl0.css +1 -0
  54. package/dist/web-ui/assets/index-TAHyKznL.js +867 -0
  55. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-CHLdsDUZ.js → infoDiagram-5YYISTIA-DayJP7Ws.js} +1 -1
  56. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-SdeinQaS.js → ishikawaDiagram-YF4QCWOH-vzxCYVSq.js} +1 -1
  57. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-BtlL2fi0.js → journeyDiagram-JHISSGLW-B-Fud82o.js} +1 -1
  58. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-BKPQYXkB.js → kanban-definition-UN3LZRKU-DzuKdB65.js} +1 -1
  59. package/dist/web-ui/assets/{mermaid.core-MkJR6w4B.js → mermaid.core-D4ql87kI.js} +5 -5
  60. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-CbOmHX_u.js → mindmap-definition-RKZ34NQL-DosvXt2g.js} +1 -1
  61. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-CypGjJP1.js → pieDiagram-4H26LBE5-DhXtMWhr.js} +1 -1
  62. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CGtemfUz.js → quadrantDiagram-W4KKPZXB-D33pLLOq.js} +1 -1
  63. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-N7YfpCvE.js → requirementDiagram-4Y6WPE33-B-iIz-XM.js} +1 -1
  64. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-CYnSrei-.js → sankeyDiagram-5OEKKPKP-BMd9AFEW.js} +1 -1
  65. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-CsB7dCPF.js → sequenceDiagram-3UESZ5HK-CI1MIdwo.js} +1 -1
  66. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DTDFUXFP.js → stateDiagram-AJRCARHV-Bq6FKPW2.js} +1 -1
  67. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-8nMhmWY5.js +1 -0
  68. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-C_bWAN9B.js → timeline-definition-PNZ67QCA-BDdmmSRo.js} +1 -1
  69. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-CX_qAuUT.js → vennDiagram-CIIHVFJN-DP2q5vY2.js} +1 -1
  70. package/dist/web-ui/assets/{wardley-L42UT6IY-q53jQ293.js → wardley-L42UT6IY-Bw3fjszD.js} +1 -1
  71. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-D34dKCJU.js → wardleyDiagram-YWT4CUSO-37bQUocJ.js} +1 -1
  72. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-BFAngp66.js → xychartDiagram-2RQKCTM6-DnLDZyNC.js} +1 -1
  73. package/dist/web-ui/index.html +2 -2
  74. package/docs/README.md +50 -16
  75. package/docs/api/guides/websocket.md +43 -0
  76. package/docs/api/reference.md +657 -0
  77. package/docs/architecture/a2a-communication.md +303 -0
  78. package/docs/architecture/agent-runtime.md +145 -28
  79. package/docs/architecture/architecture.md +30 -11
  80. package/docs/architecture/cognitive-architecture.md +189 -15
  81. package/docs/architecture/concurrent-processing.md +190 -31
  82. package/docs/architecture/context-assembly.md +264 -0
  83. package/docs/architecture/derived-views.md +463 -0
  84. package/docs/architecture/desktop-auto-update.md +185 -0
  85. package/docs/architecture/facts.md +406 -0
  86. package/docs/architecture/learning-loop.md +11 -0
  87. package/docs/architecture/limits.md +79 -0
  88. package/docs/architecture/mailbox-system.md +786 -668
  89. package/docs/architecture/memory-system.md +1 -1
  90. package/docs/architecture/messaging-gateway.md +7 -0
  91. package/docs/architecture/notification-delivery.md +221 -0
  92. package/docs/architecture/notification-sounds.md +177 -0
  93. package/docs/architecture/prompt-engineering.md +171 -700
  94. package/docs/{design/remote-access-contract.md → architecture/remote-access.md} +4 -0
  95. package/docs/architecture/state-machines.md +288 -5
  96. package/docs/architecture/tool-loop-harness.md +362 -0
  97. package/docs/architecture/tool-system.md +40 -16
  98. package/docs/design/background-callback-in-turn-delivery-2026-11-22.md +95 -0
  99. package/docs/design/c10-0b-pick-identity-leak-2026-11-22.md +233 -0
  100. package/docs/design/c10-a-identity-columns-2026-11-22.md +182 -0
  101. package/docs/design/c10-c-trust-boundary-2026-11-23.md +222 -0
  102. package/docs/design/c10-external-adapters-plan-2026-11-19.md +448 -0
  103. package/docs/design/c8-residual-mechanisms-2026-11-15.md +984 -0
  104. package/docs/design/external-signal-decision-loop-2026-11-25.md +579 -0
  105. package/docs/guides/development.md +1 -1
  106. package/docs/{architecture → guides}/mailbox-audit-checklist.md +7 -0
  107. package/docs/guides/remote-access.md +1 -1
  108. package/docs/{design/agent-stop-intent-audit.md → records/agent-stop-intent-audit-2026-11-08.md} +4 -0
  109. package/docs/records/c10-l5-gate-verification-2026-11-26.md +72 -0
  110. package/docs/records/c10-l5-live-verification-2026-11-25.md +117 -0
  111. package/docs/records/cut6-c4-verification-2026-11-12.md +268 -0
  112. package/docs/records/cut6-mailbox-address-envelope-design-2026-11-12.md +871 -0
  113. package/docs/records/cut7-c7a-red-green-evidence-2026-11-13.md +105 -0
  114. package/docs/records/cut7-c7a-workunit-implementation-2026-11-13.md +116 -0
  115. package/docs/records/cut7-c7b-verification-2026-11-14.md +90 -0
  116. package/docs/records/cut7-live-verification-2026-11-14.md +33 -0
  117. package/docs/records/cut7-wiring-negative-cache-2026-11-14.md +64 -0
  118. package/docs/records/cut7-workunit-execution-plan-2026-11-13.md +206 -0
  119. package/docs/records/cut8-a-entity-keys-design-2026-11-14.md +377 -0
  120. package/docs/records/cut8-b-turn-delta-injection-2026-11-14.md +362 -0
  121. package/docs/records/cut8-c-single-clock-2026-11-14.md +119 -0
  122. package/docs/records/cut8-c-single-clock-design-2026-11-14.md +150 -0
  123. package/docs/records/cut8-d-2026-11-14.md +231 -0
  124. package/docs/records/cut8-live-verification-2026-11-14.md +1018 -0
  125. package/docs/records/cut9-adjacent-identity-paths-2026-11-15.md +200 -0
  126. package/docs/records/cut9-identity-declaration-2026-11-15.md +163 -0
  127. package/docs/records/cut9-inbox-dual-run-diff-2026-11-15.md +117 -0
  128. package/docs/records/cut9-live-verification-2026-11-15.md +222 -0
  129. package/docs/records/cut9-runtime-probe-2026-11-19.md +520 -0
  130. package/docs/{design/deliverable-sharing.md → records/deliverable-sharing-2026-08-12.md} +10 -3
  131. package/docs/records/identity-backlog-disposition-2026-11-22.md +143 -0
  132. package/docs/records/marketplace-orphan-freeze-2026-11-22.md +239 -0
  133. package/docs/{architecture/notify-user-context-truth.md → records/notify-user-context-truth-2026-10-28.md} +6 -0
  134. package/docs/{handoff → records}/remote-access-handoff.md +1 -1
  135. package/package.json +1 -1
  136. package/templates/roles/HANDBOOK.md +1 -1
  137. package/templates/skills/agent-building/SKILL.md +1 -1
  138. package/dist/web-ui/assets/ChatComponents-Ca9tWI9W.js +0 -12
  139. package/dist/web-ui/assets/DeliverableShareModal-BvpyowYJ.js +0 -1
  140. package/dist/web-ui/assets/MarkdownMessage-DedA8Zob.js +0 -4
  141. package/dist/web-ui/assets/Settings-BQDqf4q5.js +0 -8
  142. package/dist/web-ui/assets/Switch-C6InTNUi.js +0 -1
  143. package/dist/web-ui/assets/Team-nfNyWj-s.js +0 -85
  144. package/dist/web-ui/assets/Work-BQvgkynj.js +0 -142
  145. package/dist/web-ui/assets/channel-BTSrOo6c.js +0 -1
  146. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BSYlcnF9.js +0 -1
  147. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BSYlcnF9.js +0 -1
  148. package/dist/web-ui/assets/index-CKPQYzzR.js +0 -867
  149. package/dist/web-ui/assets/index-CzHSs0Vd.css +0 -1
  150. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-AVnDjlzF.js +0 -1
  151. package/docs/api/api.md +0 -353
  152. package/docs/architecture/llm-provider-timeouts.md +0 -60
  153. package/docs/architecture/state-ownership.md +0 -83
  154. /package/docs/architecture/{frontend/team-chat.md → team-chat.md} +0 -0
  155. /package/docs/{analysis → records}/2026-10-29-a2a-cache-hit-rate.md +0 -0
  156. /package/docs/{fixes → records}/2026-11-12-session-expiry-and-mention-thinking.md +0 -0
  157. /package/docs/{handoff → records}/approval-tri-state-handoff.md +0 -0
  158. /package/docs/{design → records}/overview-attention-redesign.md +0 -0
  159. /package/docs/{remote-access/fast-path-plan.md → records/remote-access-fast-path-plan-2026-10-17.md} +0 -0
@@ -0,0 +1,362 @@
1
+ # Tool Loop Harness & Scenario Assembly
2
+
3
+ > **Scope (this file)**: how one LLM call actually *runs* — the tool-loop harness and its variants, tool execution, loop detection, task-completion reminders, reflection nudges — and how each scenario assembles its prompt, tool face, and callback replay (scenario × context matrix, scenario × tool face, async callback scenario replay).
4
+ > **Split out of** [prompt-engineering.md](./prompt-engineering.md) §4 + §5 on **2026-11-15**. Section numbers (§4.x, §5.x) are unchanged, so an existing `prompt-engineering.md §4.x/§5.x` reference resolves to the same number here.
5
+ > **Siblings**: [prompt-engineering.md](./prompt-engineering.md) — call taxonomy, cache-scope layout, system-prompt architecture (§1–§2), output-token resolution (§6); [context-assembly.md](./context-assembly.md) — token budget, compression pipeline, ContextOS anchors (§3).
6
+
7
+ ## 4. Tool Loop Harness
8
+
9
+ The "harness" is the while-loop that drives agentic tool use: LLM → tool calls → results → LLM → ... until the model stops calling tools.
10
+
11
+ ### 4.1 Harness Variants
12
+
13
+ | Harness | Location | Loop Condition | max_tokens Handling | Loop Detection | Network Retry | Iteration Limit |
14
+ |---------|----------|----------------|--------------------|--------------------|---------------|-----------------|
15
+ | `handleMessage` | Chat (non-stream) | `tool_use \|\| max_tokens` | ✅ Continuation prompt | ✅ `ToolLoopDetector` | ✅ `withNetworkRetry` | configurable (default 200) |
16
+ | `handleMessageStream` | Chat (stream) | `tool_use \|\| max_tokens` | ✅ Continuation prompt | ✅ `ToolLoopDetector` | ✅ `withNetworkRetry` | configurable (default 200) |
17
+ | `_executeTaskInternal` | Task execution | `tool_use \|\| max_tokens` | ✅ Continuation prompt | — (uses reminder instead) | ✅ `withNetworkRetry` | None |
18
+ | `respondInSession` | Session reply | `tool_use \|\| max_tokens` | ✅ Continuation prompt | — | ✅ `withNetworkRetry` | 200 |
19
+
20
+ **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.
21
+
22
+ ### 4.2 Common Harness Flow
23
+
24
+ ```
25
+ 0. Deterministic context assembly (no LLM): read recent activity + working-memory
26
+ keys; ContextEngine retrieves relevance-matched memories (bounded).
27
+ 1. Build system prompt (contextEngine.buildSystemPrompt)
28
+ → injects ## Relevant Memories (this turn only) + a deterministic ## Cognitive Context
29
+ 2. Build tool definitions (toolSelector.selectTools)
30
+ 3. Prepare messages (contextEngine.prepareMessages — compress to fit budget)
31
+ 4. LLM call (llmRouter.chat / chatStream, wrapped in withNetworkRetry)
32
+ 5. WHILE response requires continuation:
33
+ a. If tool_use: execute tools → append results → re-prepare messages → LLM call
34
+ b. If max_tokens: append continuation prompt → re-prepare messages → LLM call
35
+ 6. Output guardrail check
36
+ 7. Persist final reply to session
37
+ ```
38
+
39
+ 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`.
40
+
41
+ ### 4.3 Tool Execution
42
+
43
+ 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.
44
+
45
+ **Write serialisation under concurrency.** When the agent runs a concurrent worker pool,
46
+ state-mutating tool calls are routed through an agent-level FIFO **write lock**
47
+ (`Agent.withToolWriteLock`, see [concurrent-processing.md](./concurrent-processing.md)) so
48
+ two workers cannot mutate shared state at the same instant. Read-only tools are not
49
+ blocked; the lock is released even when the wrapped call throws. Note this serialises a
50
+ *single tool call*, not an entire multi-step flow — see the known-limitations section of
51
+ that doc.
52
+
53
+ `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.
54
+
55
+ Large tool results (>50K chars) are offloaded to `{agentDataDir}/tool-outputs/` with a preview in context (Manus-inspired "restorable compression").
56
+
57
+ ### 4.4 Loop Detection
58
+
59
+ `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.
60
+
61
+ ### 4.5 Task Completion Reminder
62
+
63
+ 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.
64
+
65
+ ### 4.6 Mid-Execution Reflection Nudge
66
+
67
+ 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.
68
+
69
+ ### 4.7 Post-Task Reflection
70
+
71
+ When a task is accepted (`triggerPostTaskReflection` in `task-service.ts`), the system sends a reflection prompt to the assigned agent. The prompt includes:
72
+ - An **execution trace summary** (execution rounds, duration, result summary, recent notes)
73
+ - Differentiated guidance for **revision** cases (focus on what went wrong) vs **success** cases (focus on what worked)
74
+ - Guidance to create **skill packages** via skill-building for complex procedures (5+ steps)
75
+
76
+ ---
77
+
78
+ ## 5. Scenario-Specific Prompt Assembly
79
+
80
+ ### 5.1 Human Chat (`handleMessage` / `handleMessageStream`)
81
+
82
+ ```
83
+ ┌─ System Prompt (full: identity + memory + tasks + scenario=chat)
84
+ ├─ Session Messages (from memory store, compressed by prepareMessages)
85
+ └─ User Message (latest)
86
+ ```
87
+
88
+ Session management:
89
+ - Uses `currentSessionId`. Creates session if none exists.
90
+ - Messages persisted to session JSON files and replayed on next call.
91
+ - Input/output guardrails applied.
92
+
93
+ ### 5.2 Task Execution (`_executeTaskInternal`)
94
+
95
+ ```
96
+ ┌─ System Prompt (full: identity + memory + tasks + scenario=task_execution)
97
+ │ + projectContext (project info, repositories, governance rules)
98
+ ├─ Task Prompt (injected as first user message):
99
+ │ [TASK EXECUTION — Task ID: xxx]
100
+ │ {description}
101
+ │ {resume/retry instructions if applicable}
102
+ │ ## Completion Requirements — MANDATORY
103
+ │ You MUST call task_submit_review ...
104
+ └─ Session Messages (task session: task_{id}_r{round})
105
+ ```
106
+
107
+ Key differences from chat:
108
+ - **Deterministic session ID**: `task_{taskId}_r{round}`. Retries within the same round reuse session history (preserving tool call results). New rounds get fresh sessions.
109
+ - **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`.
110
+ - **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.
111
+ - **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.
112
+ - **AbortController**: Linked to `cancelToken` for external cancellation.
113
+
114
+ ### 5.3 Heartbeat (`handleHeartbeat`)
115
+
116
+ Heartbeat uses `handleMessage(prompt, undefined, undefined, { sessionId: 'hb_<agentId>_<ts>', allowedTools, scenario: 'heartbeat' })`.
117
+
118
+ 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:
119
+ 1. `[HEARTBEAT CHECK-IN]` header + agent's custom checklist (from `role.heartbeatChecklist`)
120
+ 2. Last heartbeat summary (from memory search)
121
+ 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)
122
+ 4. Slim `## Failed Task Recovery` and `## Requirement Monitoring` (2-3 lines each)
123
+ 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
124
+ 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
125
+ 7. `## Finishing Up` — `memory_save` a `heartbeat:summary`, produce the daily report if required, else respond `HEARTBEAT_OK`
126
+
127
+ **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.
128
+
129
+ **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.
130
+
131
+ Tool whitelist = **reflex allowlist** (`REFLEX_CORE_TOOLS` + manager `team_status`):
132
+ `task_list`, `task_get`, `memory_save`, `memory_search`, `notify_user`, `request_user_input`,
133
+ `schedule_wakeup`, `cancel_wakeup`, `set_heartbeat_interval`, `discover_tools`, `check_mailbox`,
134
+ `file_read`, `agent_send_message`, `notebook_upsert`. MUST NOT imply `task_create` /
135
+ `requirement_propose` / `package_install` / `goal_*` in heartbeat (see Interaction Mode).
136
+
137
+ **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.
138
+
139
+ Agent communication guidance (heartbeat context):
140
+
141
+ **Reaching humans** — raw text output is NOT visible to humans in heartbeat mode:
142
+ | Situation | Tool | Example |
143
+ |-----------|------|---------|
144
+ | Status report, finding, alert | `notify_user` (appears in chat timeline + bell) | "Daily report: completed 3 tasks today" |
145
+ | Task completed notification | `notify_user` + `related_task_id` | "Task X is ready for review" (clicks to task) |
146
+ | Need user to approve/reject | `request_user_approval` | "Approve deployment to production?" |
147
+ | Need user to choose between options | `request_user_approval` with custom `options` | "Should I use approach A or B for the auth refactor?" |
148
+ | Need user freeform input | `request_user_approval` with `allow_freeform: true` | "What credentials should I use?" |
149
+ | Want to discuss interactively | Mention user via task/requirement comment | Use `task_comment` or `requirement_comment` |
150
+ | Need to review past execution details | `recall_activity` | `recall_activity({ task_id: "tsk_abc" })` to find what happened |
151
+ | Routine heartbeat, nothing notable | Neither | Agent responds with `HEARTBEAT_OK` |
152
+
153
+ **Reaching agents** — use `agent_send_message` to send to a peer agent's mailbox.
154
+
155
+ Retry: 3 retries with exponential backoff (3s base).
156
+
157
+ ### 5.4 A2A Chat
158
+
159
+ Uses `handleMessage(message, fromAgentId, senderInfo, { sessionId, scenario: 'a2a' })`.
160
+
161
+ **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).
162
+
163
+ 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).
164
+
165
+ ### 5.4.1 Group Chat
166
+
167
+ 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).
168
+
169
+ **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.
170
+
171
+ **Per-message prefix**: Only variable, per-message information remains in the user message prefix:
172
+ - Channel header (team size, agent name, channel key)
173
+ - Targeting info (who is @mentioned, reply target, whether this agent is the target)
174
+ - Team member roster (for @mention format reference)
175
+
176
+ Empty or `[NO_RESPONSE]` replies are silently discarded (not persisted or broadcast).
177
+
178
+ ### 5.5 Respond-in-Session
179
+
180
+ `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.
181
+
182
+ ### 5.6 Daily Report
183
+
184
+ ```
185
+ [DAILY REPORT REQUEST]
186
+ Generate a brief daily status report. Include:
187
+ 1. What you worked on today (if anything)
188
+ 2. Current status and any blockers
189
+ 3. What you plan to work on next
190
+ ...
191
+ Keep the report concise (3-5 sentences). Do NOT use any tools.
192
+ ```
193
+
194
+ Called via `sendMessage(prompt, undefined, undefined, { sourceType: 'daily_report', sessionId: 'sys_<agentId>_<ts>', scenario: 'heartbeat' })`.
195
+ Result written to `daily-logs/` via `memory.writeDailyLog()`.
196
+
197
+ ### 5.7 Memory Flush
198
+
199
+ ```
200
+ [MEMORY FLUSH — System Request]
201
+ The conversation context is approaching its limit...
202
+ Use memory_save to persist:
203
+ - Key decisions or conclusions reached
204
+ - Important facts learned...
205
+ ```
206
+
207
+ Called via `handleMessage(prompt, undefined, undefined, { sessionId: 'sys_<agentId>_<ts>', scenario: 'heartbeat' })`.
208
+
209
+ **Trigger (spec)**: a **turn-level preflight** — before a turn packs context, if the
210
+ previous turn's context usage crossed a threshold (~75%) and this session has not flushed
211
+ yet, run `memoryFlush` once (deduplicated per session; the flush itself uses an independent
212
+ `sys_` session so it cannot recurse into another flush). See the memory-flush spec in
213
+ [memory-system.md](./memory-system.md) for the authoritative behavior, invariants, and
214
+ tests. Status: implemented — `maybeMemoryFlushPreflight()` is wired into the three main turn paths
215
+ (`handleMessage`, `handleMessageStream`, and task execution in `agent.ts`), deduplicated per session.
216
+
217
+ ### 5.8 Dream Consolidation
218
+
219
+ Not a `handleMessage` call — uses `llmRouter.chat()` directly with a specialized prompt:
220
+
221
+ ```
222
+ System: You are a memory consolidation assistant...
223
+ User: ## Memory Entries\n{id|timestamp|type|tags|content for each entry}
224
+ ## Instructions: Output JSON with remove, merge operations...
225
+ ```
226
+
227
+ 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.
228
+
229
+ ### 5.9 Scenario × Context Matrix (2026-09-16)
230
+
231
+ Every `AgentScenario` must render a `## Current Interaction Mode` block answering three
232
+ questions the model **cannot infer from history**: (a) *is my text output visible to anyone?*,
233
+ (b) *which tool actually reaches a human?*, (c) *when must I stay silent?* Losing any of the
234
+ three is a **completeness** regression, not a token saving — a model that does not know its
235
+ output is invisible will end the turn with prose and accomplish nothing.
236
+
237
+ | Scenario | Output visible? | Reaches a human via | Silence rule | Boundary guard |
238
+ |---|---|---|---|---|
239
+ | `chat` | yes (streamed) | direct text | — | stop when done, no check-in questions |
240
+ | `task_execution` | no (logs only) | `notify_user` / `task_note` | — | `task_submit_review` mandatory |
241
+ | `heartbeat` | **no** | `notify_user` (only path) | `HEARTBEAT_OK` | reflex pack only |
242
+ | `a2a` (DM) | auto-sent to peer | — | `[NO_RESPONSE]` on ack/conclusion | DM dedup + loop guard |
243
+ | `a2a` (group channel) | **normalized → `group_chat`** | — | `[NO_RESPONSE]` | see invariant below |
244
+ | `group_chat` | auto-sent to channel | `notify_user` (private) | `[NO_RESPONSE]` (default) | @mention routing |
245
+ | `comment_response` | no | `task_comment` / `requirement_comment` | `[NO_REPLY_NEEDED]` | context-first, no bare ack |
246
+ | `requirement_action` | no | `requirement_comment` / `notify_user` | — | ≥1 action tool required |
247
+ | `workflow_action` | no | `notify_user` | — | ≥1 action tool required |
248
+ | `review` | no | `task_comment` / `notify_user` | — | reviewer ≠ assignee |
249
+ | `distillation` | no | `notify_user` (rare) | stop with no tools if nothing durable | Learning Habits |
250
+ | `memory_consolidation` | no | — (tools forbidden) | — | JSON-only output |
251
+
252
+ There is **no `deliberation` scenario**: the batch assess-then-commit turn
253
+ and its whole-queue completion tool were **deleted** in the Forever Loop refactor (M1–M7).
254
+ Which item the agent works on next — and whether a new arrival preempts, merges with
255
+ or queues behind it — is decided before the turn by the pure rule table `heuristicDecision()`
256
+ in `attention.ts` (R0–R9): no model call, no triage, no deliberation turn. Strict-state items
257
+ stay untouchable at the tool layer (`defer_mailbox_item` / `drop_mailbox_item` refuse them).
258
+
259
+ **Invariant 13a — a caller-supplied scenario is authoritative.** `agent.ts` used to force
260
+ `opts.scenario = 'a2a'` for every `sourceType: 'a2a_message'`, clobbering an explicit scenario
261
+ from the caller. `a2a_message` is a *transport* (it is what a channel message looks like when it
262
+ comes from an agent rather than a human), not a scenario. The engine now defaults to `'a2a'` only
263
+ when the caller stayed silent.
264
+
265
+ **Invariant 13b — channel-derived normalization.** `a2a` covered two physically different
266
+ channels. A group-channel item rendered the 1:1 wording — *"Humans do NOT see this conversation …
267
+ absorb silently"* — which is false in a group chat, where the reply is **auto-broadcast to
268
+ humans**. `buildSystemPrompt` now normalizes `a2a` + `channelKey.startsWith('group:')` →
269
+ `group_chat`, and `api-server.ts` stops downgrading a group channel to `'a2a'` for chained
270
+ (agent-triggered) replies. The A2A-ness of such a message is carried by the caller's injected
271
+ `[AGENT COLLABORATION]` prefix, not by switching the scenario.
272
+
273
+ Guard test: `context-scenario-matrix.test.ts` — asserts all 12 scenarios render a non-trivial
274
+ block, that each declares visibility/reachability, that `a2a`+group renders the group block and
275
+ never the DM/"humans do NOT see this" wording, and that `distillation` (which previously said only
276
+ "free-text is not a chat reply") states visibility explicitly. Run against the old code, the
277
+ group-channel and distillation cases fail.
278
+
279
+ ---
280
+
281
+ ### 5.10 Scenario × Tool Face — prompts must not name tools the model doesn't have (2026-09-16)
282
+
283
+ The matrix in §5.9 answers *what the model is told*. This section is its dual: *what the model can
284
+ actually call*. A prompt that mandates a tool absent from the request's `tools` array is worse than
285
+ a missing instruction — the model burns turns on `discover_tools` (or loops on validation errors)
286
+ and the scenario silently fails.
287
+
288
+ **The selection path.** `ToolSelector.selectTools` builds the schema from
289
+ `BASE_TOOL_NAMES` ∪ keyword-matched `ToolGroup`s ∪ `recentToolNames` ∪ `discover_tools`
290
+ activations. No budget eviction exists (PR #471) — selection only ever adds. A tool name that appears in **no**
291
+ group and is not in the keep-set can therefore never reach the model by default — even when it is
292
+ fully registered and the scenario's prompt demands it.
293
+
294
+ **The authoritative-allow-list contract.** Scenarios whose prompt issues hard mandates carry an
295
+ explicit `allowedTools` set. `agent.ts` applies it in two directions: it *filters* the selection
296
+ **and** *unions in* any allowed tool that keyword selection missed (offering its live
297
+ description/schema from the registry). The existing sets are
298
+ `HEARTBEAT_ALLOWED_TOOLS`, `DELIBERATION_ALLOWED_TOOLS`, `DISTILLATION_EXTRA_TOOLS` and — added in
299
+ this pass — `COMMENT_RESPONSE_ALLOWED_TOOLS`, `REQUIREMENT_ACTION_ALLOWED_TOOLS`,
300
+ `WORKFLOW_ACTION_ALLOWED_TOOLS` (+ `TASK_EXECUTION_EXTRA_TOOLS` spliced into the `isTaskExecution`
301
+ branch). `SCENARIO_ALLOWED_TOOLS` exposes the map.
302
+
303
+ Why each one is load-bearing:
304
+
305
+ | Scenario | Prompt mandate | Why default selection can't surface it |
306
+ |---|---|---|
307
+ | `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** |
308
+ | `workflow_action` | *"use `workflow_status`"*, *"`workflow_cancel`"* | same — no group can ever select them |
309
+ | `comment_response` | *"call `task_get`/`requirement_get` first"* | `requirement_get` is discover-only for `converse` |
310
+ | `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 |
311
+
312
+ **Invariant 14 — prompt-declared tools ⊆ scenario tool face.** Guard test
313
+ `scenario-tool-face.test.ts` builds each scenario's prompt, asserts the prompt text actually
314
+ mentions the mandated names, asserts those names are in the scenario's `allowedTools`, and asserts
315
+ they are genuinely *absent* from the always-on keep-set (proving the allowance is load-bearing
316
+ rather than redundant). It also asserts the action scenarios do **not** carry `shell_execute`,
317
+ `apply_patch`, `package_install` or `hub_install`.
318
+
319
+ **Invariant 14b — an allow-list may narrow, never widen, the capability boundary.** The union step
320
+ in `agent.ts` only offers names the scenario's allow-list declares; it is not a bypass of
321
+ `allowedTools` filtering.
322
+
323
+ ---
324
+
325
+ ### 5.11 Async callbacks must replay their originating scenario (2026-09-16)
326
+
327
+ `background_exec` is documented in the `task_execution` prompt as *"run builds and tests via
328
+ `background_exec` — continue other subtasks while waiting"*. That contract is only meaningful if
329
+ the **completion** turn can act. It could not.
330
+
331
+ Both callback dispatch branches (`callback_result`, and the callback-typed `system_event` emitted
332
+ by `deliverCallback`'s mailbox path) hardcoded `scenario: 'heartbeat'`. `heartbeat` maps to the
333
+ **reflex** pack, and `REFLEX_CORE_TOOLS` contains **no work tools** — no `file_write`,
334
+ `file_edit`, `shell_execute`, `apply_patch`, `task_note`, `subtask_complete`,
335
+ `deliverable_create`, `task_submit_review`. The heartbeat prompt additionally says *"your text
336
+ output is NOT visible … end with `HEARTBEAT_OK`"*. So a build launched from a task session could,
337
+ on completion, only **notify** — never fix the failure, never record progress, never submit.
338
+
339
+ **Mechanism.** The scenario is captured where it is still knowable and replayed where it is needed:
340
+
341
+ | Step | Where | What |
342
+ |---|---|---|
343
+ | capture | `registerBackgroundSession(...)` / `a2a_reply` / `schedule_wakeup` registration | `this.activeScenario` → `PendingCallback.originScenario` |
344
+ | carry | `deliverCallback` | writes it into the mailbox item's `payload.extra.scenario` (both delivery modes) |
345
+ | replay | `callback_result` / callback-typed `system_event` dispatch | `asAgentScenario(extra.scenario) ?? 'heartbeat'` |
346
+
347
+ Capture must happen at **registration**, not delivery: the completion fires later, outside any
348
+ turn, when `activeScenario` no longer refers to the launching scenario. Both delivery modes carry
349
+ it — `mailbox` surfaces a *new* attention cycle, but the work still needs work tools.
350
+
351
+ **Invariant 15 — an untrusted scenario string is never cast.** `buildHandleOpts` used to do
352
+ `opts.scenario = ex.scenario as AgentScenario`. Because that override runs **after** each branch's
353
+ explicit default, it silently won: any mailbox producer could set an arbitrary scenario, and
354
+ unknown/legacy values became the turn's scenario. It now goes through `asAgentScenario()` and is
355
+ ignored when unrecognized, so the branch default (`heartbeat`) survives. `AGENT_SCENARIOS` is the
356
+ runtime mirror of the `AgentScenario` union and the single validation authority.
357
+
358
+ Guard test: `callback-scenario.test.ts` — asserts reflex has no work tools, that
359
+ `registerBackgroundSession` records the launch scenario, that `deliverCallback` propagates it in
360
+ both modes, that dispatch replays it, that a missing scenario falls back to `heartbeat`, and that
361
+ invalid values (`'bogus-scenario'`) are rejected rather than passed through.
362
+
@@ -24,14 +24,22 @@ would inflate the system/tool prefix (token tax) and dilute the model's attentio
24
24
 
25
25
  ### 1.0 Spec: Scenario Capability Packs
26
26
 
27
+ This table is the **single authoritative pack definition**. `agent-runtime.md` §2.1 points here
28
+ instead of carrying its own copy; on 2026-11-15 the two copies had already drifted (one put
29
+ `heartbeat` in `reflex`, the other in `converse`, and one omitted `workflow_action`). The code
30
+ (`packages/core/src/capability-packs.ts`) is the final authority and agrees with this table.
31
+
27
32
  MUST: Each scenario maps to exactly one pack: `reflex` | `converse` | `execute` | `govern`.
28
33
 
29
34
  | Pack | Scenarios | `toolDefTokens` budget |
30
35
  |------|-----------|------------------------|
31
- | `reflex` | heartbeat, memory_consolidation, memory_flush, dream | 3_000 |
32
- | `converse` | chat, a2a, group_chat, comment_response, requirement_action | 8_000 |
33
- | `execute` | task_execution | 10_000 |
34
- | `govern` | review, deliberation | 8_000 |
36
+ | `reflex` | `memory_consolidation` (dream), `memory_flush`, `distillation` | 3_000 |
37
+ | `converse` | `heartbeat`, `chat`, `a2a`, `group_chat`, `comment_response`, `requirement_action`, `workflow_action` | 8_000 |
38
+ | `execute` | `task_execution` | 10_000 |
39
+ | `govern` | `review`, `deliberation` | 8_000 |
40
+
41
+ `heartbeat` is `converse`, not `reflex`: a heartbeat turn is a full conversational turn with the
42
+ same capability as a chat turn, and it no longer runs on a slim reflex toolset.
35
43
 
36
44
  MUST: `reflex` default allowlist MUST be the slim core in AGENT-RUNTIME §2.2
37
45
  (MUST NOT include `package_install`, `goal_*`, `spawn_subagent(s)`, `deliverable_create`, …).
@@ -43,23 +51,20 @@ MUST: `execute` MUST include code/shell/coding capability groups.
43
51
 
44
52
  Test IDs: `A-pack-reflex-tools`, `A-pack-converse-no-spawn`, `A-pack-execute-has-code`.
45
53
 
46
- ### 1.0.1 Spec: ToolDef budget eviction
54
+ ### 1.0.1 Spec: progressive disclosure — no budget eviction
47
55
 
48
56
  MUST: Boot/create/restore MUST **register** skill/MCP/Feishu tools without `activateTools`.
49
57
  LIVE schemas enter only via `discover_tools`. Sticky `recentToolNames` MUST NOT re-activate
50
58
  skill/MCP namespaces.
51
59
 
52
- MUST: After selection, if estimated tool-definition tokens exceed the pack budget, keep
53
- `TOOL_DEF_CORE_KEEP` + `discover_tools` + HITL, then evict skill/MCP (LRU among activated)
54
- and other extras until under budget.
55
-
56
- MUST (§Afford.S2): Evicted names MUST appear in a compact catalog (in the volatile `[Live
57
- context]` tail, keyed for rediscovery via `discover_tools`; name-only or name + ≤40 chars, total ≤
58
- `DEFERRED_CATALOG_MAX_CHARS` ≈ 1500 chars).
60
+ MUST NOT: Shrink the tool face to fit a token budget. The eviction mechanism
61
+ (`evictToolsToBudget` / `toolEvictionTier` / `packToolDefBudget` / `TOOL_DEF_BUDGET_*` /
62
+ the deferred-tool catalog) was **removed** (Owner 2026-11-20, PR #471): every first-party
63
+ tool is immune and external tools enter only via sticky activation, so no legal eviction
64
+ victim existed. The tool face is a FIXED segment — when the prompt is too big, ContextOS
65
+ compresses the VARIABLE segment (history). Availability is a hard invariant, not a budget line.
59
66
 
60
- MUST NOT: Append the eviction catalog into `discover_tools.description` (inflates
61
- `toolDefTokens` and defeats the pack budget). This is enforced as a *cache*
62
- invariant too: the description MUST be a pure function of the tool registry and
67
+ MUST: `discover_tools.description` is a pure function of the tool registry and
63
68
  the skill catalog — never of the per-turn selection — because `tools` serialises
64
69
  ahead of `system` + `messages`, so any per-turn drift there invalidates the whole
65
70
  cached prefix. Regression guard:
@@ -69,7 +74,26 @@ byte-stable regardless of per-turn recentToolNames`.
69
74
  MUST: Activated skill bodies inject as `## Activated Skills` (not under the converse
70
75
  `dynamicContext` 800-char cap).
71
76
 
72
- Test IDs: `A-tooldef-budget`, `A-tooldef-sticky-capped`, `S-catalog-not-in-tooldef`.
77
+ Test IDs: `A-pack-execute-has-code`; tool-face survival suites `action-tool-reachability`,
78
+ `task-lifecycle-tool-reachability`, `capability-packs` (face far beyond any former budget,
79
+ nothing dropped).
80
+
81
+ ### 1.0.2 Spec: action tools are always present
82
+
83
+ History (2026-10-13 → 2026-11-20): the face used to be capped by a token budget and evicted
84
+ by tier + schema size, so an agent under pressure could silently lose the tools that let it
85
+ **act** — create / update / submit work, read its ledger, look at its queue, answer a human.
86
+ The fix went through two stages: action tools made eviction-immune, then the eviction
87
+ mechanism removed outright (§1.0.1). The face is never shrunk for size; the whitelist below
88
+ is now a reachability assertion, not an eviction exemption.
89
+
90
+ | Rule | Statement |
91
+ |---|---|
92
+ | Whitelist is derived | `ACTION_TOOL_GROUPS` in `packages/core/src/capability-packs.ts` groups action tools by need (`task`, `ledger`, `human`); `ACTION_TOOL_IDS` is derived from those groups, never hand-listed. |
93
+ | Fail closed on a ghost id | A name in the whitelist that is absent from the tool registry is a startup/test error, not silently filtered. The live sample: `request_user_input` was copied out of prose into an intended whitelist and did not exist in the registry. |
94
+ | Action tools are not situational extras | They are selected unconditionally for the active pack, never treated as optional keyword additions. |
95
+ | The face is never shrunk for size | No budget eviction exists (§1.0.1). Context pressure compresses history, never the tool face. |
96
+ | Single switch | One derived set answers "is this tool required", and selection and the reachability assertion both read it. |
73
97
 
74
98
  ### 1.1 Selection inputs
75
99
 
@@ -0,0 +1,95 @@
1
+ # Background completion → in-turn delivery (rework of PR #474)
2
+
3
+ Date: 2026-11-22 · Owner directive: first principles; remove `background_wait`;
4
+ the async result must land in the **originating session**; in-turn delta
5
+ injection MUST work.
6
+
7
+ ## Invariant
8
+
9
+ A background command's result is a debt owed to `(originSession, originWorkUnit)`
10
+ — not a competing stimulus. Exactly two delivery cases, decided by whether the
11
+ origin turn is still running when the result is delivered:
12
+
13
+ 1. **Origin turn active** → deliver the FULL result inside that turn, before its
14
+ next LLM call, and consume the mailbox row so no continuation turn fires.
15
+ 2. **Origin turn ended** → the `callback_result` row drives a lineage
16
+ continuation (same session / scenario, coalesced) — the path PR #474 already
17
+ fixed (durable lineage + coalescing). This stays.
18
+
19
+ ## Why not a new tool
20
+
21
+ `shell_execute` is execute-and-wait but capped (300s) and serial; `background_exec`
22
+ exists for long / parallel jobs. The common "launch → need result" intent is
23
+ logically synchronous and must not be forced across an async boundary. The fix is
24
+ delivery into the origin session, not a pull tool. `background_wait` is removed.
25
+
26
+ ## Why reuse the C8-B injection point (and its one limitation)
27
+
28
+ `injectTurnDelta` (agent.ts:821) is the single writer of `turnDeltaCursor` and the
29
+ safe point where same-work-unit queued rows are surfaced before the next LLM call
30
+ (4 sites: chat 6291 / stream 7072 / task 7839 / ris 8375). Reusing it keeps the
31
+ cursor single-writer and delivers at a safe point instead of an external append.
32
+
33
+ LIMITATION: `buildTurnDeltaSegment` is a ≤600-char, label-only teaser
34
+ (`payload.summary`, 120 chars). A command result is kilobytes of stdout/stderr in
35
+ `payload.content`. So background results are NOT rendered through the teaser;
36
+ they are appended as a full-content session message at the same injection point,
37
+ then consumed. The teaser keeps handling contradiction/authoritative/decision
38
+ facts unchanged.
39
+
40
+ ## Changes
41
+
42
+ ### core/src/agent.ts — `injectTurnDelta`
43
+ - Partition `mailbox.deltaSince(WU, cursor)` rows into:
44
+ - background results: `sourceType==='callback_result'` &&
45
+ `payload.extra.callbackType==='background_exec'`;
46
+ - other facts: everything else.
47
+ - For each background result (seq order): append
48
+ `{role:'user', content: payload.content}` to the session (tail append,
49
+ cache-safe); consume it — `mailbox.complete(item.id)` +
50
+ `markBackgroundResultConsumed(extra.callbackId)` +
51
+ `pendingCallbackRegistry.resolve(extra.callbackId)`.
52
+ - Advance the cursor past ALL rows (incl. background) so nothing is re-read;
53
+ build the teaser segment from the non-background rows only.
54
+ - Results never cancel; return `continue`.
55
+
56
+ ### core/src/agent.ts — bus listener (~1412)
57
+ - Remove the `hasActiveBackgroundWaiter` yield (no waiters exist).
58
+ - Keep: registry ownership check → resolve → `wasBackgroundResultConsumed` guard
59
+ → build content → `deliverCallback(in_session, workUnitRef, scenario)`.
60
+
61
+ ### core/src/tools/process-manager.ts
62
+ - Delete `background_wait` tool (484-566), `activeWaiters`,
63
+ `hasActiveBackgroundWaiter`.
64
+ - Keep `consumedResults` / `markBackgroundResultConsumed` /
65
+ `wasBackgroundResultConsumed` (used by `process poll/log`, the new in-turn
66
+ delivery, and the callback_result dedupe).
67
+ - `background_exec` description: drop background_wait references; state the
68
+ result arrives in-turn if the turn is still running, else as a continuation.
69
+
70
+ ### core/src/agent.ts — case 'callback_result' (3487)
71
+ - Keep consumed-dedupe + coalescing + scenario replay (ended-turn path).
72
+
73
+ ### capability-packs.ts
74
+ - Remove `background_wait` (4 packs: 448/466/487/507).
75
+
76
+ ### web-ui
77
+ - Remove `background_wait` from toolCategories runtime prefix, execution-utils
78
+ TOOL_META + TOOL_ICON_NAME (revert the 2b8f1814 additions). Drift guard stays
79
+ green because the tool no longer exists in core.
80
+
81
+ ## Tests (real process, must bite)
82
+ - Rewrite `background-wait.test.ts` → in-turn delivery: launch a real background
83
+ command, keep the turn alive, assert the FULL result is appended to the origin
84
+ session in-turn AND no continuation turn fires; a second completion for the
85
+ same session is not re-delivered.
86
+ - Keep/extend `background-callback-lineage.test.ts` (ended-turn continuation +
87
+ coalescing + scenario replay) and `callback-scenario.test.ts`.
88
+ - `turn-delta-injection.test.ts` must stay green (owner emphasis).
89
+ - Mutation falsification: disable the in-turn consumption → the no-continuation
90
+ assertion must go red.
91
+
92
+ ## Verification
93
+ tsc -b core; core background + turn-delta tests; full node regression; web-ui
94
+ toolCategories + tsc -p web-ui; architecture-guard; eslint. Update the 4
95
+ architecture docs (state-machines, lock table, cognitive-architecture, overview).