@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.
- package/dist/background-maintenance.d.ts +25 -0
- package/dist/background-maintenance.d.ts.map +1 -1
- package/dist/background-maintenance.js +61 -0
- package/dist/background-maintenance.js.map +1 -1
- package/dist/commands/im-inbound-origin.d.ts +38 -0
- package/dist/commands/im-inbound-origin.d.ts.map +1 -0
- package/dist/commands/im-inbound-origin.js +48 -0
- package/dist/commands/im-inbound-origin.js.map +1 -0
- package/dist/commands/start.d.ts.map +1 -1
- package/dist/commands/start.js +211 -46
- package/dist/commands/start.js.map +1 -1
- package/dist/markus.mjs +18523 -9866
- package/dist/web-ui/assets/{AsyncState-_UC7xcxJ.js → AsyncState-ByYn1wrM.js} +1 -1
- package/dist/web-ui/assets/ChatComponents-Bwh8SlUV.js +14 -0
- package/dist/web-ui/assets/{ContentRenderer-C-V5k_3K.js → ContentRenderer-GLgoGp2a.js} +6 -6
- package/dist/web-ui/assets/DeliverableShareModal-CRfnRuR3.js +1 -0
- package/dist/web-ui/assets/{Deliverables-CQnWqbTb.js → Deliverables-EFsnf6kU.js} +2 -2
- package/dist/web-ui/assets/MarkdownMessage-CaLBeMto.js +4 -0
- package/dist/web-ui/assets/{Search-CVYQIy_D.js → Search-COiaXUNr.js} +1 -1
- package/dist/web-ui/assets/{SendToChat-IOAvuta-.js → SendToChat-DleryIlc.js} +1 -1
- package/dist/web-ui/assets/Settings-CzY8z2Yh.js +8 -0
- package/dist/web-ui/assets/{Store-BEsLd_RN.js → Store-C4VpQCM_.js} +1 -1
- package/dist/web-ui/assets/Switch-ByogYoGH.js +1 -0
- package/dist/web-ui/assets/Team-Cutq2J24.js +93 -0
- package/dist/web-ui/assets/Work-BO-mz-na.js +142 -0
- package/dist/web-ui/assets/{arc-DP1Vf7Sx.js → arc-mYv67jdD.js} +1 -1
- package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-Buq8JYN8.js → architectureDiagram-3BPJPVTR-Bzpz_1r6.js} +1 -1
- package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-BCa2p2_X.js → blockDiagram-GPEHLZMM-BBrLiivl.js} +1 -1
- package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BxsgggQY.js → c4Diagram-AAUBKEIU-BwDUoXA_.js} +1 -1
- package/dist/web-ui/assets/channel-Bx09lbhA.js +1 -0
- package/dist/web-ui/assets/{chunk-2J33WTMH-BJZZ60c9.js → chunk-2J33WTMH-DCSfJ-S9.js} +1 -1
- package/dist/web-ui/assets/{chunk-4BX2VUAB-C5hc4E6J.js → chunk-4BX2VUAB-CI0n1b2H.js} +1 -1
- package/dist/web-ui/assets/{chunk-55IACEB6-CbyvZ6Mk.js → chunk-55IACEB6-DqlSWLrm.js} +1 -1
- package/dist/web-ui/assets/{chunk-727SXJPM-JmNt9TVA.js → chunk-727SXJPM-BtmAfGYV.js} +1 -1
- package/dist/web-ui/assets/{chunk-AQP2D5EJ-BTk0v5ba.js → chunk-AQP2D5EJ-BgkA4lpQ.js} +1 -1
- package/dist/web-ui/assets/{chunk-FMBD7UC4-BO-dhB1U.js → chunk-FMBD7UC4-DCSr1JH4.js} +1 -1
- package/dist/web-ui/assets/{chunk-ND2GUHAM-BdjCcLdb.js → chunk-ND2GUHAM-CETYBRRm.js} +1 -1
- package/dist/web-ui/assets/{chunk-QZHKN3VN-BAzRC82n.js → chunk-QZHKN3VN-C58yD7lH.js} +1 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-DGZqU3iA.js +1 -0
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-DGZqU3iA.js +1 -0
- package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-CVffmErT.js → cose-bilkent-S5V4N54A-BpvdK03m.js} +1 -1
- package/dist/web-ui/assets/{dagre-BM42HDAG-Dd9pB2fX.js → dagre-BM42HDAG-CZ1K-KD5.js} +1 -1
- package/dist/web-ui/assets/{diagram-2AECGRRQ-BG_AUqzM.js → diagram-2AECGRRQ-D136Ok1V.js} +1 -1
- package/dist/web-ui/assets/{diagram-5GNKFQAL-D5qFMRFf.js → diagram-5GNKFQAL-Ji6qPYYV.js} +1 -1
- package/dist/web-ui/assets/{diagram-KO2AKTUF-B3qTxSWl.js → diagram-KO2AKTUF-B-s2RC-f.js} +1 -1
- package/dist/web-ui/assets/{diagram-LMA3HP47-BrxC1636.js → diagram-LMA3HP47-COWaps70.js} +1 -1
- package/dist/web-ui/assets/{diagram-OG6HWLK6-BvXyEQ9-.js → diagram-OG6HWLK6-bh6MvwWn.js} +1 -1
- package/dist/web-ui/assets/{docx-preview-DBAZFeEb.js → docx-preview-BRynUqJd.js} +1 -1
- package/dist/web-ui/assets/{erDiagram-TEJ5UH35-CMap9oy_.js → erDiagram-TEJ5UH35-DOPh2LlL.js} +1 -1
- package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-BZerJtvk.js → flowDiagram-I6XJVG4X-B_kxDHIp.js} +1 -1
- package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-CagPMHMO.js → ganttDiagram-6RSMTGT7-DYBKHOkK.js} +1 -1
- package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-DZ5dDKRu.js → gitGraphDiagram-PVQCEYII-D8_0BxLC.js} +1 -1
- package/dist/web-ui/assets/index-9SXWNIl0.css +1 -0
- package/dist/web-ui/assets/index-TAHyKznL.js +867 -0
- package/dist/web-ui/assets/{infoDiagram-5YYISTIA-CHLdsDUZ.js → infoDiagram-5YYISTIA-DayJP7Ws.js} +1 -1
- package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-SdeinQaS.js → ishikawaDiagram-YF4QCWOH-vzxCYVSq.js} +1 -1
- package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-BtlL2fi0.js → journeyDiagram-JHISSGLW-B-Fud82o.js} +1 -1
- package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-BKPQYXkB.js → kanban-definition-UN3LZRKU-DzuKdB65.js} +1 -1
- package/dist/web-ui/assets/{mermaid.core-MkJR6w4B.js → mermaid.core-D4ql87kI.js} +5 -5
- package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-CbOmHX_u.js → mindmap-definition-RKZ34NQL-DosvXt2g.js} +1 -1
- package/dist/web-ui/assets/{pieDiagram-4H26LBE5-CypGjJP1.js → pieDiagram-4H26LBE5-DhXtMWhr.js} +1 -1
- package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CGtemfUz.js → quadrantDiagram-W4KKPZXB-D33pLLOq.js} +1 -1
- package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-N7YfpCvE.js → requirementDiagram-4Y6WPE33-B-iIz-XM.js} +1 -1
- package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-CYnSrei-.js → sankeyDiagram-5OEKKPKP-BMd9AFEW.js} +1 -1
- package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-CsB7dCPF.js → sequenceDiagram-3UESZ5HK-CI1MIdwo.js} +1 -1
- package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DTDFUXFP.js → stateDiagram-AJRCARHV-Bq6FKPW2.js} +1 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-8nMhmWY5.js +1 -0
- package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-C_bWAN9B.js → timeline-definition-PNZ67QCA-BDdmmSRo.js} +1 -1
- package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-CX_qAuUT.js → vennDiagram-CIIHVFJN-DP2q5vY2.js} +1 -1
- package/dist/web-ui/assets/{wardley-L42UT6IY-q53jQ293.js → wardley-L42UT6IY-Bw3fjszD.js} +1 -1
- package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-D34dKCJU.js → wardleyDiagram-YWT4CUSO-37bQUocJ.js} +1 -1
- package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-BFAngp66.js → xychartDiagram-2RQKCTM6-DnLDZyNC.js} +1 -1
- package/dist/web-ui/index.html +2 -2
- package/docs/README.md +50 -16
- package/docs/api/guides/websocket.md +43 -0
- package/docs/api/reference.md +657 -0
- package/docs/architecture/a2a-communication.md +303 -0
- package/docs/architecture/agent-runtime.md +145 -28
- package/docs/architecture/architecture.md +30 -11
- package/docs/architecture/cognitive-architecture.md +189 -15
- package/docs/architecture/concurrent-processing.md +190 -31
- package/docs/architecture/context-assembly.md +264 -0
- package/docs/architecture/derived-views.md +463 -0
- package/docs/architecture/desktop-auto-update.md +185 -0
- package/docs/architecture/facts.md +406 -0
- package/docs/architecture/learning-loop.md +11 -0
- package/docs/architecture/limits.md +79 -0
- package/docs/architecture/mailbox-system.md +786 -668
- package/docs/architecture/memory-system.md +1 -1
- package/docs/architecture/messaging-gateway.md +7 -0
- package/docs/architecture/notification-delivery.md +221 -0
- package/docs/architecture/notification-sounds.md +177 -0
- package/docs/architecture/prompt-engineering.md +171 -700
- package/docs/{design/remote-access-contract.md → architecture/remote-access.md} +4 -0
- package/docs/architecture/state-machines.md +288 -5
- package/docs/architecture/tool-loop-harness.md +362 -0
- package/docs/architecture/tool-system.md +40 -16
- package/docs/design/background-callback-in-turn-delivery-2026-11-22.md +95 -0
- package/docs/design/c10-0b-pick-identity-leak-2026-11-22.md +233 -0
- package/docs/design/c10-a-identity-columns-2026-11-22.md +182 -0
- package/docs/design/c10-c-trust-boundary-2026-11-23.md +222 -0
- package/docs/design/c10-external-adapters-plan-2026-11-19.md +448 -0
- package/docs/design/c8-residual-mechanisms-2026-11-15.md +984 -0
- package/docs/design/external-signal-decision-loop-2026-11-25.md +579 -0
- package/docs/guides/development.md +1 -1
- package/docs/{architecture → guides}/mailbox-audit-checklist.md +7 -0
- package/docs/guides/remote-access.md +1 -1
- package/docs/{design/agent-stop-intent-audit.md → records/agent-stop-intent-audit-2026-11-08.md} +4 -0
- package/docs/records/c10-l5-gate-verification-2026-11-26.md +72 -0
- package/docs/records/c10-l5-live-verification-2026-11-25.md +117 -0
- package/docs/records/cut6-c4-verification-2026-11-12.md +268 -0
- package/docs/records/cut6-mailbox-address-envelope-design-2026-11-12.md +871 -0
- package/docs/records/cut7-c7a-red-green-evidence-2026-11-13.md +105 -0
- package/docs/records/cut7-c7a-workunit-implementation-2026-11-13.md +116 -0
- package/docs/records/cut7-c7b-verification-2026-11-14.md +90 -0
- package/docs/records/cut7-live-verification-2026-11-14.md +33 -0
- package/docs/records/cut7-wiring-negative-cache-2026-11-14.md +64 -0
- package/docs/records/cut7-workunit-execution-plan-2026-11-13.md +206 -0
- package/docs/records/cut8-a-entity-keys-design-2026-11-14.md +377 -0
- package/docs/records/cut8-b-turn-delta-injection-2026-11-14.md +362 -0
- package/docs/records/cut8-c-single-clock-2026-11-14.md +119 -0
- package/docs/records/cut8-c-single-clock-design-2026-11-14.md +150 -0
- package/docs/records/cut8-d-2026-11-14.md +231 -0
- package/docs/records/cut8-live-verification-2026-11-14.md +1018 -0
- package/docs/records/cut9-adjacent-identity-paths-2026-11-15.md +200 -0
- package/docs/records/cut9-identity-declaration-2026-11-15.md +163 -0
- package/docs/records/cut9-inbox-dual-run-diff-2026-11-15.md +117 -0
- package/docs/records/cut9-live-verification-2026-11-15.md +222 -0
- package/docs/records/cut9-runtime-probe-2026-11-19.md +520 -0
- package/docs/{design/deliverable-sharing.md → records/deliverable-sharing-2026-08-12.md} +10 -3
- package/docs/records/identity-backlog-disposition-2026-11-22.md +143 -0
- package/docs/records/marketplace-orphan-freeze-2026-11-22.md +239 -0
- package/docs/{architecture/notify-user-context-truth.md → records/notify-user-context-truth-2026-10-28.md} +6 -0
- package/docs/{handoff → records}/remote-access-handoff.md +1 -1
- package/package.json +1 -1
- package/templates/roles/HANDBOOK.md +1 -1
- package/templates/skills/agent-building/SKILL.md +1 -1
- package/dist/web-ui/assets/ChatComponents-Ca9tWI9W.js +0 -12
- package/dist/web-ui/assets/DeliverableShareModal-BvpyowYJ.js +0 -1
- package/dist/web-ui/assets/MarkdownMessage-DedA8Zob.js +0 -4
- package/dist/web-ui/assets/Settings-BQDqf4q5.js +0 -8
- package/dist/web-ui/assets/Switch-C6InTNUi.js +0 -1
- package/dist/web-ui/assets/Team-nfNyWj-s.js +0 -85
- package/dist/web-ui/assets/Work-BQvgkynj.js +0 -142
- package/dist/web-ui/assets/channel-BTSrOo6c.js +0 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BSYlcnF9.js +0 -1
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BSYlcnF9.js +0 -1
- package/dist/web-ui/assets/index-CKPQYzzR.js +0 -867
- package/dist/web-ui/assets/index-CzHSs0Vd.css +0 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-AVnDjlzF.js +0 -1
- package/docs/api/api.md +0 -353
- package/docs/architecture/llm-provider-timeouts.md +0 -60
- package/docs/architecture/state-ownership.md +0 -83
- /package/docs/architecture/{frontend/team-chat.md → team-chat.md} +0 -0
- /package/docs/{analysis → records}/2026-10-29-a2a-cache-hit-rate.md +0 -0
- /package/docs/{fixes → records}/2026-11-12-session-expiry-and-mention-thinking.md +0 -0
- /package/docs/{handoff → records}/approval-tri-state-handoff.md +0 -0
- /package/docs/{design → records}/overview-attention-redesign.md +0 -0
- /package/docs/{remote-access/fast-path-plan.md → records/remote-access-fast-path-plan-2026-10-17.md} +0 -0
|
@@ -1,6 +1,12 @@
|
|
|
1
|
-
# Prompt Engineering &
|
|
1
|
+
# Prompt Engineering & Cache Layout
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> **Scope (this file)**: how a request is *built and cached* — LLM call taxonomy, the cache-scope layout principle, system-prompt architecture, prefix-cache invariants, ContextOS v2 volatile delivery, prompt profiles, fail-closed packing, and output-token resolution.
|
|
4
|
+
> **Split**: §3 (message assembly & compression) and §4–§5 (tool loop harness, scenario assembly) were split out of this document on **2026-11-15**. Section numbers were kept, so the gap at §3–§5 marks exactly the material that moved.
|
|
5
|
+
> **Siblings**: [context-assembly.md](./context-assembly.md) — how history is packed into the request and compressed; [tool-loop-harness.md](./tool-loop-harness.md) — how one call runs (tool loop) and how each scenario is assembled.
|
|
6
|
+
|
|
7
|
+
> **2026-11-15 重排章节编号** — §2 sub-sections were renumbered to be unique and monotonic (old duplicated `### 2.2 Section Details` → `2.3`, `2.3 Spec: Prompt profiles` → `2.4`, `2.4 Spec: Afford fail-closed packing` → `2.5`, the out-of-order `2.3 Skill Filtering` → `2.6`), and the `####` section-detail entries that had drifted below §2.4 (`Identity`, `Skills`, `Task Board`, `Mailbox`, `Concurrency`, `Scenario`, `Referencing`, `Async Work`, `Behavioral Policies`) were moved back under their parent §2.3 Section Details. No wording, table, threshold, date annotation, or invariant was changed.
|
|
8
|
+
|
|
9
|
+
This document specifies how Markus constructs prompts and keeps them cacheable, and how it 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
10
|
|
|
5
11
|
---
|
|
6
12
|
|
|
@@ -28,7 +34,7 @@ P2 (Directed Retrieval) and P4 (Assembly) are code-only phases with no LLM call.
|
|
|
28
34
|
| 2 | **Human Chat** (stream/SSE) | API `/api/agents/:id/chat?stream=1` | `handleMessageStream()` | Yes | Yes | Yes | 200 (safety net) |
|
|
29
35
|
| 3 | **Task Execution** | `TaskService.runTask()` → `_executeTaskInternal()` | `llmRouter.chatStream()` | Yes | Yes | Yes | **None** |
|
|
30
36
|
| 4 | **Respond-in-Session** | API `/api/agents/:id/sessions/:sid/messages` | `respondInSession()` | Yes | Yes | Yes | 200 (safety net) |
|
|
31
|
-
| 5 | **Heartbeat** | `
|
|
37
|
+
| 5 | **Heartbeat / liveness patrol** | `agent.triggerHeartbeat()` (manager / API-server dirty-state fallback) → `runHeartbeatPatrol()` → `handleHeartbeat()` | `handleMessage(scenario:'heartbeat')` | No | Subset | Yes (via handleMessage) | 200 + 3 retries |
|
|
32
38
|
| 6 | **A2A Chat** | API `/api/agents/:id/a2a` / channel routing | `handleMessage(scenario:'a2a')` | No | Yes | Yes (via handleMessage) | 200 |
|
|
33
39
|
| 7 | **Comment Response** | Mailbox `task_comment` / `requirement_update` | `handleMessage(scenario:'comment_response')` | No | Yes | Yes (via handleMessage) | 200 |
|
|
34
40
|
| 8 | **Internal (Lightweight)** | Various | `handleMessage(scenario:'heartbeat')` | No | Varies | Yes (via handleMessage) | 200 |
|
|
@@ -44,10 +50,71 @@ These are `handleMessage()` calls with `scenario: 'heartbeat'` and typed session
|
|
|
44
50
|
| Sub-scenario | Trigger | Session ID Pattern | Purpose |
|
|
45
51
|
|-------------|---------|-------------------|---------|
|
|
46
52
|
| **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 |
|
|
53
|
+
| **Memory Flush** | turn-level preflight when context usage is high (see [tool-loop-harness.md](./tool-loop-harness.md) §5.7) | `sys_<agentId>_<ts>` | Prompt agent to `memory_save` important info before the context window fills |
|
|
48
54
|
| **LLM Summarizer** | `contextEngine.smartSummarizeAndTruncate()` | N/A (internal) | Compress older conversation messages into a summary (no tools) |
|
|
49
55
|
| **Dream Consolidation** | `consolidateMemory()` (once/day, ≥50 entries) | `sys_<agentId>_<ts>` | LLM reviews memory entries, outputs prune/merge plan (no tools) |
|
|
50
56
|
|
|
57
|
+
### 1.3 Provider timeout & retry governance
|
|
58
|
+
|
|
59
|
+
> **Status: risk inventory / target design (2026-09).** Rows resolved since are marked **RESOLVED**
|
|
60
|
+
> in place rather than deleted, so the reasoning stays available.
|
|
61
|
+
|
|
62
|
+
> Last updated: 2026-09. Distilled from the provider timeout audits (set A + set B).
|
|
63
|
+
> This is the **current-state design reference** for how each LLM provider adapter
|
|
64
|
+
> handles timeouts / hangs / retries — what is bounded, what is not, and the agreed
|
|
65
|
+
> target design. Do not add per-file line references here (they drift); describe
|
|
66
|
+
> behavior, not line numbers.
|
|
67
|
+
|
|
68
|
+
#### 1.3.1 Governing matrix (current state)
|
|
69
|
+
|
|
70
|
+
| Provider adapter | Non-stream timeout | Stream idle timeout | Hard cap | External abort | Retry | Notes |
|
|
71
|
+
|------------------|--------------------|---------------------|----------|----------------|-------|-------|
|
|
72
|
+
| **openai** | ✅ configurable | ✅ idle (per-chunk reset) + hard | ✅ | ✅ shared AbortController | — | Reference implementation; fails loudly |
|
|
73
|
+
| **markus-provider** | ✅ | ✅ idle (per-chunk reset) + hard | ✅ | ✅ external abort | ✅ budget shared across retries (not reset) | Aligned baseline with openai |
|
|
74
|
+
| **anthropic** | ✅ configurable (default 90 s) | ✅ idle (per-chunk reset) + hard | ✅ | ✅ | — | ~~Most severe gap (set A)~~ **RESOLVED** |
|
|
75
|
+
| **google** | ✅ (60 s) | ✅ idle (per-chunk reset) + hard | ✅ | ✅ (stream) | — | ~~Needs hardening (set A)~~ **RESOLVED** |
|
|
76
|
+
| **dashscope** | ✅ via OpenAIProvider (chat) | ✅ via OpenAIProvider | ✅ | ✅ | — | ~~Needs timeout coverage (set A)~~ **RESOLVED** (chat inherits openai; media paths self-timed) |
|
|
77
|
+
| **ollama** | ✅ (120 s) | ✅ idle (per-chunk reset) + hard | ✅ | ✅ (stream) | — | ~~Needs timeout coverage (set A)~~ **RESOLVED** |
|
|
78
|
+
| **openai-codex** | — | — | ✅ single 180 s | — | — | Single coarse root timer |
|
|
79
|
+
| **proxy-fetch** | ❌ **no built-in timeout** | — | — | relies on caller-passed signal | — | Caller must pass `signal`, else unbounded |
|
|
80
|
+
| **minimax** | ✅ | ✅ | — | — | — | **Video polling can hang ~30 min, not externally cancellable; silent `max_tokens` downgrade + empty-array fallbacks** |
|
|
81
|
+
|
|
82
|
+
#### 1.3.2 Known risk inventory (priority order)
|
|
83
|
+
|
|
84
|
+
1. **RESOLVED** — **anthropic non-streaming chat: no timeout at all** — a hung model call blocks the
|
|
85
|
+
turn indefinitely. Must get an idle timeout + hard cap (openai semantics).
|
|
86
|
+
*(Now: `chatTimeoutMs` default 90 s + idle/hard stream caps.)*
|
|
87
|
+
2. **minimax video polling: ~30 min without external cancel** — plus silent degradation
|
|
88
|
+
(downgraded `max_tokens`, empty-array response accepted as success). Needs a real poll
|
|
89
|
+
timeout + fail-loud on degradation.
|
|
90
|
+
3. **proxy-fetch: no own timeout** — unbounded unless the caller threads a signal.
|
|
91
|
+
Should default to a sane timeout and still honor an external signal.
|
|
92
|
+
4. **RESOLVED** — **google / dashscope / ollama**: partial coverage — streaming idle semantics and hard
|
|
93
|
+
caps not consistently implemented. *(Now: google/ollama implement idle + hard caps; dashscope inherits openai.)*
|
|
94
|
+
5. **Streaming errors thrown as bare `AbortError`** in several adapters — callers cannot
|
|
95
|
+
distinguish user-cancel from provider failure; wrap with intent.
|
|
96
|
+
6. **Timer leaks** where timers are not cleared on completion paths.
|
|
97
|
+
7. **Hardcoded durations** in several adapters — should be configurable (openai-style).
|
|
98
|
+
|
|
99
|
+
#### 1.3.3 Target design (agreed direction)
|
|
100
|
+
|
|
101
|
+
- **Idle semantics**: per-chunk timer reset on every received chunk (stream stays alive
|
|
102
|
+
while tokens flow), plus a **hard cap** as the outer bound.
|
|
103
|
+
- **Configurable durations** with sane defaults; no hardcoded magic numbers.
|
|
104
|
+
- **External abort**: all adapters accept a caller-provided `AbortController`/signal and
|
|
105
|
+
cooperate with it (used by streaming cancel — see streaming-and-reattach.md §4.2).
|
|
106
|
+
- **Fail-loud**: timeouts and degradations surface as structured errors, never as silent
|
|
107
|
+
success (see mailbox-system.md §27.3 fail-loud chain).
|
|
108
|
+
- **Single-timer consolidation**: one timer mechanism per adapter (roadmap item from the
|
|
109
|
+
frontend resilience audit §5.5).
|
|
110
|
+
- **Reference baseline**: `openai` and `markus-provider` are the alignment targets.
|
|
111
|
+
|
|
112
|
+
#### 1.3.4 Rule of thumb for new adapters
|
|
113
|
+
|
|
114
|
+
Every new provider adapter MUST implement: non-stream timeout, stream idle timeout,
|
|
115
|
+
hard cap, external abort, and fail-loud error wrapping — before being merged. A provider
|
|
116
|
+
call that can hang without bound is a scheduling-chain violation (mailbox-system.md §27).
|
|
117
|
+
|
|
51
118
|
---
|
|
52
119
|
|
|
53
120
|
### 2.0 Cache-Scope Layout Principle (design philosophy)
|
|
@@ -97,7 +164,7 @@ miss. Two live leaks of this kind were measured on 2026-09-16 across 30 agents /
|
|
|
97
164
|
**Corollary 5 — measure, or the invariant rots.** The only reason these survived four
|
|
98
165
|
audit rounds is that no cache-hit telemetry existed to falsify the "cache-friendly"
|
|
99
166
|
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).
|
|
167
|
+
hit rate is recorded per session ([context-assembly.md](./context-assembly.md) §3.9, RC4).
|
|
101
168
|
|
|
102
169
|
---
|
|
103
170
|
|
|
@@ -140,7 +207,6 @@ dynamic content is moved **out of the system prompt entirely** into a volatile t
|
|
|
140
207
|
║ Channel History (recent msgs) · Date/locale · Mailbox ║
|
|
141
208
|
║ & attention · Team Status · Working Memory · ║
|
|
142
209
|
║ Cognitive/Notebook context · task board · deliverables ║
|
|
143
|
-
║ · deferred-tool catalog (Afford.S2) ║
|
|
144
210
|
║ · Your Knowledge (knowledge.md) · Working State ║
|
|
145
211
|
║ (notebook) ← agent-written, see §2.1.1 inv. 5 ║
|
|
146
212
|
╚══════════════════════════════════════════════════════════╝
|
|
@@ -150,11 +216,11 @@ dynamic content is moved **out of the system prompt entirely** into a volatile t
|
|
|
150
216
|
|
|
151
217
|
`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
218
|
|
|
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 ↔
|
|
219
|
+
1. **Tier 1 (Stable)**: Role, policies, tool usage rules, communication rules, collaboration rules. Scenario-free — stay cached across ALL mode switches (chat ↔ heartbeat ↔ a2a ↔ task_execution). A cache breakpoint after this tier caches this prefix across all calls.
|
|
154
220
|
|
|
155
221
|
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
222
|
|
|
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
|
|
223
|
+
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. 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
224
|
|
|
159
225
|
> **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
226
|
|
|
@@ -186,7 +252,7 @@ guard test; break one and long sessions silently re-bill their whole history on
|
|
|
186
252
|
|---|-----------|-------|-----------|
|
|
187
253
|
| 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
254
|
| 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
|
|
255
|
+
| 3 | The tool face is never shrunk for size — no budget eviction exists (PR #471); context pressure compresses history, never the face | `ToolSelector.selectTools` (no evictor) | `action-tool-reachability.test.ts`, `capability-packs.test.ts` |
|
|
190
256
|
| 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
257
|
| 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
258
|
| 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 …` |
|
|
@@ -324,7 +390,7 @@ this call's tail:
|
|
|
324
390
|
(last-write-wins) and are folded away by the normal compaction path.
|
|
325
391
|
- **Single choke point** — written inside `prepareMessages`, not at the ~8 call
|
|
326
392
|
sites, so a new call site cannot forget it (same rationale as the
|
|
327
|
-
slots/summary derivation in §3.7).
|
|
393
|
+
slots/summary derivation in [context-assembly.md](./context-assembly.md) §3.7).
|
|
328
394
|
- **Best-effort** — a persistence failure logs a warning; that call's tail still
|
|
329
395
|
carries the state verbatim, so the agent is never blind.
|
|
330
396
|
- Recognised by `isSyntheticMessage()`, so a checkpoint never counts as a user turn.
|
|
@@ -357,7 +423,7 @@ prefix is unaffected.
|
|
|
357
423
|
|
|
358
424
|
**Regression guard**: `packages/core/test/context-volatile-gating.test.ts`.
|
|
359
425
|
|
|
360
|
-
**Resolved in v2.1** — see §3.8. A single turn issuing 60+ LLM calls is now
|
|
426
|
+
**Resolved in v2.1** — see [context-assembly.md](./context-assembly.md) §3.8. A single turn issuing 60+ LLM calls is now
|
|
361
427
|
folded in place: when the absolute history ceiling trips, the fold boundary is
|
|
362
428
|
the END of history instead of the current turn start, so the same block-wise fold
|
|
363
429
|
reaches inside the current turn. No separate intra-turn code path was needed.
|
|
@@ -413,7 +479,7 @@ injection point cannot silently land in a stable tier and bust the cache prefix.
|
|
|
413
479
|
- **Status**: implemented (Scheme A — volatile tail; adds the enforcing guard tests, the
|
|
414
480
|
byte-stability regression, and the `usage.compressed`-driven cache/compression metrics).
|
|
415
481
|
|
|
416
|
-
### 2.
|
|
482
|
+
### 2.3 Section Details
|
|
417
483
|
|
|
418
484
|
#### Role System Prompt (§1)
|
|
419
485
|
Source: `role.systemPrompt` parsed from the agent's `ROLE.md`.
|
|
@@ -458,94 +524,10 @@ The legacy notebook aliases `update_working_memory` / `clear_working_memory` wer
|
|
|
458
524
|
| **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
525
|
| **L1** | Identity (capped roster), org/workspace, knowledge, active tasks | Identity always; tasks when present |
|
|
460
526
|
| **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` / `
|
|
527
|
+
| **L3+** | Skill full bodies, Error Recovery, Quality Gates, full Task Workflow, deliverable format | `discover_tools` activate, or scenarios: `task_execution` / `review` / `comment_response` |
|
|
462
528
|
|
|
463
529
|
> **SSOT**: Budgets, packs, and afford fail-closed rules live in [agent-runtime.md](./agent-runtime.md). The sections below are normative Spec supplements.
|
|
464
530
|
|
|
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
531
|
#### Identity Section (§7)
|
|
550
532
|
Source: `buildIdentitySection()`.
|
|
551
533
|
Contains:
|
|
@@ -604,7 +586,7 @@ by `HANDOFF_CONTEXT_LIMIT` (8).
|
|
|
604
586
|
|
|
605
587
|
#### Scenario Section (§15)
|
|
606
588
|
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:
|
|
589
|
+
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 [tool-loop-harness.md](./tool-loop-harness.md) §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
590
|
|
|
609
591
|
| Scenario | Key Instructions | Output Visibility | Communication Tools |
|
|
610
592
|
|----------|-----------------|-------------------|-------------------|
|
|
@@ -616,10 +598,19 @@ Placed at the **end of Tier 2** so the identity/org prefix remains stable across
|
|
|
616
598
|
| `a2a` | Coordination only. Concise, structured. Complex work → `task_create`. | Visible to **peer agent** only | Reply directly; `notify_user` to escalate to humans |
|
|
617
599
|
| `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
600
|
| `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
601
|
| `review` | Evaluate deliverable quality against acceptance criteria. | **Not directly visible** | `task_update` for verdict; `notify_user` optionally |
|
|
621
602
|
| `memory_consolidation` | Internal memory management. Purely private. | **Not visible**; internal only | No communication tools needed |
|
|
622
603
|
|
|
604
|
+
There is **no `deliberation` scenario**. The batch "assess the whole queue, then commit" turn
|
|
605
|
+
and its whole-queue completion tool were **deleted** in the Forever Loop refactor (M1–M7): no
|
|
606
|
+
`## Current Interaction Mode` block is rendered for it and no such turn is ever started.
|
|
607
|
+
Pick-order and interruption are decided **before** any turn starts, by the pure rule table
|
|
608
|
+
`heuristicDecision()` in `attention.ts` (R0–R9, first match wins: same-user/same-session `merge`,
|
|
609
|
+
new human chat `preempt`, same-task comment `merge`, higher priority `preempt`, otherwise
|
|
610
|
+
`continue`): no model call, no triage, no deliberation turn. Queue inspection and queue management
|
|
611
|
+
(`check_mailbox`, `defer_mailbox_item`, `drop_mailbox_item`, `notebook_upsert`) and the goal tools
|
|
612
|
+
(`goal_create`, `goal_update`, `goal_status`) stay available inside *whichever* scenario is running.
|
|
613
|
+
|
|
623
614
|
#### Referencing Markus Resources
|
|
624
615
|
|
|
625
616
|
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:
|
|
@@ -653,622 +644,100 @@ Placed in **Tier 1 (Stable)** (`## Error Recovery` + `## Autonomy & Escalation`)
|
|
|
653
644
|
- **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
645
|
- **Decision-ready return contract**: async results and delegation replies are summarized for immediate action, not raw stdout/log dumps.
|
|
655
646
|
|
|
656
|
-
### 2.
|
|
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
|
|
647
|
+
### 2.4 Spec: Prompt profiles (`promptProfile`)
|
|
955
648
|
|
|
956
|
-
|
|
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).
|
|
649
|
+
MUST: `buildSystemPrompt()` MUST accept `promptProfile: 'reflex' | 'converse' | 'execute' | 'govern'` derived from the scenario pack ([agent-runtime.md](./agent-runtime.md) §2 / §4).
|
|
1081
650
|
|
|
1082
|
-
|
|
651
|
+
| Section | reflex | converse | execute/govern |
|
|
652
|
+
|---------|--------|----------|----------------|
|
|
653
|
+
| ROLE | full (soft warn metric) | full | full |
|
|
654
|
+
| Collaboration Rules (L0) | yes | yes | yes |
|
|
655
|
+
| knowledge.md as `## Your Knowledge` | omitted | capped (`KNOWLEDGE_PROMPT_MAX_TOKENS_CONVERSE`) | capped (`KNOWLEDGE_PROMPT_MAX_TOKENS`) |
|
|
656
|
+
| ~~state.md~~ | — | retired 2026-09-16 → notebook `system` tier | — |
|
|
657
|
+
| L3 quality/git/error-recovery | omitted | omitted (incl. comments) | included |
|
|
658
|
+
| Search Strategy | complete, concise | complete, concise | complete, concise |
|
|
659
|
+
| Team announcements / norms | capped | 400 chars | 2000 chars |
|
|
660
|
+
| Channel history / shared deliverables | omitted | optional short | as needed |
|
|
661
|
+
| Full roster | manager + ≤3 active | existing caps | existing caps |
|
|
662
|
+
| Date / locale / Interaction Mode | yes | always retained | yes |
|
|
1083
663
|
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
-
|
|
664
|
+
MUST: ROLE.md is always injected in full (persona only). `ROLE_PROMPT_MAX_TOKENS` is warn-only.
|
|
665
|
+
MUST NOT: Append `HANDBOOK.md` into ROLE. Distill collaboration hard rules into L0
|
|
666
|
+
`## Markus Collaboration Rules`; HANDBOOK.md is a depth handbook via `file_read`.
|
|
667
|
+
Long-tail API/reference content belongs in skills, not ROLE/HANDBOOK always-on.
|
|
668
|
+
MUST: knowledge injection MUST exclude observations buffer; converse uses a short
|
|
669
|
+
digest cap (full text via `memory_search` / files). Knowledge body headings `##`
|
|
670
|
+
MUST be demoted to `###` under `## Your Knowledge` so they do not collide with
|
|
671
|
+
system sections; stale fault/transcript sections are deprioritized when truncating.
|
|
672
|
+
MUST NOT: Inject full history into reflex (the retired `state.md` block is gone — situational state rides `## Notebook`).
|
|
673
|
+
MUST: Converse size is controlled by progressive disclosure + afford guard, **not**
|
|
674
|
+
by post-assemble truncation of ROLE/L0/Collaboration Rules/mode/date.
|
|
675
|
+
MUST NOT: Emit `_[ROLE truncated]_` / `_[system trimmed]_` markers.
|
|
1088
676
|
|
|
1089
|
-
|
|
677
|
+
#### Conversation-first vs Task-when-needed (L0 + chat scenario)
|
|
1090
678
|
|
|
1091
|
-
|
|
679
|
+
MUST: Human chat defaults to **conversation-first** — agents MAY advance real work
|
|
680
|
+
(edit files, run commands, multi-step debugging) in the live conversation without
|
|
681
|
+
forcing `task_create`.
|
|
682
|
+
MUST: Task workflow is for async work, delegation, multi-agent parallel delivery,
|
|
683
|
+
formal review/audit trail, or when the human explicitly asks for a task.
|
|
684
|
+
MUST: **STOP** means only: after `task_create` for a piece of work, do not continue
|
|
685
|
+
**that task** in chat. Work never placed on a task may continue conversationally.
|
|
686
|
+
MUST: Requirements gate applies to **tasks** (`gate all tasks`), not to conversational chat work.
|
|
687
|
+
MUST: Conflict priority:
|
|
688
|
+
`Owner explicit instruction > conversation-first default > Protocol (once a task exists) > ROLE persona > Position (manager)`.
|
|
689
|
+
MUST: Managers are **player-coach** — Position does not forbid hands-on building when ROLE is a builder/founder.
|
|
1092
690
|
|
|
1093
|
-
|
|
691
|
+
MUST: L0 includes **How Your Prompt Is Composed** — ROLE.md is persona; L0 is always-on
|
|
692
|
+
platform rules; HANDBOOK/skills are on demand. ROLE line count ≠ full constraints.
|
|
1094
693
|
|
|
1095
|
-
|
|
694
|
+
MUST (`task_submit_review`): Auto-fill `task_id` from execution ALS/`activeTasks` when
|
|
695
|
+
present; otherwise `task_id` is required. MUST NOT guess from the TaskService board.
|
|
696
|
+
Work-context-bound tools MUST NOT sticky into free chat — but MUST remain available in
|
|
697
|
+
entity-bound sessions (task_execution, review, comment_response, requirement_action,
|
|
698
|
+
workflow_action) (`S-execute-only-no-sticky-converse`).
|
|
1096
699
|
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
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
|
-
```
|
|
700
|
+
Test IDs: `A-profile-reflex-omits`, `A-profile-role-full`, `A-collab-rules-always-on`,
|
|
701
|
+
`A-conversation-first-chat`, `A-knowledge-heading-demote`, `A-role-no-shared-append`,
|
|
702
|
+
`A-knowledge-cap`, `A-profile-converse-no-l3`, `S-execute-only-no-sticky-converse`.
|
|
1106
703
|
|
|
1107
|
-
|
|
1108
|
-
Result written to `daily-logs/` via `memory.writeDailyLog()`.
|
|
704
|
+
### 2.5 Spec: Afford fail-closed packing
|
|
1109
705
|
|
|
1110
|
-
|
|
706
|
+
MUST: After assembling system + tools, compute `fixed = systemTokens + toolDefTokens`.
|
|
707
|
+
MUST: If `promptAffordTokens != null` and
|
|
708
|
+
`fixed + PROMPT_AFFORD_OUTPUT_RESERVE + safetyMargin > promptAffordTokens`:
|
|
709
|
+
1. Downgrade once to `reflex` pack + profile and re-assemble.
|
|
710
|
+
2. If still over, MUST NOT call the provider; return actionable error (`prompt_pack_rejected`).
|
|
711
|
+
MUST: Heartbeat paths that hit reject MUST end activity with `success: false`.
|
|
712
|
+
MUST NOT: Only shrink `messageBudget` while shipping an over-afford fixed prefix.
|
|
1111
713
|
|
|
1112
|
-
|
|
1113
|
-
|
|
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
|
-
```
|
|
714
|
+
MUST (§Afford.S1): `handleMessageStream` MUST use the same `ensureAffordablePromptPack`
|
|
715
|
+
gate as `handleMessage` before any provider call.
|
|
1119
716
|
|
|
1120
|
-
|
|
717
|
+
MUST (§Afford.S3): `SYSTEM_PROMPT_BUDGET_CONVERSE` is a soft observe/warn metric for
|
|
718
|
+
converse system size. MUST NOT truncate ROLE/L0/mode/date to meet it. Hard limits
|
|
719
|
+
are enforced by the provider afford guard (downgrade/reject).
|
|
1121
720
|
|
|
1122
|
-
|
|
1123
|
-
|
|
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.
|
|
721
|
+
MUST (§Afford.S4): Provider MUST clamp `max_tokens` to remaining afford (proactive when
|
|
722
|
+
`lastPromptAffordTokens` known; reactive on reservation 402).
|
|
1129
723
|
|
|
1130
|
-
|
|
724
|
+
Test IDs: `A-afford-downgrade`, `A-afford-heartbeat-fail`, `S-stream-afford-reject`,
|
|
725
|
+
`S-stream-afford-downgrade`, `S-converse-system-budget`, `S-converse-keeps-date`,
|
|
726
|
+
`S-max-tokens-clamp-remaining`.
|
|
1131
727
|
|
|
1132
|
-
|
|
728
|
+
Cold-start acceptance: converse fixed ≤ 28_000; reflex fixed ≤ 8_000
|
|
729
|
+
(`A-budget-contract-converse`, `A-budget-contract-reflex`).
|
|
1133
730
|
|
|
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
|
-
```
|
|
731
|
+
### 2.6 Skill Filtering
|
|
1139
732
|
|
|
1140
|
-
|
|
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.
|
|
733
|
+
**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 [context-assembly.md](./context-assembly.md) §3.9.1 O4.
|
|
1185
734
|
|
|
1186
735
|
---
|
|
1187
736
|
|
|
1188
|
-
|
|
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.
|
|
737
|
+
> **Split (2026-11-15)** — §3 and §4–§5 live in sibling files: **how history is packed and compressed** → [context-assembly.md](./context-assembly.md) (token budget, compression pipeline, task-prompt protection, ContextOS fixed/variable split & SLOT anchors, compaction defects §3.8 and root causes §3.9); **how one call runs and how each scenario is assembled** → [tool-loop-harness.md](./tool-loop-harness.md) (harness variants, loop detection, reflection nudges, scenario × context matrix §5.9, scenario × tool face §5.10, async callback replay §5.11). The section-number gap at §3–§5 below is exactly that moved material.
|
|
1229
738
|
|
|
1230
739
|
---
|
|
1231
740
|
|
|
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
741
|
## 6. Output Token Resolution
|
|
1273
742
|
|
|
1274
743
|
The `LLMRouter` resolves `maxTokens` (output token limit) for every LLM call:
|
|
@@ -1297,7 +766,7 @@ Five primary memory tools (down from seven); legacy aliases preserved:
|
|
|
1297
766
|
|
|
1298
767
|
**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
768
|
|
|
1300
|
-
Goal tools (`goal_create`, `goal_update`, `goal_status`) are available
|
|
769
|
+
Goal tools (`goal_create`, `goal_update`, `goal_status`) are available in every scenario — including **heartbeat** patrols — for standing-goal management.
|
|
1301
770
|
|
|
1302
771
|
`ToolSelector.selectTools()` determines which tools appear in each LLM call:
|
|
1303
772
|
|
|
@@ -1308,7 +777,7 @@ Goal tools (`goal_create`, `goal_update`, `goal_status`) are available during **
|
|
|
1308
777
|
5. **Recently used tools**: Tools used in recent calls are re-included to maintain continuity
|
|
1309
778
|
6. **Mailbox management tools**: `defer_mailbox_item`, `drop_mailbox_item`,
|
|
1310
779
|
`prioritize_mailbox_item` — registered for all agents, available during
|
|
1311
|
-
|
|
780
|
+
every scenario, including heartbeat patrols and focused processing.
|
|
1312
781
|
7. **Activated tools**: Tools the agent explicitly activated via `discover_tools`
|
|
1313
782
|
8. **Skill-provided tools**: MCP tools from activated skills
|
|
1314
783
|
9. **`discover_tools` meta-tool**: Always present, enabling agents to list/activate/install skills at runtime
|
|
@@ -1365,13 +834,15 @@ For Claude Opus 4.x and Sonnet 4.x models, Anthropic's server-side `compact_2026
|
|
|
1365
834
|
|
|
1366
835
|
| Document | Relationship |
|
|
1367
836
|
|----------|-------------|
|
|
1368
|
-
| [
|
|
1369
|
-
| [
|
|
1370
|
-
| [
|
|
837
|
+
| [context-assembly.md](./context-assembly.md) | **Split out of this document 2026-11-15** (§3): message assembly, token budget, compression pipeline, ContextOS fixed/variable split & SLOT anchors, compaction defects and root causes |
|
|
838
|
+
| [tool-loop-harness.md](./tool-loop-harness.md) | **Split out of this document 2026-11-15** (§4 + §5): tool-loop harness, loop detection, scenario-specific assembly, scenario × context matrix, scenario × tool face, async callback replay |
|
|
839
|
+
| [state-machines.md](./state-machines.md) | Task state transitions trigger different LLM call paths ([tool-loop-harness.md](./tool-loop-harness.md) §5.2 task execution, §5.3 heartbeat review) |
|
|
840
|
+
| [memory-system.md](./memory-system.md) | Notebook + `knowledge.md` layers (`state.md` retired 2026-09-16); `## Your Knowledge` and `## Notebook` in prompts; consolidation ([tool-loop-harness.md](./tool-loop-harness.md) §5.6-5.8) |
|
|
841
|
+
| [cognitive-architecture.md](./cognitive-architecture.md) | Deterministic context assembly ([context-assembly.md](./context-assembly.md) §3); CPP and its depth levels removed |
|
|
1371
842
|
| `packages/core/src/agent.ts` | Implementation of all 8 LLM call scenarios and 4 harness variants |
|
|
1372
843
|
| `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) |
|
|
844
|
+
| `packages/core/src/context-slot.ts` | SLOT segment model: `SlotEntry` / `SlotsStore` / `buildSlotSegment()` — the never-compacted anchors ([context-assembly.md](./context-assembly.md) §3.7) |
|
|
845
|
+
| `packages/core/src/tools/session.ts` | Session 10-op tool family (compact/pin/include/retrieve…) + `checkOwnership` ([context-assembly.md](./context-assembly.md) §3.7) |
|
|
1375
846
|
| `packages/core/src/llm/router.ts` | Provider routing, circuit breaker, model catalog, output token resolution |
|
|
1376
847
|
| `packages/core/src/tool-selector.ts` | Tool selection logic |
|
|
1377
|
-
| ~~`context-os.md`~~ | **Merged into
|
|
848
|
+
| ~~`context-os.md`~~ | **Merged into [context-assembly.md](./context-assembly.md) §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. |
|