@markus-global/cli 0.11.0 → 0.11.2-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/commands/start.d.ts.map +1 -1
  2. package/dist/commands/start.js +0 -9
  3. package/dist/commands/start.js.map +1 -1
  4. package/dist/markus.mjs +1625 -742
  5. package/dist/web-ui/assets/{CommentInput-DD_rURUZ.js → CommentInput-Cqi5Hldw.js} +1 -1
  6. package/dist/web-ui/assets/{ContentRenderer-DL4CN5a7.js → ContentRenderer-BAB3il9e.js} +2 -2
  7. package/dist/web-ui/assets/{DeliverableShareModal-CA94fQ6t.js → DeliverableShareModal-DJXkM66x.js} +1 -1
  8. package/dist/web-ui/assets/{Deliverables-CVXKnarN.js → Deliverables-zKPxgZAN.js} +1 -1
  9. package/dist/web-ui/assets/{Notifications-BSIjXIB2.js → Notifications-HAycgg2x.js} +1 -1
  10. package/dist/web-ui/assets/{Search-CHu38tSq.js → Search-SZuDcxy0.js} +1 -1
  11. package/dist/web-ui/assets/Settings-CZgNsYSC.js +8 -0
  12. package/dist/web-ui/assets/{Store-COP7-vkU.js → Store-BS7VNrsr.js} +1 -1
  13. package/dist/web-ui/assets/Team-B6vw2Oj5.js +84 -0
  14. package/dist/web-ui/assets/{Work-CgX3_06k.js → Work-BN-LsW3k.js} +1 -1
  15. package/dist/web-ui/assets/{arc-Bg5CJocT.js → arc-CsnWE2QW.js} +1 -1
  16. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-DawJCAej.js → architectureDiagram-3BPJPVTR-CLek8I2z.js} +1 -1
  17. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-ZqMoGvfv.js → blockDiagram-GPEHLZMM-jSgWEHN7.js} +1 -1
  18. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-J4ibZgWS.js → c4Diagram-AAUBKEIU-BaC188UT.js} +1 -1
  19. package/dist/web-ui/assets/channel-CqbBz9iL.js +1 -0
  20. package/dist/web-ui/assets/{chunk-2J33WTMH-ChOj8jk6.js → chunk-2J33WTMH-CdtP4-T4.js} +1 -1
  21. package/dist/web-ui/assets/{chunk-4BX2VUAB-Dir-D5hS.js → chunk-4BX2VUAB-BSgBKyC9.js} +1 -1
  22. package/dist/web-ui/assets/{chunk-55IACEB6-C18FzAkt.js → chunk-55IACEB6-XB_ZMqfw.js} +1 -1
  23. package/dist/web-ui/assets/{chunk-727SXJPM-DU4-VKO-.js → chunk-727SXJPM-YFPBFW4M.js} +1 -1
  24. package/dist/web-ui/assets/{chunk-AQP2D5EJ-Dl-u5apY.js → chunk-AQP2D5EJ-CDbFN1Un.js} +1 -1
  25. package/dist/web-ui/assets/{chunk-FMBD7UC4-lI8cDDzS.js → chunk-FMBD7UC4-BGKt8xP8.js} +1 -1
  26. package/dist/web-ui/assets/{chunk-ND2GUHAM-CVITQFgK.js → chunk-ND2GUHAM-DKicpX2b.js} +1 -1
  27. package/dist/web-ui/assets/{chunk-QZHKN3VN-DT0Z-Y7D.js → chunk-QZHKN3VN-BD4tv8RZ.js} +1 -1
  28. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-DDQJP38f.js +1 -0
  29. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-DDQJP38f.js +1 -0
  30. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-e0DTysr0.js → cose-bilkent-S5V4N54A-BjOoIarG.js} +1 -1
  31. package/dist/web-ui/assets/{dagre-BM42HDAG-B7SXE46x.js → dagre-BM42HDAG-BWal5GOH.js} +1 -1
  32. package/dist/web-ui/assets/{diagram-2AECGRRQ-D18E4VJp.js → diagram-2AECGRRQ-CJj-CzRg.js} +1 -1
  33. package/dist/web-ui/assets/{diagram-5GNKFQAL-BV5eG_wQ.js → diagram-5GNKFQAL-4IMjuEPm.js} +1 -1
  34. package/dist/web-ui/assets/{diagram-KO2AKTUF-DcghAM6V.js → diagram-KO2AKTUF-DQiRAfss.js} +1 -1
  35. package/dist/web-ui/assets/{diagram-LMA3HP47-Bucs338Z.js → diagram-LMA3HP47-BMPvbEbY.js} +1 -1
  36. package/dist/web-ui/assets/{diagram-OG6HWLK6-CsBqS8rc.js → diagram-OG6HWLK6-D5_vmdXl.js} +1 -1
  37. package/dist/web-ui/assets/{docx-preview-COrTZlTm.js → docx-preview-Cdouj_6e.js} +1 -1
  38. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-CkTtYa1F.js → erDiagram-TEJ5UH35-DOnDuvXd.js} +1 -1
  39. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-BGu3cWC4.js → flowDiagram-I6XJVG4X-DL6G76eC.js} +1 -1
  40. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-Bja9GKgP.js → ganttDiagram-6RSMTGT7-CwHnuRR8.js} +1 -1
  41. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-CCcnEeV5.js → gitGraphDiagram-PVQCEYII-BFUnsmW_.js} +1 -1
  42. package/dist/web-ui/assets/index-3PQIqBtv.css +1 -0
  43. package/dist/web-ui/assets/{index-Cfoh0Mcj.js → index-BSktaJwx.js} +71 -71
  44. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-BE95DmBY.js → infoDiagram-5YYISTIA-DhU1bQNw.js} +1 -1
  45. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-BlqFOGrb.js → ishikawaDiagram-YF4QCWOH-o6ujfUJF.js} +1 -1
  46. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-cmEbyfXZ.js → journeyDiagram-JHISSGLW-Dx_SZ8zv.js} +1 -1
  47. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-CF310DyR.js → kanban-definition-UN3LZRKU-D4BWXcIn.js} +1 -1
  48. package/dist/web-ui/assets/{mermaid.core-BHixne0g.js → mermaid.core-BHDulYyB.js} +5 -5
  49. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-AhUT5u2O.js → mindmap-definition-RKZ34NQL-BVy6py_h.js} +1 -1
  50. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-BTMsfIc7.js → pieDiagram-4H26LBE5-CUr5__J1.js} +1 -1
  51. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-BUX6sxIv.js → quadrantDiagram-W4KKPZXB-C5Owt_r4.js} +1 -1
  52. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-OlQTxuLJ.js → requirementDiagram-4Y6WPE33-Bb933lBb.js} +1 -1
  53. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-DESVEkFB.js → sankeyDiagram-5OEKKPKP-CJq-boMJ.js} +1 -1
  54. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-_55AKRLt.js → sequenceDiagram-3UESZ5HK-BP8L47v3.js} +1 -1
  55. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DWoVTo_b.js → stateDiagram-AJRCARHV-Byk9-Yrm.js} +1 -1
  56. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-CWa-Q2Gf.js +1 -0
  57. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-Cfzp_g3K.js → timeline-definition-PNZ67QCA-2z8RR-l_.js} +1 -1
  58. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-D7bha1C9.js → vennDiagram-CIIHVFJN-CSwDDhHv.js} +1 -1
  59. package/dist/web-ui/assets/{wardley-L42UT6IY-B1fPVVfR.js → wardley-L42UT6IY-DW30MdHd.js} +1 -1
  60. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-D4g5vAsu.js → wardleyDiagram-YWT4CUSO-DUb2r21l.js} +1 -1
  61. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-BLPxDXtu.js → xychartDiagram-2RQKCTM6-4DTcVUL8.js} +1 -1
  62. package/dist/web-ui/index.html +2 -2
  63. package/package.json +1 -1
  64. package/dist/web-ui/assets/Settings-dRGc1-cI.js +0 -8
  65. package/dist/web-ui/assets/Team-D3bZCMAY.js +0 -84
  66. package/dist/web-ui/assets/channel-Dpx2_w7L.js +0 -1
  67. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-DrvFH67-.js +0 -1
  68. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-DrvFH67-.js +0 -1
  69. package/dist/web-ui/assets/index-DxPx73Ja.css +0 -1
  70. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-DylgAjTF.js +0 -1
package/dist/markus.mjs CHANGED
@@ -3890,6 +3890,21 @@ var init_mailbox = __esm({
3890
3890
  }
3891
3891
  });
3892
3892
 
3893
+ // ../shared/dist/utils/literal-replace.js
3894
+ function replaceLiteral(content, search, replacement) {
3895
+ return content.replace(search, () => replacement);
3896
+ }
3897
+ function replaceAllLiteral(content, search, replacement) {
3898
+ if (search === "")
3899
+ return content;
3900
+ return content.split(search).join(replacement);
3901
+ }
3902
+ var init_literal_replace = __esm({
3903
+ "../shared/dist/utils/literal-replace.js"() {
3904
+ "use strict";
3905
+ }
3906
+ });
3907
+
3893
3908
  // ../shared/dist/types/workflow-template.js
3894
3909
  function validateWorkflowTemplate(template) {
3895
3910
  const errors = [];
@@ -4037,12 +4052,12 @@ function detectCycles(steps) {
4037
4052
  function renderStepPrompt(step, params, runNumber) {
4038
4053
  let prompt = step.prompt;
4039
4054
  for (const [key2, value] of Object.entries(params)) {
4040
- prompt = prompt.replaceAll(`{{${key2}}}`, value);
4055
+ prompt = replaceAllLiteral(prompt, `{{${key2}}}`, value);
4041
4056
  }
4042
4057
  const now3 = /* @__PURE__ */ new Date();
4043
- prompt = prompt.replaceAll("{{date}}", formatDate(now3));
4044
- prompt = prompt.replaceAll("{{time}}", formatDateTime(now3));
4045
- prompt = prompt.replaceAll("{{run_number}}", String(runNumber));
4058
+ prompt = replaceAllLiteral(prompt, "{{date}}", formatDate(now3));
4059
+ prompt = replaceAllLiteral(prompt, "{{time}}", formatDateTime(now3));
4060
+ prompt = replaceAllLiteral(prompt, "{{run_number}}", String(runNumber));
4046
4061
  if (step.inputs && step.inputs.length > 0) {
4047
4062
  const inputContext = step.inputs.map((inp) => `## Upstream output: ${inp.as}
4048
4063
  From step: ${inp.from}
@@ -4122,6 +4137,7 @@ var INTERVAL_RE, INTERVAL_MULTIPLIERS;
4122
4137
  var init_workflow_template = __esm({
4123
4138
  "../shared/dist/types/workflow-template.js"() {
4124
4139
  "use strict";
4140
+ init_literal_replace();
4125
4141
  INTERVAL_RE = /^(\d+)(s|m|h|d|w)$/;
4126
4142
  INTERVAL_MULTIPLIERS = {
4127
4143
  s: 1e3,
@@ -4133,20 +4149,6 @@ var init_workflow_template = __esm({
4133
4149
  }
4134
4150
  });
4135
4151
 
4136
- // ../shared/dist/types/cognitive.js
4137
- var CognitiveDepth;
4138
- var init_cognitive = __esm({
4139
- "../shared/dist/types/cognitive.js"() {
4140
- "use strict";
4141
- (function(CognitiveDepth2) {
4142
- CognitiveDepth2[CognitiveDepth2["D0_Reflexive"] = 0] = "D0_Reflexive";
4143
- CognitiveDepth2[CognitiveDepth2["D1_Reactive"] = 1] = "D1_Reactive";
4144
- CognitiveDepth2[CognitiveDepth2["D2_Deliberative"] = 2] = "D2_Deliberative";
4145
- CognitiveDepth2[CognitiveDepth2["D3_MetaCognitive"] = 3] = "D3_MetaCognitive";
4146
- })(CognitiveDepth || (CognitiveDepth = {}));
4147
- }
4148
- });
4149
-
4150
4152
  // ../shared/dist/types/model-catalog.js
4151
4153
  var MODEL_CAPABILITY_TYPES;
4152
4154
  var init_model_catalog = __esm({
@@ -5416,12 +5418,8 @@ var init_update_checker = __esm({
5416
5418
  });
5417
5419
 
5418
5420
  // ../shared/dist/limits.js
5419
- function hasCompletionMarker(reply) {
5420
- const outside = reply.replace(/<think>[\s\S]*?<\/think>/g, "");
5421
- return outside.includes(COMPLETION_MARKER);
5422
- }
5423
- function stripCompletionMarkerLeak(text) {
5424
- return text.replace(COMPLETION_MARKER_LEAK_RE, "");
5421
+ function stripLegacyCompletionToken(text) {
5422
+ return text.replace(LEGACY_COMPLETION_TOKEN_RE, "");
5425
5423
  }
5426
5424
  function withJitter(baseMs, factor = 0.2) {
5427
5425
  const jitter = baseMs * factor * (2 * Math.random() - 1);
@@ -5432,7 +5430,7 @@ function clampHeartbeatIntervalMs(ms) {
5432
5430
  return DEFAULT_HEARTBEAT_INTERVAL_MS;
5433
5431
  return Math.max(MIN_HEARTBEAT_INTERVAL_MS, Math.min(MAX_HEARTBEAT_INTERVAL_MS, Math.round(ms)));
5434
5432
  }
5435
- var TASK_GET_NOTES_DEFAULT, TASK_GET_DELIVERABLES_DEFAULT, TASK_GET_STATUS_HISTORY_DEFAULT, REQUIREMENT_LIST_DEFAULT, ENTITY_COMMENTS_DEFAULT, PROMPT_TASK_NOTES_MAX, PROMPT_TASK_NOTE_CHARS, PROMPT_DEP_NOTES_MAX, PROMPT_DEP_NOTE_CHARS, PROMPT_DEP_DESC_CHARS, PROMPT_EXECUTION_ROUNDS_MAX, PROMPT_LOG_ENTRY_CHARS, PROMPT_RECENT_ERRORS_MAX, PROMPT_HUMAN_COMMENTS_MAX, REVIEWER_NOTES_MAX, SYSTEM_MY_TASKS_MAX, SYSTEM_TEAM_TASKS_MAX, SYSTEM_TASK_DESC_CHARS, PROMPT_PROJECT_DESC_CHARS, PROMPT_REQUIREMENT_DESC_CHARS, REVIEWER_FILE_LIST_MAX, DELIVERABLE_TITLE_CHARS, REVISION_REASON_CHARS, TASK_MAX_RETRIES, MAILBOX_ITEM_MAX_RETRIES, COMPLETION_MARKER, COMPLETION_MARKER_INSTRUCTION, COMPLETION_MARKER_LEAK_RE, TASK_MAX_NO_SUBMIT_RETRIES, TASK_RETRY_DELAYS_MS, PREEMPT_REQUEUE_DELAY_MS, SYSTEM_KNOWLEDGE_CHARS, SYSTEM_SOPS_CHARS, SYSTEM_LONGTERM_MEMORY_CHARS, MEMORY_MD_SECTION_MAX_CHARS, MEMORY_MD_TOTAL_MAX_CHARS, MEMORY_OBSERVATIONS_MAX_CHARS, KNOWLEDGE_SECTION_KEY_MAX_CHARS, KNOWLEDGE_STUB_MAX_CHARS, MEMORY_ENTRY_MAX_CHARS, KNOWLEDGE_MD_SELF_HEAL_BYTES, SYSTEM_LESSON_ENTRIES_MAX, SYSTEM_BEST_PRACTICE_ENTRIES_MAX, SYSTEM_DELIVERABLES_CHARS, SYSTEM_DAILY_LOG_CHARS, SYSTEM_DAILY_LOG_DAYS, SYSTEM_USER_PROFILE_CHARS, SYSTEM_CHAT_SESSIONS_MAX, HEARTBEAT_DAILY_LOG_CHARS, SYSTEM_PROJECT_DESC_CHARS, SYSTEM_DELIVERABLE_PREVIEW_CHARS, SYSTEM_MAILBOX_MERGED_CHARS, SYSTEM_MAILBOX_ITEM_PREVIEW_CHARS, TASK_LIST_PAGE_SIZE, TASK_LIST_PAGE_MAX, ARCHIVE_COMPLETED_AFTER_DAYS, ARCHIVE_TERMINAL_AFTER_DAYS, ARCHIVE_REQUIREMENT_AFTER_DAYS, ARCHIVE_SCAN_INTERVAL_MS, CHANNEL_CONTEXT_MESSAGES, CHANNEL_CONTEXT_MSG_CHARS, SYSTEM_CONTEXT_MD_CHARS, SYSTEM_TEAM_PROJECT_DESC_CHARS, MAILBOX_QUEUED_TTL_MS, MAILBOX_COALESCE_WINDOW_MS, MAILBOX_PROCESSING_TIMEOUT_MS, BACKSTOP_CANCEL_GRACE_MS, SSE_DISCONNECT_FORCE_STOP_MS, WATCHDOG_INTERVAL_MS, WATCHDOG_DRIFT_THRESHOLD_MS, TRIAGE_BACKLOG_THRESHOLD, TRIAGE_PROMPT_MAX_ITEMS, TRIAGE_MAX_TOKENS, TRIAGE_TEMPERATURE, TRIAGE_CONTEXT_MESSAGES_MAX, TRIAGE_CONTEXT_MSG_CHARS, TRIAGE_ITEM_CONTENT_CHARS, TRIAGE_STALE_INFO_TTL_MS, TRIAGE_STALE_DROP_TYPES, TRIAGE_MAX_TOOL_ITERATIONS, TRIAGE_ALLOWED_TOOLS, DELIBERATION_ALLOWED_TOOLS, DEFAULT_HEARTBEAT_INTERVAL_MS, MIN_HEARTBEAT_INTERVAL_MS, MAX_HEARTBEAT_INTERVAL_MS, NOTEBOOK_MAX_ENTRIES, NOTEBOOK_MAX_AGENT_ENTRIES, NOTEBOOK_MAX_CHARS_PER_ENTRY, NOTEBOOK_PROMPT_MAX_CHARS, NOTEBOOK_TTL_MS_AGENT, NOTEBOOK_TTL_MS_SYSTEM, NOTEBOOK_KEY_MAX_CHARS, NOTEBOOK_RELEVANT_CONTEXT_MAX_CHARS, NOTEBOOK_PERSIST_MAX_WAIT_MS, WORKING_MEMORY_MAX_ENTRIES, WORKING_MEMORY_MAX_CHARS, SUBAGENT_TASK_PREVIEW_CHARS, SUBAGENT_THINKING_PREVIEW_CHARS, SUBAGENT_RESULT_PREVIEW_CHARS, SUBAGENT_LOG_ENTRY_CHARS, SUBAGENT_ERROR_PREVIEW_CHARS, SUBAGENT_MAX_PARALLEL, SUBAGENT_MAX_AGGREGATE_ITERATIONS, SUBAGENT_MAX_LLM_RETRIES, SUBAGENT_RETRY_BASE_MS, SHELL_TIMEOUT_DEFAULT_MS, SHELL_TIMEOUT_MAX_MS, SHELL_MAX_SESSIONS_PER_AGENT, SHELL_SESSION_IDLE_TIMEOUT_MS, SHELL_SESSION_MAX_OUTPUT_BYTES, APPROVAL_WAIT_TIMEOUT_MS, HEARTBEAT_MIN_INITIAL_DELAY_MS, HEARTBEAT_STARTUP_JITTER_MS, LLM_CIRCUIT_RESET_RATE_LIMIT_MS, SESSION_STORAGE_COMPACT_TRIGGER, SESSION_STORAGE_COMPACT_KEEP, SESSION_STORAGE_TOOL_SHRINK_CHARS, SESSION_REQUEST_HISTORY_MIN, SESSION_REQUEST_HISTORY_BLOCK, CONTEXT_ABSURD_MESSAGE_CHARS, CONTEXT_PROACTIVE_COMPACT_RATIO, CONTEXT_WARN_RATIO, CONTEXT_CRIT_RATIO, CONTEXT_SLOT_MAX_CHARS, CONTEXT_VOLATILE_REARM_CALLS, CONTEXT_ABS_HISTORY_TOKENS, CONTEXT_ABS_HISTORY_TARGET_TOKENS, SESSION_RESTORE_MAX_MESSAGES, SESSION_RESTORE_MAX_MESSAGE_TOKENS, TOOL_RESULT_OFFLOAD_CHARS, SYSTEM_COLLEAGUES_MAX, SYSTEM_OTHER_TEAMS_MAX, SYSTEM_OTHER_TEAM_MEMBERS_MAX, SYSTEM_HUMANS_MAX, PROMPT_AFFORD_OUTPUT_RESERVE, TOOL_DEF_BUDGET_REFLEX, TOOL_DEF_BUDGET_CONVERSE, TOOL_DEF_BUDGET_EXECUTE, TOOL_DEF_BUDGET_GOVERN, ROLE_PROMPT_MAX_TOKENS, KNOWLEDGE_PROMPT_MAX_TOKENS, KNOWLEDGE_PROMPT_MAX_TOKENS_CONVERSE, KNOWLEDGE_PROMPT_MAX_TOKENS_REFLEX, COLD_CONVERSE_FIXED_MAX, COLD_REFLEX_FIXED_MAX, SYSTEM_PROMPT_BUDGET_CONVERSE, SYSTEM_ANNOUNCEMENTS_CHARS_CONVERSE, SYSTEM_NORMS_CHARS_CONVERSE, SYSTEM_ANNOUNCEMENTS_CHARS, SYSTEM_NORMS_CHARS, SYSTEM_WORKFLOWS_MAX_CONVERSE, SYSTEM_WORKFLOW_DESC_CHARS_CONVERSE, SYSTEM_DYNAMIC_CONTEXT_CHARS_CONVERSE, DEFERRED_CATALOG_MAX_CHARS, MAX_TOKENS_AFFORD_SAFETY, MAX_TOKENS_REMAINING_MARGIN, MAX_TOKENS_CLAMP_FLOOR, DEEP_SLEEP_IDLE_HEARTBEATS, SUBTASK_SOFT_CAP, PROMPT_AFFORD_SAFETY_MARGIN, LLM_MAX_CONCURRENT_PER_PROVIDER, LLM_CONCURRENCY_JITTER_BASE_MS;
5433
+ var TASK_GET_NOTES_DEFAULT, TASK_GET_DELIVERABLES_DEFAULT, TASK_GET_STATUS_HISTORY_DEFAULT, REQUIREMENT_LIST_DEFAULT, ENTITY_COMMENTS_DEFAULT, PROMPT_TASK_NOTES_MAX, PROMPT_TASK_NOTE_CHARS, PROMPT_DEP_NOTES_MAX, PROMPT_DEP_NOTE_CHARS, PROMPT_DEP_DESC_CHARS, PROMPT_EXECUTION_ROUNDS_MAX, PROMPT_LOG_ENTRY_CHARS, PROMPT_RECENT_ERRORS_MAX, PROMPT_HUMAN_COMMENTS_MAX, REVIEWER_NOTES_MAX, SYSTEM_MY_TASKS_MAX, SYSTEM_TEAM_TASKS_MAX, SYSTEM_TASK_DESC_CHARS, PROMPT_PROJECT_DESC_CHARS, PROMPT_REQUIREMENT_DESC_CHARS, REVIEWER_FILE_LIST_MAX, DELIVERABLE_TITLE_CHARS, REVISION_REASON_CHARS, TASK_MAX_RETRIES, MAILBOX_ITEM_MAX_RETRIES, END_TURN_REPLY_SENTINEL, LEGACY_COMPLETION_TOKEN_RE, TASK_MAX_NO_SUBMIT_RETRIES, TASK_RETRY_DELAYS_MS, PREEMPT_REQUEUE_DELAY_MS, SYSTEM_KNOWLEDGE_CHARS, SYSTEM_SOPS_CHARS, SYSTEM_LONGTERM_MEMORY_CHARS, MEMORY_MD_SECTION_MAX_CHARS, MEMORY_MD_CURATED_MAX_CHARS, MEMORY_MD_CURATED_HARD_MAX_CHARS, MEMORY_HEALTH_WARN_PERCENT, MEMORY_DREAM_TRIGGER_PERCENT, MEMORY_DREAM_MIN_ENTRIES, MEMORY_HEALTH_CRITICAL_PERCENT, MEMORY_OBSERVATIONS_MAX_CHARS, MEMORY_OBSERVATIONS_HARD_MAX_CHARS, MEMORY_FRAGMENTS_MAX_CHARS, KNOWLEDGE_SECTION_KEY_MAX_CHARS, KNOWLEDGE_STUB_MAX_CHARS, MEMORY_ENTRY_MAX_CHARS, KNOWLEDGE_MD_SELF_HEAL_BYTES, SYSTEM_LESSON_ENTRIES_MAX, SYSTEM_BEST_PRACTICE_ENTRIES_MAX, SYSTEM_DELIVERABLES_CHARS, SYSTEM_DAILY_LOG_CHARS, SYSTEM_DAILY_LOG_DAYS, SYSTEM_USER_PROFILE_CHARS, SYSTEM_CHAT_SESSIONS_MAX, HEARTBEAT_DAILY_LOG_CHARS, SYSTEM_PROJECT_DESC_CHARS, SYSTEM_DELIVERABLE_PREVIEW_CHARS, SYSTEM_MAILBOX_MERGED_CHARS, SYSTEM_MAILBOX_ITEM_PREVIEW_CHARS, TASK_LIST_PAGE_SIZE, TASK_LIST_PAGE_MAX, ARCHIVE_COMPLETED_AFTER_DAYS, ARCHIVE_TERMINAL_AFTER_DAYS, ARCHIVE_REQUIREMENT_AFTER_DAYS, ARCHIVE_SCAN_INTERVAL_MS, CHANNEL_CONTEXT_MESSAGES, CHANNEL_CONTEXT_MSG_CHARS, SYSTEM_CONTEXT_MD_CHARS, SYSTEM_TEAM_PROJECT_DESC_CHARS, MAILBOX_QUEUED_TTL_MS, MAILBOX_COALESCE_WINDOW_MS, MAILBOX_PROCESSING_TIMEOUT_MS, BACKSTOP_CANCEL_GRACE_MS, SSE_DISCONNECT_FORCE_STOP_MS, WATCHDOG_INTERVAL_MS, WATCHDOG_DRIFT_THRESHOLD_MS, TRIAGE_BACKLOG_THRESHOLD, TRIAGE_PROMPT_MAX_ITEMS, TRIAGE_MAX_TOKENS, TRIAGE_TEMPERATURE, TRIAGE_CONTEXT_MESSAGES_MAX, TRIAGE_CONTEXT_MSG_CHARS, TRIAGE_ITEM_CONTENT_CHARS, TRIAGE_STALE_INFO_TTL_MS, TRIAGE_STALE_DROP_TYPES, TRIAGE_MAX_TOOL_ITERATIONS, TRIAGE_ALLOWED_TOOLS, DELIBERATION_ALLOWED_TOOLS, DEFAULT_HEARTBEAT_INTERVAL_MS, MIN_HEARTBEAT_INTERVAL_MS, MAX_HEARTBEAT_INTERVAL_MS, NOTEBOOK_MAX_ENTRIES, NOTEBOOK_MAX_AGENT_ENTRIES, NOTEBOOK_MAX_CHARS_PER_ENTRY, NOTEBOOK_PROMPT_MAX_CHARS, NOTEBOOK_TTL_MS_AGENT, NOTEBOOK_TTL_MS_SYSTEM, NOTEBOOK_KEY_MAX_CHARS, NOTEBOOK_RELEVANT_CONTEXT_MAX_CHARS, NOTEBOOK_PERSIST_MAX_WAIT_MS, WORKING_MEMORY_MAX_ENTRIES, WORKING_MEMORY_MAX_CHARS, SUBAGENT_TASK_PREVIEW_CHARS, SUBAGENT_THINKING_PREVIEW_CHARS, SUBAGENT_RESULT_PREVIEW_CHARS, SUBAGENT_LOG_ENTRY_CHARS, SUBAGENT_ERROR_PREVIEW_CHARS, SUBAGENT_MAX_PARALLEL, SUBAGENT_MAX_AGGREGATE_ITERATIONS, SUBAGENT_MAX_LLM_RETRIES, SUBAGENT_RETRY_BASE_MS, SHELL_TIMEOUT_DEFAULT_MS, SHELL_TIMEOUT_MAX_MS, SHELL_MAX_SESSIONS_PER_AGENT, SHELL_SESSION_IDLE_TIMEOUT_MS, SHELL_SESSION_MAX_OUTPUT_BYTES, APPROVAL_WAIT_TIMEOUT_MS, HEARTBEAT_MIN_INITIAL_DELAY_MS, HEARTBEAT_STARTUP_JITTER_MS, LLM_CIRCUIT_RESET_RATE_LIMIT_MS, SESSION_STORAGE_COMPACT_TRIGGER, SESSION_STORAGE_COMPACT_KEEP, SESSION_STORAGE_TOOL_SHRINK_CHARS, SESSION_REQUEST_HISTORY_MIN, SESSION_REQUEST_HISTORY_BLOCK, CONTEXT_ABSURD_MESSAGE_CHARS, CONTEXT_PROACTIVE_COMPACT_RATIO, CONTEXT_WARN_RATIO, CONTEXT_CRIT_RATIO, CONTEXT_SLOT_MAX_CHARS, CONTEXT_VOLATILE_REARM_CALLS, CONTEXT_ABS_HISTORY_TOKENS, CONTEXT_ABS_HISTORY_TARGET_TOKENS, SESSION_RESTORE_MAX_MESSAGES, SESSION_RESTORE_MAX_MESSAGE_TOKENS, TOOL_RESULT_OFFLOAD_CHARS, SYSTEM_COLLEAGUES_MAX, SYSTEM_OTHER_TEAMS_MAX, SYSTEM_OTHER_TEAM_MEMBERS_MAX, SYSTEM_HUMANS_MAX, PROMPT_AFFORD_OUTPUT_RESERVE, TOOL_DEF_BUDGET_REFLEX, TOOL_DEF_BUDGET_CONVERSE, TOOL_DEF_BUDGET_EXECUTE, TOOL_DEF_BUDGET_GOVERN, ROLE_PROMPT_MAX_TOKENS, KNOWLEDGE_PROMPT_MAX_TOKENS, KNOWLEDGE_PROMPT_MAX_TOKENS_CONVERSE, KNOWLEDGE_PROMPT_MAX_TOKENS_REFLEX, COLD_CONVERSE_FIXED_MAX, COLD_REFLEX_FIXED_MAX, SYSTEM_PROMPT_BUDGET_CONVERSE, SYSTEM_ANNOUNCEMENTS_CHARS_CONVERSE, SYSTEM_NORMS_CHARS_CONVERSE, SYSTEM_ANNOUNCEMENTS_CHARS, SYSTEM_NORMS_CHARS, SYSTEM_WORKFLOWS_MAX_CONVERSE, SYSTEM_WORKFLOW_DESC_CHARS_CONVERSE, SYSTEM_DYNAMIC_CONTEXT_CHARS_CONVERSE, DEFERRED_CATALOG_MAX_CHARS, MAX_TOKENS_AFFORD_SAFETY, MAX_TOKENS_REMAINING_MARGIN, MAX_TOKENS_CLAMP_FLOOR, DEEP_SLEEP_IDLE_HEARTBEATS, SUBTASK_SOFT_CAP, PROMPT_AFFORD_SAFETY_MARGIN, LLM_MAX_CONCURRENT_PER_PROVIDER, LLM_CONCURRENCY_JITTER_BASE_MS;
5436
5434
  var init_limits = __esm({
5437
5435
  "../shared/dist/limits.js"() {
5438
5436
  "use strict";
@@ -5461,11 +5459,8 @@ var init_limits = __esm({
5461
5459
  REVISION_REASON_CHARS = 200;
5462
5460
  TASK_MAX_RETRIES = 3;
5463
5461
  MAILBOX_ITEM_MAX_RETRIES = 2;
5464
- COMPLETION_MARKER = "<<HANDLE_COMPLETE>>";
5465
- COMPLETION_MARKER_INSTRUCTION = `
5466
-
5467
- [IMPORTANT: When you have finished processing this request, you MUST end your final response with the exact token: ${COMPLETION_MARKER}]`;
5468
- COMPLETION_MARKER_LEAK_RE = /<{1,2}\s*HANDLE_COMPLETE\s*>{1,2}/gi;
5462
+ END_TURN_REPLY_SENTINEL = "[end_turn]";
5463
+ LEGACY_COMPLETION_TOKEN_RE = /<{1,2}\s*HANDLE_COMPLETE\s*>{1,2}/gi;
5469
5464
  TASK_MAX_NO_SUBMIT_RETRIES = 8;
5470
5465
  TASK_RETRY_DELAYS_MS = [3e4, 6e4, 12e4, 24e4, 48e4, 6e5];
5471
5466
  PREEMPT_REQUEUE_DELAY_MS = 3e3;
@@ -5473,8 +5468,15 @@ var init_limits = __esm({
5473
5468
  SYSTEM_SOPS_CHARS = 3e3;
5474
5469
  SYSTEM_LONGTERM_MEMORY_CHARS = 5e3;
5475
5470
  MEMORY_MD_SECTION_MAX_CHARS = 3e3;
5476
- MEMORY_MD_TOTAL_MAX_CHARS = 15e3;
5471
+ MEMORY_MD_CURATED_MAX_CHARS = 15e3;
5472
+ MEMORY_MD_CURATED_HARD_MAX_CHARS = 3 * MEMORY_MD_CURATED_MAX_CHARS;
5473
+ MEMORY_HEALTH_WARN_PERCENT = 70;
5474
+ MEMORY_DREAM_TRIGGER_PERCENT = MEMORY_HEALTH_WARN_PERCENT;
5475
+ MEMORY_DREAM_MIN_ENTRIES = 50;
5476
+ MEMORY_HEALTH_CRITICAL_PERCENT = 90;
5477
5477
  MEMORY_OBSERVATIONS_MAX_CHARS = 3e4;
5478
+ MEMORY_OBSERVATIONS_HARD_MAX_CHARS = 2e5;
5479
+ MEMORY_FRAGMENTS_MAX_CHARS = 6e4;
5478
5480
  KNOWLEDGE_SECTION_KEY_MAX_CHARS = 64;
5479
5481
  KNOWLEDGE_STUB_MAX_CHARS = 400;
5480
5482
  MEMORY_ENTRY_MAX_CHARS = 4e3;
@@ -5752,8 +5754,6 @@ __export(dist_exports, {
5752
5754
  CLI_EXIT_CODES: () => CLI_EXIT_CODES,
5753
5755
  COLD_CONVERSE_FIXED_MAX: () => COLD_CONVERSE_FIXED_MAX,
5754
5756
  COLD_REFLEX_FIXED_MAX: () => COLD_REFLEX_FIXED_MAX,
5755
- COMPLETION_MARKER: () => COMPLETION_MARKER,
5756
- COMPLETION_MARKER_INSTRUCTION: () => COMPLETION_MARKER_INSTRUCTION,
5757
5757
  CONTEXT_ABSURD_MESSAGE_CHARS: () => CONTEXT_ABSURD_MESSAGE_CHARS,
5758
5758
  CONTEXT_ABS_HISTORY_TARGET_TOKENS: () => CONTEXT_ABS_HISTORY_TARGET_TOKENS,
5759
5759
  CONTEXT_ABS_HISTORY_TOKENS: () => CONTEXT_ABS_HISTORY_TOKENS,
@@ -5762,12 +5762,12 @@ __export(dist_exports, {
5762
5762
  CONTEXT_SLOT_MAX_CHARS: () => CONTEXT_SLOT_MAX_CHARS,
5763
5763
  CONTEXT_VOLATILE_REARM_CALLS: () => CONTEXT_VOLATILE_REARM_CALLS,
5764
5764
  CONTEXT_WARN_RATIO: () => CONTEXT_WARN_RATIO,
5765
- CognitiveDepth: () => CognitiveDepth,
5766
5765
  DEEP_SLEEP_IDLE_HEARTBEATS: () => DEEP_SLEEP_IDLE_HEARTBEATS,
5767
5766
  DEFAULT_HEARTBEAT_INTERVAL_MS: () => DEFAULT_HEARTBEAT_INTERVAL_MS,
5768
5767
  DEFERRED_CATALOG_MAX_CHARS: () => DEFERRED_CATALOG_MAX_CHARS,
5769
5768
  DELIBERATION_ALLOWED_TOOLS: () => DELIBERATION_ALLOWED_TOOLS,
5770
5769
  DELIVERABLE_TITLE_CHARS: () => DELIVERABLE_TITLE_CHARS,
5770
+ END_TURN_REPLY_SENTINEL: () => END_TURN_REPLY_SENTINEL,
5771
5771
  ENTERPRISE_FEATURES: () => ENTERPRISE_FEATURES,
5772
5772
  ENTITY_COMMENTS_DEFAULT: () => ENTITY_COMMENTS_DEFAULT,
5773
5773
  ENTITY_SCOPE_ORDER: () => ENTITY_SCOPE_ORDER,
@@ -5795,9 +5795,16 @@ __export(dist_exports, {
5795
5795
  MAX_TOKENS_AFFORD_SAFETY: () => MAX_TOKENS_AFFORD_SAFETY,
5796
5796
  MAX_TOKENS_CLAMP_FLOOR: () => MAX_TOKENS_CLAMP_FLOOR,
5797
5797
  MAX_TOKENS_REMAINING_MARGIN: () => MAX_TOKENS_REMAINING_MARGIN,
5798
+ MEMORY_DREAM_MIN_ENTRIES: () => MEMORY_DREAM_MIN_ENTRIES,
5799
+ MEMORY_DREAM_TRIGGER_PERCENT: () => MEMORY_DREAM_TRIGGER_PERCENT,
5798
5800
  MEMORY_ENTRY_MAX_CHARS: () => MEMORY_ENTRY_MAX_CHARS,
5801
+ MEMORY_FRAGMENTS_MAX_CHARS: () => MEMORY_FRAGMENTS_MAX_CHARS,
5802
+ MEMORY_HEALTH_CRITICAL_PERCENT: () => MEMORY_HEALTH_CRITICAL_PERCENT,
5803
+ MEMORY_HEALTH_WARN_PERCENT: () => MEMORY_HEALTH_WARN_PERCENT,
5804
+ MEMORY_MD_CURATED_HARD_MAX_CHARS: () => MEMORY_MD_CURATED_HARD_MAX_CHARS,
5805
+ MEMORY_MD_CURATED_MAX_CHARS: () => MEMORY_MD_CURATED_MAX_CHARS,
5799
5806
  MEMORY_MD_SECTION_MAX_CHARS: () => MEMORY_MD_SECTION_MAX_CHARS,
5800
- MEMORY_MD_TOTAL_MAX_CHARS: () => MEMORY_MD_TOTAL_MAX_CHARS,
5807
+ MEMORY_OBSERVATIONS_HARD_MAX_CHARS: () => MEMORY_OBSERVATIONS_HARD_MAX_CHARS,
5801
5808
  MEMORY_OBSERVATIONS_MAX_CHARS: () => MEMORY_OBSERVATIONS_MAX_CHARS,
5802
5809
  MIN_HEARTBEAT_INTERVAL_MS: () => MIN_HEARTBEAT_INTERVAL_MS,
5803
5810
  MODEL_CAPABILITY_TYPES: () => MODEL_CAPABILITY_TYPES,
@@ -5949,7 +5956,6 @@ __export(dist_exports, {
5949
5956
  getProviderBootstrapModel: () => getProviderBootstrapModel,
5950
5957
  getRunStatePath: () => getRunStatePath,
5951
5958
  getTextContent: () => getTextContent,
5952
- hasCompletionMarker: () => hasCompletionMarker,
5953
5959
  inspectSubscriptionKey: () => inspectSubscriptionKey,
5954
5960
  installCrashGuard: () => installCrashGuard,
5955
5961
  isCliErrorResponse: () => isCliErrorResponse,
@@ -5983,6 +5989,8 @@ __export(dist_exports, {
5983
5989
  readManifest: () => readManifest,
5984
5990
  readRunState: () => readRunState,
5985
5991
  renderStepPrompt: () => renderStepPrompt,
5992
+ replaceAllLiteral: () => replaceAllLiteral,
5993
+ replaceLiteral: () => replaceLiteral,
5986
5994
  requirementId: () => requirementId,
5987
5995
  resolveBinary: () => resolveBinary,
5988
5996
  resolveEntityKey: () => resolveEntityKey,
@@ -5995,8 +6003,8 @@ __export(dist_exports, {
5995
6003
  saveConfig: () => saveConfig,
5996
6004
  scoreKeywordHaystack: () => scoreKeywordHaystack,
5997
6005
  scoreKeywordQuery: () => scoreKeywordQuery,
5998
- stripCompletionMarkerLeak: () => stripCompletionMarkerLeak,
5999
6006
  stripInternalBlocks: () => stripInternalBlocks,
6007
+ stripLegacyCompletionToken: () => stripLegacyCompletionToken,
6000
6008
  summarizeEnv: () => summarizeEnv,
6001
6009
  taskId: () => taskId,
6002
6010
  toPackageSlug: () => toPackageSlug,
@@ -6027,7 +6035,6 @@ var init_dist = __esm({
6027
6035
  init_file_storage();
6028
6036
  init_mailbox();
6029
6037
  init_workflow_template();
6030
- init_cognitive();
6031
6038
  init_model_catalog();
6032
6039
  init_license();
6033
6040
  init_coding_tool();
@@ -6038,6 +6045,7 @@ var init_dist = __esm({
6038
6045
  init_crash();
6039
6046
  init_id();
6040
6047
  init_text();
6048
+ init_literal_replace();
6041
6049
  init_platform();
6042
6050
  init_keyword_search();
6043
6051
  init_models();
@@ -6359,6 +6367,17 @@ var init_lock_resources = __esm({
6359
6367
  }
6360
6368
  });
6361
6369
 
6370
+ // ../core/dist/memory/dream-trigger.js
6371
+ function shouldRunDreamCycle(input) {
6372
+ return input.observationPercent >= MEMORY_DREAM_TRIGGER_PERCENT || input.entryCount >= MEMORY_DREAM_MIN_ENTRIES;
6373
+ }
6374
+ var init_dream_trigger = __esm({
6375
+ "../core/dist/memory/dream-trigger.js"() {
6376
+ "use strict";
6377
+ init_dist();
6378
+ }
6379
+ });
6380
+
6362
6381
  // ../core/dist/tracing.js
6363
6382
  function setTracingProvider(provider) {
6364
6383
  activeProvider = provider;
@@ -7888,6 +7907,91 @@ var init_taxonomy = __esm({
7888
7907
  }
7889
7908
  });
7890
7909
 
7910
+ // ../core/dist/memory/residue-repair.js
7911
+ function isArchiveStub(line) {
7912
+ return /^\s*_\[archived →/.test(line);
7913
+ }
7914
+ function indexArchiveBodies(archiveText) {
7915
+ const bodies = /* @__PURE__ */ new Map();
7916
+ if (!archiveText)
7917
+ return bodies;
7918
+ for (const part of archiveText.split(/\n(?=## )/)) {
7919
+ const m = part.match(/^## (.+)\n?/);
7920
+ if (!m)
7921
+ continue;
7922
+ const name = (m[1] ?? "").trim();
7923
+ if (!name || name === "_observations" || name === "_session_fragments")
7924
+ continue;
7925
+ const body = part.slice(m[0].length).trim();
7926
+ if (!body)
7927
+ continue;
7928
+ const arr = bodies.get(name);
7929
+ if (arr)
7930
+ arr.push(body);
7931
+ else
7932
+ bodies.set(name, [body]);
7933
+ }
7934
+ return bodies;
7935
+ }
7936
+ function emptyResult() {
7937
+ return { repaired: 0, ambiguous: [], notFound: [] };
7938
+ }
7939
+ function nearestHeadingName(lines, i) {
7940
+ for (let j = i - 1; j >= 0; j--) {
7941
+ const s2 = (lines[j] ?? "").trim();
7942
+ if (!s2)
7943
+ continue;
7944
+ if (s2.startsWith("<!--"))
7945
+ continue;
7946
+ if (isArchiveStub(s2))
7947
+ continue;
7948
+ return s2.replace(/^#+\s*/, "").trim();
7949
+ }
7950
+ return null;
7951
+ }
7952
+ function healStubLines(text, bodies) {
7953
+ const result = emptyResult();
7954
+ if (!text || bodies.size === 0 || !text.includes(ARCHIVE_STUB_SENTINEL)) {
7955
+ return { text, result };
7956
+ }
7957
+ const lines = text.split("\n");
7958
+ for (let i = 0; i < lines.length; i++) {
7959
+ if (!isArchiveStub(lines[i] ?? ""))
7960
+ continue;
7961
+ const name = nearestHeadingName(lines, i);
7962
+ if (!name) {
7963
+ result.notFound.push("(no heading above stub)");
7964
+ continue;
7965
+ }
7966
+ const candidates = bodies.get(name);
7967
+ if (!candidates || candidates.length === 0) {
7968
+ result.notFound.push(name);
7969
+ continue;
7970
+ }
7971
+ if (candidates.length > 1) {
7972
+ result.ambiguous.push({ name, candidates: candidates.length });
7973
+ continue;
7974
+ }
7975
+ lines[i] = candidates[0];
7976
+ result.repaired += 1;
7977
+ }
7978
+ return { text: lines.join("\n"), result };
7979
+ }
7980
+ function accumulateResidue(into, from) {
7981
+ for (const a of from.ambiguous) {
7982
+ into.ambiguous.set(a.name, Math.max(into.ambiguous.get(a.name) ?? 0, a.candidates));
7983
+ }
7984
+ for (const n2 of from.notFound)
7985
+ into.notFound.add(n2);
7986
+ }
7987
+ var ARCHIVE_STUB_SENTINEL;
7988
+ var init_residue_repair = __esm({
7989
+ "../core/dist/memory/residue-repair.js"() {
7990
+ "use strict";
7991
+ ARCHIVE_STUB_SENTINEL = "_[archived \u2192";
7992
+ }
7993
+ });
7994
+
7891
7995
  // ../core/dist/atomic-write.js
7892
7996
  import { renameSync, writeFileSync as writeFileSync5 } from "node:fs";
7893
7997
  function writeFileAtomic(filePath, content) {
@@ -7928,11 +8032,70 @@ var init_context_slot = __esm({
7928
8032
  }
7929
8033
  });
7930
8034
 
8035
+ // ../core/dist/memory/records.js
8036
+ function coerceEntry(raw) {
8037
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
8038
+ return null;
8039
+ const r = raw;
8040
+ const id = typeof r["id"] === "string" ? r["id"].trim() : "";
8041
+ if (!id)
8042
+ return null;
8043
+ const type = typeof r["type"] === "string" && VALID_ENTRY_TYPES.has(r["type"]) ? r["type"] : "note";
8044
+ let content = typeof r["content"] === "string" ? r["content"] : "";
8045
+ if (content.length > MAX_CONTENT_CHARS)
8046
+ content = content.slice(0, MAX_CONTENT_CHARS);
8047
+ const timestamp = typeof r["timestamp"] === "string" && r["timestamp"] ? r["timestamp"] : (/* @__PURE__ */ new Date()).toISOString();
8048
+ const m = r["metadata"];
8049
+ const metadata = m && typeof m === "object" && !Array.isArray(m) ? m : void 0;
8050
+ return { id, timestamp, type, content, ...metadata ? { metadata } : {} };
8051
+ }
8052
+ function parseRecords(text) {
8053
+ if (!text || !text.trim())
8054
+ return { entries: [] };
8055
+ let raw;
8056
+ try {
8057
+ raw = JSON.parse(text);
8058
+ } catch (err) {
8059
+ return { entries: [], error: `invalid JSON: ${String(err)}` };
8060
+ }
8061
+ if (!Array.isArray(raw))
8062
+ return { entries: [], error: "expected a JSON array of records" };
8063
+ return { entries: raw.map(coerceEntry).filter((e) => e !== null) };
8064
+ }
8065
+ function serializeRecords(entries2) {
8066
+ return `${JSON.stringify(entries2, null, 2)}
8067
+ `;
8068
+ }
8069
+ var VALID_ENTRY_TYPES, MAX_CONTENT_CHARS;
8070
+ var init_records = __esm({
8071
+ "../core/dist/memory/records.js"() {
8072
+ "use strict";
8073
+ VALID_ENTRY_TYPES = /* @__PURE__ */ new Set([
8074
+ "conversation",
8075
+ "fact",
8076
+ "task_result",
8077
+ "note",
8078
+ "insight",
8079
+ "conversation_fragment"
8080
+ ]);
8081
+ MAX_CONTENT_CHARS = 2e6;
8082
+ }
8083
+ });
8084
+
7931
8085
  // ../core/dist/memory/store.js
7932
8086
  import { readFileSync as readFileSync6, writeFileSync as writeFileSync6, existsSync as existsSync8, mkdirSync as mkdirSync6, readdirSync, appendFileSync as appendFileSync2, statSync, unlinkSync as unlinkSync2, renameSync as renameSync2 } from "node:fs";
7933
8087
  import { basename as basename2, join as join7 } from "node:path";
8088
+ function isPromptScaffoldingHeading(name) {
8089
+ const n2 = name.trim();
8090
+ if (PROMPT_SCAFFOLDING_HEADINGS.has(n2))
8091
+ return true;
8092
+ return /^(Available Skills|Deferred Tools|Relevant Memories|Concurrency Context|Current Conversation)\b/.test(n2);
8093
+ }
7934
8094
  function sanitizeSectionBody(content) {
7935
- return content.replace(/^## /gm, "### ");
8095
+ return stripThinkBlocks(content).replace(/^## /gm, "### ");
8096
+ }
8097
+ function stripThinkBlocks(text) {
8098
+ return text.replace(/<think>[\s\S]*?<\/think>/g, "").replace(/<think>[\s\S]*$/g, "").replace(/^\s*<\/think>\s*$/gm, "");
7936
8099
  }
7937
8100
  function normalizeSectionKey(raw) {
7938
8101
  const flat = String(raw ?? "").replace(/[\r\n]+/g, " ").trim();
@@ -7965,14 +8128,6 @@ function sanitizeEntry(raw) {
7965
8128
  metadata: typeof r.metadata === "object" && r.metadata !== null ? r.metadata : void 0
7966
8129
  };
7967
8130
  }
7968
- function safeJson(value) {
7969
- try {
7970
- const s2 = JSON.stringify(value);
7971
- return typeof s2 === "string" ? s2 : "";
7972
- } catch {
7973
- return "";
7974
- }
7975
- }
7976
8131
  function parseDataMeta(raw) {
7977
8132
  if (!raw)
7978
8133
  return void 0;
@@ -8112,6 +8267,24 @@ function formatTags(metadata) {
8112
8267
  const tags = metadata?.tags;
8113
8268
  return Array.isArray(tags) ? tags.map(String).join(" ") : "";
8114
8269
  }
8270
+ function decodeEntryBodyLine(line) {
8271
+ return /^(\\\\|\\### |\\<!-- )/.test(line) ? line.slice(1) : line;
8272
+ }
8273
+ function extractFragmentRegion(content) {
8274
+ if (content.startsWith(FRAGMENT_REGION_HEADER)) {
8275
+ const nl = content.indexOf("\n");
8276
+ return nl >= 0 ? content.slice(nl + 1) : "";
8277
+ }
8278
+ return content;
8279
+ }
8280
+ function splitKnowledgeSections(content) {
8281
+ const idx = content.indexOf("\n## _observations");
8282
+ if (idx >= 0)
8283
+ return { curated: content.slice(0, idx), observations: content.slice(idx) };
8284
+ if (content.startsWith("## _observations"))
8285
+ return { curated: "", observations: content };
8286
+ return { curated: content, observations: "" };
8287
+ }
8115
8288
  function parseCuratedSections(markdown) {
8116
8289
  if (!markdown.trim())
8117
8290
  return [];
@@ -8136,16 +8309,30 @@ function parseCuratedSections(markdown) {
8136
8309
  function slugSectionId(name) {
8137
8310
  return name.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/gi, "_").replace(/^_|_$/g, "").slice(0, 80) || "section";
8138
8311
  }
8139
- var log8, VALID_TYPES, NOTEBOOK_HEADING_RE, NOTEBOOK_UPDATED_RE, NOTEBOOK_MANAGED_RE, MemoryStore;
8312
+ var log8, VALID_TYPES, PROMPT_SCAFFOLDING_HEADINGS, NOTEBOOK_HEADING_RE, NOTEBOOK_UPDATED_RE, NOTEBOOK_MANAGED_RE, MemoryStore, FRAGMENT_REGION_HEADER;
8140
8313
  var init_store = __esm({
8141
8314
  "../core/dist/memory/store.js"() {
8142
8315
  "use strict";
8143
8316
  init_dist();
8144
8317
  init_taxonomy();
8318
+ init_residue_repair();
8145
8319
  init_atomic_write();
8146
8320
  init_context_slot();
8321
+ init_records();
8147
8322
  log8 = createLogger("memory-store");
8148
8323
  VALID_TYPES = /* @__PURE__ */ new Set(["conversation", "fact", "task_result", "note", "insight", "conversation_fragment"]);
8324
+ PROMPT_SCAFFOLDING_HEADINGS = /* @__PURE__ */ new Set([
8325
+ "Relevant Memories",
8326
+ "Your Knowledge",
8327
+ "Your Attention State",
8328
+ "Current Conversation",
8329
+ "Team Status",
8330
+ "Context",
8331
+ "How Your Prompt Is Composed",
8332
+ "Tool Usage Rules",
8333
+ "Concurrency Context",
8334
+ "Concurrency Context\uFF08\u5E76\u53D1\u4E0A\u4E0B\u6587\uFF09"
8335
+ ]);
8149
8336
  NOTEBOOK_HEADING_RE = /^## (.+)$/;
8150
8337
  NOTEBOOK_UPDATED_RE = /^<!-- updated: (.+) -->$/;
8151
8338
  NOTEBOOK_MANAGED_RE = /^<!-- managed: (\w+) -->$/;
@@ -8162,6 +8349,21 @@ var init_store = __esm({
8162
8349
  saveDebounce = /* @__PURE__ */ new Map();
8163
8350
  longTermFile;
8164
8351
  longTermArchiveFile;
8352
+ /** §27 — archived records that are PROMPT SCAFFOLDING: kept aside, never served as knowledge. */
8353
+ longTermArchiveScaffoldingFile;
8354
+ /**
8355
+ * H24 — observations live in a JSON record file. Structure is JSON's, so no payload can forge a
8356
+ * record boundary; the H13/H17/H18/H22 family is gone by construction, not by another heuristic.
8357
+ */
8358
+ observationFile;
8359
+ observationArchiveFile;
8360
+ /**
8361
+ * H16 — session compaction fragments live in their OWN pool + file, never mixed
8362
+ * with `this.entries` (agent-authored observations). See MEMORY_FRAGMENTS_MAX_CHARS.
8363
+ */
8364
+ fragments = [];
8365
+ fragmentFile;
8366
+ fragmentArchiveFile;
8165
8367
  constructor(dataDir) {
8166
8368
  this.dataDir = dataDir;
8167
8369
  this.sessionsDir = join7(dataDir, "sessions");
@@ -8171,38 +8373,116 @@ var init_store = __esm({
8171
8373
  mkdirSync6(this.logsDir, { recursive: true });
8172
8374
  ensureKnowledgeFile(dataDir);
8173
8375
  this.longTermFile = knowledgePath(dataDir);
8174
- this.longTermArchiveFile = join7(dataDir, "knowledge-archive.md");
8376
+ this.longTermArchiveFile = join7(dataDir, "knowledge-archive.json");
8377
+ this.longTermArchiveScaffoldingFile = join7(dataDir, "knowledge-archive-scaffolding.json");
8378
+ this.observationFile = join7(dataDir, "observations.json");
8379
+ this.observationArchiveFile = join7(dataDir, "observations-archive.json");
8380
+ this.fragmentFile = join7(dataDir, "session-fragments.json");
8381
+ this.fragmentArchiveFile = join7(dataDir, "session-fragments-archive.json");
8175
8382
  this.loadFromDisk();
8383
+ this.loadFragmentsFromDisk();
8384
+ this.migrateLegacyArchive();
8385
+ if (!existsSync8(this.migrationMarkerPath())) {
8386
+ this.repairStubResidue();
8387
+ try {
8388
+ writeFileSync6(this.migrationMarkerPath(), (/* @__PURE__ */ new Date()).toISOString(), "utf-8");
8389
+ } catch {
8390
+ }
8391
+ }
8176
8392
  this.loadSessionsFromDisk();
8177
8393
  }
8178
8394
  getStoreFileName() {
8179
8395
  return basename2(this.longTermFile);
8180
8396
  }
8397
+ /**
8398
+ * §24 — marker for the ONE-SHOT memory migration (legacy prose containers + the H13
8399
+ * residue repair). Present ⇒ this agent is fully migrated: the load path is pure JSON,
8400
+ * parses no prose and rewrites no content. Delete criterion for the whole migration
8401
+ * module: every `agents/*` dir has this marker (docs §24.4).
8402
+ */
8403
+ migrationMarkerPath() {
8404
+ return join7(this.dataDir, ".memory-v2-migrated");
8405
+ }
8181
8406
  /** 归档文件名:超预算段落正文的**无损**去处(可被 memory_search 检索,不注入)。 */
8182
8407
  getArchiveFileName() {
8183
8408
  return basename2(this.longTermArchiveFile);
8184
8409
  }
8410
+ /**
8411
+ * §27 — the curated region's "preamble": everything BEFORE the first `## ` heading.
8412
+ *
8413
+ * Legacy files carry one (`# Lessons Learned` …). The section-based tools could not touch it,
8414
+ * so a write-only region with no removal path accumulated stale content in the ONE place that
8415
+ * is injected into every prompt (same law as "a write-only store inflates until it fills up").
8416
+ * These methods give the preamble the same write/forget symmetry as any named section.
8417
+ */
8418
+ getLongTermPreamble() {
8419
+ let content = "";
8420
+ try {
8421
+ if (existsSync8(this.longTermFile))
8422
+ content = readFileSync6(this.longTermFile, "utf-8");
8423
+ } catch {
8424
+ }
8425
+ const { curated } = splitKnowledgeSections(content);
8426
+ const idx = curated.search(/^## /m);
8427
+ return (idx < 0 ? curated : curated.slice(0, idx)).replace(/\s+$/, "");
8428
+ }
8429
+ setLongTermPreamble(text) {
8430
+ let content = "";
8431
+ try {
8432
+ if (existsSync8(this.longTermFile))
8433
+ content = readFileSync6(this.longTermFile, "utf-8");
8434
+ } catch {
8435
+ }
8436
+ const { curated } = splitKnowledgeSections(content);
8437
+ const idx = curated.search(/^## /m);
8438
+ const rest = idx < 0 ? "" : curated.slice(idx);
8439
+ const body = sanitizeSectionBody(text ?? "").trim();
8440
+ const updated = body ? `${body}
8441
+
8442
+ ${rest}` : rest;
8443
+ const curatedChars = splitKnowledgeSections(updated).curated.length;
8444
+ if (curatedChars > MEMORY_MD_CURATED_HARD_MAX_CHARS) {
8445
+ return {
8446
+ ok: false,
8447
+ reason: `Curated knowledge would reach ${curatedChars} chars, over the hard ceiling of ${MEMORY_MD_CURATED_HARD_MAX_CHARS}. Nothing was written.`
8448
+ };
8449
+ }
8450
+ this.writeKnowledgeMd(updated);
8451
+ return { ok: true };
8452
+ }
8453
+ removeLongTermPreamble() {
8454
+ const removed = this.getLongTermPreamble().length;
8455
+ const res = this.setLongTermPreamble("");
8456
+ return { ok: res.ok, removedChars: res.ok ? removed : 0 };
8457
+ }
8185
8458
  /**
8186
8459
  * 记忆预算健康度(审计 P-12):驱动提示词内的健康信号,让 Agent 知道何时该整理。
8187
8460
  */
8188
8461
  getMemoryHealth() {
8189
- let totalChars = 0;
8462
+ let content = "";
8190
8463
  try {
8191
8464
  if (existsSync8(this.longTermFile))
8192
- totalChars = readFileSync6(this.longTermFile, "utf-8").length;
8465
+ content = readFileSync6(this.longTermFile, "utf-8");
8193
8466
  } catch {
8194
8467
  }
8195
8468
  let archiveChars = 0;
8196
- try {
8197
- if (existsSync8(this.longTermArchiveFile))
8198
- archiveChars = readFileSync6(this.longTermArchiveFile, "utf-8").length;
8199
- } catch {
8469
+ for (const f of [this.longTermArchiveFile, this.longTermArchiveScaffoldingFile, this.observationArchiveFile, this.fragmentArchiveFile]) {
8470
+ try {
8471
+ if (existsSync8(f))
8472
+ archiveChars += readFileSync6(f, "utf-8").length;
8473
+ } catch {
8474
+ }
8200
8475
  }
8201
- const cap = MEMORY_MD_TOTAL_MAX_CHARS;
8476
+ const { curated } = splitKnowledgeSections(content);
8477
+ const curatedChars = curated.length;
8478
+ const observationChars = this.observationPayloadChars();
8202
8479
  return {
8203
- totalChars,
8204
- cap,
8205
- percent: cap > 0 ? Math.round(totalChars / cap * 100) : 0,
8480
+ curatedChars,
8481
+ curatedCap: MEMORY_MD_CURATED_MAX_CHARS,
8482
+ percent: MEMORY_MD_CURATED_MAX_CHARS > 0 ? Math.round(curatedChars / MEMORY_MD_CURATED_MAX_CHARS * 100) : 0,
8483
+ observationChars,
8484
+ observationCap: MEMORY_OBSERVATIONS_MAX_CHARS,
8485
+ observationPercent: MEMORY_OBSERVATIONS_MAX_CHARS > 0 ? Math.round(observationChars / MEMORY_OBSERVATIONS_MAX_CHARS * 100) : 0,
8206
8486
  observations: this.entries.length,
8207
8487
  curatedSections: parseCuratedSections(this.getLongTermMemory()).length,
8208
8488
  archiveChars,
@@ -8240,28 +8520,104 @@ var init_store = __esm({
8240
8520
  }
8241
8521
  }
8242
8522
  /**
8243
- * Losslessly move a curated section body into `knowledge-archive.md`
8523
+ * Losslessly move a curated section body into `knowledge-archive.json`
8244
8524
  * (审计 P-04/P-05:绝不静默丢弃 / 截断)。
8245
8525
  * 主文件保留标题 + 指针,主题仍可发现;正文原文进归档,仍可检索。
8526
+ *
8527
+ * H19 — no production caller: the old load-time curated convergence (its only producer)
8528
+ * was removed. Kept because it is exercised by the H13/H20 repair tests and the H21
8529
+ * dedup contract lives here.
8246
8530
  */
8247
8531
  archiveSection(name, body) {
8248
8532
  const trimmed = body.trim();
8249
8533
  if (!trimmed)
8250
8534
  return 0;
8251
8535
  try {
8252
- const head = "# Knowledge Archive\n\n<!-- \u8D85\u9884\u7B97\u6BB5\u843D\u6B63\u6587\u7684\u65E0\u635F\u5F52\u6863\uFF08\u7531\u8BB0\u5FC6\u670D\u52A1\u7EF4\u62A4\uFF0C\u53EF\u88AB memory_search \u68C0\u7D22\uFF09\u3002 -->\n\n";
8253
- const existing = existsSync8(this.longTermArchiveFile) ? readFileSync6(this.longTermArchiveFile, "utf-8") : head;
8254
- if (!existing.includes(trimmed)) {
8255
- appendFileSync2(this.longTermArchiveFile, `## ${name}
8256
- ${trimmed}
8257
-
8258
- `);
8536
+ const recs = this.readArchiveRecords();
8537
+ if (!recs.some((r) => r.metadata?.name === name && r.content === trimmed)) {
8538
+ let finalName = name;
8539
+ let n2 = 1;
8540
+ while (recs.some((r) => r.metadata?.name === finalName))
8541
+ finalName = `${name} (${++n2})`;
8542
+ recs.push({
8543
+ id: `archived_${slugSectionId(finalName)}`,
8544
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
8545
+ type: "fact",
8546
+ content: trimmed,
8547
+ metadata: { name: finalName, source: "archive" }
8548
+ });
8549
+ writeFileAtomic(this.longTermArchiveFile, serializeRecords(recs));
8259
8550
  }
8260
8551
  } catch (err) {
8261
- log8.warn("Failed to archive section body", { name, error: String(err) });
8552
+ log8.warn("Failed to archive section record", { name, error: String(err) });
8262
8553
  }
8263
8554
  return trimmed.length;
8264
8555
  }
8556
+ /** §27 — read the JSON archive records (archived content stays searchable). */
8557
+ readArchiveRecords() {
8558
+ try {
8559
+ if (!existsSync8(this.longTermArchiveFile))
8560
+ return [];
8561
+ const { entries: entries2, error } = parseRecords(readFileSync6(this.longTermArchiveFile, "utf-8"));
8562
+ if (error)
8563
+ log8.error("knowledge-archive.json unreadable \u2014 NOT overwriting it", { error });
8564
+ return entries2;
8565
+ } catch {
8566
+ return [];
8567
+ }
8568
+ }
8569
+ /**
8570
+ * §27 — one-time migration of the retired in-band archive container.
8571
+ *
8572
+ * The archive used to be `knowledge-archive.md` (`## name` + body). Its payload could itself
8573
+ * contain `## ` lines, so the reader forged "sections" out of them (observed: 54 headings in one
8574
+ * agent's archive, 11 of them `## Relevant Memories` — prompt dumps served back as archived
8575
+ * knowledge). Records are now JSON, where a payload is just a string. The legacy split reuses
8576
+ * the OLD reader's boundary rule (`indexArchiveBodies`) — inherited behaviour, no new guessing —
8577
+ * and prompt scaffolding is moved ASIDE (never deleted) so it stops being served.
8578
+ */
8579
+ migrateLegacyArchive() {
8580
+ const legacy = join7(this.dataDir, "knowledge-archive.md");
8581
+ if (!existsSync8(legacy))
8582
+ return;
8583
+ if (existsSync8(this.longTermArchiveFile)) {
8584
+ try {
8585
+ unlinkSync2(legacy);
8586
+ } catch {
8587
+ }
8588
+ return;
8589
+ }
8590
+ try {
8591
+ const byName = indexArchiveBodies(readFileSync6(legacy, "utf-8"));
8592
+ const keep = [];
8593
+ const scaffolding = [];
8594
+ let i = 0;
8595
+ for (const [name, bodies] of byName) {
8596
+ for (const body of bodies) {
8597
+ const rec = {
8598
+ id: `archived_${slugSectionId(name)}_${i++}`,
8599
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
8600
+ type: "fact",
8601
+ content: body,
8602
+ metadata: { name, source: "archive", migratedFrom: "knowledge-archive.md" }
8603
+ };
8604
+ (isPromptScaffoldingHeading(name) ? scaffolding : keep).push(rec);
8605
+ }
8606
+ }
8607
+ if (keep.length > 0)
8608
+ writeFileAtomic(this.longTermArchiveFile, serializeRecords(keep));
8609
+ if (scaffolding.length > 0) {
8610
+ writeFileAtomic(this.longTermArchiveScaffoldingFile, serializeRecords(scaffolding));
8611
+ }
8612
+ unlinkSync2(legacy);
8613
+ log8.info("\xA727: migrated knowledge-archive.md \u2192 JSON records", {
8614
+ kept: keep.length,
8615
+ scaffolding: scaffolding.length
8616
+ });
8617
+ } catch (err) {
8618
+ log8.warn("\xA727: knowledge-archive.md migration failed \u2014 left in place", { error: String(err) });
8619
+ }
8620
+ }
8265
8621
  /**
8266
8622
  * NOTE (2026-09-16): `getStateMemory()` / `pruneStateMemory()` were removed together
8267
8623
  * with the state.md store. Situational state is Working-layer data and lives in
@@ -8271,16 +8627,38 @@ ${trimmed}
8271
8627
  */
8272
8628
  // --- Short-term: session messages ---
8273
8629
  addEntry(entry) {
8274
- this.entries.push(sanitizeEntry(entry));
8630
+ if (entry.type === "conversation_fragment") {
8631
+ this.fragments.push(sanitizeEntry(entry));
8632
+ this.saveFragmentsToDisk();
8633
+ log8.debug("Memory fragment added", { type: entry.type, id: entry.id });
8634
+ return { ok: true };
8635
+ }
8636
+ const sanitized = sanitizeEntry(entry);
8637
+ if (this.observationPayloadChars() + sanitized.content.length > MEMORY_OBSERVATIONS_HARD_MAX_CHARS) {
8638
+ const reason = `Observation log is at its hard ceiling (${MEMORY_OBSERVATIONS_HARD_MAX_CHARS} chars). Nothing was discarded \u2014 make room with \`memory_organize\` (merge recurring observations into a curated section) or \`memory_update({ mode: "delete", ... })\`, then save again.`;
8639
+ log8.warn("observation write REFUSED at the hard ceiling (no eviction, nothing moved)", {
8640
+ chars: this.observationPayloadChars(),
8641
+ ceiling: MEMORY_OBSERVATIONS_HARD_MAX_CHARS,
8642
+ id: entry.id
8643
+ });
8644
+ return { ok: false, reason };
8645
+ }
8646
+ this.entries.push(sanitized);
8275
8647
  this.saveToDisk();
8276
8648
  log8.debug("Memory entry added", { type: entry.type, id: entry.id });
8649
+ return { ok: true };
8277
8650
  }
8278
8651
  getEntries(type, limit) {
8279
- let result = type ? this.entries.filter((e) => e.type === type) : [...this.entries];
8652
+ const source = type === "conversation_fragment" ? this.fragments : this.entries;
8653
+ let result = type ? source.filter((e) => e.type === type) : [...source];
8280
8654
  if (limit)
8281
8655
  result = result.slice(-limit);
8282
8656
  return result;
8283
8657
  }
8658
+ /** All session-compaction fragments currently held (most recent last). */
8659
+ getFragments() {
8660
+ return [...this.fragments];
8661
+ }
8284
8662
  getEntriesByTag(tag, limit) {
8285
8663
  const tagged = this.entries.filter((e) => Array.isArray(e.metadata?.tags) && e.metadata.tags.includes(tag));
8286
8664
  return limit ? tagged.slice(-limit) : tagged;
@@ -8318,24 +8696,33 @@ ${section3.body}`;
8318
8696
  });
8319
8697
  }
8320
8698
  try {
8321
- if (existsSync8(this.longTermArchiveFile)) {
8322
- const archivedText = readFileSync6(this.longTermArchiveFile, "utf-8");
8323
- for (const section3 of parseCuratedSections(archivedText)) {
8324
- const body = `## ${section3.name}
8325
- ${section3.body}`;
8326
- const score = scoreKeywordHaystack(body, tokens, fullLower);
8327
- if (score <= 0)
8328
- continue;
8329
- scored.push({
8330
- entry: {
8331
- id: `archived_${slugSectionId(section3.name)}`,
8332
- timestamp: "",
8333
- type: "fact",
8334
- content: body.length > 2500 ? `${body.slice(0, 2500)}\u2026` : body,
8335
- metadata: { source: "archive", section: section3.name, store: this.getArchiveFileName() }
8336
- },
8337
- score: score + 0.1
8338
- });
8699
+ for (const rec of this.readArchiveRecords()) {
8700
+ const name = String(rec.metadata?.name ?? "");
8701
+ const body = name ? `## ${name}
8702
+ ${rec.content}` : rec.content;
8703
+ const score = scoreKeywordHaystack(body, tokens, fullLower);
8704
+ if (score <= 0)
8705
+ continue;
8706
+ scored.push({
8707
+ entry: {
8708
+ id: rec.id,
8709
+ timestamp: rec.timestamp,
8710
+ type: "fact",
8711
+ content: body.length > 2500 ? `${body.slice(0, 2500)}\u2026` : body,
8712
+ metadata: { source: "archive", section: name, store: this.getArchiveFileName() }
8713
+ },
8714
+ score: score + 0.1
8715
+ });
8716
+ }
8717
+ } catch {
8718
+ }
8719
+ try {
8720
+ if (existsSync8(this.observationArchiveFile)) {
8721
+ for (const e of parseRecords(readFileSync6(this.observationArchiveFile, "utf-8")).entries) {
8722
+ const score = scoreKeywordHaystack(`${e.content}
8723
+ ${formatTags(e.metadata)}`, tokens, fullLower);
8724
+ if (score > 0)
8725
+ scored.push({ entry: e, score });
8339
8726
  }
8340
8727
  }
8341
8728
  } catch {
@@ -8536,8 +8923,9 @@ ${content}`);
8536
8923
  *
8537
8924
  * Returns a structured result so callers (the memory tools) can surface a refusal
8538
8925
  * to the model instead of the write silently no-op'ing (B1). `{ ok: true }` on success;
8539
- * `{ ok: false, reason }` when the write is refused (over the total cap even after
8540
- * compression) or errors.
8926
+ * `{ ok: false, reason }` when the write is refused (invalid or oversized section) or
8927
+ * errors. Note: exceeding the **total** cap is no longer a refusal — the store
8928
+ * rebalances losslessly (`compressLongTermMemory`), so the write always lands.
8541
8929
  */
8542
8930
  addLongTermMemory(rawKey, content) {
8543
8931
  const sectionKey = normalizeSectionKey(rawKey);
@@ -8564,7 +8952,7 @@ ${content}`);
8564
8952
  let updated;
8565
8953
  if (existing.includes(sectionHeader)) {
8566
8954
  const regex = new RegExp(`(## ${key2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})\\n[\\s\\S]*?(?=\\n## |$)`);
8567
- updated = existing.replace(regex, `${sectionHeader}
8955
+ updated = existing.replace(regex, () => `${sectionHeader}
8568
8956
  ${truncatedContent}
8569
8957
  `);
8570
8958
  } else {
@@ -8581,17 +8969,24 @@ ${truncatedContent}
8581
8969
  `;
8582
8970
  }
8583
8971
  }
8584
- writeFileAtomic(this.longTermFile, updated);
8585
- if (updated.length > MEMORY_MD_TOTAL_MAX_CHARS) {
8586
- const rebalanced = this.compressLongTermMemory();
8587
- log8.info("knowledge.md over budget after write \u2014 rebalanced losslessly", {
8972
+ const curatedChars = splitKnowledgeSections(updated).curated.length;
8973
+ if (curatedChars > MEMORY_MD_CURATED_HARD_MAX_CHARS) {
8974
+ return {
8975
+ ok: false,
8976
+ reason: `Curated knowledge would reach ${curatedChars} chars, over the hard ceiling of ${MEMORY_MD_CURATED_HARD_MAX_CHARS} (this region is injected into every prompt). Nothing was written. Consolidate first \u2014 \`memory_organize\` (merge related sections) or \`memory_update\` (mode:"delete" an outdated section) \u2014 then retry.`
8977
+ };
8978
+ }
8979
+ this.writeKnowledgeMd(updated);
8980
+ if (curatedChars > MEMORY_MD_CURATED_MAX_CHARS) {
8981
+ log8.warn("knowledge.md curated over SOFT budget \u2014 reported, not rewritten", {
8588
8982
  key: key2,
8589
- totalChars: updated.length,
8590
- charsAfter: rebalanced.charsAfter,
8591
- archived: rebalanced.truncatedChunks
8983
+ curatedChars,
8984
+ softCap: MEMORY_MD_CURATED_MAX_CHARS,
8985
+ hardCap: MEMORY_MD_CURATED_HARD_MAX_CHARS,
8986
+ store: this.getStoreFileName()
8592
8987
  });
8593
8988
  }
8594
- log8.debug("Long-term memory updated", { key: key2, sectionChars: truncatedContent.length, totalChars: updated.length, store: this.getStoreFileName() });
8989
+ log8.debug("Long-term memory updated", { key: key2, sectionChars: truncatedContent.length, curatedChars, store: this.getStoreFileName() });
8595
8990
  return { ok: true };
8596
8991
  } catch (err) {
8597
8992
  log8.warn("Failed to write long-term memory", { key: key2, error: String(err) });
@@ -8662,7 +9057,7 @@ ${truncatedContent}
8662
9057
  const obsIdx = content.indexOf("## _observations");
8663
9058
  const obsPart = obsIdx >= 0 ? content.slice(obsIdx).trimStart() : "";
8664
9059
  const updated = (curatedAfter.trimEnd() + (obsPart ? "\n\n" + obsPart : "")).trimEnd() + "\n";
8665
- writeFileAtomic(this.longTermFile, updated);
9060
+ this.writeKnowledgeMd(updated);
8666
9061
  log8.info("Curated section removed", {
8667
9062
  name,
8668
9063
  removedChars: curatedBefore.length - curatedAfter.length,
@@ -8872,7 +9267,7 @@ ${truncatedContent}
8872
9267
  /** Search archived conversation_fragment entries for this session. */
8873
9268
  retrieveFragments(query2, maxResults = 5) {
8874
9269
  const q = query2.trim().toLowerCase();
8875
- const hits = this.entries.filter((e) => e.type === "conversation_fragment");
9270
+ const hits = [...this.fragments, ...this.archivedFragmentEntries()].filter((e) => e.type === "conversation_fragment");
8876
9271
  const scored = hits.map((e) => {
8877
9272
  const hay = e.content.toLowerCase();
8878
9273
  let score = 0;
@@ -8890,7 +9285,7 @@ ${truncatedContent}
8890
9285
  }
8891
9286
  /** Re-inject one archived fragment back into the live session as a user message. */
8892
9287
  includeFragment(sessionId, fragmentId) {
8893
- const entry = this.entries.find((e) => e.id === fragmentId && e.type === "conversation_fragment");
9288
+ const entry = [...this.fragments, ...this.archivedFragmentEntries()].find((e) => e.id === fragmentId && e.type === "conversation_fragment");
8894
9289
  if (!entry) {
8895
9290
  return { ok: false, message: `No archived fragment with id ${fragmentId}.` };
8896
9291
  }
@@ -8912,17 +9307,17 @@ ${entry.content}
8912
9307
  }
8913
9308
  /** Purge archived fragments for a session (used by session_purge). */
8914
9309
  purgeSessionFragments(sessionId) {
8915
- const before2 = this.entries.length;
8916
- this.entries = this.entries.filter((e) => !(e.type === "conversation_fragment" && e.metadata?.sessionId === sessionId));
8917
- const removed = before2 - this.entries.length;
9310
+ const before2 = this.fragments.length;
9311
+ this.fragments = this.fragments.filter((e) => !(e.type === "conversation_fragment" && e.metadata?.sessionId === sessionId));
9312
+ const removed = before2 - this.fragments.length;
8918
9313
  if (removed > 0)
8919
- this.saveToDisk();
9314
+ this.saveFragmentsToDisk();
8920
9315
  return removed;
8921
9316
  }
8922
9317
  /** Lightweight session stats for session_status. */
8923
9318
  sessionStats(sessionId) {
8924
9319
  const session = this.sessions.get(sessionId);
8925
- const fragmentCount = this.entries.filter((e) => e.type === "conversation_fragment" && e.metadata?.sessionId === sessionId).length;
9320
+ const fragmentCount = this.fragments.filter((e) => e.type === "conversation_fragment" && e.metadata?.sessionId === sessionId).length;
8926
9321
  return {
8927
9322
  messageCount: session?.messages.length ?? 0,
8928
9323
  slotKeys: Object.keys(session?.slots ?? {}),
@@ -9006,7 +9401,32 @@ ${entry.content}
9006
9401
  log8.warn("Failed to migrate memories.json, starting fresh");
9007
9402
  }
9008
9403
  }
9009
- this.entries = this.parseObservationsFromMemoryMd();
9404
+ if (existsSync8(this.observationFile)) {
9405
+ const { entries: entries2, error } = parseRecords(readFileSync6(this.observationFile, "utf-8"));
9406
+ if (error) {
9407
+ log8.error("observations.json unreadable \u2014 NOT overwriting it; starting with empty in-memory state", {
9408
+ error,
9409
+ file: basename2(this.observationFile)
9410
+ });
9411
+ }
9412
+ this.entries = entries2.filter((e) => e.content.trim().length > 0);
9413
+ if (this.runLegacyMigrations())
9414
+ this.saveToDisk();
9415
+ this.enforceMemoryBudgets();
9416
+ return;
9417
+ }
9418
+ const hadLegacyRegion = this.hasLegacyObservationRegion();
9419
+ const parsed = this.parseObservationsFromMemoryMd();
9420
+ const migratedFragments = parsed.filter((e) => e.type === "conversation_fragment");
9421
+ if (migratedFragments.length > 0) {
9422
+ this.fragments.push(...migratedFragments);
9423
+ this.saveFragmentsToDisk();
9424
+ log8.info("Migrated session fragments out of knowledge.md observations", {
9425
+ count: migratedFragments.length,
9426
+ store: this.getStoreFileName()
9427
+ });
9428
+ }
9429
+ this.entries = parsed.filter((e) => e.type !== "conversation_fragment");
9010
9430
  const before2 = this.entries.length;
9011
9431
  this.entries = this.entries.filter((e) => e.content.trim().length > 0);
9012
9432
  if (this.entries.length < before2) {
@@ -9014,6 +9434,8 @@ ${entry.content}
9014
9434
  removed: before2 - this.entries.length,
9015
9435
  store: this.getStoreFileName()
9016
9436
  });
9437
+ }
9438
+ if (hadLegacyRegion) {
9017
9439
  this.saveToDisk();
9018
9440
  }
9019
9441
  const migrationChanged = this.runLegacyMigrations();
@@ -9037,36 +9459,316 @@ ${entry.content}
9037
9459
  if (this.entries.length > 0) {
9038
9460
  log8.info(`Loaded ${this.entries.length} observation entries from ${this.getStoreFileName()}`);
9039
9461
  }
9040
- this.convergeLongTermToCap();
9462
+ this.enforceMemoryBudgets();
9041
9463
  }
9042
9464
  /**
9043
- * Shrink knowledge.md to `MEMORY_MD_TOTAL_MAX_CHARS` if it is over budget.
9465
+ * Measure BOTH memory budgets at load time and REPORT on them. Idempotent and cheap when
9466
+ * already within budget (one read); it never rewrites, archives or evicts anything.
9467
+ *
9468
+ * Two budgets, each with its OWN contract (see `MEMORY_MD_CURATED_MAX_CHARS` /
9469
+ * `MEMORY_OBSERVATIONS_MAX_CHARS`):
9044
9470
  *
9045
- * Idempotent and cheap when already within budget (one `statSync`). Delegates to
9046
- * `compressLongTermMemory` so the per-section cap, the stub marker and the
9047
- * `## _observations` carve-out all follow one implementation.
9471
+ * 1. curated (injected) — SOFT line, report-only (H19). Over-budget is logged and carried
9472
+ * to the in-prompt banner; the agent consolidates with `memory_organize` /
9473
+ * `memory_update`. The hard ceiling (`MEMORY_MD_CURATED_HARD_MAX_CHARS`) is enforced
9474
+ * fail-closed on the write path — `addLongTermMemory` refuses, nothing is written.
9475
+ * 2. observations — ADVISORY line, report-only (§24). The buffer is the agent's own
9476
+ * scratch log, and choosing what to drop is the agent's decision. Its single hard
9477
+ * enforcement point is the append path — `addEntry` refuses past
9478
+ * `MEMORY_OBSERVATIONS_HARD_MAX_CHARS` and moves nothing.
9479
+ *
9480
+ * The platform never acts on either budget here. Earlier versions "losslessly" archived the
9481
+ * largest curated sections / the oldest observations at load; both were removed because a
9482
+ * storage-format change alone could then decide which knowledge stayed live (H25), and
9483
+ * because silently shrinking the live set is the platform deciding content (R4).
9048
9484
  */
9049
- convergeLongTermToCap() {
9050
- if (!existsSync8(this.longTermFile)) {
9051
- return { converged: false, charsBefore: 0, charsAfter: 0 };
9485
+ enforceMemoryBudgets() {
9486
+ const read = () => {
9487
+ try {
9488
+ return splitKnowledgeSections(existsSync8(this.longTermFile) ? readFileSync6(this.longTermFile, "utf-8") : "");
9489
+ } catch {
9490
+ return { curated: "", observations: "" };
9491
+ }
9492
+ };
9493
+ const start = read();
9494
+ const curated = {
9495
+ before: start.curated.length,
9496
+ after: start.curated.length,
9497
+ // H19: curated is REPORT-ONLY — the platform never rewrites it, so no enforcement
9498
+ // action is ever taken. Kept `false` to match the field's meaning everywhere else
9499
+ // ("did an enforcement action succeed?", as for `observations` below), NOT
9500
+ // "is the region within budget?" (use `before <= MEMORY_MD_CURATED_MAX_CHARS`).
9501
+ converged: false,
9502
+ archived: 0
9503
+ };
9504
+ if (curated.before > MEMORY_MD_CURATED_MAX_CHARS) {
9505
+ log8.warn("knowledge.md CURATED over soft budget at load \u2014 reported only, not rewritten", {
9506
+ charsBefore: curated.before,
9507
+ cap: MEMORY_MD_CURATED_MAX_CHARS,
9508
+ hardCap: MEMORY_MD_CURATED_HARD_MAX_CHARS,
9509
+ store: this.getStoreFileName()
9510
+ });
9511
+ }
9512
+ const obsBefore = this.observationPayloadChars();
9513
+ const observations = {
9514
+ before: obsBefore,
9515
+ after: obsBefore,
9516
+ converged: obsBefore <= MEMORY_OBSERVATIONS_MAX_CHARS,
9517
+ archived: 0
9518
+ };
9519
+ if (obsBefore > MEMORY_OBSERVATIONS_MAX_CHARS) {
9520
+ log8.warn("observation buffer over the ADVISORY line \u2014 reported only (agent decides)", {
9521
+ chars: obsBefore,
9522
+ advisory: MEMORY_OBSERVATIONS_MAX_CHARS,
9523
+ hardCeiling: MEMORY_OBSERVATIONS_HARD_MAX_CHARS,
9524
+ entries: this.entries.length,
9525
+ store: this.getStoreFileName()
9526
+ });
9527
+ }
9528
+ return { curated, observations };
9529
+ }
9530
+ /**
9531
+ * The exact set of entries that will be written into `## _observations`: the
9532
+ * per-pool COUNT cap (500 newest observations) plus the empty-content filter.
9533
+ * Kept in ONE place so the measured size and the written size can never diverge.
9534
+ * (H16: session fragments are their OWN pool/file and are NOT part of this set.)
9535
+ */
9536
+ observationWriteSet() {
9537
+ return this.entries.filter((e) => e.content.trim().length > 0).slice(-_MemoryStore.MAX_MEMORY_ENTRIES);
9538
+ }
9539
+ /**
9540
+ * Canonical size (chars) of the observation buffer = the **payload** the agent authored
9541
+ * (sum of entry bodies), NOT the container's serialized length.
9542
+ *
9543
+ * H25 — the measure must be INVARIANT under a change of container. H24 moved observations
9544
+ * from in-band markdown into `observations.json`, and this function was switched to
9545
+ * `serializeRecords(...).length` at the same time. The cap (`MEMORY_OBSERVATIONS_MAX_CHARS`)
9546
+ * was calibrated for markdown, so the same knowledge suddenly measured ~37% larger
9547
+ * (indentation + repeated keys + quotes): measured on real data, 34 entries were
9548
+ * 25 716 chars (86%, healthy) under markdown but 35 182 (117%, over) under pretty JSON —
9549
+ * and the load-time trimmer therefore **silently evicted** observations that were healthy
9550
+ * before the format change (observed in the boot log: 10 agents archived 1–6 each).
9551
+ *
9552
+ * Measuring the payload makes capacity independent of how we persist it: a future format
9553
+ * change can never again decide by itself which knowledge stays live. The count cap
9554
+ * (`MAX_MEMORY_ENTRIES`) remains the structural bound on entry count.
9555
+ */
9556
+ observationPayloadChars() {
9557
+ return this.observationWriteSet().reduce((sum, e) => sum + e.content.length, 0);
9558
+ }
9559
+ // §24 — `trimObservationBufferToCap()` was REMOVED together with the archive pool.
9560
+ //
9561
+ // It archived the OLDEST observations whenever the buffer passed its cap. Two things were
9562
+ // wrong with that, and both are structural rather than incidental:
9563
+ // 1. R4 — the platform decided, silently, what the agent gets to keep. "Lossless" is not
9564
+ // the same as "harmless": the live set shrank without the agent acting.
9565
+ // 2. R2 — it made capacity depend on the MEASUREMENT. When the container changed
9566
+ // (markdown → JSON) the same entries measured ~37% larger, so a format change alone
9567
+ // evicted healthy history (H25, observed: 10 agents archived 1–6 entries at boot).
9568
+ // The replacement is a single, honest point: `addEntry` refuses at
9569
+ // MEMORY_OBSERVATIONS_HARD_MAX_CHARS and moves nothing.
9570
+ // ─── H16: session-compaction fragments (their OWN pool + file) ──────────────
9571
+ //
9572
+ // A conversation fragment is the platform's compaction pagination payload, not an
9573
+ // agent observation. It lives in `session-fragments.json` with its OWN budget, is
9574
+ // NOT injected, and is NOT fed to the dream cycle — see MEMORY_FRAGMENTS_MAX_CHARS.
9575
+ /** Entries written to `session-fragments.json`: newest N, empty-content filtered. */
9576
+ fragmentWriteSet() {
9577
+ return this.fragments.filter((e) => e.type === "conversation_fragment" && e.content.trim().length > 0).slice(-_MemoryStore.MAX_MEMORY_ENTRIES);
9578
+ }
9579
+ /**
9580
+ * Canonical size (chars) of the fragment pool — payload only, same H25 invariant as
9581
+ * `observationPayloadChars`: the cap must not move when the container changes.
9582
+ */
9583
+ fragmentPayloadChars() {
9584
+ return this.fragmentWriteSet().reduce((sum, e) => sum + e.content.length, 0);
9585
+ }
9586
+ /**
9587
+ * Losslessly trim `session-fragments.json` to `MEMORY_FRAGMENTS_MAX_CHARS`: the
9588
+ * OLDEST fragments are appended verbatim to `session-fragments-archive.json`, which
9589
+ * `retrieveFragments` also searches — so pagination stays recoverable.
9590
+ */
9591
+ trimFragmentsToCap() {
9592
+ let archived = 0;
9593
+ while (this.fragmentPayloadChars() > MEMORY_FRAGMENTS_MAX_CHARS && this.fragments.length > 1) {
9594
+ const oldest = this.fragments.shift();
9595
+ if (!oldest)
9596
+ break;
9597
+ this.archiveFragment(oldest);
9598
+ archived++;
9599
+ }
9600
+ return { archived, converged: this.fragmentPayloadChars() <= MEMORY_FRAGMENTS_MAX_CHARS };
9601
+ }
9602
+ /** Append one fragment to the JSON archive (lossless, idempotent, deduped by id). */
9603
+ archiveFragment(entry) {
9604
+ this.appendRecords(this.fragmentArchiveFile, [entry]);
9605
+ }
9606
+ /**
9607
+ * H24 — append to a JSON record archive. Read + push + atomic write (rather than a raw text
9608
+ * append) is what makes a JSON array safe: the array structure is JSON's, so no payload can ever
9609
+ * end a record early. Deduped by id ⇒ idempotent.
9610
+ */
9611
+ appendRecords(file, entries2) {
9612
+ try {
9613
+ const existing = existsSync8(file) ? parseRecords(readFileSync6(file, "utf-8")).entries : [];
9614
+ const seen = new Set(existing.map((e) => e.id));
9615
+ const merged = [...existing, ...entries2.filter((e) => !seen.has(e.id))];
9616
+ writeFileAtomic(file, serializeRecords(merged));
9617
+ } catch (err) {
9618
+ log8.warn("Failed to append to record archive", { file: basename2(file), error: String(err) });
9619
+ }
9620
+ }
9621
+ /** Fragments that overflowed into the archive — still searchable via session_retrieve. */
9622
+ archivedFragmentEntries() {
9623
+ try {
9624
+ if (!existsSync8(this.fragmentArchiveFile))
9625
+ return [];
9626
+ return parseRecords(readFileSync6(this.fragmentArchiveFile, "utf-8")).entries.filter((e) => e.type === "conversation_fragment");
9627
+ } catch {
9628
+ return [];
9629
+ }
9630
+ }
9631
+ /**
9632
+ * H13/H20/H21 — repair the residue of the retired whole-file compression bug.
9633
+ *
9634
+ * The rules (deterministic, conservative, never-guess, idempotent) live in
9635
+ * `residue-repair.ts`; this method is the orchestrator. It heals three regions:
9636
+ * 1. the CURATED region — the part injected into every prompt (H21). A stub here is the
9637
+ * worst case: the agent's live knowledge shows an EMPTY section behind a pointer line,
9638
+ * which H20 (entry pools only) never touched — measured: 65 stubs across 25 agents.
9639
+ * 2. the observation pool, 3. the fragment pool.
9640
+ * Whatever changed is persisted here. Ambiguous (duplicate archive name) or unmatched
9641
+ * stubs are left untouched and REPORTED — the content is still in the archive, searchable.
9642
+ */
9643
+ repairStubResidue() {
9644
+ const report = {
9645
+ repaired: 0,
9646
+ ambiguous: [],
9647
+ notFound: [],
9648
+ curatedChanged: false,
9649
+ entriesChanged: false,
9650
+ fragmentsChanged: false
9651
+ };
9652
+ const bodies = /* @__PURE__ */ new Map();
9653
+ for (const rec of this.readArchiveRecords()) {
9654
+ const name = String(rec.metadata?.name ?? "").trim();
9655
+ if (!name)
9656
+ continue;
9657
+ const arr = bodies.get(name);
9658
+ if (arr)
9659
+ arr.push(rec.content);
9660
+ else
9661
+ bodies.set(name, [rec.content]);
9052
9662
  }
9053
- let chars = 0;
9663
+ if (bodies.size === 0)
9664
+ return report;
9665
+ const acc = { ambiguous: /* @__PURE__ */ new Map(), notFound: /* @__PURE__ */ new Set() };
9666
+ let curated = "";
9667
+ let curatedRaw = "";
9054
9668
  try {
9055
- chars = readFileSync6(this.longTermFile, "utf-8").length;
9669
+ if (existsSync8(this.longTermFile))
9670
+ curatedRaw = readFileSync6(this.longTermFile, "utf-8");
9056
9671
  } catch {
9057
- return { converged: false, charsBefore: 0, charsAfter: 0 };
9058
9672
  }
9059
- if (chars <= MEMORY_MD_TOTAL_MAX_CHARS) {
9060
- return { converged: false, charsBefore: chars, charsAfter: chars };
9673
+ if (curatedRaw) {
9674
+ curated = splitKnowledgeSections(curatedRaw).curated;
9675
+ const healed = healStubLines(curated, bodies);
9676
+ accumulateResidue(acc, healed.result);
9677
+ if (healed.result.repaired > 0) {
9678
+ curated = healed.text;
9679
+ report.curatedChanged = true;
9680
+ report.repaired += healed.result.repaired;
9681
+ }
9682
+ }
9683
+ for (const entry of this.entries) {
9684
+ const healed = healStubLines(entry.content, bodies);
9685
+ accumulateResidue(acc, healed.result);
9686
+ if (healed.result.repaired > 0) {
9687
+ entry.content = healed.text;
9688
+ report.entriesChanged = true;
9689
+ report.repaired += healed.result.repaired;
9690
+ }
9691
+ }
9692
+ for (const fragment of this.fragments) {
9693
+ const healed = healStubLines(fragment.content, bodies);
9694
+ accumulateResidue(acc, healed.result);
9695
+ if (healed.result.repaired > 0) {
9696
+ fragment.content = healed.text;
9697
+ report.fragmentsChanged = true;
9698
+ report.repaired += healed.result.repaired;
9699
+ }
9700
+ }
9701
+ if (report.entriesChanged) {
9702
+ this.saveToDisk();
9703
+ }
9704
+ if (report.curatedChanged) {
9705
+ this.writeKnowledgeMd(curated);
9706
+ }
9707
+ if (report.fragmentsChanged)
9708
+ this.saveFragmentsToDisk();
9709
+ report.ambiguous = [...acc.ambiguous.entries()].map(([name, candidates]) => ({ name, candidates }));
9710
+ report.notFound = [...acc.notFound];
9711
+ if (report.repaired > 0) {
9712
+ log8.warn("H13 residue repaired \u2014 re-inlined archived bodies (H21: curated region included)", {
9713
+ repaired: report.repaired,
9714
+ curatedChanged: report.curatedChanged,
9715
+ entriesChanged: report.entriesChanged,
9716
+ fragmentsChanged: report.fragmentsChanged,
9717
+ store: this.getStoreFileName(),
9718
+ archive: this.getArchiveFileName()
9719
+ });
9720
+ }
9721
+ if (report.ambiguous.length > 0 || report.notFound.length > 0) {
9722
+ log8.warn("H13 residue remains \u2014 left untouched (never guess); content still searchable in the archive", {
9723
+ ambiguous: report.ambiguous.slice(0, 20),
9724
+ notFound: report.notFound.slice(0, 20),
9725
+ store: this.getStoreFileName()
9726
+ });
9727
+ }
9728
+ return report;
9729
+ }
9730
+ loadFragmentsFromDisk() {
9731
+ try {
9732
+ if (existsSync8(this.fragmentFile)) {
9733
+ const { entries: entries2, error } = parseRecords(readFileSync6(this.fragmentFile, "utf-8"));
9734
+ if (error) {
9735
+ log8.error("session-fragments.json unreadable \u2014 NOT overwriting it; starting empty", {
9736
+ error,
9737
+ file: basename2(this.fragmentFile)
9738
+ });
9739
+ }
9740
+ this.fragments = entries2.filter((e) => e.type === "conversation_fragment" && e.content.trim().length > 0);
9741
+ if (this.fragments.length > 0) {
9742
+ log8.info(`Loaded ${this.fragments.length} session fragments from ${basename2(this.fragmentFile)}`);
9743
+ }
9744
+ return;
9745
+ }
9746
+ const legacy = join7(this.dataDir, "session-fragments.md");
9747
+ if (!existsSync8(legacy))
9748
+ return;
9749
+ const region = extractFragmentRegion(readFileSync6(legacy, "utf-8"));
9750
+ this.fragments = this.parseEntryBlocks(region, "frag_\\S*").filter((e) => e.type === "conversation_fragment" && e.content.trim().length > 0);
9751
+ this.saveFragmentsToDisk();
9752
+ try {
9753
+ unlinkSync2(legacy);
9754
+ } catch {
9755
+ }
9756
+ log8.info("H24: migrated session fragments from markdown to JSON", {
9757
+ count: this.fragments.length,
9758
+ file: basename2(this.fragmentFile)
9759
+ });
9760
+ } catch (err) {
9761
+ log8.warn("Failed to load session fragments", { error: String(err) });
9762
+ }
9763
+ }
9764
+ saveFragmentsToDisk() {
9765
+ try {
9766
+ this.trimFragmentsToCap();
9767
+ this.fragments = this.fragmentWriteSet();
9768
+ writeFileAtomic(this.fragmentFile, serializeRecords(this.fragments));
9769
+ } catch (err) {
9770
+ log8.warn("Failed to save session fragments", { error: String(err) });
9061
9771
  }
9062
- const result = this.compressLongTermMemory();
9063
- log8.warn("knowledge.md over budget at load \u2014 converged", {
9064
- charsBefore: result.charsBefore,
9065
- charsAfter: result.charsAfter,
9066
- cap: MEMORY_MD_TOTAL_MAX_CHARS,
9067
- store: this.getStoreFileName()
9068
- });
9069
- return { converged: true, charsBefore: result.charsBefore, charsAfter: result.charsAfter };
9070
9772
  }
9071
9773
  /**
9072
9774
  * Detect a knowledge.md that needs a boot-time rebuild: either unexpectedly
@@ -9087,6 +9789,20 @@ ${entry.content}
9087
9789
  }
9088
9790
  }
9089
9791
  /** Parse the ## _observations section of knowledge.md into MemoryEntry[] */
9792
+ /**
9793
+ * H26 — is the retired in-band `## _observations` region present in knowledge.md?
9794
+ * Used to decide whether the one-time migration to `observations.json` still has work to do,
9795
+ * independently of whether the buffer happens to be over budget.
9796
+ */
9797
+ hasLegacyObservationRegion() {
9798
+ try {
9799
+ if (!existsSync8(this.longTermFile))
9800
+ return false;
9801
+ return /(?:^|\n)## _observations\n/.test(readFileSync6(this.longTermFile, "utf-8"));
9802
+ } catch {
9803
+ return false;
9804
+ }
9805
+ }
9090
9806
  parseObservationsFromMemoryMd() {
9091
9807
  if (!existsSync8(this.longTermFile))
9092
9808
  return [];
@@ -9095,66 +9811,73 @@ ${entry.content}
9095
9811
  const obsMatch = content.match(/(?:^|\n)## _observations\n([\s\S]*)$/);
9096
9812
  if (!obsMatch)
9097
9813
  return [];
9098
- const obsContent = obsMatch[1];
9099
- const entries2 = [];
9100
- const subsections = obsContent.split(/\n### /).filter((s2) => s2.trim());
9101
- for (const section3 of subsections) {
9102
- const lines = section3.split("\n");
9103
- const headerLine = lines[0] ?? "";
9104
- if (headerLine.startsWith("<!--"))
9105
- continue;
9106
- const idMatch = headerLine.match(/^(\S+)/);
9107
- if (!idMatch)
9108
- continue;
9109
- const id = idMatch[1];
9110
- let type = "note";
9111
- let tags = [];
9112
- let restoredMeta;
9113
- const contentLines = [];
9114
- for (let i = 1; i < lines.length; i++) {
9115
- const metaMatch = lines[i].match(/^<!-- type: (\w+)(?:, tags: (.*?))?(?:, data-meta: (.+))? -->$/);
9116
- if (metaMatch) {
9117
- const typeVal = metaMatch[1];
9118
- if (typeVal && VALID_TYPES.has(typeVal))
9119
- type = typeVal;
9120
- let parsedMeta;
9121
- if (metaMatch[3])
9122
- parsedMeta = parseDataMeta(metaMatch[3]);
9123
- const legacyTags = metaMatch[2] ? metaMatch[2].split(",").map((t2) => t2.trim()).filter(Boolean) : [];
9124
- const metaTags = parsedMeta && Array.isArray(parsedMeta.tags) ? parsedMeta.tags : legacyTags;
9125
- if (parsedMeta) {
9126
- const rest = { ...parsedMeta };
9127
- delete rest.tags;
9128
- restoredMeta = { ...restoredMeta ?? {}, ...rest };
9129
- }
9130
- if (Array.isArray(metaTags)) {
9131
- tags = metaTags.map(String);
9132
- restoredMeta = { ...restoredMeta ?? {}, tags };
9133
- } else if (parsedMeta) {
9134
- restoredMeta = { ...restoredMeta ?? {} };
9135
- }
9136
- if (tags.some((t2) => /data-meta|\\"|\\:/i.test(t2)))
9137
- tags = [];
9138
- continue;
9139
- }
9140
- contentLines.push(lines[i]);
9141
- }
9142
- const idTs = id.match(/^obs_(\d+)/);
9143
- const timestamp = idTs ? new Date(parseInt(idTs[1])).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
9144
- entries2.push({
9145
- id,
9146
- timestamp,
9147
- type,
9148
- content: contentLines.join("\n").trim(),
9149
- metadata: restoredMeta !== void 0 ? restoredMeta : tags.length > 0 ? { tags } : void 0
9150
- });
9151
- }
9152
- return entries2;
9814
+ return this.parseEntryBlocks(obsMatch[1]);
9153
9815
  } catch (err) {
9154
9816
  log8.warn("Failed to parse observations from knowledge.md", { error: String(err) });
9155
9817
  return [];
9156
9818
  }
9157
9819
  }
9820
+ /**
9821
+ * Parse `### <id>` entry blocks (with `<!-- type: … -->` meta comments) from a region
9822
+ * body. Shared by the observation region, the session-fragment region AND the fragment
9823
+ * archive — so all three round-trip through the SAME reader (no format drift).
9824
+ */
9825
+ parseEntryBlocks(obsContent, boundaryId = "\\S+") {
9826
+ const entries2 = [];
9827
+ const subsections = obsContent.split(new RegExp(`\\n### (?=${boundaryId}\\n<!-- type: )`)).filter((s2) => s2.trim());
9828
+ for (const section3 of subsections) {
9829
+ const lines = section3.split("\n");
9830
+ const headerLine = lines[0] ?? "";
9831
+ if (headerLine.startsWith("<!--"))
9832
+ continue;
9833
+ const idMatch = headerLine.match(/^(\S+)/);
9834
+ if (!idMatch)
9835
+ continue;
9836
+ const id = idMatch[1];
9837
+ let type = "note";
9838
+ let tags = [];
9839
+ let restoredMeta;
9840
+ const contentLines = [];
9841
+ for (let i = 1; i < lines.length; i++) {
9842
+ const metaMatch = i === 1 ? lines[i].match(/^<!-- type: (\w+)(?:, tags: (.*?))?(?:, data-meta: (.+))? -->$/) : null;
9843
+ if (metaMatch) {
9844
+ const typeVal = metaMatch[1];
9845
+ if (typeVal && VALID_TYPES.has(typeVal))
9846
+ type = typeVal;
9847
+ let parsedMeta;
9848
+ if (metaMatch[3])
9849
+ parsedMeta = parseDataMeta(metaMatch[3]);
9850
+ const legacyTags = metaMatch[2] ? metaMatch[2].split(",").map((t2) => t2.trim()).filter(Boolean) : [];
9851
+ const metaTags = parsedMeta && Array.isArray(parsedMeta.tags) ? parsedMeta.tags : legacyTags;
9852
+ if (parsedMeta) {
9853
+ const rest = { ...parsedMeta };
9854
+ delete rest.tags;
9855
+ restoredMeta = { ...restoredMeta ?? {}, ...rest };
9856
+ }
9857
+ if (Array.isArray(metaTags)) {
9858
+ tags = metaTags.map(String);
9859
+ restoredMeta = { ...restoredMeta ?? {}, tags };
9860
+ } else if (parsedMeta) {
9861
+ restoredMeta = { ...restoredMeta ?? {} };
9862
+ }
9863
+ if (tags.some((t2) => /data-meta|\\"|\\:/i.test(t2)))
9864
+ tags = [];
9865
+ continue;
9866
+ }
9867
+ contentLines.push(decodeEntryBodyLine(lines[i]));
9868
+ }
9869
+ const idTs = id.match(/^obs_(\d+)/);
9870
+ const timestamp = idTs ? new Date(parseInt(idTs[1])).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
9871
+ entries2.push({
9872
+ id,
9873
+ timestamp,
9874
+ type,
9875
+ content: contentLines.join("\n").trim(),
9876
+ metadata: restoredMeta !== void 0 ? restoredMeta : tags.length > 0 ? { tags } : void 0
9877
+ });
9878
+ }
9879
+ return entries2;
9880
+ }
9158
9881
  loadSessionsFromDisk() {
9159
9882
  try {
9160
9883
  const files = readdirSync(this.sessionsDir).filter((f) => f.endsWith(".json"));
@@ -9217,57 +9940,47 @@ ${entry.content}
9217
9940
  }
9218
9941
  saveToDisk() {
9219
9942
  try {
9220
- const obsLines = [
9221
- "## _observations",
9222
- "<!-- This section is the observation buffer. Searched on-demand, NOT always injected into prompt. -->",
9223
- "<!-- Dream cycle consolidates recurring patterns into curated sections above. -->",
9224
- ""
9225
- ];
9226
- const isFrag = (e) => e.type === "conversation_fragment";
9227
- const obsCount = () => this.entries.filter((e) => !isFrag(e)).length;
9228
- let obsChars = this.entries.filter((e) => !isFrag(e)).reduce((n2, e) => n2 + e.content.length + 96, 0);
9229
- while (obsChars > MEMORY_OBSERVATIONS_MAX_CHARS && obsCount() > 1) {
9230
- const idx = this.entries.findIndex((e) => !isFrag(e));
9231
- if (idx < 0)
9232
- break;
9233
- const oldest = this.entries.splice(idx, 1)[0];
9234
- this.archiveSection(`observation ${oldest.id}`, oldest.content);
9235
- obsChars -= oldest.content.length + 96;
9236
- }
9237
- const keptObs = this.entries.filter((e) => !isFrag(e)).slice(-_MemoryStore.MAX_MEMORY_ENTRIES);
9238
- const keptFrags = this.entries.filter(isFrag).slice(-_MemoryStore.MAX_MEMORY_ENTRIES);
9239
- const keepIds = new Set([...keptObs, ...keptFrags].map((e) => e.id));
9240
- const entries2 = this.entries.filter((e) => keepIds.has(e.id) && e.content.trim().length > 0);
9943
+ const entries2 = this.observationWriteSet();
9241
9944
  this.entries = entries2;
9242
- for (const entry of entries2) {
9243
- obsLines.push(`### ${entry.id}`);
9244
- const tags = Array.isArray(entry.metadata?.tags) ? entry.metadata.tags : [];
9245
- const meta = entry.metadata && typeof entry.metadata === "object" ? { ...entry.metadata, tags } : tags.length > 0 ? { tags } : void 0;
9246
- const metaJson = meta ? safeJson(meta) : "";
9247
- obsLines.push(`<!-- type: ${entry.type}${metaJson ? `, data-meta: ${metaJson}` : ""} -->`);
9248
- obsLines.push(entry.content);
9249
- obsLines.push("");
9250
- }
9251
- const obsSection = obsLines.join("\n");
9252
- let existing = "";
9253
- if (existsSync8(this.longTermFile)) {
9254
- existing = readFileSync6(this.longTermFile, "utf-8");
9255
- }
9256
- let obsStart = existing.indexOf("\n## _observations");
9257
- if (obsStart < 0 && existing.startsWith("## _observations"))
9258
- obsStart = 0;
9259
- let updated;
9260
- if (obsStart > 0) {
9261
- updated = existing.slice(0, obsStart) + "\n" + obsSection;
9262
- } else if (obsStart === 0) {
9263
- updated = obsSection;
9264
- } else {
9265
- updated = (existing ? existing.trimEnd() + "\n\n" : "") + obsSection;
9266
- }
9267
- writeFileAtomic(this.longTermFile, updated);
9945
+ writeFileAtomic(this.observationFile, serializeRecords(entries2));
9946
+ this.writeCuratedKnowledgeMd();
9268
9947
  } catch (err) {
9269
- log8.warn("Failed to save observations to knowledge.md", { error: String(err) });
9948
+ log8.warn("Failed to save observations", { error: String(err) });
9949
+ }
9950
+ }
9951
+ /**
9952
+ * H24 — `knowledge.md` now holds ONLY the curated region (the injected, human-readable part) plus
9953
+ * a pointer comment. If a legacy `## _observations` region is still present, everything from it on
9954
+ * is dropped — that content already lives in `observations.json`.
9955
+ */
9956
+ writeCuratedKnowledgeMd() {
9957
+ let existing = "";
9958
+ try {
9959
+ if (existsSync8(this.longTermFile))
9960
+ existing = readFileSync6(this.longTermFile, "utf-8");
9961
+ } catch {
9270
9962
  }
9963
+ this.writeKnowledgeMd(existing);
9964
+ }
9965
+ /**
9966
+ * I1 — the SINGLE writer of `knowledge.md`.
9967
+ *
9968
+ * Every path that persists curated knowledge funnels through here, so "what is in
9969
+ * knowledge.md" is decided in exactly one place: the R1 defect (one fact, several writers)
9970
+ * is no longer expressible. It enforces the post-migration contract — the file holds the
9971
+ * CURATED region ONLY; anything from a legacy in-band `## _observations` region is dropped,
9972
+ * because that content lives in `observations.json` since H24 (§20). Bootstrap creation of
9973
+ * the file (`ensureKnowledgeFile`) is separate: it only ever runs when the file is absent.
9974
+ *
9975
+ * A trailing pointer comment is deliberately NOT written: the curated region is injected into
9976
+ * every prompt, so a comment after the last `## section` would be absorbed into that section's
9977
+ * body and injected with it. Where observations went is documented in
9978
+ * docs/PLATFORM-HARDENING-2026-10.md §20 and visible as observations.json next to the file.
9979
+ */
9980
+ writeKnowledgeMd(text) {
9981
+ const curated = splitKnowledgeSections(text).curated.trimEnd();
9982
+ writeFileAtomic(this.longTermFile, curated ? `${curated}
9983
+ ` : "");
9271
9984
  }
9272
9985
  saveSessionToDisk(session) {
9273
9986
  try {
@@ -9287,88 +10000,8 @@ ${entry.content}
9287
10000
  this.saveSessionToDisk(session);
9288
10001
  }, 1e3));
9289
10002
  }
9290
- /** Compress knowledge.md — truncate oversized sections to prevent context bloat */
9291
- compressLongTermMemory() {
9292
- if (!existsSync8(this.longTermFile)) {
9293
- return { charsBefore: 0, charsAfter: 0, sectionsBefore: 0, sectionsAfter: 0, truncatedChunks: 0 };
9294
- }
9295
- const content = readFileSync6(this.longTermFile, "utf-8");
9296
- const charsBefore = content.length;
9297
- const lines = content.split("\n");
9298
- let i = 0;
9299
- const preambleLines = [];
9300
- while (i < lines.length && !lines[i].startsWith("## ")) {
9301
- preambleLines.push(lines[i]);
9302
- i++;
9303
- }
9304
- const sections = [];
9305
- let currentHeader = "";
9306
- let currentBody = [];
9307
- let currentIsObs = false;
9308
- while (i < lines.length) {
9309
- const line = lines[i];
9310
- if (line.startsWith("## ")) {
9311
- if (currentHeader) {
9312
- sections.push({ headerLine: currentHeader, body: currentBody, observationBuffer: currentIsObs });
9313
- }
9314
- currentHeader = line;
9315
- currentBody = [];
9316
- currentIsObs = /^##\s+_observations\s*$/.test(line);
9317
- } else {
9318
- currentBody.push(line);
9319
- }
9320
- i++;
9321
- }
9322
- if (currentHeader) {
9323
- sections.push({ headerLine: currentHeader, body: currentBody, observationBuffer: currentIsObs });
9324
- }
9325
- const sectionsBefore = sections.length;
9326
- let archived = 0;
9327
- const render2 = () => {
9328
- const out = [...preambleLines];
9329
- for (const s2 of sections)
9330
- out.push(s2.headerLine, s2.body.join("\n"));
9331
- return out.join("\n");
9332
- };
9333
- const size = () => render2().length;
9334
- const isPointer = (s2) => /^_\[archived/.test(s2.body.join("\n").trim());
9335
- const archiveBodyOf = (section3) => {
9336
- const bodyStr = section3.body.join("\n").trim();
9337
- if (!bodyStr)
9338
- return;
9339
- const name = section3.headerLine.replace(/^##\s+/, "").trim();
9340
- this.archiveSection(name, bodyStr);
9341
- section3.body = [`_[archived \u2192 ${this.getArchiveFileName()}\uFF1B\u6B63\u6587\u5DF2\u65E0\u635F\u5F52\u6863\uFF0C\u53EF\u7528 memory_search \u68C0\u7D22]_`];
9342
- archived++;
9343
- };
9344
- for (const section3 of sections) {
9345
- if (section3.observationBuffer)
9346
- continue;
9347
- if (section3.body.join("\n").length > MEMORY_MD_SECTION_MAX_CHARS)
9348
- archiveBodyOf(section3);
9349
- }
9350
- if (size() > MEMORY_MD_TOTAL_MAX_CHARS) {
9351
- const shrinkable = sections.filter((s2) => !s2.observationBuffer && !isPointer(s2)).sort((a, b) => b.body.join("\n").length - a.body.join("\n").length);
9352
- for (const section3 of shrinkable) {
9353
- if (size() <= MEMORY_MD_TOTAL_MAX_CHARS)
9354
- break;
9355
- if (section3.body.join("\n").trim().length <= 120)
9356
- continue;
9357
- archiveBodyOf(section3);
9358
- }
9359
- }
9360
- const compressed = render2();
9361
- if (compressed !== content)
9362
- writeFileAtomic(this.longTermFile, compressed);
9363
- return {
9364
- charsBefore,
9365
- charsAfter: compressed.length,
9366
- sectionsBefore,
9367
- sectionsAfter: sections.length,
9368
- truncatedChunks: archived
9369
- };
9370
- }
9371
10003
  };
10004
+ FRAGMENT_REGION_HEADER = "## _session_fragments";
9372
10005
  }
9373
10006
  });
9374
10007
 
@@ -9399,7 +10032,8 @@ function freshCounters() {
9399
10032
  cacheWriteTokens: 0,
9400
10033
  turnsCompleted: 0,
9401
10034
  nonChatTurns: 0,
9402
- markerMissTurns: 0,
10035
+ emptyTurns: 0,
10036
+ endTurnTurns: 0,
9403
10037
  promptTokensReported: 0
9404
10038
  };
9405
10039
  }
@@ -9515,9 +10149,10 @@ var init_agent_metrics = __esm({
9515
10149
  this.scheduleSave();
9516
10150
  }
9517
10151
  /**
9518
- * C2: a mailbox turn completed. Non-chat turns are expected to end with a completion
9519
- * marker; missing markers on those turns feed the marker-failure rate. Chat turns are
9520
- * excluded (a human is reading the reply, no marker protocol applies).
10152
+ * C2: a mailbox turn completed. The honest non-chat signals are "did the turn
10153
+ * produce anything at all" (an empty reply is the real failure) and "did it close
10154
+ * itself out via the typed `end_turn` signal". Chat turns are excluded — a human is
10155
+ * reading the reply, so no completion accounting applies.
9521
10156
  */
9522
10157
  recordTurn(opts) {
9523
10158
  const c = this.counters;
@@ -9526,8 +10161,10 @@ var init_agent_metrics = __esm({
9526
10161
  c.estimatedCost += opts.costUsd;
9527
10162
  if (!opts.isChat) {
9528
10163
  c.nonChatTurns++;
9529
- if (!opts.hadCompletionMarker)
9530
- c.markerMissTurns++;
10164
+ if (opts.emptyReply)
10165
+ c.emptyTurns++;
10166
+ if (opts.endedTurnViaTool)
10167
+ c.endTurnTurns++;
9531
10168
  }
9532
10169
  this.scheduleSave();
9533
10170
  }
@@ -9559,13 +10196,15 @@ var init_agent_metrics = __esm({
9559
10196
  };
9560
10197
  }
9561
10198
  computeHarnessMetrics(c) {
9562
- const markerFailureRate = c.nonChatTurns > 0 ? c.markerMissTurns / c.nonChatTurns : 0;
10199
+ const emptyTurnRate = c.nonChatTurns > 0 ? c.emptyTurns / c.nonChatTurns : 0;
10200
+ const turnEndedViaToolRate = c.nonChatTurns > 0 ? c.endTurnTurns / c.nonChatTurns : 0;
9563
10201
  const cacheHitRate = c.promptTokens > 0 ? Math.min(1, c.cacheReadTokens / c.promptTokens) : 0;
9564
10202
  const window3 = this.computeWindowStats();
9565
10203
  const perTurnCostUsd = c.turnsCompleted > 0 ? c.estimatedCost / c.turnsCompleted : 0;
9566
10204
  return {
9567
10205
  compressionCount: c.compressionCount,
9568
- markerFailureRate,
10206
+ emptyTurnRate,
10207
+ turnEndedViaToolRate,
9569
10208
  cacheHitRate,
9570
10209
  cacheHitRateWindow: window3.cacheHitRateWindow,
9571
10210
  cacheHitRateSamples: window3.cacheHitRateSamples,
@@ -9790,6 +10429,15 @@ var init_agent_metrics = __esm({
9790
10429
  function isSkillOrMcpToolName(name) {
9791
10430
  return name.includes("__") || name.startsWith("feishu_") || name.startsWith("chrome-devtools") || name.startsWith("chrome_");
9792
10431
  }
10432
+ function toolEvictionTier(name, protectedNames = TOOL_DEF_PROTECTED, coreKeep = TOOL_DEF_CORE_KEEP) {
10433
+ if (protectedNames.has(name))
10434
+ return 0;
10435
+ if (TOOL_DEF_EVICT_FIRST.has(name) || isSkillOrMcpToolName(name))
10436
+ return 3;
10437
+ if (coreKeep.has(name))
10438
+ return 1;
10439
+ return 2;
10440
+ }
9793
10441
  function isWorkContextBoundTool(name) {
9794
10442
  return EXECUTE_SESSION_ONLY_TOOLS.has(name);
9795
10443
  }
@@ -9862,17 +10510,18 @@ function evictToolsToBudget(tools, budget, protectedNames = TOOL_DEF_PROTECTED,
9862
10510
  const current = [...tools];
9863
10511
  const evicted = [];
9864
10512
  const sizeOf = (t2) => JSON.stringify(t2).length;
9865
- const pickVictim = (predicate) => {
10513
+ const pickVictim = () => {
9866
10514
  let victimIdx = -1;
10515
+ let bestTier = 0;
9867
10516
  let victimSize = -1;
9868
10517
  for (let i = 0; i < current.length; i++) {
9869
10518
  const t2 = current[i];
9870
- if (protectedNames.has(t2.name))
9871
- continue;
9872
- if (!predicate(t2))
10519
+ const tier = toolEvictionTier(t2.name, protectedNames, coreKeep);
10520
+ if (tier === 0)
9873
10521
  continue;
9874
10522
  const sz = sizeOf(t2);
9875
- if (sz > victimSize) {
10523
+ if (tier > bestTier || tier === bestTier && sz > victimSize) {
10524
+ bestTier = tier;
9876
10525
  victimSize = sz;
9877
10526
  victimIdx = i;
9878
10527
  }
@@ -9880,13 +10529,7 @@ function evictToolsToBudget(tools, budget, protectedNames = TOOL_DEF_PROTECTED,
9880
10529
  return victimIdx;
9881
10530
  };
9882
10531
  while (estimateToolDefTokens(current) > budget && current.length > 0) {
9883
- let victimIdx = pickVictim((t2) => isSkillOrMcpToolName(t2.name));
9884
- if (victimIdx < 0) {
9885
- victimIdx = pickVictim((t2) => !coreKeep.has(t2.name));
9886
- }
9887
- if (victimIdx < 0) {
9888
- victimIdx = pickVictim(() => true);
9889
- }
10532
+ const victimIdx = pickVictim();
9890
10533
  if (victimIdx < 0)
9891
10534
  break;
9892
10535
  const [victim] = current.splice(victimIdx, 1);
@@ -9924,7 +10567,7 @@ ${names}`.slice(0, cap);
9924
10567
  }
9925
10568
  return [header, ...lines].join("\n");
9926
10569
  }
9927
- var REFLEX_CORE_TOOLS, REFLEX_MANAGER_EXTRA_TOOLS, CONVERSE_FORBIDDEN_DEFAULT, TOOL_DEF_PROTECTED, SCHEMA_INJECTED_TOOLS, TOOL_DEF_CORE_KEEP, EXECUTE_SESSION_ONLY_TOOLS, DISTILLATION_EXTRA_TOOLS, TASK_EXECUTION_EXTRA_TOOLS, COMMENT_RESPONSE_ALLOWED_TOOLS, REQUIREMENT_ACTION_ALLOWED_TOOLS, WORKFLOW_ACTION_ALLOWED_TOOLS, SCENARIO_ALLOWED_TOOLS;
10570
+ var REFLEX_CORE_TOOLS, REFLEX_MANAGER_EXTRA_TOOLS, CONVERSE_FORBIDDEN_DEFAULT, TOOL_DEF_PROTECTED, SCHEMA_INJECTED_TOOLS, TOOL_DEF_CORE_KEEP, TOOL_DEF_EVICT_FIRST, EXECUTE_SESSION_ONLY_TOOLS, DISTILLATION_EXTRA_TOOLS, TASK_EXECUTION_EXTRA_TOOLS, COMMENT_RESPONSE_ALLOWED_TOOLS, REQUIREMENT_ACTION_ALLOWED_TOOLS, WORKFLOW_ACTION_ALLOWED_TOOLS, SCENARIO_ALLOWED_TOOLS;
9928
10571
  var init_capability_packs = __esm({
9929
10572
  "../core/dist/capability-packs.js"() {
9930
10573
  "use strict";
@@ -9953,7 +10596,15 @@ var init_capability_packs = __esm({
9953
10596
  "discover_tools",
9954
10597
  "notify_user",
9955
10598
  "request_user_input",
9956
- "request_user_approval"
10599
+ "request_user_approval",
10600
+ // Turn-termination signal. Prompt text for agent↔agent DM / comment threads
10601
+ // instructs the model to "call the `end_turn` tool". If budget pressure evicts
10602
+ // it, the model is told to call a tool it does not have → it falls back to
10603
+ // writing prose about why it is not replying, and that prose IS a message that
10604
+ // re-triggers the peer → the exact meta-loop end_turn exists to kill.
10605
+ // Schema is tiny (one optional string), so protection is effectively free.
10606
+ // Listing it here also propagates to TOOL_DEF_CORE_KEEP and the reflex allowlist.
10607
+ "end_turn"
9957
10608
  ]);
9958
10609
  SCHEMA_INJECTED_TOOLS = /* @__PURE__ */ new Set([
9959
10610
  "schedule_wakeup",
@@ -9962,7 +10613,14 @@ var init_capability_packs = __esm({
9962
10613
  "recall_activity",
9963
10614
  "complete_deliberation",
9964
10615
  "notebook_upsert",
9965
- "notebook_clear"
10616
+ "notebook_clear",
10617
+ // Right-panel control (Team Chat). Same hazard as the group above: pushed via
10618
+ // pushUnique (no registerTool handler) and NOT in TOOL_DEF_PROTECTED, so budget
10619
+ // eviction defers them — and without this entry discover_tools answers
10620
+ // "unknown", leaving the feature permanently unreachable for that turn.
10621
+ // Measured 2026-10-03: evicted 65x/day before this fix.
10622
+ "open_right_panel",
10623
+ "collapse_right_panel"
9966
10624
  ]);
9967
10625
  TOOL_DEF_CORE_KEEP = /* @__PURE__ */ new Set([
9968
10626
  ...TOOL_DEF_PROTECTED,
@@ -9989,7 +10647,34 @@ var init_capability_packs = __esm({
9989
10647
  "agent_list_colleagues",
9990
10648
  "deliverable_search",
9991
10649
  "requirement_comment",
9992
- "session"
10650
+ "session",
10651
+ // Knowledge base — the read path of the memory system. The agent's ability to
10652
+ // consult its own curated knowledge is core work, not a situational extra.
10653
+ "kb_search",
10654
+ "kb_read",
10655
+ "kb_list"
10656
+ ]);
10657
+ TOOL_DEF_EVICT_FIRST = /* @__PURE__ */ new Set([
10658
+ // packaging / hub / generation
10659
+ "package_install",
10660
+ "package_list",
10661
+ "hub_search",
10662
+ "hub_install",
10663
+ "office_generate",
10664
+ // misc situational
10665
+ "decide",
10666
+ "recall_context",
10667
+ // team / org administration
10668
+ "agent_broadcast_status",
10669
+ "agent_delegate_task",
10670
+ "agent_send_group_message",
10671
+ "agent_create_group_chat",
10672
+ "agent_list_group_chats",
10673
+ "delegate_message",
10674
+ "agent_start",
10675
+ "agent_stop",
10676
+ "team_status",
10677
+ "team_list"
9993
10678
  ]);
9994
10679
  EXECUTE_SESSION_ONLY_TOOLS = /* @__PURE__ */ new Set([
9995
10680
  "task_submit_review",
@@ -10552,9 +11237,12 @@ _[norms truncated \u2014 read \`${opts.teamDataDir ?? "team"}/NORMS.md\` for ful
10552
11237
  try {
10553
11238
  const h = opts.memory.getMemoryHealth();
10554
11239
  const staleDays = h.lastConsolidatedAt ? Math.max(0, Math.floor((Date.now() - Date.parse(h.lastConsolidatedAt)) / 864e5)) : null;
10555
- if (h.percent >= 70 || staleDays !== null && staleDays >= 14) {
11240
+ if (h.percent >= MEMORY_HEALTH_WARN_PERCENT || staleDays !== null && staleDays >= 14) {
10556
11241
  const staleness = staleDays !== null && staleDays >= 14 ? ` \xB7 \u4E0A\u6B21\u6574\u7406 ${staleDays} \u5929\u524D` : "";
10557
- volatile.push(`> ${h.percent >= 90 ? "\u{1F534}" : "\u26A0\uFE0F"} **\u8BB0\u5FC6\u5065\u5EB7 ${h.percent}%**\uFF08${h.totalChars}/${h.cap} \u5B57\u7B26 \xB7 ${h.curatedSections} \u4E2A\u77E5\u8BC6\u6BB5 \xB7 ${h.observations} \u6761\u89C2\u5BDF${h.archiveChars > 0 ? ` \xB7 \u5DF2\u5F52\u6863 ${h.archiveChars} \u5B57\u7B26` : ""}${staleness}\uFF09\u3002\u8D85\u9884\u7B97\u65F6\u65E7\u77E5\u8BC6\u4F1A\u88AB**\u65E0\u635F\u5F52\u6863**\uFF08\u4E0D\u518D\u6CE8\u5165\uFF09\u3002\u5EFA\u8BAE\u7528 \`memory_organize\` \u5408\u5E76\u89C2\u5BDF\u3001\u6216 \`memory_update\`\uFF08mode:"delete"\uFF09\u5220\u9664\u8FC7\u65F6\u6761\u76EE\u3002`);
11242
+ volatile.push(`> ${h.percent >= MEMORY_HEALTH_CRITICAL_PERCENT ? "\u{1F534}" : "\u26A0\uFE0F"} **\u8BB0\u5FC6\u5065\u5EB7 ${h.percent}%**\uFF08\u6CE8\u5165\u6BB5 ${h.curatedChars}/${h.curatedCap} \u5B57\u7B26 \xB7 ${h.curatedSections} \u4E2A\u77E5\u8BC6\u6BB5${staleness}\uFF09\u3002\u6CE8\u5165\u6BB5\u8D85\u9884\u7B97\u65F6\uFF0C\u6700\u5927\u7684\u6BB5\u843D\u6B63\u6587\u4F1A\u88AB**\u65E0\u635F\u5F52\u6863**\uFF08\u79FB\u51FA\u6BCF\u8F6E\u6CE8\u5165\uFF0C\u4ECD\u53EF\u7528 \`memory_search\` \u68C0\u7D22\uFF09\u3002\u5EFA\u8BAE\u7528 \`memory_organize\` \u5408\u5E76\u6BB5\u843D\u3001\u6216 \`memory_update\`\uFF08mode:"delete"\uFF09\u5220\u9664\u8FC7\u65F6\u6761\u76EE\u3002`);
11243
+ }
11244
+ if (h.observationPercent >= MEMORY_HEALTH_WARN_PERCENT) {
11245
+ volatile.push(`> \u{1F5D2}\uFE0F **\u89C2\u5BDF\u7F13\u51B2 ${h.observationPercent}%**\uFF08${h.observationChars}/${h.observationCap} \u5B57\u7B26 \xB7 ${h.observations} \u6761\u89C2\u5BDF${h.archiveChars > 0 ? ` \xB7 \u5DF2\u5F52\u6863 ${h.archiveChars} \u5B57\u7B26` : ""}\uFF09\u3002\u89C2\u5BDF\u7F13\u51B2**\u4E0D\u6CE8\u5165** prompt\uFF08\u4EC5 \`memory_search\` \u6309\u9700\u68C0\u7D22\uFF09\uFF1B\u8D85\u4E0A\u9650\u65F6\u6700\u65E7\u7684\u89C2\u5BDF\u4F1A\u88AB\u65E0\u635F\u5F52\u6863\uFF0C\u4ECD\u53EF\u68C0\u7D22\u3002\u5E73\u53F0\u4F1A\u5728\u4E0B\u4E00\u8F6E dream \u5468\u671F\u81EA\u52A8\u5408\u5E76\u91CD\u590D\u9879\uFF1B\u4E5F\u53EF\u73B0\u5728\u5C31\u4E3B\u52A8\u5904\u7406\uFF1A\`memory_organize\`\uFF08\u628A\u91CD\u590D\u89C2\u5BDF\u5408\u5E76\u8FDB curated \u6BB5\u843D\uFF09\u6216 \`memory_update\`\uFF08\`mode:"delete"\` \u5220\u9664\u8FC7\u65F6\u9879\uFF09\u3002`);
10558
11246
  }
10559
11247
  } catch {
10560
11248
  }
@@ -10687,21 +11375,11 @@ _[dynamic context truncated]_`);
10687
11375
  }
10688
11376
  }
10689
11377
  const alreadyShownIds = /* @__PURE__ */ new Set();
10690
- const cpp = opts.cognitiveContext;
10691
- if (cpp && !cpp.isEmpty) {
10692
- if (cpp.cognitiveContext) {
10693
- dynamic.push("\n## Cognitive Context");
10694
- dynamic.push(cpp.cognitiveContext);
10695
- }
10696
- if (cpp.retrievedContext) {
10697
- dynamic.push("\n## Retrieved Context");
10698
- dynamic.push(cpp.retrievedContext);
10699
- }
10700
- if (cpp.reflection) {
10701
- dynamic.push("\n## Reflection");
10702
- dynamic.push(cpp.reflection);
10703
- }
10704
- } else if (!isDream) {
11378
+ if (opts.cognitiveContext) {
11379
+ dynamic.push("\n## Cognitive Context");
11380
+ dynamic.push(opts.cognitiveContext);
11381
+ }
11382
+ if (!isDream) {
10705
11383
  const relevantMemories = await this.retrieveRelevantMemories(opts.memory, opts.currentQuery, opts.agentId, alreadyShownIds);
10706
11384
  if (relevantMemories.length > 0) {
10707
11385
  volatile.push("\n## Relevant Memories");
@@ -10940,7 +11618,7 @@ ${ctx.mergedContent.slice(0, SYSTEM_MAILBOX_MERGED_CHARS)}`);
10940
11618
  lines.push("- [ ] Read ALL prior comments \u2014 understand the thread.");
10941
11619
  lines.push("- [ ] Is the comment directed at you? Does it change your work?");
10942
11620
  lines.push("- [ ] Reply with `reply_to_comment_id`. One consolidated reply if multiple comments.");
10943
- lines.push("- [ ] Does your reply add NEW information? If not \u2192 `[NO_REPLY_NEEDED]`.");
11621
+ lines.push("- [ ] Does your reply add NEW information? If not \u2192 no reply (call `end_turn`).");
10944
11622
  lines.push("");
10945
11623
  lines.push("**task_status_update** (usually informational):");
10946
11624
  lines.push("- [ ] Does this affect your current work or priorities?");
@@ -11132,8 +11810,12 @@ ${ctx.mergedContent.slice(0, SYSTEM_MAILBOX_MERGED_CHARS)}`);
11132
11810
  lines.push("");
11133
11811
  lines.push("**Conversation flow**: After you reply, the other agent will be automatically triggered to respond. This creates a natural back-and-forth conversation \u2014 like texting a colleague.");
11134
11812
  lines.push("");
11135
- lines.push("**CRITICAL \u2014 When to STOP replying** (respond with exactly `[NO_RESPONSE]`):");
11136
- lines.push("Your reply triggers the other agent to respond, which triggers you again \u2014 an infinite loop if you do not stop. You MUST respond with `[NO_RESPONSE]` in ALL of these cases:");
11813
+ lines.push("**CRITICAL \u2014 How to STOP the conversation**:");
11814
+ lines.push("Your reply auto-triggers the other agent, so a reply that carries no new information keeps the exchange alive forever. To end your side, **call the `end_turn` tool** and write no reply text. That is the only correct stop signal: it ends your turn without sending anything to the peer.");
11815
+ lines.push('Do NOT write a message explaining that you will not reply. Text like "no response needed", "\u65E0\u5F85\u529E", "\u5DF2\u6536\u5230\uFF0C\u4E0D\u91CD\u590D\u56DE\u590D", "\u8BE5\u6D88\u606F\u4E3A\u91CD\u590D\uFF0C\u6211\u4E0D\u518D\u56DE\u590D" is **itself a reply**: it gets delivered, re-triggers the peer, and restarts the exact loop it was meant to stop. Silence is the *absence* of a message \u2014 never a message about being silent.');
11816
+ lines.push("(Writing no reply text at all also stops the exchange, and a bare `[NO_RESPONSE]` is still accepted as a legacy shorthand \u2014 but **`end_turn` is preferred**: it cannot be paraphrased by mistake.)");
11817
+ lines.push("");
11818
+ lines.push("Stop and write nothing when:");
11137
11819
  lines.push("- The conversation has reached a natural conclusion (agreement reached, question answered, info exchanged)");
11138
11820
  lines.push("- You have nothing **new and actionable** to add \u2014 no new facts, no new questions, no new instructions");
11139
11821
  lines.push('- You are just acknowledging receipt ("OK", "got it", "understood", "\u6536\u5230", "noted", "roger", "will do", "\u4FDD\u6301\u5F85\u547D", "standby", "\u6536\u5230\uFF0C\u4FDD\u6301\u5F85\u547D")');
@@ -11141,7 +11823,7 @@ ${ctx.mergedContent.slice(0, SYSTEM_MAILBOX_MERGED_CHARS)}`);
11141
11823
  lines.push("- The other party confirmed or acknowledged your last message \u2014 the exchange is complete");
11142
11824
  lines.push('- You want to say something purely polite, ceremonial, or encouraging (e.g., "\u52A0\u6CB9", "sounds good", "great work")');
11143
11825
  lines.push('- You already got the answer you needed from this peer \u2014 do NOT paste "X \u56DE\u590D\u8BF4\uFF1A\u2026" back into this DM');
11144
- lines.push("**Default to [NO_RESPONSE]**. Only reply if you have genuinely new information, a question that needs answering, or a correction. When in doubt, STOP.");
11826
+ lines.push("**Default to writing nothing.** Only reply if you have genuinely new information, a question that needs answering, or a correction. When in doubt, STOP.");
11145
11827
  lines.push("");
11146
11828
  lines.push("**Human delivery (very important):**");
11147
11829
  lines.push("- If you asked this peer something on behalf of a human (owner/boss), deliver the answer with `notify_user` (or report it in your human chat).");
@@ -11189,8 +11871,8 @@ ${ctx.mergedContent.slice(0, SYSTEM_MAILBOX_MERGED_CHARS)}`);
11189
11871
  lines.push("4. When you accept a work assignment, verify a task has been created for it (`task_list`). If the coordinator did not create one, remind them or create it yourself with the correct `assigned_agent_id`. Do NOT make promises without task tracking.");
11190
11872
  }
11191
11873
  lines.push("5. DEFAULT IS SILENCE. Before responding, answer these questions:");
11192
- lines.push(" a) Has another agent already given a substantively similar answer? If yes \u2192 [NO_RESPONSE]");
11193
- lines.push(" b) Does your response add UNIQUE expertise or information? If no \u2192 [NO_RESPONSE]");
11874
+ lines.push(" a) Has another agent already given a substantively similar answer? If yes \u2192 no reply (call `end_turn`)");
11875
+ lines.push(" b) Does your response add UNIQUE expertise or information? If no \u2192 no reply (call `end_turn`)");
11194
11876
  lines.push(` c) Check channel history \u2014 duplicate or "me too" responses waste everyone's time.`);
11195
11877
  lines.push("6. @MENTION \u2014 CRITICAL ROUTING MECHANISM:");
11196
11878
  lines.push(" The @ symbol controls message routing. You MUST use it correctly:");
@@ -11204,13 +11886,13 @@ ${ctx.mergedContent.slice(0, SYSTEM_MAILBOX_MERGED_CHARS)}`);
11204
11886
  lines.push(`8. Your context already includes ~${CHANNEL_CONTEXT_MESSAGES} recent messages. For OLDER messages beyond that window, use recall_context(scope="channel"). For task/requirement details use task_get/requirement_get. Do NOT guess about prior discussion.`);
11205
11887
  lines.push("");
11206
11888
  lines.push("**GROUP CHAT PROCESSING CHECKLIST** (walk through before every response):");
11207
- lines.push("- [ ] Am I @mentioned or is this an open message? If directed at someone else \u2192 `[NO_RESPONSE]`.");
11208
- lines.push("- [ ] Check the channel messages in your context \u2014 has someone already answered? If yes \u2192 `[NO_RESPONSE]`.");
11209
- lines.push("- [ ] Does my role/expertise add UNIQUE value here? If no \u2192 `[NO_RESPONSE]`.");
11889
+ lines.push("- [ ] Am I @mentioned or is this an open message? If directed at someone else \u2192 no reply (call `end_turn`).");
11890
+ lines.push("- [ ] Check the channel messages in your context \u2014 has someone already answered? If yes \u2192 no reply (call `end_turn`).");
11891
+ lines.push("- [ ] Does my role/expertise add UNIQUE value here? If no \u2192 no reply (call `end_turn`).");
11210
11892
  lines.push("- [ ] Draft my reply. Is it concise and actionable? Remove filler.");
11211
11893
  lines.push("- [ ] @mention specific agents if I need their input \u2014 use correct format (`@Name` or `@[Full Name]`).");
11212
11894
  lines.push("- [ ] My text response will be auto-sent to the group. No need to call `agent_send_group_message`.");
11213
- lines.push("- [ ] Final check: does my response contain NEW information? If not \u2192 `[NO_RESPONSE]`.");
11895
+ lines.push("- [ ] Final check: does my response contain NEW information? If not \u2192 no reply (call `end_turn`).");
11214
11896
  break;
11215
11897
  case "comment_response":
11216
11898
  lines.push("You are responding to a **comment on a task or requirement**. You MUST follow the context-first protocol below.");
@@ -11238,7 +11920,7 @@ ${ctx.mergedContent.slice(0, SYSTEM_MAILBOX_MERGED_CHARS)}`);
11238
11920
  lines.push("");
11239
11921
  lines.push("**MANDATORY outcome \u2014 you MUST end with exactly one of these:**");
11240
11922
  lines.push("1. Call `task_comment` or `requirement_comment` tool to post your reply, OR");
11241
- lines.push("2. Output `[NO_REPLY_NEEDED]` in your text to explicitly signal that no response is warranted.");
11923
+ lines.push("2. Call the `end_turn` tool to explicitly signal that no response is warranted.");
11242
11924
  lines.push("");
11243
11925
  lines.push("If you finish without doing either of the above, the system will automatically retry your turn \u2014 your text output alone is NEVER sufficient.");
11244
11926
  lines.push("");
@@ -11255,10 +11937,10 @@ ${ctx.mergedContent.slice(0, SYSTEM_MAILBOX_MERGED_CHARS)}`);
11255
11937
  lines.push(` and reference others by quoting: '> [re: tc_xxx by @Bob]: "quote..." \u2014 your response'`);
11256
11938
  lines.push("- Include all addressed agent IDs in the `mentions` array for proper notifications.");
11257
11939
  lines.push("");
11258
- lines.push("**When to use `[NO_REPLY_NEEDED]` \u2014 convergence check:**");
11259
- lines.push("- Does your reply contain NEW INFORMATION, a CONCRETE ACTION, or a SPECIFIC QUESTION? If none \u2192 [NO_REPLY_NEEDED]");
11260
- lines.push("- If the last 2+ comments are agents acknowledging or restating without new substance \u2192 [NO_REPLY_NEEDED]");
11261
- lines.push("- If you and another agent exchanged views and neither has new data \u2192 [NO_REPLY_NEEDED]");
11940
+ lines.push("**When to call `end_turn` \u2014 convergence check:**");
11941
+ lines.push("- Does your reply contain NEW INFORMATION, a CONCRETE ACTION, or a SPECIFIC QUESTION? If none \u2192 call `end_turn`.");
11942
+ lines.push("- If the last 2+ comments are agents acknowledging or restating without new substance \u2192 call `end_turn`.");
11943
+ lines.push("- If you and another agent exchanged views and neither has new data \u2192 call `end_turn`.");
11262
11944
  lines.push("");
11263
11945
  lines.push('**Not a valid reason to reply:** "Got it" / "Will do" / "Agreed" / restating what was said / asking already-answered questions.');
11264
11946
  lines.push("");
@@ -13302,6 +13984,16 @@ var init_tool_selector = __esm({
13302
13984
  required: ["title", "body"]
13303
13985
  }
13304
13986
  });
13987
+ pushUnique({
13988
+ name: "end_turn",
13989
+ description: "End this turn WITHOUT sending any message to the conversation. Use it in an agent-to-agent conversation when the exchange is complete \u2014 you have no new fact, no question, and no correction. This is the ONLY correct way to stop a back-and-forth loop: do NOT write a reply saying you have nothing to add, and do NOT write an acknowledgement. Call end_turn and write no message text.",
13990
+ inputSchema: {
13991
+ type: "object",
13992
+ properties: {
13993
+ reason: { type: "string", description: "Optional short note on why the exchange is complete. Recorded locally for audit; never sent to the peer." }
13994
+ }
13995
+ }
13996
+ });
13305
13997
  if (opts.isChat) {
13306
13998
  pushUnique({
13307
13999
  name: "open_right_panel",
@@ -13539,6 +14231,15 @@ var init_tool_selector = __esm({
13539
14231
  evictedActivated: this.lastEvictedActivated
13540
14232
  });
13541
14233
  }
14234
+ const unreachable = evicted.map((e) => e.name).filter((n2) => !opts.allTools.has(n2) && !SCHEMA_INJECTED_TOOLS.has(n2));
14235
+ if (unreachable.length) {
14236
+ log12.warn("Evicted tool is not re-activatable \u2014 unreachable for this turn", {
14237
+ pack,
14238
+ budget,
14239
+ unreachable,
14240
+ hint: "Add to TOOL_DEF_PROTECTED (must never evict) or SCHEMA_INJECTED_TOOLS (discover_tools can restore it)."
14241
+ });
14242
+ }
13542
14243
  log12.debug("Tool selection complete", {
13543
14244
  total: opts.allTools.size,
13544
14245
  selected: capped.length,
@@ -14740,6 +15441,10 @@ function createShellTool(security, workspacePath, agentMeta, policy, onCommandAp
14740
15441
  session_id: {
14741
15442
  type: "string",
14742
15443
  description: "Reuse a persistent shell session by name. State (cwd, env vars, shell variables) persists across calls with the same session_id. Omit to use the default session."
15444
+ },
15445
+ max_output_chars: {
15446
+ type: "number",
15447
+ description: "Cap on how many characters of output you want back (e.g. 8000). When the output is longer, the FULL output is saved to a file (path returned to you) and only this many characters are shown \u2014 so nothing is lost and you avoid a second read. Omit for the default behaviour (offload only when very large)."
14743
15448
  }
14744
15449
  },
14745
15450
  required: ["command"]
@@ -14986,6 +15691,14 @@ var init_shell = __esm({
14986
15691
  }
14987
15692
  });
14988
15693
 
15694
+ // ../core/dist/tools/literal-replace.js
15695
+ var init_literal_replace2 = __esm({
15696
+ "../core/dist/tools/literal-replace.js"() {
15697
+ "use strict";
15698
+ init_dist();
15699
+ }
15700
+ });
15701
+
14989
15702
  // ../core/dist/tools/file.js
14990
15703
  import { readFileSync as readFileSync11, writeFileSync as writeFileSync10, mkdirSync as mkdirSync9, existsSync as existsSync15, statSync as statSync2 } from "node:fs";
14991
15704
  import { basename as basename4, dirname as dirname4, resolve as resolve7 } from "node:path";
@@ -15180,7 +15893,7 @@ function createFileEditTool(security, workspacePath, policy) {
15180
15893
  error: `old_string found ${count} times \u2014 must be unique. Add more surrounding context to make it unique.`
15181
15894
  });
15182
15895
  }
15183
- const updated = content.replace(oldStr, newStr);
15896
+ const updated = replaceLiteral(content, oldStr, newStr);
15184
15897
  writeFileSync10(path, updated);
15185
15898
  return JSON.stringify({ status: "success", path, replacements: 1 });
15186
15899
  } catch (error) {
@@ -15196,6 +15909,7 @@ var init_file = __esm({
15196
15909
  init_dist();
15197
15910
  init_security();
15198
15911
  init_write_guard();
15912
+ init_literal_replace2();
15199
15913
  MANIFEST_FILENAMES2 = /* @__PURE__ */ new Set(["agent.json", "team.json", "skill.json"]);
15200
15914
  FileReadTool = createFileReadTool();
15201
15915
  FileWriteTool = createFileWriteTool();
@@ -48455,7 +49169,7 @@ function createPatchTool(security, workspacePath, policy) {
48455
49169
  error: `Hunk ${i + 1} old_string found ${count} times in ${patch.file} \u2014 must be unique`
48456
49170
  });
48457
49171
  }
48458
- content = content.replace(hunk.old_string, hunk.new_string);
49172
+ content = replaceLiteral(content, hunk.old_string, hunk.new_string);
48459
49173
  }
48460
49174
  }
48461
49175
  if (patch.action === "create" && !patch.content && patch.content !== "") {
@@ -48477,7 +49191,7 @@ function createPatchTool(security, workspacePath, policy) {
48477
49191
  case "edit": {
48478
49192
  let content = readFileSync12(filePath, "utf-8");
48479
49193
  for (const hunk of patch.hunks) {
48480
- content = content.replace(hunk.old_string, hunk.new_string);
49194
+ content = replaceLiteral(content, hunk.old_string, hunk.new_string);
48481
49195
  }
48482
49196
  writeFileSync11(filePath, content);
48483
49197
  results.push({
@@ -48523,6 +49237,7 @@ var init_patch = __esm({
48523
49237
  "use strict";
48524
49238
  init_security();
48525
49239
  init_file();
49240
+ init_literal_replace2();
48526
49241
  }
48527
49242
  });
48528
49243
 
@@ -48975,10 +49690,12 @@ function persistSubagentLog(dataDir, subagentId, entries2) {
48975
49690
  }
48976
49691
  async function runSubagentLoop(ctx, task, opts) {
48977
49692
  const hardCap = ctx.maxToolIterations ?? DEFAULT_MAX_SUBAGENT_ITERATIONS;
48978
- const maxIter = Math.min(opts?.maxIterations ?? hardCap, hardCap);
49693
+ const maxIterations = Math.min(opts?.maxIterations ?? hardCap, hardCap);
49694
+ const iterationBudget = opts?.iterationBudget;
49695
+ const aggregateBudget = opts?.aggregateBudget ?? opts?.sharedBudget;
48979
49696
  const onProgress = opts?.onProgress;
48980
- const sharedBudget = opts?.sharedBudget;
48981
- let budgetExhausted = false;
49697
+ let status = "completed";
49698
+ let aggregateCeilingReached = false;
48982
49699
  const subagentId = `sub_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
48983
49700
  const logEntries = [];
48984
49701
  const parentTools = ctx.getTools();
@@ -49003,7 +49720,8 @@ async function runSubagentLoop(ctx, task, opts) {
49003
49720
  subagentId,
49004
49721
  taskLength: task.length,
49005
49722
  toolCount: toolMap.size,
49006
- maxIterations: maxIter
49723
+ maxIterations,
49724
+ iterationBudget
49007
49725
  });
49008
49726
  onProgress?.({
49009
49727
  type: "started",
@@ -49017,23 +49735,41 @@ async function runSubagentLoop(ctx, task, opts) {
49017
49735
  }, provider), `subagent-${subagentId}-init`);
49018
49736
  let iterations = 0;
49019
49737
  while (response.finishReason === "tool_use" && response.toolCalls?.length || response.finishReason === "max_tokens") {
49020
- if (++iterations > maxIter) {
49021
- log14.warn("Subagent hit max iterations", { parentAgent: ctx.agentId, subagentId, iterations });
49022
- onProgress?.({ type: "error", content: `Subagent hit max iterations (${maxIter})` });
49023
- break;
49024
- }
49025
- if (sharedBudget) {
49026
- if (sharedBudget.remaining <= 0) {
49027
- budgetExhausted = true;
49028
- log14.warn("Subagent stopped: shared aggregate budget exhausted", { parentAgent: ctx.agentId, subagentId, iterations });
49029
- onProgress?.({ type: "error", content: "Shared subagent budget exhausted" });
49738
+ if (aggregateBudget) {
49739
+ if (aggregateBudget.remaining <= 0) {
49740
+ aggregateCeilingReached = true;
49741
+ status = "budget_exhausted";
49742
+ log14.warn("Subagent stopped: aggregate budget ceiling reached", {
49743
+ parentAgent: ctx.agentId,
49744
+ subagentId,
49745
+ iterations
49746
+ });
49747
+ onProgress?.({ type: "error", content: "Aggregate subagent budget ceiling reached" });
49030
49748
  break;
49031
49749
  }
49032
- sharedBudget.remaining--;
49750
+ aggregateBudget.remaining--;
49751
+ }
49752
+ if (iterationBudget !== void 0 && iterations >= iterationBudget) {
49753
+ status = "budget_exhausted";
49754
+ log14.warn("Subagent stopped: own iteration budget exhausted", {
49755
+ parentAgent: ctx.agentId,
49756
+ subagentId,
49757
+ iterations,
49758
+ iterationBudget
49759
+ });
49760
+ onProgress?.({ type: "error", content: `Subagent iteration budget exhausted (${iterationBudget})` });
49761
+ break;
49762
+ }
49763
+ if (iterations >= maxIterations) {
49764
+ status = "max_iterations";
49765
+ log14.warn("Subagent hit max iterations", { parentAgent: ctx.agentId, subagentId, iterations, maxIterations });
49766
+ onProgress?.({ type: "error", content: `Subagent hit max iterations (${maxIterations})` });
49767
+ break;
49033
49768
  }
49769
+ iterations++;
49034
49770
  onProgress?.({
49035
49771
  type: "iteration",
49036
- content: `Iteration ${iterations}/${maxIter}`,
49772
+ content: `Iteration ${iterations}/${maxIterations}`,
49037
49773
  metadata: { iteration: iterations, finishReason: response.finishReason }
49038
49774
  });
49039
49775
  if (response.finishReason === "max_tokens" && !response.toolCalls?.length) {
@@ -49110,11 +49846,15 @@ async function runSubagentLoop(ctx, task, opts) {
49110
49846
  }, provider), `subagent-${subagentId}-iter${iterations}`);
49111
49847
  }
49112
49848
  const rawResult = response.content;
49113
- let cleanResult = stripThinkTags(rawResult);
49114
- if (budgetExhausted) {
49115
- cleanResult = `${cleanResult}
49849
+ let cleanResult = stripThinkTags(rawResult ?? "");
49850
+ if (status !== "completed") {
49851
+ const reason = status === "max_iterations" ? `reached its ${maxIterations}-iteration cap` : aggregateCeilingReached ? "shared aggregate iteration budget exhausted" : `own iteration budget (${iterationBudget}) exhausted`;
49852
+ const note = `[INCOMPLETE: subagent stopped early \u2014 ${reason} after ${iterations} iteration(s). Its result is incomplete; do not treat it as a completed subtask.]`;
49853
+ cleanResult = cleanResult.trim().length > 0 ? `${cleanResult.trimEnd()}
49116
49854
 
49117
- [NOTE: subagent stopped early \u2014 shared aggregate iteration budget exhausted. Result may be incomplete.]`;
49855
+ ${note}` : note;
49856
+ } else if (cleanResult.trim().length === 0) {
49857
+ cleanResult = "[Subagent completed without producing textual output.]";
49118
49858
  }
49119
49859
  logEntries.push({
49120
49860
  ts: (/* @__PURE__ */ new Date()).toISOString(),
@@ -49125,19 +49865,26 @@ async function runSubagentLoop(ctx, task, opts) {
49125
49865
  if (ctx.dataDir) {
49126
49866
  logPath = persistSubagentLog(ctx.dataDir, subagentId, logEntries);
49127
49867
  }
49128
- log14.info("Subagent completed", {
49868
+ log14.info("Subagent finished", {
49129
49869
  parentAgent: ctx.agentId,
49130
49870
  subagentId,
49871
+ status,
49131
49872
  iterations,
49873
+ aggregateCeilingReached,
49132
49874
  resultLength: cleanResult.length,
49133
49875
  logPath
49134
49876
  });
49135
49877
  onProgress?.({
49136
- type: "completed",
49137
- content: `Subagent completed in ${iterations} iterations`,
49138
- metadata: { subagentId, iterations, logPath, resultLength: cleanResult.length }
49878
+ type: status === "completed" ? "completed" : "error",
49879
+ content: status === "completed" ? `Subagent completed in ${iterations} iterations` : `Subagent stopped early (${status}) after ${iterations} iterations`,
49880
+ metadata: { subagentId, status, iterations, aggregateCeilingReached, logPath, resultLength: cleanResult.length }
49139
49881
  });
49140
- return cleanResult;
49882
+ return {
49883
+ status,
49884
+ output: cleanResult,
49885
+ iterations,
49886
+ aggregateCeilingReached
49887
+ };
49141
49888
  }
49142
49889
  function createSubagentTool(ctx) {
49143
49890
  return {
@@ -49162,6 +49909,10 @@ function createSubagentTool(ctx) {
49162
49909
  max_iterations: {
49163
49910
  type: "number",
49164
49911
  description: "Max tool iterations. Lower this for quick tasks."
49912
+ },
49913
+ iteration_budget: {
49914
+ type: "number",
49915
+ description: "Optional per-child iteration budget. When reached, the subagent returns an explicit budget_exhausted status (never an empty success)."
49165
49916
  }
49166
49917
  },
49167
49918
  required: ["task"]
@@ -49172,13 +49923,19 @@ function createSubagentTool(ctx) {
49172
49923
  return JSON.stringify({ status: "error", error: "task is required" });
49173
49924
  }
49174
49925
  try {
49175
- const result = await runSubagentLoop(ctx, task, {
49926
+ const loop = await runSubagentLoop(ctx, task, {
49176
49927
  systemPrompt: args["system_prompt"],
49177
49928
  allowedTools: args["allowed_tools"],
49178
49929
  maxIterations: args["max_iterations"],
49930
+ iterationBudget: args["iteration_budget"],
49179
49931
  onProgress: ctx.getProgressCallback?.()
49180
49932
  });
49181
- return JSON.stringify({ status: "completed", result });
49933
+ return JSON.stringify({
49934
+ status: loop.status,
49935
+ result: loop.output,
49936
+ iterations: loop.iterations,
49937
+ aggregateCeilingReached: loop.aggregateCeilingReached
49938
+ });
49182
49939
  } catch (err) {
49183
49940
  log14.error("Subagent execution failed", { error: String(err) });
49184
49941
  return JSON.stringify({ status: "error", error: `Subagent failed: ${String(err)}` });
@@ -49214,6 +49971,10 @@ function createParallelSubagentTool(ctx) {
49214
49971
  max_iterations: {
49215
49972
  type: "number",
49216
49973
  description: "Optional max iterations for this subagent."
49974
+ },
49975
+ iteration_budget: {
49976
+ type: "number",
49977
+ description: "Optional INDEPENDENT iteration budget for this subagent. Reaching it stops only this child and returns an explicit budget_exhausted status."
49217
49978
  }
49218
49979
  },
49219
49980
  required: ["id", "task"]
@@ -49251,46 +50012,71 @@ function createParallelSubagentTool(ctx) {
49251
50012
  metadata: { taskIds: tasks.map((t2) => t2.id) }
49252
50013
  });
49253
50014
  const startTime = Date.now();
49254
- const sharedBudget = { remaining: SUBAGENT_MAX_AGGREGATE_ITERATIONS };
50015
+ const aggregateBudget = { remaining: SUBAGENT_MAX_AGGREGATE_ITERATIONS };
49255
50016
  const results = await Promise.allSettled(tasks.map(async (t2) => {
49256
50017
  const perTaskProgress = onProgress ? (event) => onProgress({
49257
50018
  ...event,
49258
50019
  content: `[${t2.id}] ${event.content}`,
49259
50020
  metadata: { ...event.metadata, parallelTaskId: t2.id }
49260
50021
  }) : void 0;
49261
- const result = await runSubagentLoop(ctx, t2.task, {
50022
+ const loop = await runSubagentLoop(ctx, t2.task, {
49262
50023
  systemPrompt: sharedSystemPrompt,
49263
50024
  allowedTools: t2.allowed_tools,
49264
50025
  maxIterations: t2.max_iterations,
50026
+ iterationBudget: t2.iteration_budget,
49265
50027
  onProgress: perTaskProgress,
49266
- sharedBudget
50028
+ aggregateBudget
49267
50029
  });
49268
- return { id: t2.id, result };
50030
+ return { id: t2.id, loop };
49269
50031
  }));
49270
- const budgetExceeded = sharedBudget.remaining <= 0;
50032
+ const budgetExceeded = aggregateBudget.remaining <= 0;
49271
50033
  const output = results.map((r, i) => {
49272
50034
  if (r.status === "fulfilled") {
49273
- return { id: r.value.id, status: "completed", result: r.value.result };
50035
+ const { id, loop } = r.value;
50036
+ const result = loop.output.trim().length > 0 ? loop.output : `[INCOMPLETE: subagent "${id}" produced no output (status: ${loop.status}).]`;
50037
+ return {
50038
+ id,
50039
+ status: loop.status,
50040
+ result,
50041
+ iterations: loop.iterations,
50042
+ aggregateCeilingReached: loop.aggregateCeilingReached
50043
+ };
49274
50044
  }
49275
- return { id: tasks[i].id, status: "error", error: String(r.reason) };
50045
+ const reason = String(r.reason);
50046
+ return {
50047
+ id: tasks[i].id,
50048
+ status: "error",
50049
+ result: `[INCOMPLETE: subagent failed \u2014 ${reason}]`,
50050
+ error: reason
50051
+ };
49276
50052
  });
49277
50053
  const completed = output.filter((o) => o.status === "completed").length;
50054
+ const stoppedEarly = output.filter((o) => o.status === "budget_exhausted" || o.status === "max_iterations").length;
49278
50055
  const failed = output.filter((o) => o.status === "error").length;
49279
50056
  const durationMs = Date.now() - startTime;
49280
50057
  log14.info("Parallel subagents finished", {
49281
50058
  parentAgent: ctx.agentId,
49282
50059
  completed,
50060
+ stoppedEarly,
49283
50061
  failed,
50062
+ budgetExceeded,
49284
50063
  totalDurationMs: durationMs
49285
50064
  });
49286
50065
  onProgress?.({
49287
- type: "completed",
49288
- content: `${completed}/${tasks.length} subagents completed (${durationMs}ms)`,
49289
- metadata: { completed, failed, durationMs }
50066
+ type: stoppedEarly > 0 || failed > 0 ? "error" : "completed",
50067
+ content: `${completed}/${tasks.length} subagents completed${stoppedEarly > 0 ? `, ${stoppedEarly} stopped early` : ""} (${durationMs}ms)`,
50068
+ metadata: { completed, stoppedEarly, failed, budgetExceeded, durationMs }
49290
50069
  });
50070
+ const summaryParts = [`${completed}/${tasks.length} subagents completed`];
50071
+ if (stoppedEarly > 0)
50072
+ summaryParts.push(`${stoppedEarly} stopped early (incomplete)`);
50073
+ if (failed > 0)
50074
+ summaryParts.push(`${failed} failed`);
50075
+ if (budgetExceeded)
50076
+ summaryParts.push("aggregate iteration budget exhausted");
49291
50077
  return JSON.stringify({
49292
50078
  status: "completed",
49293
- summary: `${completed}/${tasks.length} subagents completed successfully${failed > 0 ? `, ${failed} failed` : ""}${budgetExceeded ? " (aggregate iteration budget exhausted \u2014 some results may be incomplete)" : ""}`,
50079
+ summary: summaryParts.join("; "),
49294
50080
  durationMs,
49295
50081
  budgetExceeded,
49296
50082
  aggregateIterationBudget: SUBAGENT_MAX_AGGREGATE_ITERATIONS,
@@ -50675,12 +51461,11 @@ function detectAbnormalCompletion(reply, item) {
50675
51461
  return void 0;
50676
51462
  if (reply === "[preempted]" || reply === "[cancelled]")
50677
51463
  return void 0;
51464
+ if (reply === END_TURN_REPLY_SENTINEL)
51465
+ return void 0;
50678
51466
  if (reply === void 0 || reply === "") {
50679
51467
  return "empty reply from LLM-invoking item";
50680
51468
  }
50681
- if (!hasCompletionMarker(reply)) {
50682
- return "completion marker missing from reply";
50683
- }
50684
51469
  return void 0;
50685
51470
  }
50686
51471
  var log17, AttentionController;
@@ -51462,15 +52247,7 @@ var init_attention = __esm({
51462
52247
  const retries = item.retryCount ?? 0;
51463
52248
  const isUserInteraction = _AttentionController.USER_INTERACTION_TYPES.has(item.sourceType);
51464
52249
  if (abnormalReason && retries < MAILBOX_ITEM_MAX_RETRIES) {
51465
- if (abnormalReason === "completion marker missing from reply") {
51466
- log17.warn("Completion marker still missing after in-session continuation \u2014 marking dropped without retry", {
51467
- agentId: this.agentId,
51468
- itemId: item.id,
51469
- type: item.sourceType
51470
- });
51471
- this.emitIncomplete(item, abnormalReason);
51472
- this.mailbox.drop(item.id);
51473
- } else if (isUserInteraction) {
52250
+ if (isUserInteraction) {
51474
52251
  log17.warn("Abnormal completion for user interaction \u2014 marking dropped without retry", {
51475
52252
  agentId: this.agentId,
51476
52253
  itemId: item.id,
@@ -51700,8 +52477,8 @@ var init_attention = __esm({
51700
52477
  }
51701
52478
  /**
51702
52479
  * A3: emit a structured `agent:incomplete` event when a mailbox item completes
51703
- * without finishing cleanly (marker missing after continuation, or abnormal reply
51704
- * accepted without retry). Visibility only — does not change retry semantics.
52480
+ * without finishing cleanly (an empty/abnormal reply accepted without retry).
52481
+ * Visibility only — does not change retry semantics.
51705
52482
  */
51706
52483
  /**
51707
52484
  * 等待某 worker 的在途处理 promise 结束(有界等待)。
@@ -53801,27 +54578,17 @@ function sanitizeLLMReply(reply) {
53801
54578
  return cleaned || reply;
53802
54579
  }
53803
54580
  function stripCompletionMarker(reply) {
53804
- return stripCompletionMarkerLeak(reply).trim();
54581
+ return stripLegacyCompletionToken(reply).trim();
53805
54582
  }
53806
54583
  function createMarkerStrippingDelta(rawEmit) {
53807
- const markerLen = COMPLETION_MARKER.length;
53808
- let tail = "";
53809
- const emit = (chunk) => {
53810
- tail += chunk;
53811
- if (tail.length <= markerLen)
53812
- return;
53813
- const safe = tail.slice(0, tail.length - markerLen);
53814
- tail = tail.slice(safe.length);
53815
- if (safe)
53816
- rawEmit(safe);
53817
- };
53818
- const flush = () => {
53819
- const cleaned = stripCompletionMarkerLeak(tail);
53820
- tail = "";
53821
- if (cleaned)
53822
- rawEmit(cleaned);
54584
+ return {
54585
+ emit: (chunk) => {
54586
+ if (chunk)
54587
+ rawEmit(chunk);
54588
+ },
54589
+ flush: () => {
54590
+ }
53823
54591
  };
53824
- return { emit, flush };
53825
54592
  }
53826
54593
  function addArgCasingAliases(args) {
53827
54594
  if (!args || typeof args !== "object" || Array.isArray(args)) {
@@ -53851,7 +54618,9 @@ function shouldMemoryFlushPreflight(opts) {
53851
54618
  return false;
53852
54619
  return lastUsagePercent >= threshold;
53853
54620
  }
53854
- function shouldContinueToolLoop(response) {
54621
+ function shouldContinueToolLoop(response, opts) {
54622
+ if (opts?.endTurnRequested)
54623
+ return false;
53855
54624
  return Boolean(response.finishReason === "tool_use" && response.toolCalls?.length || response.finishReason === "max_tokens");
53856
54625
  }
53857
54626
  function needsMaxTokensContinuation(response) {
@@ -53866,6 +54635,7 @@ var init_agent2 = __esm({
53866
54635
  "use strict";
53867
54636
  init_dist();
53868
54637
  init_lock_resources();
54638
+ init_dream_trigger();
53869
54639
  init_tracing();
53870
54640
  init_events();
53871
54641
  init_token_counter();
@@ -54095,8 +54865,6 @@ var init_agent2 = __esm({
54095
54865
  notebookSaveTimer;
54096
54866
  /** Earliest time the debounced notebook write may be deferred to (maxWait). */
54097
54867
  notebookSaveDeadline;
54098
- /** 审计 §8.1:CPP 的 LLM 管道已移除;仅保留配置(决定是否注入确定性情境块)。 */
54099
- cognitiveConfig;
54100
54868
  /** Ring buffer of recent activity summaries for triage context. */
54101
54869
  recentActivityRing = [];
54102
54870
  static ACTIVITY_RING_SIZE = 8;
@@ -54122,6 +54890,27 @@ var init_agent2 = __esm({
54122
54890
  onActivityLogCb;
54123
54891
  onActivityEndCb;
54124
54892
  browserCloseTabsHelper;
54893
+ /**
54894
+ * Set when the agent calls the `end_turn` tool — an explicit, typed "this turn is
54895
+ * over, send nothing" signal. Read by the tool-loop guard (all 5 entry points) to
54896
+ * stop immediately, and by the reply assembly to force an empty reply.
54897
+ *
54898
+ * Why a typed signal instead of the legacy `[NO_RESPONSE]` text token: an LLM told
54899
+ * to "reply with a token" often paraphrases the decision into prose instead — and
54900
+ * that prose IS a delivered message, which re-triggers the peer and restarts the
54901
+ * exact loop it was meant to end (observed 2026-10-03, agent↔agent DM).
54902
+ */
54903
+ endTurnRequested = false;
54904
+ /**
54905
+ * Monotonic counter of `end_turn` tool invocations. The AttentionDelegate wrapper
54906
+ * snapshots it around one mailbox turn: an increase means THIS turn ended
54907
+ * deliberately, so it returns {@link END_TURN_REPLY_SENTINEL} to the attention
54908
+ * controller (whose only source of truth for turn status is the delegate's return
54909
+ * value). A counter — not the mutable `endTurnRequested` flag, which the reply
54910
+ * assembly resets before returning — keeps the signal attributable to the
54911
+ * specific turn even with concurrent workers.
54912
+ */
54913
+ endTurnCount = 0;
54125
54914
  /** Injected by AgentManager; read at skill-activation time so Settings changes apply live. */
54126
54915
  browserElementSelectionProvider;
54127
54916
  dynamicContextProviders = /* @__PURE__ */ new Map();
@@ -54270,9 +55059,6 @@ var init_agent2 = __esm({
54270
55059
  this.guardrails = new GuardrailPipeline();
54271
55060
  this.toolHooks = new ToolHookRegistry();
54272
55061
  this.metricsCollector = new AgentMetricsCollector(this.id, options.dataDir);
54273
- if (options.cognitive?.enabled) {
54274
- this.cognitiveConfig = options.cognitive;
54275
- }
54276
55062
  this.heartbeat = new HeartbeatScheduler(this.id, this.eventBus, {
54277
55063
  intervalMs: this.config.heartbeatIntervalMs,
54278
55064
  enabled: true
@@ -54849,16 +55635,19 @@ ${notification.stdoutTail}`);
54849
55635
  return {
54850
55636
  processMailboxItem: async (item, batchItems, batchContext) => {
54851
55637
  try {
55638
+ const endTurnCountBefore = this.endTurnCount;
54852
55639
  const result = await this.processMailboxItemInternal(item, batchItems, batchContext);
55640
+ const endedTurnViaTool = this.endTurnCount > endTurnCountBefore;
54853
55641
  try {
54854
55642
  this.metricsCollector.recordTurn({
54855
55643
  isChat: item.sourceType === "human_chat",
54856
- hadCompletionMarker: typeof result === "string" && result.includes(COMPLETION_MARKER)
55644
+ endedTurnViaTool,
55645
+ emptyReply: result === void 0 || result === ""
54857
55646
  });
54858
55647
  } catch (err) {
54859
55648
  log20.debug("recordTurn failed", { agentId: this.id, itemId: item.id, error: String(err) });
54860
55649
  }
54861
- return result;
55650
+ return endedTurnViaTool ? END_TURN_REPLY_SENTINEL : result;
54862
55651
  } finally {
54863
55652
  this.clearProcessingCancel();
54864
55653
  }
@@ -54985,21 +55774,35 @@ ${notification.stdoutTail}`);
54985
55774
  sessionToolNames
54986
55775
  };
54987
55776
  }
54988
- async ensureCompletionMarker(reply, sessionId, onEvent) {
55777
+ /**
55778
+ * If a turn finished without a typed completion signal, continue in-session with
55779
+ * tools enabled so the model can finish announced-but-unfinished work rather than
55780
+ * leaving the user with a plan and no result.
55781
+ *
55782
+ * The guard is TYPED: a turn that ended via the `end_turn` tool is complete by
55783
+ * definition (as are cancellation / preemption / merge), so no continuation runs.
55784
+ * The nudge asks for the `end_turn` **tool call** — the same signal the mailbox
55785
+ * layer reads — instead of a magic string (docs/PLATFORM-HARDENING-2026-10.md §6).
55786
+ *
55787
+ * Still a single bounded continuation attempt: if it yields nothing further the
55788
+ * reply is returned as-is and the attention controller completes the item, because
55789
+ * a non-empty reply is never "abnormal".
55790
+ */
55791
+ async ensureTurnCompleted(reply, sessionId, onEvent) {
54989
55792
  if (!reply || reply === "[cancelled]" || reply === "[preempted]" || reply === "[merged]")
54990
55793
  return reply;
54991
- if (hasCompletionMarker(reply))
55794
+ if (this.endTurnRequested)
54992
55795
  return reply;
54993
55796
  if (!sessionId || !this.memory.getSession(sessionId))
54994
55797
  return reply;
54995
- log20.info("Completion marker missing \u2014 continuing in-session to obtain marker", {
55798
+ log20.info("Turn finished without an end_turn signal \u2014 continuing in-session to close it out", {
54996
55799
  agentId: this.id,
54997
55800
  sessionId,
54998
55801
  replyLength: reply.length
54999
55802
  });
55000
55803
  this.memory.appendMessage(sessionId, {
55001
55804
  role: "user",
55002
- content: `[SYSTEM] Your previous response did not include the required completion marker and may have unfinished work. Do NOT only announce remaining steps \u2014 finish them with tools now if anything is still pending. When truly done, end your response with exactly: ${COMPLETION_MARKER}`
55805
+ content: `[SYSTEM] You ended your turn without calling the end_turn tool and may have unfinished work. Do NOT only announce remaining steps \u2014 finish them with tools now if anything is still pending. When you are truly done, call the \`end_turn\` tool.`
55003
55806
  });
55004
55807
  try {
55005
55808
  const selectCtx = this.buildSessionAwareToolSelectContext(sessionId, reply, {
@@ -55012,7 +55815,7 @@ ${notification.stdoutTail}`);
55012
55815
  };
55013
55816
  let llmTools = this.buildToolDefinitions(markerToolSelectOpts);
55014
55817
  const multimodalToolNames = ["generate_image", "text_to_speech", "speech_to_text", "generate_video"];
55015
- log20.info("ensureCompletionMarker tool selection", {
55818
+ log20.info("ensureTurnCompleted tool selection", {
55016
55819
  agentId: this.id,
55017
55820
  sessionId,
55018
55821
  toolCount: llmTools.length,
@@ -55044,9 +55847,9 @@ ${notification.stdoutTail}`);
55044
55847
  }
55045
55848
  let toolIter = 0;
55046
55849
  const maxIter = Math.min(this._maxToolIterations, 24);
55047
- while (shouldContinueToolLoop(response)) {
55850
+ while (shouldContinueToolLoop(response, { endTurnRequested: this.endTurnRequested })) {
55048
55851
  if (++toolIter > maxIter) {
55049
- log20.warn("ensureCompletionMarker tool loop hit max iterations", {
55852
+ log20.warn("ensureTurnCompleted tool loop hit max iterations", {
55050
55853
  agentId: this.id,
55051
55854
  sessionId,
55052
55855
  iterations: toolIter,
@@ -55062,7 +55865,7 @@ ${notification.stdoutTail}`);
55062
55865
  });
55063
55866
  this.memory.appendMessage(sessionId, {
55064
55867
  role: "user",
55065
- content: `[Continue from where you left off. When done, end with exactly: ${COMPLETION_MARKER}]`
55868
+ content: "[Continue from where you left off. When you are truly done, call the end_turn tool.]"
55066
55869
  });
55067
55870
  } else {
55068
55871
  this.memory.appendMessage(sessionId, {
@@ -55168,8 +55971,7 @@ ${item.payload.content}` + batchSuffix;
55168
55971
  };
55169
55972
  const ts = Date.now();
55170
55973
  const registry = MAILBOX_TYPE_REGISTRY[item.sourceType];
55171
- const needsMarker = !!registry?.invokesLLM;
55172
- const markerSuffix = needsMarker ? COMPLETION_MARKER_INSTRUCTION : "";
55974
+ const needsTurnCompletion = !!registry?.invokesLLM;
55173
55975
  const buildHandleOpts = (defaults = {}) => {
55174
55976
  const opts = { ...defaults };
55175
55977
  const ex = extra;
@@ -55218,7 +56020,7 @@ ${item.payload.content}` + batchSuffix;
55218
56020
  });
55219
56021
  } else {
55220
56022
  let reply2 = await this.handleMessageStream(
55221
- item.payload.content + markerSuffix,
56023
+ item.payload.content,
55222
56024
  extra.onEvent,
55223
56025
  item.metadata?.senderId,
55224
56026
  senderInfo,
@@ -55230,8 +56032,8 @@ ${item.payload.content}` + batchSuffix;
55230
56032
  // bound memory session instead of trusting the worker pointer.
55231
56033
  extra.sessionId
55232
56034
  );
55233
- if (needsMarker && item.sourceType !== "human_chat") {
55234
- reply2 = await this.ensureCompletionMarker(reply2, this.currentSessionId, extra.onEvent);
56035
+ if (needsTurnCompletion && item.sourceType !== "human_chat") {
56036
+ reply2 = await this.ensureTurnCompleted(reply2, this.currentSessionId, extra.onEvent);
55235
56037
  }
55236
56038
  resolveResponse(reply2);
55237
56039
  return reply2;
@@ -55260,9 +56062,9 @@ ${item.payload.content}` + batchSuffix;
55260
56062
  const opts = buildHandleOpts(defaults);
55261
56063
  if (item.sourceType === "a2a_message" && extra.scenario === void 0)
55262
56064
  opts.scenario = "a2a";
55263
- let reply = await this.handleMessage(item.payload.content + markerSuffix, item.metadata?.senderId, senderInfo, opts);
55264
- if (needsMarker && item.sourceType !== "human_chat") {
55265
- reply = await this.ensureCompletionMarker(reply, opts.sessionId ?? this.currentSessionId);
56065
+ let reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, opts);
56066
+ if (needsTurnCompletion && item.sourceType !== "human_chat") {
56067
+ reply = await this.ensureTurnCompleted(reply, opts.sessionId ?? this.currentSessionId);
55266
56068
  }
55267
56069
  resolveResponse(reply);
55268
56070
  return reply;
@@ -55348,16 +56150,16 @@ ${item.payload.content}` + batchSuffix;
55348
56150
  }
55349
56151
  case "mention": {
55350
56152
  const mentionSessionId = `sys_${this.id}_${ts}`;
55351
- let reply = await this.handleMessage(item.payload.content + markerSuffix, item.metadata?.senderId, senderInfo, buildHandleOpts({ sessionId: mentionSessionId, scenario: "a2a" }));
55352
- if (needsMarker)
55353
- reply = await this.ensureCompletionMarker(reply, mentionSessionId);
56153
+ let reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, buildHandleOpts({ sessionId: mentionSessionId, scenario: "a2a" }));
56154
+ if (needsTurnCompletion)
56155
+ reply = await this.ensureTurnCompleted(reply, mentionSessionId);
55354
56156
  resolveResponse(reply);
55355
56157
  return reply;
55356
56158
  }
55357
56159
  case "requirement_update": {
55358
56160
  if (extra.actionRequired) {
55359
56161
  const reqId = item.payload.requirementId ?? "unknown";
55360
- const reply = await this.handleMessage(item.payload.content + COMPLETION_MARKER_INSTRUCTION, item.metadata?.senderId, senderInfo, buildHandleOpts({
56162
+ const reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, buildHandleOpts({
55361
56163
  sessionId: `requirement_${reqId}_${ts}`,
55362
56164
  scenario: "requirement_action",
55363
56165
  allowedTools: new Set(REQUIREMENT_ACTION_ALLOWED_TOOLS)
@@ -55374,7 +56176,7 @@ ${item.payload.content}` + batchSuffix;
55374
56176
  }
55375
56177
  case "requirement_comment": {
55376
56178
  const reqId = item.payload.requirementId ?? "unknown";
55377
- const reply = await this.handleMessage(item.payload.content + COMPLETION_MARKER_INSTRUCTION, item.metadata?.senderId, senderInfo, buildHandleOpts({
56179
+ const reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, buildHandleOpts({
55378
56180
  sessionId: `comment_${reqId}_${ts}`,
55379
56181
  scenario: "comment_response",
55380
56182
  allowedTools: new Set(COMMENT_RESPONSE_ALLOWED_TOOLS)
@@ -55385,7 +56187,7 @@ ${item.payload.content}` + batchSuffix;
55385
56187
  case "workflow_update": {
55386
56188
  if (extra.actionRequired) {
55387
56189
  const wfEvent = extra.event ?? "update";
55388
- const reply = await this.handleMessage(item.payload.content + COMPLETION_MARKER_INSTRUCTION, item.metadata?.senderId, senderInfo, buildHandleOpts({
56190
+ const reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, buildHandleOpts({
55389
56191
  sessionId: `workflow_${wfEvent}_${ts}`,
55390
56192
  scenario: "workflow_action",
55391
56193
  allowedTools: new Set(WORKFLOW_ACTION_ALLOWED_TOOLS)
@@ -55408,7 +56210,7 @@ ${item.payload.content}` + batchSuffix;
55408
56210
  this.injectUserMessage(sessionId, item.payload.content);
55409
56211
  } else {
55410
56212
  const commentTaskId = taskId2 ?? "unknown";
55411
- await this.handleMessage(item.payload.content + COMPLETION_MARKER_INSTRUCTION, item.metadata?.senderId, senderInfo, buildHandleOpts({
56213
+ await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, buildHandleOpts({
55412
56214
  sessionId: `comment_${commentTaskId}_${ts}`,
55413
56215
  scenario: "comment_response",
55414
56216
  allowedTools: new Set(COMMENT_RESPONSE_ALLOWED_TOOLS)
@@ -55419,9 +56221,9 @@ ${item.payload.content}` + batchSuffix;
55419
56221
  }
55420
56222
  case "review_request": {
55421
56223
  const reviewSessionId = `review_${this.id}_${ts}`;
55422
- let reply = await this.handleMessage(item.payload.content + markerSuffix, item.metadata?.senderId, item.metadata?.senderName ? { name: item.metadata.senderName, role: item.metadata.senderRole ?? "worker" } : void 0, buildHandleOpts({ sessionId: reviewSessionId, scenario: "review" }));
55423
- if (needsMarker)
55424
- reply = await this.ensureCompletionMarker(reply, reviewSessionId);
56224
+ let reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, item.metadata?.senderName ? { name: item.metadata.senderName, role: item.metadata.senderRole ?? "worker" } : void 0, buildHandleOpts({ sessionId: reviewSessionId, scenario: "review" }));
56225
+ if (needsTurnCompletion)
56226
+ reply = await this.ensureTurnCompleted(reply, reviewSessionId);
55425
56227
  resolveResponse(reply);
55426
56228
  return reply;
55427
56229
  }
@@ -55430,7 +56232,7 @@ ${item.payload.content}` + batchSuffix;
55430
56232
  agentId: this.id,
55431
56233
  triggeredAt: item.queuedAt
55432
56234
  });
55433
- const hbReply = hbResult === "[preempted]" || hbResult === "[cancelled]" ? hbResult : COMPLETION_MARKER;
56235
+ const hbReply = hbResult === "[preempted]" || hbResult === "[cancelled]" ? hbResult : END_TURN_REPLY_SENTINEL;
55434
56236
  resolveResponse(hbReply);
55435
56237
  return hbReply;
55436
56238
  }
@@ -55438,17 +56240,17 @@ ${item.payload.content}` + batchSuffix;
55438
56240
  case "daily_report": {
55439
56241
  const sysSessionId = `sys_${this.id}_${ts}`;
55440
56242
  const sysScenario = (extra.callbackType !== void 0 ? asAgentScenario(extra.scenario) : void 0) ?? "heartbeat";
55441
- let reply = await this.handleMessage(item.payload.content + markerSuffix, void 0, void 0, buildHandleOpts({ sessionId: sysSessionId, scenario: sysScenario }));
55442
- if (needsMarker)
55443
- reply = await this.ensureCompletionMarker(reply, sysSessionId);
56243
+ let reply = await this.handleMessage(item.payload.content, void 0, void 0, buildHandleOpts({ sessionId: sysSessionId, scenario: sysScenario }));
56244
+ if (needsTurnCompletion)
56245
+ reply = await this.ensureTurnCompleted(reply, sysSessionId);
55444
56246
  resolveResponse(reply);
55445
56247
  return reply;
55446
56248
  }
55447
56249
  case "memory_consolidation": {
55448
56250
  const memSessionId = `sys_${this.id}_${ts}`;
55449
- let reply = await this.handleMessage(item.payload.content + markerSuffix, void 0, void 0, buildHandleOpts({ sessionId: memSessionId, scenario: "memory_consolidation" }));
55450
- if (needsMarker)
55451
- reply = await this.ensureCompletionMarker(reply, memSessionId);
56251
+ let reply = await this.handleMessage(item.payload.content, void 0, void 0, buildHandleOpts({ sessionId: memSessionId, scenario: "memory_consolidation" }));
56252
+ if (needsTurnCompletion)
56253
+ reply = await this.ensureTurnCompleted(reply, memSessionId);
55452
56254
  resolveResponse(reply);
55453
56255
  return reply;
55454
56256
  }
@@ -55457,16 +56259,16 @@ ${item.payload.content}` + batchSuffix;
55457
56259
  const onLog = extra.onLog ?? (() => {
55458
56260
  });
55459
56261
  if (sessionId) {
55460
- let reply2 = await this.respondInSession(sessionId, item.payload.content + markerSuffix, onLog);
55461
- if (needsMarker)
55462
- reply2 = await this.ensureCompletionMarker(reply2, sessionId);
56262
+ let reply2 = await this.respondInSession(sessionId, item.payload.content, onLog);
56263
+ if (needsTurnCompletion)
56264
+ reply2 = await this.ensureTurnCompleted(reply2, sessionId);
55463
56265
  resolveResponse(reply2);
55464
56266
  return reply2;
55465
56267
  }
55466
56268
  const srFallbackSessionId = `sys_${this.id}_${ts}`;
55467
- let reply = await this.handleMessage(item.payload.content + markerSuffix, item.metadata?.senderId, senderInfo, buildHandleOpts({ sessionId: srFallbackSessionId }));
55468
- if (needsMarker)
55469
- reply = await this.ensureCompletionMarker(reply, srFallbackSessionId);
56269
+ let reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, buildHandleOpts({ sessionId: srFallbackSessionId }));
56270
+ if (needsTurnCompletion)
56271
+ reply = await this.ensureTurnCompleted(reply, srFallbackSessionId);
55470
56272
  resolveResponse(reply);
55471
56273
  return reply;
55472
56274
  }
@@ -55476,9 +56278,9 @@ ${item.payload.content}` + batchSuffix;
55476
56278
  const cbOpts = buildHandleOpts({ scenario: cbScenario });
55477
56279
  if (originSessionId)
55478
56280
  cbOpts.sessionId = originSessionId;
55479
- let reply = await this.handleMessage(item.payload.content + markerSuffix, void 0, void 0, cbOpts);
55480
- if (needsMarker)
55481
- reply = await this.ensureCompletionMarker(reply, cbOpts.sessionId ?? this.currentSessionId);
56281
+ let reply = await this.handleMessage(item.payload.content, void 0, void 0, cbOpts);
56282
+ if (needsTurnCompletion)
56283
+ reply = await this.ensureTurnCompleted(reply, cbOpts.sessionId ?? this.currentSessionId);
55482
56284
  resolveResponse(reply);
55483
56285
  return reply;
55484
56286
  }
@@ -55992,16 +56794,65 @@ ${item.payload.content}` + batchSuffix;
55992
56794
  * 测试与诊断断言。
55993
56795
  */
55994
56796
  cancelActiveStream(target) {
55995
- const workerId = this.resolveCancelTargetWorker(target);
55996
- if (workerId !== void 0 && this.workerWorkspaces.has(workerId)) {
55997
- this.cancelActiveStreamCore(workerId);
55998
- this.lastCancelledWorkerId = workerId;
55999
- return workerId;
56797
+ const resolved = this.resolveCancelTarget(target);
56798
+ if (resolved.kind === "worker") {
56799
+ this.cancelActiveStreamCore(resolved.workerId);
56800
+ this.lastCancelledWorkerId = resolved.workerId;
56801
+ return resolved.workerId;
56802
+ }
56803
+ if (resolved.kind === "none") {
56804
+ log20.warn("cancelActiveStream: scoped target matched no active stream \u2014 ignoring", {
56805
+ agentId: this.id,
56806
+ itemId: target?.itemId,
56807
+ sessionId: target?.sessionId,
56808
+ workerId: target?.workerId,
56809
+ workerCount: this.attentionController.getWorkerCount()
56810
+ });
56811
+ this.lastCancelledWorkerId = void 0;
56812
+ return void 0;
56000
56813
  }
56001
56814
  this.cancelActiveStreamCore();
56002
56815
  this.lastCancelledWorkerId = void 0;
56003
56816
  return void 0;
56004
56817
  }
56818
+ /**
56819
+ * 三态解析,语义严格区分:
56820
+ *
56821
+ * - `worker` 命中持有该目标的 worker → 只取消它的流;
56822
+ * - `root` **无 target** 的 legacy 调用 → 保持旧行为(ALS / 根上下文);
56823
+ * - `none` **显式给了 target 却解析不到任何在途流** → 调用方必须 no-op。
56824
+ *
56825
+ * 区分 `none` 与 `root` 正是这个 bug 的根因:旧实现把两者并成同一条兼容
56826
+ * 路径,于是「按 sessionId 取消」在目标不存在时静默升级成「取消当前在跑的
56827
+ * 那条流」—— 限定范围的请求降级为不限定范围的破坏性动作。
56828
+ */
56829
+ resolveCancelTarget(target) {
56830
+ if (!target)
56831
+ return { kind: "root" };
56832
+ if (target.workerId !== void 0) {
56833
+ return this.workerWorkspaces.has(target.workerId) ? { kind: "worker", workerId: target.workerId } : { kind: "none" };
56834
+ }
56835
+ if (this.attentionController.getWorkerCount() > 1) {
56836
+ const workerId = this.resolveCancelTargetWorker(target);
56837
+ return workerId !== void 0 ? { kind: "worker", workerId } : { kind: "none" };
56838
+ }
56839
+ const focus = this.attentionController.getCurrentFocus();
56840
+ if (!focus)
56841
+ return { kind: "none" };
56842
+ if (target.itemId !== void 0 && focus.id === target.itemId)
56843
+ return { kind: "root" };
56844
+ if (target.sessionId !== void 0 && this.focusMatchesSession(focus, target.sessionId))
56845
+ return { kind: "root" };
56846
+ return { kind: "none" };
56847
+ }
56848
+ /**
56849
+ * focus 上表达「属于哪个 DB 会话」的全部既有约定。
56850
+ * 与 `AttentionController.findWorkerBySessionId` 必须同一套匹配规则,
56851
+ * 否则串行/并发模式会对同一个 target 给出互相矛盾的答案。
56852
+ */
56853
+ focusMatchesSession(focus, sessionId) {
56854
+ return focus.metadata?.sessionId === sessionId || focus.metadata?.dbSessionId === sessionId || focus.payload?.extra?.sessionId === sessionId;
56855
+ }
56005
56856
  /** 最近一次定向取消实际命中的 workerId(未定向命中时为 undefined)。 */
56006
56857
  lastCancelledWorkerId;
56007
56858
  /** 诊断/测试:最近一次 cancelActiveStream 命中的 workerId。 */
@@ -56178,6 +57029,23 @@ ${conversationText}`
56178
57029
  }
56179
57030
  return `Task ${taskId2}`;
56180
57031
  }
57032
+ /** Banner that starts every offload payload. Used to emit it AND to detect an
57033
+ * already-offloaded result, so a capped output is never offloaded twice. */
57034
+ static OFFLOAD_BANNER_PREFIX = "[FULL output (";
57035
+ /**
57036
+ * Read the optional per-call output cap (`max_output_chars`).
57037
+ *
57038
+ * This is a cross-tool convention: any tool may advertise it, and the agent
57039
+ * honours it at the tool boundary (see `executeToolInternal`). It exists because
57040
+ * the alternative was worse — the agent had no way to *ask* for less output, so a
57041
+ * chatty command (a 46 k-char grep) was offloaded with a 2 k preview and cost a
57042
+ * second `file_read` round-trip to get at the part it actually wanted.
57043
+ */
57044
+ static readMaxOutputChars(args) {
57045
+ const raw = args?.["max_output_chars"];
57046
+ const n2 = typeof raw === "number" ? raw : typeof raw === "string" ? Number(raw) : NaN;
57047
+ return Number.isFinite(n2) && n2 > 0 ? Math.floor(n2) : void 0;
57048
+ }
56181
57049
  static BROWSER_INTERACTIVE_TOOLS = /* @__PURE__ */ new Set([
56182
57050
  "take_snapshot",
56183
57051
  "take_screenshot",
@@ -56189,15 +57057,18 @@ ${conversationText}`
56189
57057
  "performance_stop_trace",
56190
57058
  "performance_analyze_insight"
56191
57059
  ]);
56192
- offloadLargeResult(toolName, result) {
56193
- const OFFLOAD_THRESHOLD = TOOL_RESULT_OFFLOAD_CHARS;
57060
+ offloadLargeResult(toolName, result, maxOutputChars) {
57061
+ if (result.startsWith(_Agent.OFFLOAD_BANNER_PREFIX))
57062
+ return result;
57063
+ const requestedCap = maxOutputChars && maxOutputChars > 0 ? Math.floor(maxOutputChars) : void 0;
57064
+ const OFFLOAD_THRESHOLD = requestedCap ? Math.min(TOOL_RESULT_OFFLOAD_CHARS, requestedCap) : TOOL_RESULT_OFFLOAD_CHARS;
56194
57065
  if (result.length <= OFFLOAD_THRESHOLD)
56195
57066
  return result;
56196
57067
  if (toolName === "file_read")
56197
57068
  return result;
56198
57069
  const baseName = toolName.includes("__") ? toolName.split("__").pop() : toolName;
56199
57070
  const isBrowserTool = _Agent.BROWSER_INTERACTIVE_TOOLS.has(baseName);
56200
- const previewSize = isBrowserTool ? 3e4 : 2e3;
57071
+ const previewSize = requestedCap ?? (isBrowserTool ? 3e4 : 2e3);
56201
57072
  try {
56202
57073
  const offloadDir = join12(this.dataDir, "tool-outputs");
56203
57074
  mkdirSync12(offloadDir, { recursive: true });
@@ -56207,8 +57078,8 @@ ${conversationText}`
56207
57078
  const preview = safeSlice(result, 0, previewSize);
56208
57079
  const lineCount = result.split("\n").length;
56209
57080
  return [
56210
- `[FULL output (${result.length} chars, ${lineCount} lines) saved to: ${filepath}]`,
56211
- `[NOTE: The content below is only the first ${previewSize} chars. The complete, untruncated result is in the file above.]`,
57081
+ `${_Agent.OFFLOAD_BANNER_PREFIX}${result.length} chars, ${lineCount} lines) saved to: ${filepath}]`,
57082
+ `[NOTE: The content below is only the first ${previewSize} chars${requestedCap ? ` \u2014 max_output_chars=${requestedCap} was requested` : ""}. The complete, untruncated result is in the file above.]`,
56212
57083
  `[To read the full content, use file_read with offset and limit parameters to read in chunks, e.g.: file_read(path="${filepath}", offset=1, limit=500)]`,
56213
57084
  ``,
56214
57085
  preview,
@@ -56641,16 +57512,14 @@ _[truncated \u2014 full text in NOTEBOOK.md]
56641
57512
  return parts.length > 0 ? parts.join("\n\n") : void 0;
56642
57513
  }
56643
57514
  /**
56644
- * 审计 §8.1:确定性情境准备(原 CPP 的 LLM 多阶段管道已移除)。
57515
+ * 审计 §8.1:确定性情境块(原 CPP 的 LLM 多阶段管道已移除)。
56645
57516
  *
56646
57517
  * 旧 CPP 在主调用前跑 0–3 次 LLM(appraise / reflect),带来额外时延与成本,
56647
57518
  * 且与上下文引擎自身「有界的相关记忆检索」重复。现改为**纯确定性**装配一小段
56648
- * 情境块(近期活动 + 工作记忆键);更深的跨域召回由 Agent 按场景提示主动调
56649
- * `memory_search` / `kb_search` 承担。返回 undefined 表示无情境可注入。
57519
+ * 情境块(近期活动 + 工作记忆键),始终注入;更深的跨域召回由 Agent 按场景提示
57520
+ * 主动调 `memory_search` / `kb_search` 承担。返回 undefined 表示无可注入内容。
56650
57521
  */
56651
- async prepareCognitiveContext(_scenario, _message, _sender) {
56652
- if (!this.cognitiveConfig?.enabled)
56653
- return void 0;
57522
+ buildCognitiveContext() {
56654
57523
  const parts = [];
56655
57524
  const activity = this.recentActivityRing.slice(-3);
56656
57525
  if (activity.length > 0) {
@@ -56660,13 +57529,7 @@ _[truncated \u2014 full text in NOTEBOOK.md]
56660
57529
  const keys2 = [...this.workingMemory.keys()].slice(0, 8).join(", ");
56661
57530
  parts.push(`Working memory: ${this.workingMemory.size} entries (${keys2})`);
56662
57531
  }
56663
- if (parts.length === 0)
56664
- return void 0;
56665
- return {
56666
- depth: CognitiveDepth.D1_Reactive,
56667
- cognitiveContext: parts.join("\n"),
56668
- isEmpty: false
56669
- };
57532
+ return parts.length > 0 ? parts.join("\n") : void 0;
56670
57533
  }
56671
57534
  getMailboxContext() {
56672
57535
  const mind = this.attentionController.getMindState();
@@ -57164,6 +58027,7 @@ ${report}`);
57164
58027
  return "[cancelled]";
57165
58028
  }
57166
58029
  this.transitionStatus({ to: "working" });
58030
+ this.endTurnRequested = false;
57167
58031
  const scenario = options?.scenario ?? "chat";
57168
58032
  const isLightweight = scenario !== "chat" && scenario !== "task_execution" && scenario !== "review";
57169
58033
  const isPreemptable = scenario !== "chat";
@@ -57238,7 +58102,7 @@ ${report}`);
57238
58102
  const userContent = await this.buildUserContent(userMessage, options?.images, options?.fileNames, options?.imagePaths);
57239
58103
  this.memory.appendMessage(sessionId, { role: "user", content: userContent });
57240
58104
  await this.activateTokenCounterForModel();
57241
- const cognitiveContext = await this.prepareCognitiveContext(scenario, effectiveMessage, senderId);
58105
+ const cognitiveContext = this.buildCognitiveContext();
57242
58106
  const systemPromptBuild = await this.contextEngine.buildSystemPrompt({
57243
58107
  agentId: this.id,
57244
58108
  agentName: this.config.name,
@@ -57366,7 +58230,7 @@ ${report}`);
57366
58230
  const effectiveMaxIter = options?.maxToolIterations ?? this._maxToolIterations;
57367
58231
  const commentToolUsed = /* @__PURE__ */ new Set();
57368
58232
  const requirementActionToolUsed = /* @__PURE__ */ new Set();
57369
- while (shouldContinueToolLoop(response)) {
58233
+ while (shouldContinueToolLoop(response, { endTurnRequested: this.endTurnRequested })) {
57370
58234
  if (++toolIterations > effectiveMaxIter) {
57371
58235
  log20.warn("Tool loop hit max iterations", {
57372
58236
  agentId: this.id,
@@ -57546,6 +58410,8 @@ ${chatYield.item.payload.content}`;
57546
58410
  volatileState: this.volatileState
57547
58411
  });
57548
58412
  const updatedMessages = prepared2.messages;
58413
+ if (this.endTurnRequested)
58414
+ break;
57549
58415
  const llmStart2 = Date.now();
57550
58416
  response = await this.withNetworkRetry(() => this.llmRouter.chat({
57551
58417
  messages: updatedMessages,
@@ -57560,8 +58426,7 @@ ${chatYield.item.payload.content}`;
57560
58426
  this.calibrateTokenCounter(response.usage.inputTokens);
57561
58427
  this.emitLlmRequestAudit("chat", response, Date.now() - llmStart2, tokens2);
57562
58428
  }
57563
- const hasNoReplyMarker = /\[NO_REPLY_NEEDED\]/i.test(response.content ?? "");
57564
- if (scenario === "comment_response" && commentToolUsed.size === 0 && !hasNoReplyMarker && toolIterations < effectiveMaxIter) {
58429
+ if (scenario === "comment_response" && commentToolUsed.size === 0 && !this.endTurnRequested && toolIterations < effectiveMaxIter) {
57565
58430
  this.memory.appendMessage(sessionId, {
57566
58431
  role: "assistant",
57567
58432
  content: response.content,
@@ -57570,7 +58435,7 @@ ${chatYield.item.payload.content}`;
57570
58435
  });
57571
58436
  this.memory.appendMessage(sessionId, {
57572
58437
  role: "user",
57573
- content: "[SYSTEM] You are about to end your turn WITHOUT posting a reply and WITHOUT marking [NO_REPLY_NEEDED]. In this scenario your text output is NOT visible to anyone. You MUST either: (1) call `task_comment` or `requirement_comment` tool to post your reply in the comment thread, OR (2) output exactly [NO_REPLY_NEEDED] if you have determined that no response is warranted. Do it now."
58438
+ content: "[SYSTEM] You are about to end your turn WITHOUT posting a reply and WITHOUT calling the end_turn tool. In this scenario your text output is NOT visible to anyone. You MUST either: (1) call `task_comment` or `requirement_comment` tool to post your reply in the comment thread, OR (2) call the end_turn tool if you have determined that no response is warranted. Do it now."
57574
58439
  });
57575
58440
  const reminderMessages = this.requestHistory(sessionId);
57576
58441
  const preparedReminder = await this.contextEngine.prepareMessages({
@@ -57737,6 +58602,16 @@ ${chatYield.item.payload.content}`;
57737
58602
  }, this.getEffectiveProvider(), { sessionId: sessionId ?? this.currentSessionId }), "Chat LLM requirement-action-reminder-final");
57738
58603
  }
57739
58604
  }
58605
+ if (this.endTurnRequested) {
58606
+ this.endTurnRequested = false;
58607
+ this.memory.appendMessage(sessionId, { role: "assistant", content: "" });
58608
+ if (chatActivityId) {
58609
+ this.emitActivityLog(chatActivityId, "text", "[end_turn \u2014 no reply sent]");
58610
+ this.endActivity(chatActivityId);
58611
+ }
58612
+ this.transitionStatus({ to: "idle" });
58613
+ return "";
58614
+ }
57740
58615
  const rawReply = sanitizeLLMReply(response.content);
57741
58616
  const displayReply = stripCompletionMarker(rawReply);
57742
58617
  const outputCheck = await this.guardrails.checkOutput(displayReply, { agentId: this.id });
@@ -57842,7 +58717,7 @@ ${chatYield.item.payload.content}`;
57842
58717
  const userContent = await this.buildUserContent(userMessage, images, fileNames, imagePaths);
57843
58718
  this.memory.appendMessage(this.currentSessionId, { role: "user", content: userContent });
57844
58719
  await this.activateTokenCounterForModel();
57845
- const cognitiveContext = await this.prepareCognitiveContext("chat", effectiveMessage, senderId);
58720
+ const cognitiveContext = this.buildCognitiveContext();
57846
58721
  const systemPromptBuild = await this.contextEngine.buildSystemPrompt({
57847
58722
  agentId: this.id,
57848
58723
  agentName: this.config.name,
@@ -57991,7 +58866,7 @@ ${chatYield.item.payload.content}`;
57991
58866
  \u26A0\uFE0F ${response.creditWarning}` });
57992
58867
  }
57993
58868
  let streamToolIterations = 0;
57994
- while (shouldContinueToolLoop(response)) {
58869
+ while (shouldContinueToolLoop(response, { endTurnRequested: this.endTurnRequested })) {
57995
58870
  if (++streamToolIterations > this._maxToolIterations) {
57996
58871
  log20.warn("Stream tool loop hit max iterations", {
57997
58872
  agentId: this.id,
@@ -58261,7 +59136,7 @@ ${streamYield.item.payload.content}`;
58261
59136
  if (streamChatActivityId)
58262
59137
  this.endActivity(streamChatActivityId, { success: false });
58263
59138
  this.transitionStatus({ to: "idle" });
58264
- return truncated + COMPLETION_MARKER;
59139
+ return truncated;
58265
59140
  }
58266
59141
  if (streamChatActivityId)
58267
59142
  this.endActivity(streamChatActivityId, { success: !cancelToken?.userStopped });
@@ -58461,7 +59336,7 @@ ${streamYield.item.payload.content}`;
58461
59336
  this.memory.appendMessage(sessionId, { role: "user", content: taskPrompt });
58462
59337
  }
58463
59338
  await this.activateTokenCounterForModel();
58464
- const cognitiveContext = await this.prepareCognitiveContext("task_execution", taskPrompt);
59339
+ const cognitiveContext = this.buildCognitiveContext();
58465
59340
  const systemPromptBuild = await this.contextEngine.buildSystemPrompt({
58466
59341
  agentId: this.id,
58467
59342
  agentName: this.config.name,
@@ -58567,7 +59442,7 @@ ${streamYield.item.payload.content}`;
58567
59442
  this.updateTokensUsed(taskLlmTokens);
58568
59443
  this.calibrateTokenCounter(response.usage.inputTokens);
58569
59444
  this.emitLlmRequestAudit("task_execution", response, Date.now() - taskLlmStart, taskLlmTokens);
58570
- while (shouldContinueToolLoop(response)) {
59445
+ while (shouldContinueToolLoop(response, { endTurnRequested: this.endTurnRequested })) {
58571
59446
  taskToolIterations++;
58572
59447
  if (cancelToken?.cancelled) {
58573
59448
  flushText();
@@ -58932,7 +59807,7 @@ ${yieldResult.item.payload.content}`
58932
59807
  const emitDelta = markerDeltaRIS.emit;
58933
59808
  this.memory.getOrCreateSession(this.id, sessionId);
58934
59809
  this.memory.appendMessage(sessionId, { role: "user", content: userMessage });
58935
- const cognitiveContext = await this.prepareCognitiveContext("chat", userMessage);
59810
+ const cognitiveContext = this.buildCognitiveContext();
58936
59811
  const systemPromptBuild = await this.contextEngine.buildSystemPrompt({
58937
59812
  agentId: this.id,
58938
59813
  agentName: this.config.name,
@@ -59020,7 +59895,7 @@ ${yieldResult.item.payload.content}`
59020
59895
  this.emitLlmRequestAudit("respond_in_session", response, Date.now() - risLlmStart, risTokens);
59021
59896
  let toolIter = 0;
59022
59897
  const effectiveMaxIter = this._maxToolIterations;
59023
- while (shouldContinueToolLoop(response)) {
59898
+ while (shouldContinueToolLoop(response, { endTurnRequested: this.endTurnRequested })) {
59024
59899
  if (++toolIter > effectiveMaxIter) {
59025
59900
  log20.warn("respondInSession tool loop hit max iterations", {
59026
59901
  agentId: this.id,
@@ -60370,7 +61245,27 @@ ${d.text}
60370
61245
  }
60371
61246
  return await this.executeToolInternal(toolCall, onOutput, sessionId);
60372
61247
  }
61248
+ /**
61249
+ * Tool-boundary entry point. Every tool invocation funnels through here (write-locked
61250
+ * or not), which makes it the single place that can honour a per-call output cap
61251
+ * (`max_output_chars`) exactly once, whichever loop drove the call.
61252
+ *
61253
+ * The cap is enforced LOSSLESSLY: hitting it delegates to `offloadLargeResult`, which
61254
+ * writes the complete output to a file and returns a capped preview plus that path.
61255
+ */
60373
61256
  async executeToolInternal(toolCall, onOutput, sessionId) {
61257
+ const raw = await this.runTool(toolCall, onOutput, sessionId);
61258
+ const cap = _Agent.readMaxOutputChars(toolCall.arguments);
61259
+ return cap ? this.offloadLargeResult(toolCall.name, raw, cap) : raw;
61260
+ }
61261
+ async runTool(toolCall, onOutput, sessionId) {
61262
+ if (toolCall.name === "end_turn") {
61263
+ this.endTurnRequested = true;
61264
+ this.endTurnCount++;
61265
+ const reason = typeof toolCall.arguments.reason === "string" ? toolCall.arguments.reason.trim() : "";
61266
+ log20.info("Agent ended turn via end_turn tool", { agentId: this.id, sessionId, reason: reason || void 0 });
61267
+ return JSON.stringify({ status: "ok", ended: true, note: "Turn ended. Do not send further messages in this turn." });
61268
+ }
60374
61269
  if (toolCall.name === "discover_tools") {
60375
61270
  return await this.handleDiscoverTools(toolCall.arguments);
60376
61271
  }
@@ -61231,14 +62126,14 @@ ${todayLog.slice(0, HEARTBEAT_DAILY_LOG_CHARS)}
61231
62126
  try {
61232
62127
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
61233
62128
  const entries2 = this.memory.getObservations();
62129
+ const health = this.memory.getMemoryHealth();
61234
62130
  const dreamKey = entries2.length > 500 ? `${today}_${Math.floor(Date.now() / (6 * 36e5))}` : today;
61235
- if (entries2.length >= 50 && this.lastDreamDate !== dreamKey) {
62131
+ if (shouldRunDreamCycle({ observationPercent: health.observationPercent, entryCount: entries2.length }) && this.lastDreamDate !== dreamKey) {
61236
62132
  this.lastDreamDate = dreamKey;
61237
62133
  await _Agent.acquireDreamSlot();
61238
62134
  try {
61239
62135
  await this.resourceLocks.withLock(memoryResourceLock("knowledge"), async () => {
61240
62136
  await this.dreamConsolidateMemory(entries2);
61241
- this.pruneMemoryMd();
61242
62137
  this.memory.markConsolidated?.();
61243
62138
  });
61244
62139
  } finally {
@@ -61426,117 +62321,6 @@ ${promo.content}` : promo.content;
61426
62321
  log20.warn("Dream cycle failed", { agentId: this.id, error: String(error) });
61427
62322
  }
61428
62323
  }
61429
- /**
61430
- * Enforce knowledge.md hygiene: remove daily-report sections (they belong in
61431
- * daily-logs/), strip leaked LLM <think> blocks, and enforce section/total
61432
- * size limits via heuristic compression. Preserves ## _observations.
61433
- */
61434
- pruneMemoryMd() {
61435
- const content = this.memory.getLongTermMemory();
61436
- if (!content)
61437
- return;
61438
- const lines = content.split("\n");
61439
- const afterSectionPrune = [];
61440
- let inDailyReport = false;
61441
- for (const line of lines) {
61442
- if (line.startsWith("## daily-report-")) {
61443
- inDailyReport = true;
61444
- continue;
61445
- }
61446
- if (inDailyReport && line.startsWith("## ")) {
61447
- inDailyReport = false;
61448
- }
61449
- if (!inDailyReport)
61450
- afterSectionPrune.push(line);
61451
- }
61452
- const sections = [];
61453
- let currentHeading = "";
61454
- let currentBody = [];
61455
- let sectionStart = 0;
61456
- for (let i = 0; i <= afterSectionPrune.length; i++) {
61457
- const line = i < afterSectionPrune.length ? afterSectionPrune[i] : void 0;
61458
- const isHeading = line !== void 0 && /^#{1,3}\s/.test(line);
61459
- if (isHeading || line === void 0) {
61460
- if (currentHeading || currentBody.length > 0) {
61461
- sections.push({
61462
- heading: currentHeading,
61463
- body: currentBody.join("\n").trim(),
61464
- startIdx: sectionStart
61465
- });
61466
- }
61467
- currentHeading = line ?? "";
61468
- currentBody = [];
61469
- sectionStart = i;
61470
- } else {
61471
- currentBody.push(line);
61472
- }
61473
- }
61474
- const headingLastIdx = /* @__PURE__ */ new Map();
61475
- const normalizeHeading = (h) => h.replace(/^#+\s*/, "").trim().toLowerCase();
61476
- for (let i = 0; i < sections.length; i++) {
61477
- const key2 = normalizeHeading(sections[i].heading);
61478
- if (key2)
61479
- headingLastIdx.set(key2, i);
61480
- }
61481
- const deduped = [];
61482
- for (let i = 0; i < sections.length; i++) {
61483
- const s2 = sections[i];
61484
- const key2 = normalizeHeading(s2.heading);
61485
- if (key2 && headingLastIdx.get(key2) !== i && headingLastIdx.has(key2)) {
61486
- continue;
61487
- }
61488
- deduped.push(s2);
61489
- }
61490
- afterSectionPrune.length = 0;
61491
- for (const s2 of deduped) {
61492
- if (s2.heading)
61493
- afterSectionPrune.push(s2.heading);
61494
- if (s2.body)
61495
- afterSectionPrune.push(s2.body);
61496
- afterSectionPrune.push("");
61497
- }
61498
- const outputLines = [];
61499
- let inThinkBlock = false;
61500
- for (const line of afterSectionPrune) {
61501
- if (line.trim() === "<think>") {
61502
- inThinkBlock = true;
61503
- continue;
61504
- }
61505
- if (inThinkBlock && line.trim() === "</think>") {
61506
- inThinkBlock = false;
61507
- continue;
61508
- }
61509
- if (!inThinkBlock)
61510
- outputLines.push(line);
61511
- }
61512
- const pruned = outputLines.join("\n").replace(/\n{3,}/g, "\n\n").trim();
61513
- if (pruned !== content.trim()) {
61514
- const knowledgeMdPath = join12(this.dataDir, "knowledge.md");
61515
- let obsTail = "";
61516
- try {
61517
- if (existsSync19(knowledgeMdPath)) {
61518
- const existing = readFileSync13(knowledgeMdPath, "utf-8");
61519
- const obsStart = existing.indexOf("\n## _observations");
61520
- if (obsStart >= 0)
61521
- obsTail = existing.slice(obsStart);
61522
- else if (existing.startsWith("## _observations"))
61523
- obsTail = "\n" + existing;
61524
- }
61525
- } catch {
61526
- }
61527
- writeFileSync13(knowledgeMdPath, pruned + (obsTail ? "\n" + obsTail.replace(/^\n+/, "") : "") + "\n");
61528
- log20.info("Pruned knowledge.md: removed daily-report sections and LLM artifacts", { agentId: this.id });
61529
- }
61530
- const compressed = this.memory.compressLongTermMemory();
61531
- if (compressed.truncatedChunks > 0) {
61532
- log20.info("Compressed knowledge.md during Dream Cycle", {
61533
- agentId: this.id,
61534
- charsBefore: compressed.charsBefore,
61535
- charsAfter: compressed.charsAfter,
61536
- sectionsTrimmed: compressed.truncatedChunks
61537
- });
61538
- }
61539
- }
61540
62324
  };
61541
62325
  }
61542
62326
  });
@@ -131908,7 +132692,7 @@ var require_buffers = __commonJS({
131908
132692
  // ../../node_modules/.pnpm/binary@0.3.0/node_modules/binary/lib/vars.js
131909
132693
  var require_vars = __commonJS({
131910
132694
  "../../node_modules/.pnpm/binary@0.3.0/node_modules/binary/lib/vars.js"(exports2, module2) {
131911
- module2.exports = function(store) {
132695
+ module2.exports = function(store2) {
131912
132696
  function getset(name, value) {
131913
132697
  var node = vars.store;
131914
132698
  var keys2 = name.split(".");
@@ -131930,7 +132714,7 @@ var require_vars = __commonJS({
131930
132714
  set: function(name, value) {
131931
132715
  return getset(name, value);
131932
132716
  },
131933
- store: store || {}
132717
+ store: store2 || {}
131934
132718
  };
131935
132719
  return vars;
131936
132720
  };
@@ -192363,12 +193147,12 @@ var require_fontkit_umd = __commonJS({
192363
193147
  (_codePoints = codePoints).unshift.apply(_codePoints, this.glyphs[componentGlyph].codePoints);
192364
193148
  var action = actions.getItem(actionIndex++);
192365
193149
  last = !!(action & LAST_MASK);
192366
- var store = !!(action & STORE_MASK);
193150
+ var store2 = !!(action & STORE_MASK);
192367
193151
  var offset2 = (action & OFFSET_MASK) << 2 >> 2;
192368
193152
  offset2 += this.glyphs[componentGlyph].id;
192369
193153
  var component = components.getItem(offset2);
192370
193154
  ligatureIndex += component;
192371
- if (last || store) {
193155
+ if (last || store2) {
192372
193156
  var ligatureEntry = ligatureList.getItem(ligatureIndex);
192373
193157
  this.glyphs[componentGlyph] = this.font.getGlyph(ligatureEntry, codePoints);
192374
193158
  ligatureGlyphs.push(componentGlyph);
@@ -202902,15 +203686,24 @@ function createMemoryTools(ctx) {
202902
203686
  content,
202903
203687
  metadata: tagArray?.length ? { tags: tagArray } : void 0
202904
203688
  };
202905
- ctx.memory.addEntry(entry);
203689
+ const wrote = ctx.memory.addEntry(entry);
203690
+ if (wrote && wrote.ok === false) {
203691
+ return JSON.stringify({
203692
+ status: "error",
203693
+ ok: false,
203694
+ id: entry.id,
203695
+ error: wrote.reason ?? "memory write refused",
203696
+ store: storeName(ctx.memory)
203697
+ });
203698
+ }
202906
203699
  if (ctx.semanticSearch?.isEnabled()) {
202907
203700
  ctx.semanticSearch.indexMemory(entry, ctx.agentId).catch((err) => {
202908
203701
  log27.warn("Failed to index memory for semantic search", { error: String(err) });
202909
203702
  });
202910
203703
  }
202911
- const store = storeName(ctx.memory);
202912
- log27.info("Agent saved memory", { agentId: ctx.agentId, type, contentLen: content.length, store });
202913
- return JSON.stringify({ status: "saved", id: entry.id, type, store });
203704
+ const store2 = storeName(ctx.memory);
203705
+ log27.info("Agent saved memory", { agentId: ctx.agentId, type, contentLen: content.length, store: store2 });
203706
+ return JSON.stringify({ status: "saved", id: entry.id, type, store: store2 });
202914
203707
  }
202915
203708
  },
202916
203709
  {
@@ -202938,7 +203731,7 @@ function createMemoryTools(ctx) {
202938
203731
  const query2 = args["query"] ?? "";
202939
203732
  const type = args["type"];
202940
203733
  const limit = args["limit"] ?? 10;
202941
- const store = storeName(ctx.memory);
203734
+ const store2 = storeName(ctx.memory);
202942
203735
  if (!query2.trim()) {
202943
203736
  const entries2 = ctx.memory.getEntries(type ?? void 0, limit);
202944
203737
  return JSON.stringify({
@@ -202950,7 +203743,7 @@ function createMemoryTools(ctx) {
202950
203743
  tags: e.metadata?.tags
202951
203744
  })),
202952
203745
  count: entries2.length,
202953
- store
203746
+ store: store2
202954
203747
  });
202955
203748
  }
202956
203749
  let keywordResults = ctx.memory.search(query2);
@@ -202987,7 +203780,7 @@ function createMemoryTools(ctx) {
202987
203780
  })),
202988
203781
  count: merged.length,
202989
203782
  searchMethod: extras.length > 0 ? "semantic+keyword" : "semantic",
202990
- store
203783
+ store: store2
202991
203784
  });
202992
203785
  }
202993
203786
  log27.info("Semantic search returned 0 results, using keyword search", {
@@ -203011,13 +203804,13 @@ function createMemoryTools(ctx) {
203011
203804
  })),
203012
203805
  count: results.length,
203013
203806
  searchMethod: "keyword",
203014
- store
203807
+ store: store2
203015
203808
  });
203016
203809
  }
203017
203810
  },
203018
203811
  {
203019
203812
  name: "memory_update",
203020
- description: 'Update a curated section in knowledge.md (injected as "## Your Knowledge" on later turns). Use for personal multi-step procedures / durable domain lessons \u2014 not one-off tips (use memory_save). Args: { section, content, mode?: "replace"|"patch"|"append"|"forget"|"delete" }. append\u2261patch. Prefer patch/append; replace only when rewriting the whole section. mode="forget" removes the named curated section entirely (superseded knowledge must be removable \u2014 the store is capped, so a write-only store would inflate until it fills up). mode="delete" removes observation entries listed in "ids". Do not put ## headings in content (auto-downgraded to ###). Success: { status:"updated", store:"knowledge.md" }. On error, retry \u2014 never claim updated without status.',
203813
+ description: 'Update a curated section in knowledge.md (injected as "## Your Knowledge" on later turns). Use for personal multi-step procedures / durable domain lessons \u2014 not one-off tips (use memory_save). Args: { section, content, mode?: "replace"|"patch"|"append"|"forget"|"delete" }. append\u2261patch. Prefer patch/append; replace only when rewriting the whole section. Mode="forget" removes the named curated section entirely (superseded knowledge must be removable \u2014 the store is capped, so a write-only store would inflate until it fills up). Reserved key `_preamble` targets the text BEFORE the first `## ` heading (legacy scaffold). mode="delete" removes observation entries listed in "ids". Do not put ## headings in content (auto-downgraded to ###). Success: { status:"updated", store:"knowledge.md" }. On error, retry \u2014 never claim updated without status.',
203021
203814
  inputSchema: {
203022
203815
  type: "object",
203023
203816
  properties: {
@@ -203047,10 +203840,27 @@ function createMemoryTools(ctx) {
203047
203840
  const content = args["content"] ?? "";
203048
203841
  const mode = normalizeWriteMode(args["mode"]);
203049
203842
  const ids = args["ids"];
203050
- const store = storeName(ctx.memory);
203843
+ const store2 = storeName(ctx.memory);
203844
+ if (section3 === "_preamble") {
203845
+ if (mode === "forget" || mode === "delete") {
203846
+ const r = ctx.memory.removeLongTermPreamble?.();
203847
+ if (!r)
203848
+ return JSON.stringify({ status: "error", error: "this store does not support preamble removal", store: store2 });
203849
+ if (!r.ok)
203850
+ return JSON.stringify({ status: "error", error: "preamble removal refused", store: store2 });
203851
+ log27.info("Agent cleared the curated preamble", { agentId: ctx.agentId, removedChars: r.removedChars });
203852
+ return JSON.stringify({ status: "forgotten", section: "_preamble", removedChars: r.removedChars, store: store2 });
203853
+ }
203854
+ const w = ctx.memory.setLongTermPreamble?.(content);
203855
+ if (!w)
203856
+ return JSON.stringify({ status: "error", error: "this store does not support a preamble", store: store2 });
203857
+ if (!w.ok)
203858
+ return JSON.stringify({ status: "error", error: w.reason ?? "preamble write refused", section: section3, store: store2 });
203859
+ return JSON.stringify({ status: "updated", section: "_preamble", mode, store: store2 });
203860
+ }
203051
203861
  if (mode === "delete") {
203052
203862
  if (!ids?.length) {
203053
- return JSON.stringify({ status: "error", error: "Provide ids to delete.", store });
203863
+ return JSON.stringify({ status: "error", error: "Provide ids to delete.", store: store2 });
203054
203864
  }
203055
203865
  const capped = ids.slice(0, 20);
203056
203866
  const removed = ctx.memory.removeEntries(capped);
@@ -203062,15 +203872,15 @@ function createMemoryTools(ctx) {
203062
203872
  }
203063
203873
  }
203064
203874
  log27.info("Agent deleted memories", { agentId: ctx.agentId, removed });
203065
- return JSON.stringify({ status: "deleted", removed, store });
203875
+ return JSON.stringify({ status: "deleted", removed, store: store2 });
203066
203876
  }
203067
203877
  if (mode === "forget") {
203068
203878
  if (!section3?.trim()) {
203069
- return JSON.stringify({ status: "error", error: "Provide the section name to forget.", store });
203879
+ return JSON.stringify({ status: "error", error: "Provide the section name to forget.", store: store2 });
203070
203880
  }
203071
203881
  const result = ctx.memory.removeLongTermSection(section3);
203072
203882
  if (!result.ok) {
203073
- return JSON.stringify({ status: "error", error: result.reason ?? "Failed to forget section.", store });
203883
+ return JSON.stringify({ status: "error", error: result.reason ?? "Failed to forget section.", store: store2 });
203074
203884
  }
203075
203885
  log27.info("Agent forgot a curated section", {
203076
203886
  agentId: ctx.agentId,
@@ -203081,12 +203891,12 @@ function createMemoryTools(ctx) {
203081
203891
  status: "forgotten",
203082
203892
  section: section3,
203083
203893
  removedChars: result.removedChars,
203084
- reason: `Section "${section3}" removed from ${store}.`,
203085
- store
203894
+ reason: `Section "${section3}" removed from ${store2}.`,
203895
+ store: store2
203086
203896
  });
203087
203897
  }
203088
203898
  if (!section3?.trim()) {
203089
- return JSON.stringify({ status: "error", error: "section is required", store });
203899
+ return JSON.stringify({ status: "error", error: "section is required", store: store2 });
203090
203900
  }
203091
203901
  let writeResult;
203092
203902
  if (mode === "patch") {
@@ -203099,10 +203909,10 @@ ${content}` : content;
203099
203909
  }
203100
203910
  if (!writeResult.ok) {
203101
203911
  log27.warn("Agent long-term memory write refused", { agentId: ctx.agentId, section: section3, mode, reason: writeResult.reason });
203102
- return JSON.stringify({ status: "error", ok: false, error: writeResult.reason ?? "knowledge.md write refused", section: section3, mode, store });
203912
+ return JSON.stringify({ status: "error", ok: false, error: writeResult.reason ?? "knowledge.md write refused", section: section3, mode, store: store2 });
203103
203913
  }
203104
- log27.info("Agent updated long-term memory", { agentId: ctx.agentId, section: section3, mode, contentLen: content.length, store });
203105
- return JSON.stringify({ status: "updated", section: section3, mode, store });
203914
+ log27.info("Agent updated long-term memory", { agentId: ctx.agentId, section: section3, mode, contentLen: content.length, store: store2 });
203915
+ return JSON.stringify({ status: "updated", section: section3, mode, store: store2 });
203106
203916
  }
203107
203917
  },
203108
203918
  // Backward compatibility aliases
@@ -203145,16 +203955,16 @@ ${content}` : content;
203145
203955
  async execute(args) {
203146
203956
  const ids = args["ids"];
203147
203957
  const tag = args["tag"];
203148
- const store = storeName(ctx.memory);
203958
+ const store2 = storeName(ctx.memory);
203149
203959
  if (!ids?.length && !tag)
203150
- return JSON.stringify({ status: "error", error: "Provide ids or tag.", store });
203960
+ return JSON.stringify({ status: "error", error: "Provide ids or tag.", store: store2 });
203151
203961
  let removed = 0;
203152
203962
  if (ids?.length) {
203153
203963
  removed = ctx.memory.removeEntries(ids.slice(0, 20));
203154
203964
  } else if (tag) {
203155
203965
  removed = ctx.memory.removeEntriesByTag(tag);
203156
203966
  }
203157
- return JSON.stringify({ status: "deleted", removed, store });
203967
+ return JSON.stringify({ status: "deleted", removed, store: store2 });
203158
203968
  }
203159
203969
  },
203160
203970
  {
@@ -203173,7 +203983,7 @@ ${content}` : content;
203173
203983
  const section3 = args["section"];
203174
203984
  const content = args["content"];
203175
203985
  const mode = normalizeWriteMode(args["mode"]);
203176
- const store = storeName(ctx.memory);
203986
+ const store2 = storeName(ctx.memory);
203177
203987
  let writeResult;
203178
203988
  if (mode === "patch") {
203179
203989
  const existing = ctx.memory.getLongTermSection(section3);
@@ -203183,17 +203993,17 @@ ${content}` : content);
203183
203993
  writeResult = ctx.memory.addLongTermMemory(section3, content);
203184
203994
  }
203185
203995
  if (!writeResult.ok) {
203186
- return JSON.stringify({ status: "error", ok: false, error: writeResult.reason ?? "knowledge.md write refused", section: section3, mode, store });
203996
+ return JSON.stringify({ status: "error", ok: false, error: writeResult.reason ?? "knowledge.md write refused", section: section3, mode, store: store2 });
203187
203997
  }
203188
- return JSON.stringify({ status: "updated", section: section3, mode, store });
203998
+ return JSON.stringify({ status: "updated", section: section3, mode, store: store2 });
203189
203999
  }
203190
204000
  },
203191
204001
  {
203192
204002
  name: "memory_stats",
203193
- description: "Inspect your memory health: knowledge.md size vs budget, observation count, curated section count. Use periodically (or when memory feels bloated) to decide whether to run memory_organize. Returns JSON with budget usage percent. No args.",
204003
+ description: "Inspect your memory health: the CURATED (injected) knowledge budget vs its cap, plus the separate `## _observations` buffer usage, observation count and curated section count. Note the two budgets are independent \u2014 the observation buffer is NOT injected into the prompt. Use periodically (or when memory feels bloated) to decide whether to run memory_organize. Returns JSON with budget usage percent. No args.",
203194
204004
  inputSchema: { type: "object", properties: {} },
203195
204005
  async execute() {
203196
- const store = storeName(ctx.memory);
204006
+ const store2 = storeName(ctx.memory);
203197
204007
  const health = ctx.memory.getMemoryHealth();
203198
204008
  const curated = ctx.memory.getLongTermMemory();
203199
204009
  const obs = ctx.memory.getObservations();
@@ -203201,17 +204011,25 @@ ${content}` : content);
203201
204011
  const obsChars = obs.reduce((s2, e) => s2 + (e.content?.length ?? 0), 0);
203202
204012
  return JSON.stringify({
203203
204013
  status: "ok",
203204
- store,
204014
+ store: store2,
204015
+ // The injected budget — the one that actually costs prompt space.
203205
204016
  budget: {
203206
- totalChars: health.totalChars,
203207
- limit: health.cap,
204017
+ curatedChars: health.curatedChars,
204018
+ limit: health.curatedCap,
203208
204019
  usedPercent: health.percent
203209
204020
  },
204021
+ // A separate, non-injected budget (searched on demand).
204022
+ observationBuffer: {
204023
+ chars: health.observationChars,
204024
+ limit: health.observationCap,
204025
+ usedPercent: health.observationPercent
204026
+ },
203210
204027
  observations: { count: obs.length, chars: obsChars },
203211
204028
  curatedSections: { count: sectionNames.length, names: sectionNames.slice(0, 20) },
203212
204029
  archivedChars: health.archiveChars,
203213
204030
  lastConsolidatedAt: health.lastConsolidatedAt,
203214
- hint: health.percent > 80 ? 'Approaching budget \u2014 run memory_organize to merge observations into curated sections, or memory_update mode="forget" on superseded knowledge.' : void 0
204031
+ hint: health.percent >= MEMORY_HEALTH_WARN_PERCENT ? 'Injected knowledge is near its budget \u2014 run memory_organize to merge sections, or memory_update mode="forget" on superseded knowledge.' : void 0,
204032
+ observationHint: health.observationPercent >= MEMORY_HEALTH_WARN_PERCENT ? "The observation buffer is near its own limit (it is NOT injected into the prompt). It is trimmed losslessly, oldest-first, when it overflows \u2014 memory_organize merges recurring patterns into curated sections before that happens." : void 0
203215
204033
  });
203216
204034
  }
203217
204035
  },
@@ -203242,16 +204060,16 @@ ${content}` : content);
203242
204060
  required: ["target_section"]
203243
204061
  },
203244
204062
  async execute(args) {
203245
- const store = storeName(ctx.memory);
204063
+ const store2 = storeName(ctx.memory);
203246
204064
  const target = String(args["target_section"] ?? "").trim();
203247
204065
  if (!target) {
203248
- return JSON.stringify({ status: "error", error: "target_section is required.", store });
204066
+ return JSON.stringify({ status: "error", error: "target_section is required.", store: store2 });
203249
204067
  }
203250
204068
  if (/^_observations$/i.test(target)) {
203251
204069
  return JSON.stringify({
203252
204070
  status: "error",
203253
204071
  error: 'The `_observations` buffer is not a curated section \u2014 merge INTO a named section (e.g. "procedures").',
203254
- store
204072
+ store: store2
203255
204073
  });
203256
204074
  }
203257
204075
  const query2 = String(args["query"] ?? "").trim().toLowerCase();
@@ -203273,7 +204091,7 @@ ${content}` : content);
203273
204091
  archived: 0,
203274
204092
  section: target,
203275
204093
  message: "No matching observations found.",
203276
- store
204094
+ store: store2
203277
204095
  });
203278
204096
  }
203279
204097
  const selected = matches2.slice(-limit);
@@ -203293,7 +204111,7 @@ ${newLines.join("\n")}` : newLines.join("\n");
203293
204111
  error: writeResult.reason ?? "knowledge.md write refused",
203294
204112
  moved: 0,
203295
204113
  section: target,
203296
- store
204114
+ store: store2
203297
204115
  });
203298
204116
  }
203299
204117
  const archived = ctx.memory.removeEntries(selected.map((e) => e.id));
@@ -203317,7 +204135,7 @@ ${newLines.join("\n")}` : newLines.join("\n");
203317
204135
  archived,
203318
204136
  section: target,
203319
204137
  message: `Merged ${selected.length} observation(s) into "${target}" and archived them.`,
203320
- store
204138
+ store: store2
203321
204139
  });
203322
204140
  }
203323
204141
  }
@@ -207408,6 +208226,41 @@ var init_semantic_search = __esm({
207408
208226
  }
207409
208227
  });
207410
208228
 
208229
+ // ../core/dist/skill-warnings.js
208230
+ function resolveMissingSkills(config, registry) {
208231
+ const assigned = config?.skills ?? [];
208232
+ if (assigned.length === 0)
208233
+ return [];
208234
+ if (!registry)
208235
+ return [...assigned];
208236
+ return assigned.filter((name) => !registry.get(name));
208237
+ }
208238
+ function buildSkillWarnings(config, registry) {
208239
+ const missing = resolveMissingSkills(config, registry);
208240
+ const available = registry ? registry.list().map((s2) => s2.name).slice(0, SKILL_WARNINGS_AVAILABLE_LIMIT) : [];
208241
+ return { missing, available };
208242
+ }
208243
+ function setAgentSkillWarnings(agent, warnings) {
208244
+ store.set(agent, {
208245
+ missing: [...warnings.missing],
208246
+ available: [...warnings.available]
208247
+ });
208248
+ }
208249
+ function getAgentSkillWarnings(agent) {
208250
+ const stored = store.get(agent);
208251
+ if (!stored)
208252
+ return void 0;
208253
+ return { missing: [...stored.missing], available: [...stored.available] };
208254
+ }
208255
+ var SKILL_WARNINGS_AVAILABLE_LIMIT, store;
208256
+ var init_skill_warnings = __esm({
208257
+ "../core/dist/skill-warnings.js"() {
208258
+ "use strict";
208259
+ SKILL_WARNINGS_AVAILABLE_LIMIT = 50;
208260
+ store = /* @__PURE__ */ new WeakMap();
208261
+ }
208262
+ });
208263
+
207411
208264
  // ../core/dist/tools/chrome-dialog-clicker.js
207412
208265
  import { execFile as execFile3, spawn as spawn5 } from "node:child_process";
207413
208266
  import { platform as platform6, homedir as homedir8 } from "node:os";
@@ -210294,6 +211147,7 @@ var init_agent_manager = __esm({
210294
211147
  init_recall();
210295
211148
  init_session();
210296
211149
  init_semantic_search();
211150
+ init_skill_warnings();
210297
211151
  init_chrome_dialog_clicker();
210298
211152
  init_markus_browser_bridge();
210299
211153
  init_markus_browser_mcp();
@@ -210383,7 +211237,6 @@ var init_agent_manager = __esm({
210383
211237
  recallCallbacks;
210384
211238
  delegationManager;
210385
211239
  _maxToolIterations = Infinity;
210386
- _cognitiveConfig;
210387
211240
  _concurrentConfig;
210388
211241
  _codingToolsEnabled = false;
210389
211242
  _codingToolsConfigs;
@@ -210576,12 +211429,6 @@ Priority: ${delegation.priority}`, envelope.from, { name: envelope.from, role: "
210576
211429
  set maxToolIterations(value) {
210577
211430
  this._maxToolIterations = value <= 0 ? Infinity : value;
210578
211431
  }
210579
- get cognitiveConfig() {
210580
- return this._cognitiveConfig;
210581
- }
210582
- set cognitiveConfig(value) {
210583
- this._cognitiveConfig = value;
210584
- }
210585
211432
  get concurrentConfig() {
210586
211433
  return this._concurrentConfig;
210587
211434
  }
@@ -211186,7 +212033,6 @@ You are ${request.name}.`,
211186
212033
  pathPolicy,
211187
212034
  skillRegistry: this.skillRegistry,
211188
212035
  maxToolIterations: this._maxToolIterations,
211189
- cognitive: this._cognitiveConfig,
211190
212036
  handbookPath: this.resolveHandbookPath(roleName)
211191
212037
  };
211192
212038
  const agent = new Agent(agentOpts);
@@ -211225,14 +212071,15 @@ You are ${request.name}.`,
211225
212071
  if (this.skillRegistry) {
211226
212072
  agent.setAvailableSkillCatalog(this.skillRegistry.getSkillCatalog());
211227
212073
  }
212074
+ const skillWarnings = buildSkillWarnings(config, this.skillRegistry);
212075
+ setAgentSkillWarnings(agent, skillWarnings);
212076
+ if (skillWarnings.missing.length > 0) {
212077
+ log53.debug(`Agent ${config.name} (${id}) references skills not found in registry`, {
212078
+ missing: skillWarnings.missing,
212079
+ available: skillWarnings.available
212080
+ });
212081
+ }
211228
212082
  if (this.skillRegistry && config.skills.length > 0) {
211229
- const missingSkills = config.skills.filter((s2) => !this.skillRegistry.get(s2));
211230
- if (missingSkills.length > 0) {
211231
- log53.warn(`Agent ${config.name} (${id}) references skills not found in registry`, {
211232
- missing: missingSkills,
211233
- available: this.skillRegistry.list().map((s2) => s2.name)
211234
- });
211235
- }
211236
212083
  for (const skillName of config.skills) {
211237
212084
  const skill = this.skillRegistry.get(skillName);
211238
212085
  if (skill?.manifest.mcpServers) {
@@ -212000,20 +212847,20 @@ You are ${row.name}.`,
212000
212847
  restoredState: { tokensUsedToday: row.tokensUsedToday ?? 0 },
212001
212848
  skillRegistry: this.skillRegistry,
212002
212849
  maxToolIterations: this._maxToolIterations,
212003
- cognitive: this._cognitiveConfig,
212004
212850
  handbookPath: this.resolveHandbookPath(row.roleId ?? row.roleName)
212005
212851
  });
212006
212852
  if (this.skillRegistry) {
212007
212853
  agent.setAvailableSkillCatalog(this.skillRegistry.getSkillCatalog());
212008
212854
  }
212855
+ const skillWarnings = buildSkillWarnings(config, this.skillRegistry);
212856
+ setAgentSkillWarnings(agent, skillWarnings);
212857
+ if (skillWarnings.missing.length > 0) {
212858
+ log53.debug(`Restored agent ${config.name} (${id}) references skills not found in registry`, {
212859
+ missing: skillWarnings.missing,
212860
+ available: skillWarnings.available
212861
+ });
212862
+ }
212009
212863
  if (this.skillRegistry && config.skills.length > 0) {
212010
- const missingSkills = config.skills.filter((s2) => !this.skillRegistry.get(s2));
212011
- if (missingSkills.length > 0) {
212012
- log53.warn(`Restored agent ${config.name} (${id}) references skills not found in registry`, {
212013
- missing: missingSkills,
212014
- available: this.skillRegistry.list().map((s2) => s2.name)
212015
- });
212016
- }
212017
212864
  const mcpConnections = [];
212018
212865
  for (const skillName of config.skills) {
212019
212866
  const skill = this.skillRegistry.get(skillName);
@@ -222245,8 +223092,8 @@ var init_external_gateway = __esm({
222245
223092
  setTasksFetcher(fetcher) {
222246
223093
  this.tasksFetcher = fetcher;
222247
223094
  }
222248
- setStore(store) {
222249
- this.store = store;
223095
+ setStore(store2) {
223096
+ this.store = store2;
222250
223097
  }
222251
223098
  /** Load persisted registrations from the store into memory. Call once at startup. */
222252
223099
  async loadFromStore(agentExists) {
@@ -226689,6 +227536,7 @@ __export(dist_exports3, {
226689
227536
  ReviewService: () => ReviewService,
226690
227537
  RoleLoader: () => RoleLoader,
226691
227538
  SCENARIO_ALLOWED_TOOLS: () => SCENARIO_ALLOWED_TOOLS,
227539
+ SKILL_WARNINGS_AVAILABLE_LIMIT: () => SKILL_WARNINGS_AVAILABLE_LIMIT,
226692
227540
  SUPPORTED_EXTERNAL_FORMATS: () => SUPPORTED_EXTERNAL_FORMATS,
226693
227541
  SecurityGuard: () => SecurityGuard,
226694
227542
  SemanticMemorySearch: () => SemanticMemorySearch,
@@ -226714,6 +227562,7 @@ __export(dist_exports3, {
226714
227562
  buildDistillationPrompt: () => buildDistillationPrompt,
226715
227563
  buildModelsAuthHeaders: () => buildModelsAuthHeaders,
226716
227564
  buildModelsEndpoint: () => buildModelsEndpoint,
227565
+ buildSkillWarnings: () => buildSkillWarnings,
226717
227566
  buildTaskContextPackage: () => buildTaskContextPackage,
226718
227567
  checkAutoClickStatus: () => checkAutoClickStatus,
226719
227568
  clearEnvironmentCache: () => clearEnvironmentCache,
@@ -226777,6 +227626,7 @@ __export(dist_exports3, {
226777
227626
  generateHandbook: () => generateHandbook,
226778
227627
  generateIdempotencyKey: () => generateIdempotencyKey,
226779
227628
  getAdapter: () => getAdapter,
227629
+ getAgentSkillWarnings: () => getAgentSkillWarnings,
226780
227630
  getAllAdapters: () => getAllAdapters,
226781
227631
  getAvailableProfiles: () => getAvailableProfiles,
226782
227632
  getBridgeToolDescriptors: () => getBridgeToolDescriptors,
@@ -226820,11 +227670,13 @@ __export(dist_exports3, {
226820
227670
  resetMarkitdownCache: () => resetMarkitdownCache,
226821
227671
  resolveMarkusRoute: () => resolveMarkusRoute,
226822
227672
  resolveMarkusSearchProvider: () => resolveMarkusSearchProvider,
227673
+ resolveMissingSkills: () => resolveMissingSkills,
226823
227674
  runSubagentLoop: () => runSubagentLoop,
226824
227675
  saveNotebook: () => saveNotebook,
226825
227676
  scenarioToPack: () => scenarioToPack,
226826
227677
  sensitiveDataGuardrail: () => sensitiveDataGuardrail,
226827
227678
  serializeNotebook: () => serializeNotebook,
227679
+ setAgentSkillWarnings: () => setAgentSkillWarnings,
226828
227680
  setTracingProvider: () => setTracingProvider,
226829
227681
  shouldDistillTask: () => shouldDistillTask,
226830
227682
  shouldEnterDeepSleep: () => shouldEnterDeepSleep,
@@ -226842,6 +227694,7 @@ var init_dist7 = __esm({
226842
227694
  init_tracing();
226843
227695
  init_agent_manager();
226844
227696
  init_role_loader();
227697
+ init_skill_warnings();
226845
227698
  init_heartbeat();
226846
227699
  init_context_engine();
226847
227700
  init_token_counter();
@@ -227675,6 +228528,23 @@ var init_org_service = __esm({
227675
228528
  const results = await Promise.all(restorePromises);
227676
228529
  const restoredCount = results.filter(Boolean).length;
227677
228530
  log73.info(`Restored ${restoredCount} agents from DB`);
228531
+ try {
228532
+ const affected = [];
228533
+ for (const row of toRestore) {
228534
+ try {
228535
+ const inst = this.agentManager.getAgent(row.id);
228536
+ const w = getAgentSkillWarnings(inst);
228537
+ if (w && w.missing.length > 0)
228538
+ affected.push({ name: row.name, missing: w.missing });
228539
+ } catch {
228540
+ }
228541
+ }
228542
+ if (affected.length > 0) {
228543
+ log73.warn(`${affected.length} of ${toRestore.length} restored agents reference skills that are not installed \u2014 those skills' tools are unavailable`, { affectedAgents: affected.map((a) => a.name), details: affected });
228544
+ }
228545
+ } catch (summaryErr) {
228546
+ log73.warn("Failed to summarize missing-skill warnings after restore", { error: String(summaryErr) });
228547
+ }
227678
228548
  } catch (error) {
227679
228549
  log73.warn("Failed to restore agents from DB", { error: String(error) });
227680
228550
  }
@@ -237148,7 +238018,7 @@ var init_task_service = __esm({
237148
238018
  if (agentStreak >= 2) {
237149
238019
  lines.push(``);
237150
238020
  lines.push(`Thread activity: ${agentStreak} consecutive agent comments on this task (no human input in between).`);
237151
- lines.push(`Consider whether your reply adds genuinely new information. If the discussion is going in circles, output [NO_REPLY_NEEDED] and let results speak.`);
238021
+ lines.push(`Consider whether your reply adds genuinely new information. If the discussion is going in circles, call the end_turn tool and let results speak.`);
237152
238022
  }
237153
238023
  lines.push(``);
237154
238024
  lines.push(`**MANDATORY before replying**: You MUST first understand the full context:`);
@@ -237292,7 +238162,7 @@ var init_task_service = __esm({
237292
238162
  if (agentStreak >= 2) {
237293
238163
  lines.push(``);
237294
238164
  lines.push(`Thread activity: ${agentStreak} consecutive agent comments on this requirement (no human input in between).`);
237295
- lines.push(`Consider whether your reply adds genuinely new information. If the discussion is going in circles, output [NO_REPLY_NEEDED] and let results speak.`);
238165
+ lines.push(`Consider whether your reply adds genuinely new information. If the discussion is going in circles, call the end_turn tool and let results speak.`);
237296
238166
  }
237297
238167
  lines.push(``);
237298
238168
  lines.push(`**MANDATORY before replying**: You MUST first understand the full context:`);
@@ -351261,7 +352131,7 @@ var init_sse_handler = __esm({
351261
352131
  const segText = this.msgSegments.filter((s2) => s2.type === "text").map((s2) => s2.content).join("");
351262
352132
  persistReply = segText || "";
351263
352133
  }
351264
- persistReply = stripCompletionMarkerLeak(persistReply).trim() || persistReply;
352134
+ persistReply = stripLegacyCompletionToken(persistReply).trim() || persistReply;
351265
352135
  const isEmptyTerminal = !persistReply && this.msgSegments.every((s2) => s2.type !== "tool" && !(s2.type === "text" && (s2.content || s2.thinking)));
351266
352136
  const treatAsStopped = wasCancelled || isCancelledReply && isEmptyTerminal;
351267
352137
  const donePayload = {
@@ -354892,6 +355762,11 @@ function evaluateDirtyState(input, lookupTask = () => void 0, now3 = Date.now(),
354892
355762
  if (hbFresh) {
354893
355763
  return { dirty: false, reason: "heartbeat fresh \u2014 agent still self-patrolling" };
354894
355764
  }
355765
+ const lp = parseTs(input.lastProgressAt);
355766
+ const progressFresh = !Number.isNaN(lp) && nowMs - lp < cfg.progressGraceMs;
355767
+ if (progressFresh) {
355768
+ return { dirty: false, reason: "recent progress \u2014 agent actively working (tool/LLM events)" };
355769
+ }
354895
355770
  const actStartedTs = input.currentActivity?.startedAt ? parseTs(input.currentActivity.startedAt) : NaN;
354896
355771
  const activityStale = Number.isNaN(actStartedTs) || nowMs - actStartedTs >= cfg.staleAfterMs;
354897
355772
  if (hasActivity && !activityStale) {
@@ -355047,8 +355922,14 @@ function evaluateConservator(input, lookupTask = () => void 0, now3 = Date.now()
355047
355922
  currentActivity: input.currentActivity,
355048
355923
  activeTaskIds: input.activeTaskIds,
355049
355924
  lastHeartbeat: input.lastHeartbeat,
355925
+ lastProgressAt: input.lastProgressAt,
355050
355926
  lastErrorAt: input.lastErrorAt
355051
- }, lookupTask, nowMs, { enabled: cfg.enabled, staleAfterMs: cfg.staleAfterMs, heartbeatGraceMs: cfg.heartbeatGraceMs });
355927
+ }, lookupTask, nowMs, {
355928
+ enabled: cfg.enabled,
355929
+ staleAfterMs: cfg.staleAfterMs,
355930
+ heartbeatGraceMs: cfg.heartbeatGraceMs,
355931
+ progressGraceMs: cfg.progressGraceMs
355932
+ });
355052
355933
  const stall = evaluateStall({ runtime }, nowMs, { stallAfterMs: cfg.stallAfterMs });
355053
355934
  const base = { agentId: input.agentId, runtime, dirty, stall };
355054
355935
  if (!cfg.enabled)
@@ -355121,13 +356002,15 @@ function evaluateConservator(input, lookupTask = () => void 0, now3 = Date.now()
355121
356002
  const hbFresh = !Number.isNaN(lh) && nowMs - lh < cfg.heartbeatGraceMs;
355122
356003
  const actStart = input.currentActivity?.startedAt ? parseTs(input.currentActivity.startedAt) : NaN;
355123
356004
  const actFresh = hasActivity && !Number.isNaN(actStart) && nowMs - actStart < cfg.staleAfterMs;
355124
- if (hbFresh || actFresh) {
356005
+ const lp = parseTs(input.lastProgressAt);
356006
+ const progressFresh = !Number.isNaN(lp) && nowMs - lp < cfg.progressGraceMs;
356007
+ if (hbFresh || actFresh || progressFresh) {
355125
356008
  return {
355126
356009
  ...base,
355127
356010
  stage: "observe",
355128
356011
  action: "none",
355129
- criterion: hbFresh ? "fresh-heartbeat" : "fresh-activity",
355130
- reason: hbFresh ? "processing-like but heartbeat fresh \u2014 short observation window, hold off" : "activity just started \u2014 within stale window, hold off",
356012
+ criterion: hbFresh ? "fresh-heartbeat" : actFresh ? "fresh-activity" : "fresh-progress",
356013
+ reason: hbFresh ? "processing-like but heartbeat fresh \u2014 short observation window, hold off" : actFresh ? "activity just started \u2014 within stale window, hold off" : "processing-like with recent progress (tool/LLM events) \u2014 actively working, hold off",
355131
356014
  suggestions: ["\u4FDD\u6301\u89C2\u5BDF\uFF1B\u82E5 continue processing \u65E0\u8FDB\u5C55\u518D\u5347\u7EA7"]
355132
356015
  };
355133
356016
  }
@@ -355161,8 +356044,10 @@ var init_agent_conservator = __esm({
355161
356044
  enabled: true,
355162
356045
  staleAfterMs: 5 * 6e4,
355163
356046
  // 5 分钟无进展
355164
- heartbeatGraceMs: 2 * 6e4
356047
+ heartbeatGraceMs: 2 * 6e4,
355165
356048
  // 心跳 2 分钟内视为存活
356049
+ progressGraceMs: 10 * 6e4
356050
+ // 10 分钟内有工具/LLM 进展即视为存活(> shell 5 分钟上界)
355166
356051
  };
355167
356052
  DEFAULT_STALL_CONFIG = {
355168
356053
  stallAfterMs: 30 * 6e4
@@ -355180,6 +356065,7 @@ var init_agent_conservator = __esm({
355180
356065
  enabled: true,
355181
356066
  staleAfterMs: 5 * 6e4,
355182
356067
  heartbeatGraceMs: 2 * 6e4,
356068
+ progressGraceMs: 10 * 6e4,
355183
356069
  stallAfterMs: 30 * 6e4,
355184
356070
  retryBaseMs: CONSERVATOR_RETRY_AFTER_MS,
355185
356071
  backoffMaxMs: CONSERVATOR_BACKOFF_MAX_MS,
@@ -356827,7 +357713,7 @@ ${cleanText}`,
356827
357713
  `[CHANNEL] channel_key="${channel}"`
356828
357714
  ];
356829
357715
  if ((chainCtx?.depth ?? 0) >= 2) {
356830
- prefixLines.push("[LOOP GUARD] This DM already exchanged replies. Default to [NO_RESPONSE] unless you have a NEW fact, question, or instruction.", 'Do NOT acknowledge with \u6536\u5230/\u4FDD\u6301\u5F85\u547D/OK. Do NOT paste "\u56DE\u590D\u8BF4" back into this DM \u2014 use notify_user for humans.');
357716
+ prefixLines.push("[LOOP GUARD] This DM already exchanged replies. If you have no NEW fact, question, or instruction, call the end_turn tool instead of replying.", 'Do NOT acknowledge with \u6536\u5230/\u4FDD\u6301\u5F85\u547D/OK. Do NOT paste "\u56DE\u590D\u8BF4" back into this DM \u2014 use notify_user for humans.');
356831
357717
  }
356832
357718
  prefixLines.push("---", "");
356833
357719
  messagePrefix = prefixLines.join("\n");
@@ -356856,7 +357742,7 @@ ${cleanText}`,
356856
357742
  prefixLines.push(">>> You are the target of this message. You SHOULD respond. <<<");
356857
357743
  } else {
356858
357744
  prefixLines.push(">>> STOP. This message is NOT for you. The user is talking to " + [...targetNames].join(", ") + ", not you.");
356859
- prefixLines.push("You MUST respond with exactly: [NO_RESPONSE]");
357745
+ prefixLines.push("You MUST end your turn by calling the end_turn tool \u2014 do not write a reply.");
356860
357746
  prefixLines.push('The ONLY exception: you are directly contradicted by a factual error. Offering opinions, agreement, "me too", or generic help does NOT count. <<<');
356861
357747
  }
356862
357748
  } else if (!isA2A) {
@@ -356878,7 +357764,7 @@ ${cleanText}`,
356878
357764
  }
356879
357765
  if (isTargeted && !thisAgentIsTarget && !isA2A) {
356880
357766
  prefixLines.push("");
356881
- prefixLines.push("REMINDER: This message is directed at " + [...targetNames].join(", ") + ". You are " + agentName + ". Respond ONLY with [NO_RESPONSE].");
357767
+ prefixLines.push("REMINDER: This message is directed at " + [...targetNames].join(", ") + ". You are " + agentName + ". End your turn by calling the end_turn tool instead of replying.");
356882
357768
  }
356883
357769
  prefixLines.push("---", "");
356884
357770
  messagePrefix = prefixLines.join("\n");
@@ -358907,6 +359793,18 @@ ${cleanText}`,
358907
359793
  }, taskLookup, void 0, DEFAULT_CONSERVATOR_CONFIG);
358908
359794
  return { ...a, runtime: { ...runtime, stall: verdict.stall, dirty: verdict.dirty } };
358909
359795
  });
359796
+ const skillAgentManager = this.orgService.getAgentManager();
359797
+ agents = agents.map((a) => {
359798
+ try {
359799
+ const inst = skillAgentManager.getAgent(a.id);
359800
+ const w = getAgentSkillWarnings(inst);
359801
+ if (w && w.missing.length > 0) {
359802
+ return { ...a, skillWarnings: { missing: w.missing } };
359803
+ }
359804
+ } catch {
359805
+ }
359806
+ return a;
359807
+ });
358910
359808
  this.json(res, 200, { agents });
358911
359809
  return;
358912
359810
  }
@@ -360114,8 +361012,11 @@ ${userText}` : userText;
360114
361012
  const h = mem.getMemoryHealth?.();
360115
361013
  return h ? {
360116
361014
  usedPercent: h.percent,
360117
- budgetChars: h.totalChars,
360118
- budgetLimit: h.cap,
361015
+ budgetChars: h.curatedChars,
361016
+ budgetLimit: h.curatedCap,
361017
+ observationPercent: h.observationPercent,
361018
+ observationChars: h.observationChars,
361019
+ observationLimit: h.observationCap,
360119
361020
  observationCount: h.observations,
360120
361021
  curatedCount: h.curatedSections,
360121
361022
  archivedChars: h.archiveChars,
@@ -360710,6 +361611,10 @@ EXPLANATION_END`;
360710
361611
  activeTaskCount: state.activeTaskCount,
360711
361612
  activeTaskIds: state.activeTaskIds,
360712
361613
  skills: agent.getActiveSkillNames(),
361614
+ // H9: assigned skills that are not installed in the registry. Stamped on the agent
361615
+ // instance at create/restore; full shape here (missing + available catalog, capped).
361616
+ // Always present so the UI has a stable field to render the ⚠️ degradation banner.
361617
+ skillWarnings: getAgentSkillWarnings(agent) ?? { missing: [], available: [] },
360713
361618
  availableSkills: this.skillRegistry?.list().map((s2) => ({
360714
361619
  name: s2.name,
360715
361620
  description: s2.description,
@@ -362642,7 +363547,6 @@ EXPLANATION_END`;
362642
363547
  const am = this.orgService.getAgentManager();
362643
363548
  this.json(res, 200, {
362644
363549
  maxToolIterations: am.maxToolIterations,
362645
- cognitive: am.cognitiveConfig ?? { enabled: false },
362646
363550
  concurrent: am.concurrentConfig ?? { enabled: true, maxWorkers: 3 }
362647
363551
  });
362648
363552
  return;
@@ -362658,16 +363562,6 @@ EXPLANATION_END`;
362658
363562
  am.maxToolIterations = body["maxToolIterations"];
362659
363563
  changed = true;
362660
363564
  }
362661
- if (body["cognitive"] && typeof body["cognitive"] === "object") {
362662
- const cc = body["cognitive"];
362663
- am.cognitiveConfig = {
362664
- enabled: cc["enabled"] === true,
362665
- maxDepth: typeof cc["maxDepth"] === "number" ? cc["maxDepth"] : void 0,
362666
- appraisalModel: typeof cc["appraisalModel"] === "string" ? cc["appraisalModel"] : void 0,
362667
- timeoutMs: typeof cc["timeoutMs"] === "number" ? cc["timeoutMs"] : void 0
362668
- };
362669
- changed = true;
362670
- }
362671
363565
  if (body["concurrent"] && typeof body["concurrent"] === "object") {
362672
363566
  const cc = body["concurrent"];
362673
363567
  const policy = cc["conflictPolicy"];
@@ -362683,7 +363577,6 @@ EXPLANATION_END`;
362683
363577
  saveConfig({
362684
363578
  agent: {
362685
363579
  maxToolIterations: am.maxToolIterations,
362686
- cognitive: am.cognitiveConfig,
362687
363580
  concurrent: am.concurrentConfig
362688
363581
  }
362689
363582
  }, this.markusConfigPath);
@@ -362706,7 +363599,6 @@ EXPLANATION_END`;
362706
363599
  }
362707
363600
  this.json(res, 200, {
362708
363601
  maxToolIterations: am.maxToolIterations,
362709
- cognitive: am.cognitiveConfig ?? { enabled: false },
362710
363602
  concurrent: am.concurrentConfig ?? { enabled: true, maxWorkers: 3 }
362711
363603
  });
362712
363604
  return;
@@ -386487,15 +387379,6 @@ async function createServices(config) {
386487
387379
  if (config.agent?.maxToolIterations) {
386488
387380
  agentManager.maxToolIterations = config.agent.maxToolIterations;
386489
387381
  }
386490
- if (config.agent?.cognitive) {
386491
- const cc = config.agent.cognitive;
386492
- agentManager.cognitiveConfig = {
386493
- enabled: cc.enabled ?? false,
386494
- maxDepth: cc.maxDepth,
386495
- appraisalModel: cc.appraisalModel,
386496
- timeoutMs: cc.timeoutMs
386497
- };
386498
- }
386499
387382
  if (config.codingTools) {
386500
387383
  agentManager.setCodingToolsConfig(config.codingTools);
386501
387384
  }